branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>microchip78/D3TestBench<file_sep>/views/examples/first_d3_selection.html
<section class="instruction-group">
<p class="instructions">
First step is to create a variable to hold data. For this exercises we are jusing using simple data, an array of numbers stored in variable
</p>
<div hljs>
var nums = [80, 53, 125, 200, 28, 97];
</div>
</section>
<section class="instruction-group">
<p class="instructions">
Append SVG element to d3demo element created before and set height and width attribute to 200
</p>
<div hljs>
var svg = d3demo.append('svg').attr("width", 200).attr("height", 200)
</div>
</section>
<section class="instruction-group">
<p class="instructions">Create selections of 'rect' elements and assign to variable bars</p>
<div hljs>
var bars = svg.selectAll('rect');
</div>
<p class="instructions">Currently this selection is not holding any element as there is no 'rect' element in the page</p>
</section>
<script type="text/javascript">
var nums = [80, 53, 125, 200, 28, 97];
var svg = d3demo.append('svg');
svg.attr("width", 200).attr("height", 200)
// adding data to selection
var bars = svg.selectAll('rect').data(nums);
// creating subset of enter and append rect to that subset
bars.enter().append('rect');
// setting width and height of each rect
bars.attr("width", 20).attr("height", 20);
// position each rect to the location based on bar's position
bars.attr("x", function(d, i) {
return 30 * i;
});
// changing height of bar based on data
bars.attr("height", function(d, i) {
return d;
})
// as svg cordinates start from top left corner of the container, by default y = 0 set the bar showing upside down
// offset each bar by height of container - height of bar to showing in correct orientation
bars.attr("y", function(d, i) {
return 200 - d;
})
</script>
<file_sep>/js/app.js
var d3app = angular.module('d3app', ['ui.router', 'oc.lazyLoad', 'hljs']);
<file_sep>/README.md
# D3BoilerPlate
This is a D3 Boiler Plate, comes with all required package.json and bower.json file
All you have to do is download the application and run 'npm install' and 'bower install' to install all required dependencies.
run gulp from command prompt to run the application
<file_sep>/js/controllers.js
d3app.controller('homeController', ['$scope', function($scope) {
$scope.title = "Welcome to D3 Boiler Plate";
}]);
d3app.controller('featuresController', ['$scope', function($scope) {
$scope.title = "This app has following features";
}]);
d3app.controller('aboutController', ['$scope', function($scope) {
$scope.title = "About this application";
}]);
d3app.controller('examplesController', ['$scope', function($scope) {
$scope.title = "See some of awesome examples";
$scope.examples = [
{
title: "Loading D3.js",
state_ref: "example.checking_d3_available"
},
{
title: "Adding DOM Elements",
state_ref: "example.adding_dom_elements"
},
{
title: "Loading Json Data File",
state_ref: "example.load_json_data_file"
},
{
title: "Loading different types of data",
state_ref: "example.loading_different_data"
},
{
title: "First bar chart crafted in SVG using markup",
state_ref: "example.svg_bar_chart"
},
{
title: "First look at d3 selection and creating barchart",
state_ref: "example.first_d3_selection"
},
{
title: "Fully interactive D3 barchart with animation",
state_ref: "example.d3_interactive_bar_chart"
},
{
title: "D3 Selection and Subselection",
state_ref: "example.selection_and_subselection"
},
{
title: "D3 - DIY Bar Chart",
state_ref: "example.diy_bar_chart"
},
{
title: "D3 - DIY Column Chart",
state_ref: "example.diy_column_chart"
},
{
title: "D3 - DIY Grouped Column Chart",
state_ref: "example.diy_grouped_column_chart"
},
{
title: "D3 - DIY Grouped Column Chart [Re-thinked]",
state_ref: "example.diy_grouped_column_chart_reusable"
},
{
title: "D3 - Path Animation",
state_ref: "example.path_animation"
}
];
}]);<file_sep>/views/examples/diy_grouped_column_chart_reusable.js
var container = window.d3demo;
var config = {
size: {
width: $('#demo').width(),
height: 700
},
margins: {
top : 40,
right: 20,
bottom: 50,
left: 50
}
};
function csv(data, rowsKeyName) {
var _getSeriesLabels = function() {
var seriesLabels = [];
data.map(set => {
var keys = d3.keys(set).filter(function(key) { return key != rowsKeyName; });
keys.forEach(k => {
if(seriesLabels.indexOf(k) == -1) {
seriesLabels.push(k);
}
});
});
return seriesLabels;
};
var _getSeries = function() {
var seriesLabels = _getSeriesLabels();
return seriesLabels.map(t => {
return {
name: t,
active: true
};
});
};
var toChartData = function() {
var legends = _getSeries(data, rowsKeyName);
var formatedData = data.map(set => {
return {
groupKey: set[rowsKeyName],
groupData: legends.map(legend => {
return {
name: legend.name,
value: +set[legend.name]
};
})
};
});
return {
chartData: formatedData,
chartLegends: legends
};
};
var toChartSeriesData = function() {
var series = _getSeries();
series.map(s => {
s.points = data.map(set => {
return {
label: s.name,
name: set[rowsKeyName],
value: +set[s.name]
};
});
});
return series;
};
var transposed = function(columnsKeyName) {
var series = _getSeriesLabels();
return data.map(set => {
return {
name: set.State,
active: true,
points: series.map(s => {
return {
label: set.State,
name: s,
value: +set[s]
};
})
};
});
};
return {
toChartData: toChartData,
toChartSeriesData: toChartSeriesData,
transposed: transposed
};
}
function groupedColumnChart(viz, config, data) {
var vizConfig = {};
vizConfig.size = {
width: config.size.width - config.margins.left - config.margins.right,
height: config.size.height - config.margins.top - config.margins.bottom
};
vizConfig.scale = {
x: d3.scale.ordinal().rangeRoundBands([0, vizConfig.size.width], 0.1),
y: d3.scale.linear().range([vizConfig.size.height, 0]),
colors: d3.scale.ordinal().range(['#9e0142','#d53e4f','#f46d43','#fdae61','#66c2a5','#3288bd','#5e4fa2'])
};
vizConfig.axis = {
x: d3.svg.axis().scale(vizConfig.scale.x).orient("bottom"),
y: d3.svg.axis().scale(vizConfig.scale.y).orient("left").tickFormat(d3.format(".2s"))
};
var axisGroups = {};
axisGroups.x = viz.append('g')
.attr({
class : "axis x-axis only-ticks",
transform : "translate(" + [0, vizConfig.size.height ] + ")"
})
.call(vizConfig.axis.x);
axisGroups.y = viz.append('g')
.attr("class", "axis y-axis")
.call(vizConfig.axis.y);
var axisLables = {};
axisLables.x = axisGroups.x.append('text')
.classed('axis-label x-label', true)
.attr({
x: vizConfig.size.width / 2,
y: 40
});
axisLables.y = axisGroups.y.append('text')
.classed('axis-label y-label', true)
.attr({
transform: "rotate(-90)",
y: 10
});
var columnGroups = [];
var columns = [];
var legends = [];
var createViz = function(data) {
// // Example code for chaining transitions
// // First transition the line & label to the new city.
// var t0 = svg.transition().duration(750);
// t0.selectAll(".line").attr("d", line);
// t0.selectAll(".label").attr("transform", transform).text(city);
// // Then transition the y-axis.
// y.domain(d3.extent(data, function(d) { return d[city]; }));
// var t1 = t0.transition();
// t1.selectAll(".line").attr("d", line);
// t1.selectAll(".label").attr("transform", transform);
// t1.selectAll(".y.axis").call(yAxis);
var _getDataPoints = function() {
var dataPoints = [];
data.map(set => {
set.points.map(p => {
if(dataPoints.indexOf(p.name) == -1) {
dataPoints.push(p.name);
}
});
});
return dataPoints;
};
var resetColumns = function() {
if(plotted) {
columns.transition().duration(1000).ease("out").delay(function(d, i) { return i * 100; })
.attr({
height: function(d) { return vizConfig.size.height - vizConfig.scale.y(0); }
});
}
};
var updateScale = function() {
vizConfig.scale.x.domain(data[0].points.map(function(d) { return d.name; }));
vizConfig.scale.x1 =
d3.scale
.ordinal()
.domain(data.filter(function(d) { return d.active; }).map(function(d) { return d.name; }))
.rangeRoundBands([0, vizConfig.scale.x.rangeBand()]);
var dataMaxValue = d3.max(data.filter(function(d) { return d.active; }), function(d) { return d3.max(d.points, function(d) { return d.value; }); });
vizConfig.scale.y.domain([0, dataMaxValue]);
};
var updateAxis = function() {
axisGroups.x.transition().call(vizConfig.axis.x);
axisGroups.y.transition().call(vizConfig.axis.y);
};
var updateLabels = function(xLabel, yLabel) {
axisLables.x.text(xLabel);
axisLables.y.text(yLabel);
};
var createColumnGroups = function() {
var columnGroupAttrs = {
entering: {
class: "column-group",
transform: function(d) { return "translate(" + [vizConfig.scale.x(d[0].name), 0] + ")"; }
}
};
var groupData = _getDataPoints().map(dp => {
return data.filter(function(s) { return s.active === true; }).map(set => {
return set.points.filter(function(p) { return p.name == dp; })[0];
});
});
columnGroups = viz.selectAll('.column-group').data(groupData);
columnGroups.exit().remove();
columnGroups.attr(columnGroupAttrs.entering);
columnGroups.enter().append('g').attr(columnGroupAttrs.entering);
};
var createColumns = function() {
var columnsAttributes = {
init: {
x: function(d) { return vizConfig.scale.x1(d.label); },
y: function(d) { return vizConfig.scale.y(0); },
width: function() { return vizConfig.scale.x1.rangeBand() },
height: function(d) { return vizConfig.size.height - vizConfig.scale.y(0); },
fill: function(d) { return vizConfig.scale.colors(d.label); }
},
final: {
x: function(d) { return vizConfig.scale.x1(d.label); },
y: function(d) { return vizConfig.scale.y(d.value); },
width: function() { return vizConfig.scale.x1.rangeBand() },
height: function(d) { return vizConfig.size.height - vizConfig.scale.y(d.value); },
fill: function(d) { return vizConfig.scale.colors(d.label); }
}
};
columns = columnGroups.selectAll('rect.column').data(function(d) { return d; });
var exitingColumns = columns.exit().transition().ease("elastic").duration(1000).remove();
columns.transition()
.attr(columnsAttributes.final)
.attr("width", vizConfig.scale.x1.rangeBand());
var enteringColumns = columns.enter()
.append("rect")
.classed('column', true)
.attr(columnsAttributes.init)
.attr("width", vizConfig.scale.x1.rangeBand());
enteringColumns.transition()
.ease("elastic")
.duration(1000)
.delay(function(d, i) { return i * 100; })
.attr(columnsAttributes.final)
.attr("height", function(d) { return vizConfig.size.height - vizConfig.scale.y(d.value); })
.attr("y", function(d) { return vizConfig.scale.y(d.value); })
.attr("width", vizConfig.scale.x1.rangeBand());
};
var createLegends = function() {
legendsAttrs = {
entering: {
class: "legend",
transform: function(d, i) {
return "translate(" + [0, i * 20] + ")";
}
},
updating: {
opacity: function(d) {
if(d.active) return 1;
else return 0.3;
}
}
};
legendRectAttrs = {
entering: {
x: vizConfig.size.width - 20,
width: 20,
height: 20,
fill: function(d) {
return vizConfig.scale.colors(d.name)
},
cursor: "pointer"
}
};
legendTextAttrs = {
entering: {
x: vizConfig.size.width - 24,
y: 10,
dy: "0.35em",
}
};
legends = viz.selectAll(".legend").data(data);
legends.attr(legendsAttrs.updating);
legends.select('text').text(function(d) { return d.name; });
legends.exit().remove();
var enteringLegends = legends.enter().append("g");
enteringLegends.attr(legendsAttrs.entering).attr(legendsAttrs.updateing);
enteringLegends.append("rect")
.attr(legendRectAttrs.entering);
enteringLegends.append('text')
.attr(legendTextAttrs.entering)
.style("text-anchor", "end")
.text(function(d) { return d.name; });
};
resetColumns();
updateScale(data);
updateAxis();
updateLabels("US States", "Population");
createColumnGroups();
createColumns();
createLegends();
legends.on('click', function(d) {
d.active = !d.active;
updateScale(data);
updateAxis();
createColumnGroups();
createColumns();
createLegends();
});
};
var plotted = false;
var plot = function(data) {
createViz(data, plotted);
plotted = true;
};
return {
plot: plot
};
}
var vizIt = function(csvData) {
console.log(container);
console.log(config);
var createSVG = function(svgSize) {
var svg = container
.append('svg')
.attr({
width: svgSize.width,
height: svgSize.height
});
return svg;
};
var createViz = function(svg, svgMargins) {
return svg
.append('g')
.attr({
"class" : "viz",
"transform" : "translate(" + [svgMargins.left, svgMargins.top] + ")"
});
};
var createButton = function(svg) {
var bg = svg.append('g').classed('toggle', true)
.attr("transform", "translate("+[config.size.width - 160, 0]+")");
bg.append('line').attr({
x1: 0,
y1: 22,
x2: 141,
y2: 22
});
bg.append('text')
.attr({
x: 0,
y: 15
})
.text("Arrange By Age Group");
return bg;
};
var svg = createSVG(config.size);
var bg = createButton(svg);
var viz = createViz(svg, config.margins);
var columnChart = new groupedColumnChart(viz, config);
var chartData = csvData.toChartSeriesData();
columnChart.plot(chartData);
bg.on('click', function(d, i) {
var isSelected = d3.select(this).classed('selected');
isSelected = !isSelected;
d3.select(this).classed('selected', isSelected);
if(isSelected) {
// d3.select(this).select('text').text('')
//groupByAgeGroup(d, i, this, vizConfig);
var transposedChartData = csvData.transposed();
columnChart.plot(transposedChartData);
} else {
var chartData = csvData.toChartSeriesData();
columnChart.plot(chartData);
}
});
};
var loadData = function() {
d3.csv("data/state_age_population.csv", function(error, data) {
if (error) return console.warn(error);
var csvData = csv(data, "State");
vizIt(csvData);
});
};
var init = function() {
loadData();
};
init();
|
734c776d4bd1b61d80c834a81c0abcc679a92b36
|
[
"JavaScript",
"HTML",
"Markdown"
] | 5 |
HTML
|
microchip78/D3TestBench
|
016078448d6fccf212f73c87f0790d6c3c0caa8e
|
4ec3487a311c436a954a960eb53009e147736bcf
|
refs/heads/master
|
<file_sep>import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
class ListFrame extends JFrame implements ActionListener{
private String colName[] = {"๋ฒํธ","์ด๋ฆ"};
private DefaultTableModel model = new DefaultTableModel(colName,0);
private DefaultTableModel model1 = new DefaultTableModel(colName,0);
private DefaultTableModel model2 = new DefaultTableModel(colName,0);
private DefaultTableModel model3 = new DefaultTableModel(colName,0);
private DefaultTableModel model4 = new DefaultTableModel(colName,0);
private DefaultTableModel model5 = new DefaultTableModel(colName,0);
private DefaultTableModel model6 = new DefaultTableModel(colName,0);
private DefaultTableModel model7 = new DefaultTableModel(colName,0);
private DefaultTableModel model8 = new DefaultTableModel(colName,0);
private JTable table = new JTable(model);
private JTable table1 = new JTable(model1);
private JTable table2 = new JTable(model2);
private JTable table3 = new JTable(model3);
private JTable table4 = new JTable(model4);
private JTable table5 = new JTable(model5);
private JTable table6 = new JTable(model6);
private JTable table7 = new JTable(model7);
private JTable table8 = new JTable(model8);
private JPanel pan = new JPanel();
private JPanel pan1 = new JPanel();
private JPanel pan2 = new JPanel();
private JPanel pan3 = new JPanel();
private JPanel pan4 = new JPanel();
private JPanel pan5 = new JPanel();
private JPanel pan6 = new JPanel();
private JPanel pan7 = new JPanel();
private JPanel pan8 = new JPanel();
private JScrollPane tableScroll;
private JScrollPane tableScroll1;
private JScrollPane tableScroll2;
private JScrollPane tableScroll3;
private JScrollPane tableScroll4;
private JScrollPane tableScroll5;
private JScrollPane tableScroll6;
private JScrollPane tableScroll7;
private JScrollPane tableScroll8;
JButton ok;
InfoManager infomg;
public void savetable(String id, String text, DefaultTableModel model){
String row[][] = new String[infomg.heallist.size()][2];
int count = 0;
for(int i=0; i<infomg.heallist.size(); i++){
if(id.equals(infomg.heallist.get(i).get_id()) && infomg.heallist.get(i).get_skill().equals(text)){
count++;
row[i][0] = Integer.toString(count);
row[i][1] = infomg.heallist.get(i).get_name();
model.addRow(row[i]);}
}
}
public void settable(JTable table){
DefaultTableCellRenderer celAlignCenter = new DefaultTableCellRenderer(); // ๊ฐ์ด๋ฐ ์ ๋ ฌ
celAlignCenter.setHorizontalAlignment(JLabel.CENTER);
table.getColumn("๋ฒํธ").setPreferredWidth(30);
table.getColumn("์ด๋ฆ").setPreferredWidth(50);
table.getColumn("๋ฒํธ").setCellRenderer(celAlignCenter);
table.getColumn("์ด๋ฆ").setCellRenderer(celAlignCenter);
table.setEnabled(false);
}
public ListFrame(InfoManager temp_infomg){ //๋ฆฌ์คํธ ๋ชฉ๋กGUI
infomg = temp_infomg;
setTitle("๋ฌด์ ๋ณ ์ธ์ ๋ฆฌ์คํธ");
setLayout(new BorderLayout());
JPanel totalskill = new JPanel(new GridLayout(1,9));
JLabel skill = new JLabel("๋ณต์ฑ");
JLabel skill1 = new JLabel("๋ฌด์ํ์ด");
JLabel skill2 = new JLabel("์ฃผ์ง์");
JLabel skill3 = new JLabel("ํ๊ถ๋");
JLabel skill4 = new JLabel("๊ฒ๋");
JLabel skill5 = new JLabel("๋ ์ฌ๋ง");
JLabel skill6 = new JLabel("์นดํฌ์๋ผ");
JLabel skill7 = new JLabel("์ ๋");
JLabel skill8 = new JLabel("์ฐ์");
skill.setHorizontalAlignment(JLabel.CENTER);
skill1.setHorizontalAlignment(JLabel.CENTER);
skill2.setHorizontalAlignment(JLabel.CENTER);
skill3.setHorizontalAlignment(JLabel.CENTER);
skill4.setHorizontalAlignment(JLabel.CENTER);
skill5.setHorizontalAlignment(JLabel.CENTER);
skill6.setHorizontalAlignment(JLabel.CENTER);
skill7.setHorizontalAlignment(JLabel.CENTER);
skill8.setHorizontalAlignment(JLabel.CENTER);
totalskill.add(skill);
totalskill.add(skill1);
totalskill.add(skill2);
totalskill.add(skill3);
totalskill.add(skill4);
totalskill.add(skill5);
totalskill.add(skill6);
totalskill.add(skill7);
totalskill.add(skill8);
JPanel totallist = new JPanel(new GridLayout(1,9));
String id = infomg.id;
savetable(id,"๋ณต์ฑ",model);
savetable(id,"๋ฌด์ํ์ด",model1);
savetable(id,"์ฃผ์ง์",model2);
savetable(id,"ํ๊ถ๋",model3);
savetable(id,"๊ฒ๋",model4);
savetable(id,"๋ ์ฌ๋ง",model5);
savetable(id,"์นดํฌ์๋ผ",model6);
savetable(id,"์ ๋",model7);
savetable(id,"์ฐ์",model8);
settable(table);
settable(table1);
settable(table2);
settable(table3);
settable(table4);
settable(table5);
settable(table6);
settable(table7);
settable(table8);
pan.add(table);
pan1.add(table1);
pan2.add(table2);
pan3.add(table3);
pan4.add(table4);
pan5.add(table5);
pan6.add(table6);
pan7.add(table7);
pan8.add(table8);
totallist.add(pan);
totallist.add(pan1);
totallist.add(pan2);
totallist.add(pan3);
totallist.add(pan4);
totallist.add(pan5);
totallist.add(pan6);
totallist.add(pan7);
totallist.add(pan8);
//ํ์ธ ๋ฒํผ
JPanel okp = new JPanel();
ok = new JButton("ํ์ธ");
ok.addActionListener(this);
okp.add(ok);
add("North", totalskill);
add("Center", totallist);
add("South", okp);
setSize(1000,400);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ok){
dispose();
}
}
}
<file_sep>import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class Exercise extends JFrame implements ActionListener{
JTextField tfheight; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ํค ํ
์คํธ ํ๋
JTextField tfweight; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ๋ชธ๋ฌด๊ฒ ํ
์คํธ ํ๋
JRadioButton boxing; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ๋ณต์ฑ ๋ผ๋์ค ๋ฒํผ
JRadioButton muatie; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ๋ฌด์ํ์ด ๋ผ๋์ค ๋ฒํผ
JRadioButton jujitsu; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ์ฃผ์ง์ ๋ผ๋์ค ๋ฒํผ
JRadioButton taegyundo; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ํ๊ถ๋ ๋ผ๋์ค ๋ฒํผ
JRadioButton gumdo; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ๊ฒ๋ ๋ผ๋์ค ๋ฒํผ
JRadioButton wrestling; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ๋ ์คํ
๋ผ๋์ค ๋ฒํผ
JRadioButton kapoara; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ์นดํฌ์๋ผ ๋ผ๋์ค ๋ฒํผ
JRadioButton youdo; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ์ ๋ ๋ผ๋์ค ๋ฒํผ
JRadioButton yuswu; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ์ฐ์ ๋ผ๋์ค ๋ฒํผ
JButton ok; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ํ์ธ ๋ฒํผ
JButton cancel; //๋ฌด์ ๋ฑ๋ก์ฐฝ์ ์ทจ์ ๋ฒํผ
InfoManager info; //Heallist์ ๋ก๊ทธ์ธ id์ ํ์ ์ด๋ฆ์ ๋ถ๋ฌ์ค๊ธฐ ์ํ ๋ฉ๋์ ๋ณ์
String id = null; //Health ์ ์์ด๋ ์ ์ฅ
String name = null; //Health ์ ํ์ ์ด๋ฆ ์ ์ฅ
String height = null; //Health ์ ํ์ ํค ์ ์ฅ
String weight = null; //Health ์ ํ์ ๋ชธ๋ฌด๊ฒ ์ ์ฅ
String skill = null; //Health ์ ํ์ ๋ฌด์ ์ ์ฅ
public Exercise(InfoManager tempinfo,String id, String name){
setTitle("Martial Arts");
info = tempinfo;
this.id = id;
this.name = name;
for(int i =0; i<info.heallist.size(); i++){
if(name.equals(info.heallist.get(i).get_name()) && id.equals(info.heallist.get(i).get_id())){
height = info.heallist.get(i).get_height();
weight = info.heallist.get(i).get_weight();
skill = info.heallist.get(i).get_skill();
}
}
JPanel total = new JPanel(new BorderLayout());
Border border=BorderFactory.createEtchedBorder();
Border heightB=BorderFactory.createTitledBorder(border, "ํค");
Border weightB=BorderFactory.createTitledBorder(border, "๋ชธ๋ฌด๊ฒ");
JPanel bodyp = new JPanel(new FlowLayout());
JPanel heightp = new JPanel();
JPanel weightp = new JPanel();
heightp.setBorder(heightB);
weightp.setBorder(weightB);
tfheight = new JTextField(10);
tfheight.setText(height);
tfweight = new JTextField(10);
tfweight.setText(weight);
heightp.add(tfheight);
weightp.add(tfweight);
bodyp.add(heightp);
bodyp.add(weightp);
JPanel artp = new JPanel(new BorderLayout());
Border skillb=BorderFactory.createTitledBorder(border, "๋ฌด์ ");
artp.setBorder(skillb);
JLabel top = new JLabel(name+"๋์ด ๋ฐฐ์ฐ๊ณ ์ถ์ ๋ฌด์ ํ๋๋ฅผ ๊ณ ๋ฅด์์ค.");
top.setHorizontalAlignment(JLabel.CENTER);
JPanel artkind = new JPanel(new GridLayout(3,3));
ButtonGroup artgroup = new ButtonGroup();
boxing = new JRadioButton("๋ณต์ฑ",true);
muatie = new JRadioButton("๋ฌด์ํ์ด",true);
jujitsu = new JRadioButton("์ฃผ์ง์",true);
taegyundo = new JRadioButton("ํ๊ถ๋",true);
gumdo = new JRadioButton("๊ฒ๋",true);
wrestling = new JRadioButton("๋ ์ฌ๋ง",true);
kapoara = new JRadioButton("์นดํฌ์๋ผ",true);
youdo = new JRadioButton("์ ๋",true);
yuswu = new JRadioButton("์ฐ์",true);
artgroup.add(boxing);
artgroup.add(muatie);
artgroup.add(jujitsu);
artgroup.add(taegyundo);
artgroup.add(gumdo);
artgroup.add(wrestling);
artgroup.add(kapoara);
artgroup.add(youdo);
artgroup.add(yuswu);
artkind.add(boxing);
artkind.add(muatie);
artkind.add(jujitsu);
artkind.add(taegyundo);
artkind.add(gumdo);
artkind.add(wrestling);
artkind.add(kapoara);
artkind.add(youdo);
artkind.add(yuswu);
if(skill == null){
}else{
if(skill.equals("๋ณต์ฑ")){
boxing.setSelected(true);
}else if(skill.equals("๋ฌด์ํ์ด")){
muatie.setSelected(true);
}else if(skill.equals("์ฃผ์ง์")){
jujitsu.setSelected(true);
}else if(skill.equals("ํ๊ถ๋")){
taegyundo.setSelected(true);
}else if(skill.equals("๊ฒ๋")){
gumdo.setSelected(true);
}else if(skill.equals("๋ ์ฌ๋ง")){
wrestling.setSelected(true);
}else if(skill.equals("์นดํฌ์๋ผ")){
kapoara.setSelected(true);
}else if(skill.equals("์ ๋")){
youdo.setSelected(true);
}else if(skill.equals("์ฐ์")){
yuswu.setSelected(true);
}
}
artp.add("North",top);
artp.add("Center", artkind);
//ํ์ธ ์ทจ์,
JPanel but = new JPanel();
JPanel okp = new JPanel();
JPanel cancelp = new JPanel();
ok = new JButton("ํ์ธ");
cancel = new JButton("์ทจ์");
ok.addActionListener(this);
cancel.addActionListener(this);
okp.add(ok);
cancelp.add(cancel);
but.add(okp);
but.add(cancel);
total.add("North",bodyp);
total.add("Center",artp);
total.add("South",but);
add(total);
setSize(300,500);
setVisible(true);
}
public boolean range(String text){ //String์ด ์ซ์์ธ์ง ํ๋ณํ๋ ๋ฉ์๋
try{
int num = Integer.parseInt(text);
}catch(NumberFormatException e){
return true;
}
return false;
}
public void warning(String text){ //์ค๋ฅ ๋ฉ์์ง ์ถ๋ ฅ
JOptionPane.showMessageDialog(null, text, "Message",
JOptionPane.ERROR_MESSAGE);
}
public String selectedArts(){
if(boxing.isSelected()){
return "๋ณต์ฑ";
}else if(muatie.isSelected()){
return "๋ฌด์ํ์ด";
}else if(jujitsu.isSelected()){
return "์ฃผ์ง์";
}else if(taegyundo.isSelected()){
return "ํ๊ถ๋";
}else if(gumdo.isSelected()){
return "๊ฒ๋";
}else if(wrestling.isSelected()){
return "๋ ์ฌ๋ง";
}else if(kapoara.isSelected()){
return "์นดํฌ์๋ผ";
}else if(youdo.isSelected()){
return "์ ๋";
}else if(yuswu.isSelected()){
return "์ฐ์";
}
return null;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ok){
String height2 = tfheight.getText();
if(range(height2)){
warning("ํค๋ฅผ ๋ค์ ์
๋ ฅํ์์ค");
tfheight.setText("");
tfheight.requestFocus();
return;
}
String weight2 = tfweight.getText();
if(range(weight2)){
warning("๋ชธ๋ฌด๊ฒ๋ฅผ ๋ค์ ์
๋ ฅํ์์ค");
tfweight.setText("");
tfweight.requestFocus();
return;
}
String arts = null;
arts = selectedArts();
boolean is = true;
int search = 0;
for(int i =0; i<info.heallist.size(); i++){
if(name.equals(info.heallist.get(i).get_name()) && id.equals(info.heallist.get(i).get_id())){
is = false;
search=i;
info.heallist.remove(i);
info.heallist.add(i, new Health(id,name,height2,weight2,arts));
JOptionPane.showMessageDialog(null, "์์ ๋์์ต๋๋ค.", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
}
if(is){
info.heallist.add(new Health(id,name,height2,weight2,arts));
JOptionPane.showMessageDialog(null, "๋ฑ๋ก๋์์ต๋๋ค.", "Message",
JOptionPane.INFORMATION_MESSAGE);
}
dispose();
}else if(e.getSource() == cancel){
dispose();
}
}
}
<file_sep># Health-Manager
Java Swing์ ์ด์ฉํ์ฌ GUI๋ฅผ ์ ๊ณตํ์๊ณ , ์ด๋ฒคํธ ์ฒ๋ฆฌ๋ฅผ ํ๋ฉฐ ๊ฐ๋ฐํ ์ฒซ ํ๋ก๊ทธ๋จ์
๋๋ค. ๋๋ถ๋ถ์ ์ฝ๋๊ฐ Java Swing์ ์ฌ์ฉํ UI ์ฝ๋์
๋๋ค. Java Swing์ ์ฒ์ ์ฌ์ฉํ์๋ ๋ถ๋ค์ด ๋ณด๋ฉด ์ข์ ๊ฒ ๊ฐ์ต๋๋ค.
#### ๋ง๋ ๋ ์ง : 2015.06
## 1. ์ฌ์ฉ๋ฒ
```
# Main ํด๋์ค๋ฅผ ์คํํ์๋ฉด ๋ฉ๋๋ค.
```
<file_sep>import java.io.Serializable;
public class Info implements Serializable{
private String name;
private String gender;
private String year;
private String phonenum;
private String job;
private String address;
private String blood;
private String id;
public Info(String name,String gender, String year, String phonenum, String job,String address,String blood,String id){
this.name = name;
this.gender = gender;
this.year = year;
this.phonenum = phonenum;
this.job = job;
this.address = address;
this.blood = blood;
this.id = id;
}
public String get_company(){
return "";
}
public String get_level(){
return "";
}
public String get_univ(){
return "";
}
public String get_grade(){
return "";
}
public String get_thing(){
return "";
}
public String toString(){
return "์ด๋ฆ : "+name+'\n'+"์๋
์์ผ : "+year+"\n"+"ํธ๋ํฐ๋ฒํธ : "+phonenum+"\n"+"์ฃผ์ : "+address+"\n"+"์ฑ๋ณ : "+gender+"\n"+"ํ์กํ : "+blood+"\n"+"์ง์
: "+job;
}
public String get_id(){
return this.id;
}
public String get_blood(){
return this.blood;
}
public String get_address(){
return this.address;
}
public String get_name(){
return this.name;
}
public String get_phonenum(){
return this.phonenum;
}
public String get_year(){
return this.year;
}
public String get_gender(){
return this.gender;
}
public String get_job(){
return this.job;
}
}
class CompanyInfo extends Info{
String company;
String level;
public CompanyInfo(String name,String gender, String year, String phonenum, String job,String address,String blood,String id,String company, String level){
super(name,gender,year,phonenum, job, address, blood,id);
this.company = company;
this.level = level;
}
public String toString(){
return super.toString()+"\n"+"ํ์ฌ : "+company+"\n"+"์ง๊ธ : "+level;
}
public String get_company(){
return super.get_company()+this.company;
}
public String get_level(){
return super.get_level()+this.level;
}
}
class UnivInfo extends Info{
String univ;
String grade;
public UnivInfo(String name,String gender, String year, String phonenum, String job,String address,String blood,String id,String univ, String grade){
super(name,gender,year,phonenum, job, address, blood,id);
this.univ = univ;
this.grade = grade;
}
public String toString(){
return super.toString()+"\n"+"ํ๊ต : "+univ+"\n"+"ํ๋
: "+grade;
}
public String get_univ(){
return super.get_univ()+this.univ;
}
public String get_grade(){
return super.get_grade()+this.grade;
}
}
class PersonInfo extends Info{
String thing;
public PersonInfo(String name,String gender, String year, String phonenum, String job,String address,String blood,String id,String thing){
super(name,gender,year,phonenum, job, address, blood,id);
this.thing = thing;
}
public String toString(){
return super.toString()+"\n"+"ํ๋์ผ : "+thing;
}
public String get_thing(){
return super.get_thing()+this.thing;
}
}
<file_sep>import java.io.Serializable;
public class Health implements Serializable{
String id; //ํ์์ ๋ฉ๋์ง ์์ด๋
String name; //ํ์์ ์ด๋ฆ
String height; //ํ์์ ํค
String weight; //ํ์์ ๋ชธ๋ฌด๊ฒ
String skill; //ํ์์ ๋ฌด์
public Health(String id, String name,String height,String weight,String skill){
this.id = id;
this.name = name;
this.height = height;
this.weight = weight;
this.skill = skill;
}
public String toString(){
return "ํค : "+height+"cm"+"\n"+"๋ชธ๋ฌด๊ฒ : "+weight+"kg"+"\n"+"๋ฐฐ์ฐ๋ ๋ฌด์ : "+skill;
}
public String get_id() {
return id;
}
public String get_name() {
return name;
}
public String get_height() {
return height;
}
public String get_weight() {
return weight;
}
public String get_skill() {
return skill;
}
}
|
321d4c61f12edc013aad0aa6526c7f8a368330d3
|
[
"Markdown",
"Java"
] | 5 |
Java
|
JinHyukParkk/Health-Manager
|
defeb6e7bb94d2da47226dea7a77e9651d1c6a1b
|
7570fcd75ca381701ce47460a3a1b50964631df7
|
refs/heads/main
|
<file_sep>package com.ir;
import com.brettonw.bedrock.bag.BagArrayFrom;
import com.brettonw.bedrock.bag.BagObject;
import com.brettonw.bedrock.bag.formats.MimeType;
import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.orekit.propagation.analytical.tle.TLE;
public class SpaceTrack {
private static final String BASE_URL = "https://www.space-track.org";
private static final String LOGIN_PATH = "/ajaxauth/login";
private static final String QUERY_PATH = "/basicspacedata/query/class/";
private final String loginIdentity;
private final String loginPassword;
public SpaceTrack(String username, String password) {
loginIdentity = username;
loginPassword = <PASSWORD>;
}
// doPost: POSTS a raw data request to an HTTP server and returns the raw
// data result
// NOTE: these are raw bytes, not strings! If you want to use strings,
// they should be encoded/decoded (UTF-8 is always a good choice).
private byte[] doPost (String url, byte[] postData) {
try {
// build the connection to POST the login and query
var connection = (HttpsURLConnection) (new URL(url).openConnection());
connection.setDoOutput(true);
connection.setRequestMethod("POST");
try (var outputStream = connection.getOutputStream()) {
outputStream.write(postData);
}
// if the POST succeeded, read the response
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (var inputStream = connection.getInputStream()) {
return inputStream.readAllBytes();
}
}
} catch (Exception exception) {
System.out.println("Exception: " + exception);
}
return null;
}
private BagObject buildQueryObject (String query) {
return BagObject
.open("identity", loginIdentity)
.put ("password", <PASSWORD>)
.put ("query", BASE_URL + QUERY_PATH + query);
}
// doQuery takes the query portion of the URL you want to execute, and returns one of three results:
// a) NULL - something went wrong with the post or the response
// b) {"error":"You must be logged in to complete this action"} - your credentials are invalid
// c) [{"CCSDS_OMM_VERS":"2.0","COMMENT":"GENERATED VIA SPAC... - an array of the tracking elements requested
public String doQuery (String query) {
var postData = buildQueryObject (query).toString(MimeType.URL).getBytes(StandardCharsets.UTF_8);
return new String (doPost (BASE_URL + LOGIN_PATH, postData), StandardCharsets.UTF_8);
}
// return a bag object representing the requested object
public BagObject getGP (int noradCatalogId) {
var bagArray = BagArrayFrom.url(BASE_URL + LOGIN_PATH,
buildQueryObject("gp/NORAD_CAT_ID/" + noradCatalogId),
MimeType.URL);
return ((bagArray != null) && (bagArray.getCount() > 0)) ? bagArray.getBagObject(0) : null;
}
public TLE getTLE (int noradCatalogId) {
var tle = getGP(noradCatalogId);
return (tle != null) ? new TLE (tle.getString("TLE_LINE1"), tle.getString("TLE_LINE2")) : null;
}
}
<file_sep># Space Track
https://www.space-track.org/
https://celestrak.com/
https://www.orekit.org/
download orekit-data-master from https://www.orekit.org/site-orekit-10.0/configuration.html
|
4c80087c94293ffcccf6fff00c5c9e5d56106294
|
[
"Markdown",
"Java"
] | 2 |
Java
|
brettonw/space-track
|
277a361a3b14359a19ae6698767e0ca16d191361
|
bbc9e3ae1f11e6fbf65c867bd0535441196a19ab
|
refs/heads/master
|
<repo_name>lberserq/shor_cpp<file_sep>/qregister.h
#ifndef QREGISTER_H
#define QREGISTER_H
#include <vector>
#include "config.h"
/*! \class Qvector
*\brief Register of Qubits
*States with amplitudes stored in states
*Amplitudes of this states stored
*
*/
class Qregister
{
std::vector<mcomplex> ampl;
std::vector<state> states;
int m_width;
public:
/*!
*\fn Creates the new Qregister with size width and one initial state
*/
Qregister(int width, state init_state);
/*!
*\fn Returns width of Qregister
*/
int getWidth() const {
return m_width;
}
/*!
*\fn Returns states of register
*/
std::vector<state> &getStates() {
return states;
}
/*!
*\fn Returns amplitudes of Register
*/
std::vector<mcomplex> &getAmpls() {
return ampl;
}
const int getSize() const {
return states.size();
}
/*!
*\fn Setter for amplitudes
*/
void setAmpls(const std::vector<mcomplex> &) {
ampl = amp;
}
/*!
*\fn Setter for states
*/
void setStates(const std::vector<state> &st) {
states = st;
}
/*!
*\fn Alloc additional size(increase width of Qregister)
*/
void alloc_smem(int size);
/*!
*\fn Setter for amplitudes
*/
/*!
*\fn Remove states with \param
*
*/
void collapse_state(int id, long double prob_amp);
friend void reg_swap(int width, Qregister &in);
void print();
};
void DeleteLocalVars(Qregister ®, int size);
void SwapXY(Qregister ®, int width_x);
#endif // QREGISTER_H
<file_sep>/qregister.cpp
#include "qregister.h"
#include "common.h"
#include <cstdio>
using namespace std;
Qregister::Qregister(int width, state init_state)
{
ampl.resize(1);
states.resize(1);
m_width = width;
ampl[0] = 1.0f;
states[0] = init_state;
}
void reg_swap(int width, Qregister &in)
{
for (int i = 0; i < in.getSize(); i++) {
state cur_state = (in.getStates())[i];
state left = cur_state % (1 << width);
state right = 0;
for (int j = 0; j < width; j++) {
right += cur_state & static_cast<state>(1 << (width + j));
}
state new_state = cur_state ^ (left | right);
new_state |= (left << width);
new_state |= (right >> width);
(in.getStates())[i] = new_state;
}
}
void Qregister::alloc_smem(int size)
{
m_width += size;
for (unsigned i = 0; i < states.size();i++) {
states[i] = (state)(states[i] << size);
}
}
void Qregister::print()
{
unsigned m_len = states.size();
for (unsigned i = 0; i < m_len; i++) {
mcomplex amplit = ampl[i];
fprintf(stderr, "%llf + i%llf |%llu|", amplit.real(), amplit.imag(), states[i]);
for (int st = m_width - 1; st >= 0; st--) {
int id = ((static_cast<state>(1 << st) & (states[i])) != 0);
if (st % 8 == 7) {
fprintf(stderr, " ");
}
fprintf(stderr, "%i",id);
}
fprintf(stderr, "\n");
}
}
void Qregister::collapse_state(int id, long double prob_amp)
{
long double sum = 0.0f;
int size = 0;
bool flag = std::abs(prob_amp) < g_eps;
unsigned m_len = states.size();
for (unsigned i = 0; i < m_len; i++) {
state st = states[i];
int state_id1 = ((st & (state)(1 << id)) != 0);
if (state_id1 == !flag) {
mcomplex p = ampl[i];
size++;
sum += std::pow(std::abs(p), 2);
}
}
std::vector<state> new_st;
std::vector<mcomplex> new_ampls;
new_st.resize(size);
new_ampls.resize(size);
m_width--;
int cnt = 0;
m_len = states.size();
for(unsigned i = 0; i < m_len; i++)
{
state st = states[i];
int state_id1 = ((st & (state)(1 << id)) != 0);
if(state_id1 == !flag)
{
state right_part = 0;
state left_part = 0;
mcomplex amplitude = ampl[i];
for (int j = 0; j < id; j++) {
right_part |= (state)(1 << j);
}
right_part &= st;
for (int j = sizeof(state) * 8 - 1; j > id; j--) {
left_part |= (state)(1 << j);
}
left_part &= st;
new_st[cnt] = (left_part >> 1) | right_part;
new_ampls[cnt++] = (1.0 / std::sqrt(sum))* amplitude;
}
}
ampl = new_ampls;
states = new_st;
}
static void delete_var(Qregister ®, int id)
{
long double probs = 0.0f;
register int m_len = reg.getSize();
for (int i = 0; i < m_len; i++) {
state st = reg.getStates()[i];
int state_id = ((st & static_cast<state>(1 << id)) != 0);
if (!state_id) {
mcomplex amp = reg.getAmpls()[i];
probs += std::pow(std::abs(amp), 2);
}
}
long double rnd_num = static_cast<long double>(rand()) / RAND_MAX;
long double targ_val = 0.0f;
if (rnd_num > probs) {
targ_val = 1.0f;
}
reg.collapse_state(id, targ_val);
}
void DeleteLocalVars(Qregister ®, int size)
{
for (int i = 0; i < size; i++) {
delete_var(reg, 0);
}
}
void SwapXY(Qregister ®, int width_x)
{
for (int i = 0; i < width_x / 2; i++) {
ApplySWAP(reg, i, width_x - i - 1);
}
}
<file_sep>/main.cpp
#include "config.h"
#include "common.h"
#include "qregister.h"
#include "qft.h"
#include "measure.h"
#include "multiplier.h"
#include "adder.h"
#include <cstdio>
#include <cstdlib>
state igcd(state a, state b) {
while (a && b) {
if (a > b) {
a %= b;
} else {
b %= a;
}
}
return (a) ? a : b;
}
state ipow(state base, int exp) {
state res = 1;
for (int i = 0; i < exp; i++, res *= base);
return res;
}
int get_dim(state n) {
int i = 0;
while ((1<< i) < n) {
i++;
}
return i;
}
std::pair<state, state> con_frac_approx(long double val, long double maxdenum) {
state numerator = 1, denumerator = 0;
state numlast = 0, denumlast = 1;
const float interpolation_step = g_eps * 1e4 * 5;
long double ai = val;
long double step = 0.0f;
do {
step = ai + 0.000005;
step = std::floor(step);
ai -= step - 0.0010005;
ai = 1.0f / ai;
if (step * denumerator + denumlast > maxdenum) {
break;
}
state savenum = numerator;
state savedenum = denumerator;
numerator = step * numerator + numlast;
denumerator = step * denumerator + denumlast;
numlast = savenum;
denumlast = savedenum;
}while(std::fabs(static_cast<long double>(numerator) / denumerator - val) > 1.0 / (2.0 * maxdenum));
if (numerator < 0 && denumerator < 0) {
numerator = -numerator;
denumerator = -denumerator;
}
std::pair<state, state> res = std::make_pair(numerator, denumerator);
return res;
}
enum
{
MAX_TICK_COUNT = 10000
};
/*!
* \brief shor
* \param n number to represent
*
*Algorithm Alloc mem and padding
*Apply Uf
*Apply QFT
*Measure First reg
*approximate mes_val / (1 << width) with elementary partition
*use denominator as a period
*
*/
void shor(int n) {
int all_width = get_dim(n * n);
int width_local = get_dim(n);
printf("Factorization of %d\n", n);
fprintf(stderr, "w %d sw %d\n", all_width, width_local);
int local_variables_size = 3 * width_local + 2;
printf("We need %d qbits\n", all_width + 3 * width_local);
if (all_width + 3 * width_local > 63) {
printf("Too big number\n");
return;
}
state m_state;
int tick_count = 0;
while (tick_count < MAX_TICK_COUNT) {
Qregister *tmp = new Qregister(all_width, 0);
for(int i = 0; i < all_width; i++) {
ApplyHadamard(*tmp, i);
}
// Alloc mem for Uf
tmp->alloc_smem(local_variables_size);
int a = rand() % n;
while (igcd(a, n) > 1 || a < 2) {
a = rand() % n;
}
if (n == 20) {
a = 17;
}
fprintf(stdout, "New Round\n RANDOM NUMBER == %d\n", a);
//Apply Uf
expamodn(*tmp, n, a, all_width, width_local);
//stage1 delete local vars which we used, in Uf
DeleteLocalVars(*tmp, local_variables_size);
//stage2 Apply QFT on whole register(because it`s simplier, than use *** paddings)
QFT::ApplyQft(*tmp, all_width);
//Swap XY because measurer works only with X
SwapXY(*tmp, all_width);
//Measure Y(now in X) with simple Measurer(basis is natural(like |0><0|)
m_state = Measurer::Measure(*tmp);
if (m_state == static_cast<state>(-1)) {
std::fprintf(stdout, "Invalid Measurement\n");
delete tmp;
continue;
}
if (m_state == 0) {
std::fprintf(stderr, "Zero measurement\n");
delete tmp;
continue;
}
long double val = static_cast<double>(m_state) / static_cast<state>(1 << all_width);
fprintf(stderr, "MESVAL == %llu / %llu \n", m_state, static_cast<state>(1 << all_width));
std::pair<state, state> frac = con_frac_approx(val, static_cast<long double>(1 << all_width));
fprintf(stderr, "SIMPLIFIER %llu / %llu\n", frac.first, frac.second);
if (frac.second % 2 == 1) {
fprintf(stdout, "Unfortunately, but denumerator is odd next round\n");
delete tmp;
continue;
}
int del0 = ipow(a, frac.second / 2) + 1;
int del1 = del0 - 2; // also == ipow(a, frac.second / 2) - 1;
del0 = del0 % n;
del1 = del1 % n;
int div1 = igcd(n, del0);
int div2 = igcd(n, del1);
if (div1 > 1 && div1 != n) {
fprintf(stdout, "Lucky round divisors `ve been found %d * %d == %d\n", n / div1, div1, n);
return;
} else if (div2 > 1 && div2 != n) {
fprintf(stdout, "Lucky round divisors `ve been found %d * %d == %d\n", n / div2, div2, n);
return;
} else {
fprintf(stdout, "Unlucky round\n");
}
}
fprintf(stdout, "Cant find divisors with %d iterations, maybe %d is prime ?", MAX_TICK_COUNT, n);
}
int main(int argc, char *argv[])
{
//gates_test();
//return 0;
//shor(10);
//shor(23 * 89);
if (argc < 2) {
fprintf(stderr, "Usage %s Number\n", argv[0]);
return 1;
}
int n;
if (!sscanf(argv[1], "%d", &n)) {
fprintf(stderr, "%s is not a number\n", argv[1]);
return 1;
}
shor(n);
}
<file_sep>/qmatrix.cpp
#include "qmatrix.h"
QMatrix::QMatrix(int w, int h)
{
rows_cnt = h;
columns_cnt = w;
data_ptr = new mcomplex *[h];
for (int i = 0; i < h; i++) {
data_ptr[i] = new mcomplex[w];
}
}
QMatrix::~QMatrix()
{
for (int i = 0; i < rows_cnt; i++) {
delete [] data_ptr[i];
}
delete [] data_ptr;
}
<file_sep>/common.h
#ifndef COMMON_H
#define COMMON_H
#include "qmatrix.h"
#include "qregister.h"
/*!
*\brief this file contains basic gates. Complicated gates in the specified files\n
*/
/*!
*\fn applies Unitary complex matrix m(2x2) to register reg on qubit specified in id0\n
*/
void ApplyQbitMatrix(const QMatrix &m, Qregister ®, int id0);
/*!
*\fn applies Unitary complex matrix m(4x4) to register reg on 2 qubits specified in id0 id1\n
*/
void ApplyDiQbitMatrix(const QMatrix &m, Qregister ®, int id0, int id1);
/*!
*\fn applies Unitary complex matrix m(8x9) to register reg on 3 qubits specified in id0 id1 id2\n
*/
void ApplyTriQbitMatrix(const QMatrix &m, Qregister ®, int id0, int id1, int id2);
/*!
*\fn applies Toffolli gate |x,y,z>->|x,y,z xor xy>\n
*|1 0 0 0 0 0 0 0|\n
*|0 1 0 0 0 0 0 0|\n
*|0 0 1 0 0 0 0 0|\n
*|0 0 0 1 0 0 0 0|\n
*|0 0 0 0 1 0 0 0|\n
*|0 0 0 0 0 1 0 0|\n
*|0 0 0 0 0 0 0 1|\n
*|0 0 0 0 0 0 1 0|\n
*/
void ApplyToffoli(Qregister ®, int id0, int id1, int id2);
/*!
*\fn faster version of ApplyToffoli\n
*/
void ApplyFToffoli(Qregister ®, int id0, int id1, int id2);
/*!
*\fn applies CNOT gate to reg |x,y> ->|x, x xor y> with toffolli and not
*creates the computational basis\n
*|1 0 0 0|\n
*|0 1 0 0|\n
*|0 0 0 1|\n
*|0 0 1 0|\n
*/
void ApplyCnot(Qregister ®, int id0, int id1);
/*!
*\fn faster version of ApplyCnot
*/
void ApplyFcnot(Qregister ®, int id0, int id1);
/*!
*\fn applies Controlled Rotation gate to reg\n
*|1 0 0 0|\n
*|0 1 0 0|\n
*|0 0 1 0|\n
*|0 0 0 exp(i * alpha)|\n
*/
void ApplyCRot(Qregister ®, int id1, int id2, double alpha);
/*!
*\fn applies Hadamard gate to reg\n
*|1 -1|\n
*|1 1| * sqrt(1/2.0)\n
*/
void ApplyHadamard(Qregister ®, int id1);
/*!
*\fn applies Not gate to reg\n
*|0 1|\n
*|1 0|\n
*/
void ApplyNot(Qregister ®, int id);
/*!
*\fn applies Swap gate to reg\n
*|1 0 0 0|\n
*|0 0 1 0|\n
*|0 1 0 0|\n
*|0 0 0 1|\n
*/
void ApplySWAP(Qregister ®, int id0, int id1);
/*!
*\fn applies Controlled Swap gate to reg\n
*|1 0 0 0|\n
*|0 0 1 0|\n
*|0 1 0 0|\n
*|0 0 0 1|\n
*/
void ApplyCSWAP(Qregister ®, int id0, int id1, int id2);
#endif // COMMON_H
<file_sep>/qmatrix.h
#ifndef QMATRIX_H
#define QMATRIX_H
#include "config.h"
class QMatrix
{
mcomplex ** data_ptr;
int rows_cnt;
int columns_cnt;
public:
QMatrix(int w, int h);
mcomplex & operator() (int i, int j) {
return (data_ptr[i][j]);
}
const
mcomplex & operator() (int i, int j) const {
return (data_ptr[i][j]);
}
/* mcomplex operator() (int i, int j) {
return (data_ptr[i][j]);
}*/
~QMatrix();
};
#endif // QMATRIX_H
<file_sep>/qft.cpp
#include "qft.h"
#include "common.h"
QFT::QFT()
{
}
//QFT -- scheme
void QFT::ApplyQft(Qregister ®, int reg_width)
{
for (int i = reg_width - 1; i >= 0; i--) {
for (int j = reg_width - 1; j > i; j--) {
double alpha = M_PI / ((state)(1 << (j - i)));
ApplyCRot(reg, j, i, alpha);
}
ApplyHadamard(reg, i);
}
}
<file_sep>/multiplier.h
#ifndef MULTIPLIER_H
#define MULTIPLIER_H
#include "common.h"
/*!
*\brief Class Multiplier Multiply the val in Register in with the width width on a % n used
*ctl_id as a local variable\n
*
*how it works \n
*x * y = (x * 2 ^ p0 + x * 2 ^p1 + ... x * 2^pt\n
*where is 2^p0 + 2^p1 + ... + 2^pt == y\n
*basic_multiplication creates in the local_variables_size x * 2 ^ i\n
*then mull calls adder to sum this values
*
*/
class Multiplier
{
Qregister &m_reg;
int m_N;
int m_a;
int m_width;
int m_ctlid;
void mul();
void mulinverse();
void basic_multiplication(int x);
public:
Multiplier(Qregister &in, int N, int width, int a, int ctl_id);
Qregister &perform();
};
/*!
*\fn Main part of shor algorithm realize the Uf gate\n
* calculates \param x ^ (reg_val) % \param N\n
* width_in is a actual width of reg which store reg_val\n
* local_width -- width of local_variables\n
* Realized by \param val_width multiplications
*/
Qregister &expamodn(Qregister &in, int N, int x, int val_width, int local_width);
#endif // MULTIPLIER_H
<file_sep>/adder.cpp
#include "adder.h"
#include "qmatrix.h"
#include "common.h"
#include "config.h"
/*!
* \brief Adder::Adder
* \param a
* \param n
* \param width
* \param in
*adds a to register by modulo n
*/
Adder::Adder(int a, int n, int width, Qregister &in):
m_N(n),
m_a(a),
m_reg(in),
m_width(width)
{
}
Qregister & Adder::perform()
{
addition_n();
addition_inv(); // disentangle with ancill
return m_reg;
}
void Adder::addition_n()
{
find_xlt(m_N - m_a);
gate_add((1 << m_width) + m_a - m_N, m_a);
}
void Adder::addition_inv()
{
ApplyCnot(m_reg, 2 * m_width + 1, 2 * m_width);
gate_add_inv((1 << m_width) - m_a, m_N - m_a);
reg_swap(m_width, m_reg);
find_xlt(m_a);
}
void Adder::gate_add(int x, int x_inv)
{
int id = 0;//what actions will happen (0 + 0 == 0, 1 + 1 id == 3, 1 + 0 == id == 2, 0 + 1 == id == 1)
for (int i = 0; i < m_width - 1; i++) {
if (x & (1 << i)) {
id = 2;
} else {
id = 0;
}
if (x_inv & (1 << i)) {
id++;
}
full_adder(id, m_width + i, i, i + 1, 2 * m_width);
}
id = 0;
if (x & (1 << (m_width - 1))) {
id = 2;
}
if (x_inv & (1 << (m_width - 1))) {
id++;
}//perform last addition
half_adder(id, 2 * m_width - 1, m_width - 1, 2 * m_width);
}
void Adder::gate_add_inv(int x, int x_inv)
{
int id = 0;
id = 0;
if (x & (1 << (m_width - 1))) {
id = 2;
}
if (x_inv & (1 << (m_width - 1))) {
id++;
}
inverse_half_adder(id, m_width - 1, 2 * m_width - 1, 2 * m_width);
for (int i = m_width - 2; i >= 0; i--) {
if (x & (1 << i)) {
//id = 1 << i;
id = 2;
} else {
id = 0;
}
if (x_inv & (1 << i)) {
id++;
}
inverse_full_adder(id, i, m_width + i, m_width + i + 1, 2 * m_width);
}
}
//add x to dest carry in carry_pin xlt is a
//len xlt is a local variables-bits(ancilled)
void Adder::half_adder(int x, int dest_pin, int carry_pin, int xlt) {
int ctl_id = 2 * m_width + 1;
if (x == 0) {//add of 0 and now its 0
ApplyCnot(m_reg, dest_pin, carry_pin);
}
if (x == 1) {//add of 0 and now its 1
ApplyCnot(m_reg, dest_pin, carry_pin);
ApplyToffoli(m_reg, ctl_id, xlt, carry_pin);
}
if (x == 2) {//add of 1 and now its 0 we need to save fact about it
ApplyNot(m_reg, xlt);
ApplyToffoli(m_reg, ctl_id, xlt, carry_pin);
ApplyCnot(m_reg, dest_pin, carry_pin);
ApplyNot(m_reg, xlt);
}
if (x == 3) {
ApplyCnot(m_reg, ctl_id, carry_pin);
ApplyCnot(m_reg, dest_pin, carry_pin);
}
}
void Adder::inverse_half_adder(int x, int dest_pin, int carry_pin, int xlt)
{
int ctl_id = 2 * m_width + 1;
if (x == 0) {//add of 0 and now its 0
ApplyCnot(m_reg, dest_pin, carry_pin);
}
if (x == 1) {//add of 0 and now its 1
ApplyCnot(m_reg, dest_pin, carry_pin);
ApplyToffoli(m_reg, ctl_id, xlt, carry_pin);
}
if (x == 2) {//add of 1 and now its 0 we need to save fact about it
ApplyNot(m_reg, xlt);
ApplyCnot(m_reg, dest_pin, carry_pin);
ApplyToffoli(m_reg, ctl_id, xlt, carry_pin);
ApplyNot(m_reg, xlt);
}
if (x == 3) {
ApplyCnot(m_reg, ctl_id, carry_pin);
ApplyCnot(m_reg, dest_pin, carry_pin);
}
}
void Adder::full_adder(int x, int dest_pin, int carry_in, int carry_out, int xlt)
{
int ctl_id = 2 * m_width + 1;
if (x == 0) {
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyCnot(m_reg, dest_pin, carry_in);
}
if (x == 1) {
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyCnot(m_reg, dest_pin, carry_in);
}
if (x == 2) {
ApplyNot(m_reg, xlt);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyCnot(m_reg, dest_pin, carry_in);
ApplyNot(m_reg, xlt);
}
if (x == 3) {
ApplyToffoli(m_reg, ctl_id, carry_in, carry_out);
ApplyCnot(m_reg, ctl_id, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyCnot(m_reg, dest_pin, carry_in);
}
}
void Adder::inverse_full_adder(int x, int dest_pin, int carry_in, int carry_out, int xlt)
{
int ctl_id = 2 * m_width + 1;
if (x == 0) {
ApplyCnot(m_reg, dest_pin, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
}
if (x == 1) {
ApplyCnot(m_reg, dest_pin, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
}
if (x == 2) {
ApplyNot(m_reg, xlt);
ApplyCnot(m_reg, dest_pin, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyToffoli(m_reg, ctl_id, xlt, dest_pin);
ApplyNot(m_reg, xlt);
}
if (x == 3) {
ApplyCnot(m_reg, dest_pin, carry_in);
ApplyToffoli(m_reg, dest_pin, carry_in, carry_out);
ApplyCnot(m_reg, ctl_id, carry_in);
ApplyToffoli(m_reg, ctl_id, carry_in, carry_out);
}
}
//apply
void Adder::find_xlt(int x)
{
int ctl_id = 2 * m_width + 1;
if (x & (1 << (m_width - 1))) {
ApplyCnot(m_reg, 2 * m_width - 1, m_width - 1);
ApplyNot(m_reg, 2 * m_width - 1);
ApplyCnot(m_reg, 2 * m_width - 1, 0);
} else {
ApplyNot(m_reg, 2 * m_width - 1);
ApplyCnot(m_reg, 2 * m_width - 1, m_width - 1);
}
for (int i = m_width - 2; i > 0; i--) {
if (x & (1 << i)) {
ApplyToffoli(m_reg, i + 1, m_width + i, i);
ApplyNot(m_reg, m_width + i);
ApplyToffoli(m_reg, i + 1, m_width + i, 0);
} else {
ApplyNot(m_reg, m_width + i);
ApplyToffoli(m_reg, i + 1, m_width + i, i);
}
}
if (x & 1) {
ApplyNot(m_reg, m_width);
ApplyToffoli(m_reg, m_width, 1, 0);
}
ApplyToffoli(m_reg, ctl_id, 0, 2 * m_width);
if (x & 1) {
ApplyToffoli(m_reg, m_width, 1, 0);
ApplyNot(m_reg, m_width);
}
for (int i = 1; i <= m_width - 2; i++) {
if (x & (1 << i)) {
ApplyToffoli(m_reg, i + 1, m_width + i, 0);
ApplyNot(m_reg, m_width + i);
ApplyToffoli(m_reg, i + 1, m_width + i, i);
} else {
ApplyToffoli(m_reg, i + 1, m_width + i, i);
ApplyNot(m_reg, m_width + i);
}
}
if (x & (1 << (m_width - 1))) {
ApplyCnot(m_reg, 2 * m_width - 1, 0);
ApplyNot(m_reg, 2 * m_width - 1);
ApplyCnot(m_reg, 2 * m_width - 1, m_width - 1);
} else {
ApplyCnot(m_reg, 2 * m_width - 1, m_width - 1);
ApplyNot(m_reg, 2 * m_width - 1);
}
}
<file_sep>/qft.h
#ifndef QFT_H
#define QFT_H
#include "qregister.h"
class QFT
{
public:
QFT();
/*! \brief
*|x0>-^------^----^---H-|y3>\n
*|x1>-|-^----|-^--|-H---|y2>\n
*|x2>-|-|-^--|-|-H------|y1>\n
*|x3>-|-|-|-H-----------|y0>\n
*H -- Hadamard\n
*^\n
*| -- CROT(M_PI / 1 << |j - i|)\n
*/
static void ApplyQft(Qregister ®, int reg_width);
};
#endif // QFT_H
<file_sep>/adder.h
#ifndef ADDER_H
#define ADDER_H
#include "qregister.h"
//adder inspired by ideas in libquantum(Copyright <NAME>, <NAME>) adder
//License of libquantum is GPL V3
/*!
* \brief The Adder class required a lot of mem.
*perform addition\n
*main idea use cnot to add the bit\n
*if (result is 1 or 2) (entangle and set the carry bits and continue)\n
*else do nothing\n
*adder contains of width - 1 full_adders and one half_adder\n
*full adder entangles and use carry_qbits(to out)\n
*(new carry sets in carry out\n
*half_adder only us carry_in\n
*find_xlt set up the inverse x by modulo n and check the vars\n
*/
class Adder
{
int m_N, m_a;
Qregister &m_reg;
int m_width;
void full_adder(int x, int dest_pin, int carry_in, int carry_out, int xlt);
void inverse_full_adder(int x, int dest_pin, int carry_in, int carry_out, int xlt);
//half adders dont know about the carry
void half_adder(int x, int dest_pin, int carry_pin, int xlt);
void inverse_half_adder(int x, int dest_pin, int carry_pin, int xlt);
//in xlt we store the indicator of carry of the carrying//
void find_xlt(int x);
void gate_add(int x, int x_inv);
void gate_add_inv(int x, int x_inv);
void addition_n();
void addition_inv();
public:
Adder(int a, int n, int width, Qregister &in);
Qregister &perform();
};
#endif // ADDER_H
<file_sep>/config.h
#ifndef CONFIG_H
#define CONFIG_H
#include <stdint.h>
enum
{
REG_NUM = 4
};
const double g_eps = 1e-8;
typedef unsigned long long state;
#include <complex>
typedef std::complex<long double> mcomplex;
#include <stdlib.h>
#include <stdio.h>
#endif // CONFIG_H
<file_sep>/measure.cpp
#include "measure.h"
#include <cstdlib>
state Measurer::Measure(Qregister ®)
{
double rnd = static_cast<double>(rand()) / RAND_MAX;
int i = 0;
register int sz = reg.getSize();
while (i < sz && !(rnd < 0)) {
mcomplex ampl = reg.getAmpls()[i];
long double probability = std::abs(ampl) * std::abs(ampl);
rnd -= probability;
if (rnd < 0 || std::abs(rnd - probability) < g_eps) {
return reg.getStates()[i];
}
i++;
}
return -1;
}
<file_sep>/multiplier.cpp
#include "multiplier.h"
#include "adder.h"
Multiplier::Multiplier(Qregister &in, int N, int width, int a, int ctl_id)
:m_reg(in),
m_N(N),
m_width(width),
m_a(a),
m_ctlid(ctl_id)
{
}
void fix_local_vars(Qregister &in, int var_pin, int width) {
for (int i = 0; i < width; i++) {
ApplyCSWAP(in, var_pin, 2 * width + 2 + i, width + i);
}
}
Qregister& Multiplier::perform()
{
mul();
fix_local_vars(m_reg, m_ctlid, m_width);
mulinverse();
return m_reg;
}
/*!
*\fn
*
*built multiplicand in register
*
*represent m_a as a sum of a numbers x * y = x * (yi * (1 << i)
*and add m_a * (1 << i) % N and sum this into a first part of a register
*and sum this in register
*
*/
void Multiplier::mul()
{
int tw = 2 * m_width + 1; // local var for multiplier
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2, tw);
basic_multiplication(m_a % m_N);
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2, tw);
for (int i = 1; i < m_width; i++) {
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2 + i, tw);
//(1 << i) *(1 >> i) == 1
Adder *add = new Adder(((1 << i) * m_a) % m_N, m_N, m_width, m_reg);
m_reg = add->perform();
delete add;
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2 + i, tw);
}
}
/*!
*\brief Calculates the a^-1 in this Field
*If N is not prime not for all a a^-1 exists
*/
static int abel_inverse(int a, int N) {
int i = 1;
while ( (i * a) % N != 1) {
i++;
}
return i;
}
/*!
*\fn
*
*inversive version of mul\n
*
*/
void Multiplier::mulinverse()
{
int tw = 2 * m_width + 1; // first local var
m_a = abel_inverse(m_a, m_N);
for (int i = m_width - 1; i > 0; i--) {
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2 + i, tw);
Adder *add = new Adder(m_N - ((1 << i) * m_a) % m_N, m_N, m_width, m_reg);
m_reg = add->perform();
delete add;
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2 + i, tw);
}
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2, tw);
basic_multiplication(m_a % m_N);
ApplyToffoli(m_reg, m_ctlid, 2 * m_width + 2, tw);
}
/*!
*\fn search bits in x\n
* m_width + i qbit contains m_reg(first width qbits) * (1 << i)\n
*
*/
void Multiplier::basic_multiplication(int x) {
int tw = 2 * m_width + 1;
for (int i = m_width - 1; i >= 0; i--) {
if ((x >> i) & 1) { // i
ApplyToffoli(m_reg, 2 * m_width + 2, tw, m_width + i); //m_width +i = m_reg * (1 << i) * indc(
}
}
}
Qregister &expamodn(Qregister &in, int N, int x, int val_width, int local_width)
{
ApplyNot(in, 2 * local_width + 2);
for (int i = 0; i < val_width; i++) {
int pow = x % N;
for (int j = 1; j < i + 1; j++) {
pow *= pow;
pow %= N;
}
Multiplier *mp = new Multiplier(in, N, local_width, pow, 3 * local_width + i + 2);
in = mp->perform();
delete mp;
}
return in;
}
<file_sep>/measure.h
#ifndef MEASURE_H
#define MEASURE_H
#include "qregister.h"
/*!
*\class
*\brief static class with method Measure(Measured register with the "natural" basis
*
*/
class Measurer
{
public:
static state Measure(Qregister ®);
};
#endif // MEASURE_H
<file_sep>/common.cpp
#include "common.h"
#include "config.h"
#include <vector>
#include <map>
#include <algorithm>
int set_bit(state x, unsigned char id, int val) {
switch (val) {
case 0:
x &= ~(1 << id);
break;
case 1:
x |= (1 << id);
break;
default:
break;
}
return x;
}
void ApplyCRot(Qregister ®, int id1, int id2, double alpha)
{
mcomplex mult = std::exp(mcomplex(0, alpha));
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
state st = reg.getStates()[i];
int id1_bit = ((st & static_cast<state>(1 << id1)) != 0);
int id2_bit = ((st & static_cast<state>(1 << id2)) != 0);
if (id1_bit && id2_bit) {
reg.getAmpls()[i] *= mult;
}
}
}
void ApplyHadamard(Qregister ®, int id1)
{
QMatrix m(2, 2);
for (int i = 0 ; i < 2; i++) {
for (int j = 0; j < 2; j++) {
m(i, j) = mcomplex(M_SQRT1_2l, 0);
}
}
m(1, 1) *= -1.0;
ApplyQbitMatrix(m, reg, id1);
}
void ApplyNot(Qregister ®, int id) {
QMatrix m(2, 2);
m(0, 0) = m(1, 1) = mcomplex(0, 0);
m(1, 0) = m(0, 1) = mcomplex(1, 0);
ApplyQbitMatrix(m, reg, id);
}
//naive realization not fast at all
void ApplyCnot(Qregister ®, int id0, int id1) {
QMatrix m(4, 4);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
m(i, j) = mcomplex(0, 0);
}
}
m(0, 0) = m(1, 1) = m(2, 3) = m(3, 2) = mcomplex(1, 0);
ApplyDiQbitMatrix(m, reg, id0, id1);
}
void ApplyFcnot(Qregister ®, int id0, int id1) {
register int sz = reg.getStates().size();
for (int i = 0; i < sz; i++) {
state st = (reg.getStates())[i];
int st_id = (st & static_cast<state>(1 << id0));
if (st_id != 0) {
st ^= static_cast<state>(1 << id1);
reg.getStates()[i] = st;
}
}
}
//naive realization not fast at all
void ApplyToffoli(Qregister ®, int id0, int id1, int id2) {
QMatrix m(8, 8);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
m(i, j) = mcomplex(0, 0);
}
}
for (int i = 0; i < 6; i++) {
m(i, i) = mcomplex(1, 0);
}
m(6, 7) = m(7, 6) = mcomplex(1, 0);
ApplyTriQbitMatrix(m, reg, id0, id1, id2);
}
void ApplyFToffoli(Qregister ®, int id0, int id1, int id2)
{
register int sz = reg.getStates().size();
for (int i = 0; i < sz; i++){
state st = (reg.getStates())[i];
int st_id0 = (st & static_cast<state>(1 << id0));
int st_id1 = (st & static_cast<state>(1 << id1));
if (st_id0 != 0 && st_id1 != 0) {
st ^= static_cast<state>(1 << id2);
reg.getStates()[i] = st;
}
}
}
void ApplyQbitMatrix(const QMatrix &m, Qregister ®, int id0)
{
std::vector<state> states;
std::vector<mcomplex> ampls;
std::map<state, int> used;
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
state st = (reg.getStates())[i];
int stateid0 = ((st & static_cast<state>(1 << id0)) != 0);
mcomplex cur_ampl = (reg.getAmpls())[i];
for (int j = 0; j < 2; j++) {
mcomplex res_ampl = m(j, stateid0) * cur_ampl;
if (std::abs(res_ampl) > g_eps) {
state st_t = st;
st_t = set_bit(st_t, id0, j);
bool found = used.find(st_t) != used.end();
if (!found) {
states.push_back(st_t);
ampls.push_back(res_ampl);
used[st_t] = states.size() - 1;
} else {
ampls[used[st_t]] += res_ampl;
}
}
}
}
std::vector<state> new_states;
std::vector<mcomplex> new_ampls;
sz = ampls.size();
for (int i = 0; i < sz; i++) {
if (std::abs(ampls[i]) > g_eps) {
new_states.push_back(states[i]);
new_ampls.push_back(ampls[i]);
}
}
reg.setAmpls(new_ampls);
reg.setStates(new_states);
}
void ApplyDiQbitMatrix(const QMatrix &m, Qregister ®, int id0,int id1)
{
std::vector<state> states;
std::vector<mcomplex> ampls;
std::map<state, int> used;
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
int st = (reg.getStates())[i];
int stateid0 = ((st & static_cast<state>(1 << id0)) != 0);
int stateid1 = ((st & static_cast<state>(1 << id1)) != 0);
mcomplex cur_ampl = (reg.getAmpls())[i];
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
mcomplex res_ampl = m(j * 2 + k, stateid0 * 2 + stateid1) * cur_ampl;
if (std::abs(res_ampl) > g_eps) {
state st_t = st;
st_t = set_bit(st_t, id0, j);
st_t = set_bit(st_t, id1, k);
bool found = used.find(st_t) != used.end();
if (!found) {
states.push_back(st_t);
ampls.push_back(res_ampl);
used[st_t] = states.size() - 1;
} else {
ampls[used[st_t]] += res_ampl;
}
}
}
}
}
std::vector<state> new_states;
std::vector<mcomplex> new_ampls;
sz = ampls.size();
for (int i = 0; i < sz; i++) {
if (std::abs(ampls[i]) > g_eps) {
new_states.push_back(states[i]);
new_ampls.push_back(ampls[i]);
}
}
reg.setAmpls(new_ampls);
reg.setStates(new_states);
}
void ApplyTriQbitMatrix(const QMatrix &m, Qregister ®, int id0, int id1, int id2)
{
std::vector<state> states;
std::vector<mcomplex> ampls;
std::map<state, int> used;
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
state st = (reg.getStates())[i];
int stateid0 = ((st & static_cast<state>(1 << id0)) != 0);
int stateid1 = ((st & static_cast<state>(1 << id1)) != 0);
int stateid2 = ((st & static_cast<state>(1 << id2)) != 0);
mcomplex cur_ampl = (reg.getAmpls())[i];
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
for (int l = 0; l < 2; l++) {
mcomplex res_ampl = m(j * 4 + k * 2 + l, stateid0 * 4 + stateid1 * 2 + stateid2) * cur_ampl;
if (std::abs(res_ampl) > g_eps) {
state st_t = st;
st_t = set_bit(st_t, id0, j);
st_t = set_bit(st_t, id1, k);
st_t = set_bit(st_t, id2, l);
bool found = used.find(st_t) != used.end();
if (!found) {
states.push_back(st_t);
ampls.push_back(res_ampl);
used[st_t] = states.size() - 1;
} else {
ampls[used[st_t]] += res_ampl;
}
}
}
}
}
}
std::vector<state> new_states;
std::vector<mcomplex> new_ampls;
sz = ampls.size();
for (int i = 0; i < sz; i++) {
if (std::abs(ampls[i]) > g_eps) {
new_states.push_back(states[i]);
new_ampls.push_back(ampls[i]);
}
}
reg.setAmpls(new_ampls);
reg.setStates(new_states);
}
void ApplySWAP(Qregister ®, int id0, int id1) {
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
state st = reg.getStates()[i];
int st_id0 = ((st & static_cast<state>(1 << id0)) != 0);
int st_id1 = ((st & static_cast<state>(1 << id1)) != 0);
st = set_bit(st, id0, st_id1);
st = set_bit(st, id1, st_id0);
reg.getStates()[i] = st;
}
}
void ApplyCSWAP(Qregister ®, int id0, int id1, int id2) {
register int sz = reg.getSize();
for (int i = 0; i < sz; i++) {
state st = reg.getStates()[i];
int st_id0 = ((st & static_cast<state>(1 << id0)) != 0);
int st_id1 = ((st & static_cast<state>(1 << id1)) != 0);
int st_id2 = ((st & static_cast<state>(1 << id2)) != 0);
if (st_id0) {
st = set_bit(st, id1, st_id2);
st = set_bit(st, id2, st_id1);
reg.getStates()[i] = st;
}
}
}
|
7a0ea49a48c85c9075415c05634e99d56680c05e
|
[
"C",
"C++"
] | 16 |
C++
|
lberserq/shor_cpp
|
e3deb199c65662d45b2a99155689a8a327bbb2d1
|
7cb46ab62cc86585e098a913a1fbc17c6b190db3
|
refs/heads/master
|
<file_sep>@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package com.lukelorusso.calendartrendview
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import com.lukelorusso.simplepaperview.SimplePaperView
import org.threeten.bp.LocalDate
import java.util.*
import kotlin.math.max
/**
* Show a cartesian trend graph based on calendar dates
*/
class CalendarTrendView constructor(context: Context, attrs: AttributeSet) :
SimplePaperView(context, attrs) {
companion object {
private const val DEFAULT_MAX_VALUE = 10F
private const val DEFAULT_MIN_VALUE = 0F
private const val INSIDER_DOT_MULTIPLIER = 0.8F
}
enum class StartFrom {
NOWHERE,
ORIGIN,
FIRST_VALUE
}
private var trends = mutableListOf<Trend>()
private var startFrom = StartFrom.NOWHERE
private var showToday = false
var maxValue = DEFAULT_MAX_VALUE
var minValue = DEFAULT_MIN_VALUE
var numberOfDaysToShowAtLeast = 0
var xUnitMeasureInDp = 0F
var yUnitMeasureInDp = 0F
var lineWeightsInDp = 1F
var paddingBottomInDp = 40F
var paddingRightInDp = 18F
var stepLineColor = Color.GRAY
var dayLabelColor = Color.BLACK
var monthLabelColor = Color.BLACK
var todayLabelColor = Color.BLACK
var labelTypeFace: Typeface? = null
var dateFormatPattern: String = "yyyy-MM-dd"
init {
invertY = true
// Load the styled attributes and set their properties
val attributes = context.obtainStyledAttributes(attrs, R.styleable.CalendarTrendView, 0, 0)
startFrom =
StartFrom.values()[attributes.getInt(
R.styleable.CalendarTrendView_ctv_startFrom,
startFrom.ordinal
)]
showToday = attributes.getBoolean(R.styleable.CalendarTrendView_ctv_showToday, showToday)
stepLineColor =
attributes.getColor(R.styleable.CalendarTrendView_ctv_stepLineColor, stepLineColor)
dayLabelColor =
attributes.getColor(R.styleable.CalendarTrendView_ctv_dayLabelColor, dayLabelColor)
monthLabelColor =
attributes.getColor(R.styleable.CalendarTrendView_ctv_monthLabelColor, monthLabelColor)
todayLabelColor =
attributes.getColor(R.styleable.CalendarTrendView_ctv_todayLabelColor, todayLabelColor)
xUnitMeasureInDp =
context.pixelToDp(
attributes.getDimensionPixelSize(
R.styleable.CalendarTrendView_ctv_xUnitMeasure,
0
).toFloat()
)
yUnitMeasureInDp =
context.pixelToDp(
attributes.getDimensionPixelSize(
R.styleable.CalendarTrendView_ctv_yUnitMeasure,
0
).toFloat()
)
attributes.recycle()
}
//region MODELS
/**
* Object for this class.
* @param label The label for the trend.
* @param valueMap HashMap of date-value in the form of: <"yyyy-MM-dd", 1.0F>.
* @param color The color hor the trend.
* @param lineWeightInDp The line weight.
*/
class Trend(
var label: String,
var valueMap: HashMap<String, Float?> = hashMapOf(),
var color: Int = Color.BLACK,
var lineWeightInDp: Float? = null
)
//endregion
//region EXPOSED METHODS
/**
* Trend values can be ONLY in the minValue..maxValue range
*/
fun addTrend(trend: Trend) {
trends.add(trend)
drawTrends()
}
fun removeTrend(trend: Trend) {
trends.remove(trend)
drawTrends()
}
fun removeTrendAt(position: Int) {
trends.removeAt(position)
drawTrends()
}
fun removeTrendByLabel(label: String) {
trends.forEach { trend ->
if (label == trend.label) {
removeTrend(trend)
return
}
}
}
/**
* Trends values can be ONLY in the minValue..maxValue range
*/
fun setTrends(trends: MutableList<Trend>) {
this.trends = trends
drawTrends()
}
fun clearTrends() {
trends.clear()
drawTrends()
}
fun getUniqueDates(): Set<LocalDate> {
var setOfDates = mutableSetOf<LocalDate>()
trends.forEach { trend ->
trend.valueMap.forEach { value ->
setOfDates.add(value.key.toLocalDate(dateFormatPattern))
}
}
if (showToday) setOfDates.add(todayToLocalDate())
setOfDates = setOfDates.toSortedSet()
if (setOfDates.size < numberOfDaysToShowAtLeast) {
var lastDay = setOfDates.elementAt(setOfDates.size - 1)
while (setOfDates.size < numberOfDaysToShowAtLeast) {
while (setOfDates.contains(lastDay)) lastDay = lastDay.minusDays(1)
setOfDates.add(lastDay)
}
}
setOfDates = setOfDates.toSortedSet()
return setOfDates.sorted().toSet()
}
//endregion
//region PRIVATE METHODS
private fun drawTrends() {
clearPaper(false)
var maxWidth = 0F
var maxWeight = lineWeightsInDp
val trendsToDraw = arrayListOf<DrawableItem>()
val dotsToDraw = arrayListOf<Circle>()
val setOfDates = getUniqueDates()
var numberOfStepLines = 0
// Collecting all the trend lines to draw
for (trend in trends) {
val sortedMap = hashMapOf<LocalDate, Float?>().apply {
trend.valueMap.forEach { entry ->
this[entry.key.toLocalDate(dateFormatPattern)] = entry.value
}
}.toSortedMap()
var lastValue = 0F // used to know where to start drawing a value's line
var countFromFirstDay = 0 // will concur to the "numberOfStepLines"
var lastDrawnCount = 0
var i = 0 // is the count of the values inside a trend
for ((key, value) in sortedMap) {
i++
countFromFirstDay = setOfDates.indexOf(key) + 1
var croppedValue: Float
value?.also {
// Avoiding cheating the imposed range
croppedValue = when {
value > maxValue -> maxValue
value < minValue -> minValue
else -> value
}
// Applying starting behaviour
if (i == 1) {
when (startFrom) {
StartFrom.NOWHERE -> {
lastDrawnCount = countFromFirstDay
lastValue = croppedValue
}
StartFrom.FIRST_VALUE -> lastValue = croppedValue
else -> {
}
}
}
val ax = lastDrawnCount * xUnitMeasureInDp
var ay = lastValue * yUnitMeasureInDp
if (paddingBottomInDp > 0) ay += paddingBottomInDp
val bx = countFromFirstDay * xUnitMeasureInDp
var by = croppedValue * yUnitMeasureInDp
if (paddingBottomInDp > 0) by += paddingBottomInDp
lastValue = croppedValue
val weight = trend.lineWeightInDp ?: lineWeightsInDp
val line = Line(ax, ay, bx, by, trend.color, weight)
trendsToDraw.add(line)
maxWeight = max(maxWeight, weight)
maxWidth = max(maxWidth, max(ax, bx))
//maxHeight = max(maxHeight, max(y, dy))
lastDrawnCount = countFromFirstDay
// Collecting trend's final dots
dotsToDraw.add(
Circle(
line.dx,
line.dy,
line.weight,
Color.WHITE
)
)
dotsToDraw.add(
Circle(
line.dx,
line.dy,
line.weight * INSIDER_DOT_MULTIPLIER,
line.color
)
)
}
}
numberOfStepLines = max(numberOfStepLines, countFromFirstDay)
}
// Collecting vertical step lines
val stepLinesToDraw = arrayListOf<Line>()
val labelsToDraw = arrayListOf<DrawableItem>()
@Suppress("UnnecessaryVariable")
for (i in 0..setOfDates.size) {
val ax = i * xUnitMeasureInDp
val ay = 10 * yUnitMeasureInDp + paddingBottomInDp
val bx = ax
var by = 0F
if (paddingBottomInDp > 0) by += paddingBottomInDp
stepLinesToDraw.add(Line(ax, ay, bx, by, stepLineColor, 0.8F))
maxWidth = max(maxWidth, max(ax, bx))
// Creating day and month labels
if (i > 0) {
val date = setOfDates.elementAt(i - 1)
val isToday = date == todayToLocalDate()
// Today particular case
if (isToday) {
var background = getBackgroundColor()
if (background == Color.TRANSPARENT) background = Color.WHITE
labelsToDraw.add(
Circle(
bx, 18F, 14F, todayLabelColor
)
)
labelsToDraw.add(
Circle(
bx, 18F, 13F, background
)
)
}
labelsToDraw.add(
TextLabel(
date.dayOfMonth.toString(),
10F,
ax,
18F,
if (isToday)
todayLabelColor
else dayLabelColor,
true,
labelTypeFace
)
)
labelsToDraw.add(
TextLabel(
date.month
.getDisplayName(resources)
.substring(0, 3)
.toUpperCase(Locale.getDefault()),
8F,
bx,
12F,
if (isToday)
todayLabelColor
else monthLabelColor,
true,
labelTypeFace
)
)
}
}
// Drawing collected items
drawInDp(stepLinesToDraw, false)
var i = 0
trendsToDraw.forEach { trendLine ->
drawInDp(trendLine, false)
// drawing previous line's dots (avoiding overlapping)
if (i > 0 && dotsToDraw.size > 1) {
val dot1 = dotsToDraw[0]
val dot2 = dotsToDraw[1]
drawInDp(dot1, false)
drawInDp(dot2, false)
dotsToDraw.remove(dot1)
dotsToDraw.remove(dot2)
}
i++
}
drawInDp(dotsToDraw, false) // drawing eventual remaining dots
drawInDp(labelsToDraw, false)
// Forcing padding right by drawing transparent line
// + invalidating PaperView
drawInDp(
Line(
0F,
0F,
maxWidth + paddingRightInDp,
(maxValue * yUnitMeasureInDp) + paddingBottomInDp,
Color.TRANSPARENT,
maxWeight
), false
)
drawInDp(
Circle(
maxWidth + paddingRightInDp,
(maxValue * yUnitMeasureInDp) + paddingBottomInDp,
maxWeight,
Color.TRANSPARENT
), true
)
}
//endregion
}
<file_sep>allprojects {
repositories {
google()
mavenCentral()
gradlePluginPortal()
maven { url 'https://jitpack.io' }
}
}
ext {
// APP VERSION
androidVersionCode = 10
androidVersionName = '1.1.8' // REMEMBER: also update README.md
// ANDROID VERSION
androidMinSdkVersion = 16
androidTargetSdkVersion = 30
// KOTLIN
kotlinStdlib = "org.jetbrains.kotlin:kotlin-stdlib:${ext.kotlin_version}"
// ANDROID LIB
androidXAppCompat = "androidx.appcompat:appcompat:1.2.0"
// THREE TEN ABP
threeTenABP = "com.jakewharton.threetenabp:threetenabp:1.3.1"
// LUKE LORUSSO
simplePaperViewVersion = '1.1.6'
simplePaperViewGroupId = "com.github.lukelorusso"
simplePaperViewArtifactId = "SimplePaperView"
simplePaperView = "$simplePaperViewGroupId:$simplePaperViewArtifactId:$simplePaperViewVersion"
// DEPENDENCY CHECK STRATEGY
dependencyUpdatesStrategy = {
componentSelection { rules ->
rules.all { ComponentSelection selection ->
boolean rejected = ['alpha', 'beta', 'rc', 'cr', 'm'].any { qualifier ->
selection.candidate.version ==~ /(?i).*[.-]${qualifier}[.\d-]*/
}
if (rejected) {
selection.reject('Release candidate')
}
}
}
}
}
<file_sep>CalendarTrendView
=================
[](https://opensource.org/licenses/Apache-2.0) [](http://developer.android.com/index.html) [](https://android-arsenal.com/api?level=16) [](https://jitpack.io/#lukelorusso/CalendarTrendView)
## Presentation ##

This is the source code of an Android library: `-=:[ CalendarTrendView ]:=-`
Show a cartesian trend graph based on calendar dates
This library make use of [SimplePaperView](https://github.com/lukelorusso/SimplePaperView) to draw shapes!
- - -
## Why would you need it? ##
Let's say you want to represent one or more behaviours.
By "behaviour" I mean a list of events, happening once per day, evaluated as Float numbers in the range of `0.0` to `10.0` (percentage; you can change min and max values ๐).
It would be useful to show a trend of how this events evolve as the days pass by.
With CalendarTrendView you can show a meaningful "trend graph" (a cartesian x,y board) that tracks the evolution of your behaviours.
In this example you see the evolution of 4 behaviours, or "Trends".
Each `Trend` is a class with:
* a label
* an `HashMap<String, Float?>` where `String` is a date in a predefined format pattern
* a color
* [optional] the weight (thickness) of our line in dp
- - -
## How to use it? ##
Step 1. add the JitPack repository to your ROOT build.gradle at the end of repositories:
```groovy
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
Step 2. add the dependency:
```groovy
implementation 'com.github.lukelorusso:CalendarTrendView:1.1.8'
```
That's it!
Now you can add the view to your layout:
```xml
<com.lukelorusso.calendartrendview.CalendarTrendView
android:id="@+id/calendarTrendView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
```
maybe add some colors, set if you need to show today or not... you may also want to put x and y unit measures:
```
...
android:background="@color/graphBackground"
app:ctv_dayLabelColor="@color/graphTextLabelDay"
app:ctv_monthLabelColor="@color/graphTextLabelMonth"
app:ctv_todayLabelColor="@color/colorAccent"
app:ctv_stepLineColor="@color/graphStepLine"
app:ctv_showToday="true"
app:ctv_startFrom="nowhere"
app:ctv_xUnitMeasure="25dp"
app:ctv_yUnitMeasure="22dp"
...
```
- - -
# Attributes #
Ok by now, let's move to the code!
This is a `Trend`:
```kotlin
val trend = CalendarTrendView.Trend(
"Precipitations",
hashMapOf(
"2019-05-11" to 4F,
"2019-05-12" to 4.3F,
"2019-05-13" to 4F,
"2019-05-14" to 4F,
"2019-05-15" to 4.3F
),
Color.RED
)
```
You can also define a `List<Trend>` to show.
Remember that your value is a Float, but can also be unknown (null).
Let's customize our view a little more:
```kotlin
calendarTrendView.numberOfDaysToShowAtLeast = 14
calendarTrendView.maxValue = 1000F // you may want to customize this...
calendarTrendView.minValue = 100F // ...or that
calendarTrendView.xUnitMeasureInDp = context.dpToPixel(25F) // if you don't like...
calendarTrendView.yUnitMeasureInDp = context.dpToPixel(22F) // ...using XML attributes
calendarTrendView.labelTypeFace = ResourcesCompat.getFont(this, R.font.proxima_nova_regular) // you can choose a font for days' labels
calendarTrendView.lineWeightsInDp = 4F // the global "thickness"; however, each Trend can override this with its own lineWeightsInDp
```
If you need to adopt another date format just let the view know it:
```kotlin
calendarTrendView.dateFormatPattern = "dd/MM/yyyy" // or any other pattern you like
```
Time to add our Trend:
```kotlin
calendarTrendView.addTrend(trend)
```
...or our list of trends:
```kotlin
calendarTrendView.setTrends(trendList)
```
Other useful methods:
```kotlin
calendarTrendView.removeTrend(trend)
calendarTrendView.removeTrendAt(0)
calendarTrendView.removeTrendByLabel("Precipitations")
calendarTrendView.clearTrends()
```
If you need all the represented LocalDate in the graph:
```kotlin
val setOfDates = calendarTrendView.getUniqueDates()
```
This is a useful way to get today's LocalDate:
```kotlin
val todayLocalDate = todayToLocalDate()
```
- - -
# Explore! #
Feel free to checkout and launch the example app ๐ก
- - -
# Copyright #
Make with ๐ by [<NAME>](http://lukelorusso.com), licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0)
<file_sep>include ':calendartrendview', ':calendartrendview-example'
<file_sep>package com.lukelorusso.calendartrendviewsample
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.lukelorusso.calendartrendview.CalendarTrendView
import com.lukelorusso.calendartrendview.parseToString
import com.lukelorusso.calendartrendview.toLocalDate
import com.lukelorusso.calendartrendview.todayToLocalDate
import com.lukelorusso.calendartrendviewsample.databinding.ActivityMainBinding
import org.threeten.bp.LocalDate
class MainActivity : AppCompatActivity() {
companion object {
private const val MY_DATE_PATTERN = "dd/MM/yyyy"
}
private val binding by viewBinding(ActivityMainBinding::inflate)
private var colors = listOf<Int>()
private var labels = listOf<String>()
private var trends = listOf<CalendarTrendView.Trend>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
initData()
initView()
}
//region PRIVATE METHODS
private fun initData() {
labels = mutableListOf(
getString(R.string.health),
getString(R.string.welfare),
getString(R.string.serenity),
getString(R.string.relation)
)
colors = mutableListOf(
ContextCompat.getColor(this, R.color.graphHealth),
ContextCompat.getColor(this, R.color.graphWelfare),
ContextCompat.getColor(this, R.color.graphSerenity),
ContextCompat.getColor(this, R.color.graphRelation)
)
trends = mutableListOf(
CalendarTrendView.Trend(
labels[0],
hashMapOf(
"11/04/2021" to 7F,
"12/04/2021" to 7F,
"13/04/2021" to 8F,
"14/04/2021" to 8F,
"15/04/2021" to 8F,
"16/04/2021" to 7.2F,
"17/04/2021" to 7.3F,
"18/04/2021" to 7.6F,
"19/04/2021" to 7.7F,
"20/04/2021" to 8.7F,
"21/04/2021" to 8.8F,
"22/04/2021" to 9.3F,
"23/04/2021" to 9.4F
),
colors[0]
),
CalendarTrendView.Trend(
labels[1],
hashMapOf(
"11/04/2021" to 4F,
"12/04/2021" to 4.3F,
"13/04/2021" to 4F,
"14/04/2021" to 4F,
"15/04/2021" to 4.3F,
"16/04/2021" to 5.2F,
"17/04/2021" to 5.3F,
"18/04/2021" to 5.6F,
"19/04/2021" to 5.7F,
"20/04/2021" to 6.7F,
"21/04/2021" to 6.8F,
"22/04/2021" to 7.3F,
"23/04/2021" to 6.9F
),
colors[1]
),
CalendarTrendView.Trend(
labels[2],
hashMapOf(
"11/04/2021" to 3F,
"12/04/2021" to 2.8F,
"13/04/2021" to 2.5F,
"14/04/2021" to 2.5F,
"15/04/2021" to 2.7F,
"16/04/2021" to 4.2F,
"17/04/2021" to 4.3F,
"18/04/2021" to 4.6F,
"19/04/2021" to 4.7F,
"20/04/2021" to 5F,
"21/04/2021" to 5F,
"22/04/2021" to 5.3F,
"23/04/2021" to 5.1F
),
colors[2]
),
CalendarTrendView.Trend(
labels[3],
hashMapOf(
"11/04/2021" to 1F,
"12/04/2021" to 1.1F,
"13/04/2021" to 0.9F,
"14/04/2021" to 0.9F,
"15/04/2021" to 0.8F,
"16/04/2021" to 1.8F,
"17/04/2021" to 1.8F,
"18/04/2021" to 2.2F,
"19/04/2021" to 2.3F,
"20/04/2021" to 3F,
"21/04/2021" to 3.1F,
"22/04/2021" to 3.7F,
"23/04/2021" to 3.3F
),
colors[3]
)
)
}
private fun initView() {
binding.calendarTrendView.apply {
labelTypeFace = ResourcesCompat.getFont(this@MainActivity, R.font.proxima_nova_regular)
dateFormatPattern = MY_DATE_PATTERN
lineWeightsInDp = 4F
numberOfDaysToShowAtLeast = 14
if (isDayTracked(todayToLocalDate())) {
todayLabelColor = dayLabelColor
}
setTrends(trends.toMutableList()) // in this way I set a copy of my list
setOnDrawListener {
post {
binding.calendarScrollView.fullScroll(
View.FOCUS_RIGHT
)
}
}
}
createRatioButtons()
binding.mainBtnAddValues.setOnClickListener {
addTrendValues(
todayToLocalDate().parseToString(MY_DATE_PATTERN),
listOf(10F, 10F, 10F, 10F)
)
}
}
private fun createRatioButtons() {
binding.calendarTrendsCheckGroup.removeAllViews()
for ((i, label) in labels.withIndex()) {
val checkBox = CheckBox(this).apply {
text = label
isChecked = true
setTextColor(colors[i])
}
checkBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) trends.forEach { trend ->
if (label == trend.label) binding.calendarTrendView.addTrend(
trend
)
}
else binding.calendarTrendView.removeTrendByLabel(label)
}
binding.calendarTrendsCheckGroup.addView(checkBox)
}
}
private fun isDayTracked(day: LocalDate): Boolean {
for (trend in trends) for (entry in trend.valueMap) {
if (entry.key.toLocalDate(MY_DATE_PATTERN) == day) return true
}
return false
}
private fun addTrendValues(dateAsString: String, newValues: List<Float>) {
if (trends.size == newValues.size) {
for (i in trends.indices) {
val valueMap: HashMap<String, Float?> = trends[i].valueMap
valueMap[dateAsString] = newValues[i]
trends[i].valueMap = valueMap
}
initView()
}
}
//endregion
}
|
a14cea3b059581598ead8d4efba7961fec571d42
|
[
"Markdown",
"Kotlin",
"Gradle"
] | 5 |
Kotlin
|
lukelorusso/CalendarTrendView
|
ce2fd9e8255652819edf314744918e853cb69ecb
|
72dafb957e9cf0514702ad25220d3e347e4ea4d4
|
refs/heads/master
|
<repo_name>davidwparker/various-jquery-old<file_sep>/js/jquery.tableFilter-1.0.js
/*
* jQuery.filterTable
*
* Adds a row after the first row with input boxes for searching the values within that column
* dynamically. It currently does not provide
*
* @version 1.0
* @author <NAME> [davidwparker(at)gmail(dot)com]
* @copyright Copyright (c) 2009 <NAME>
* @license MIT
* @demo: http://davidwparker.com/
*
* @function filterTable(options)
* @param options object
* @options: default: description
* ajax: false: Determines if this table search should use ajax (currently not implemented)
* classClear: clear: Class used for the clear link (jQuery selector)
* classClearAdd: "" Class used for the clear link (not a selector, can be used for padding, etc)
* classFilterBy: filterBy Class used for hidden input
* classFilterCol: filterCol Class used to apply to all td elements and value for hidden input
* classFilterInput: filterInput Class used for input type=text for the filter
* classFilterRow: filterRow Class used for
* classFiltered: highlight Class used for filtered objects
* classFilteredOut: hide Class used for filtered out objects
* classRowToFilter: rowToFilter Class used for rows that can be filtered
* filter: filter filter|filterOut - Determines if filter or filter out objects
* filteredRow: tr:first jQuery Selector for the row to filter and insert filter row after (generally the first row)
* styleFiltered: {display:none} Style used for filtered objects
* styleUnfiltered: {display:""} Style used for unfiltered objects
* styleFilteredOut {display:none} Style used for filtered out objects
* styleUnfilteredOut {display:""} Style used for unfiltered out objects
* textClear: clear Text to be used for the clear link
* @return jQuery object
*
* @note: ensure that element (div) surrounding the table has the following styles:
* overflow-y:scroll;
* height:XXXpx;
* to get the desired effect.
*/
(function($){
$.fn.extend({
filterTable: function(opts){
//setup the defaults for the filter, add the insert row, and add removeClass to all td elements
var defaults = {
ajax:false,
classClear:"clear",
classClearAdd:"",
classFilterBy:"filterBy",
classFilterCol:"filterCol",
classFilterInput:"filterInput",
classFilterRow:"filterRow",
classFiltered:"highlight",
classFilteredOut:"hide",
classRowToFilter:"rowToFilter",
filter:"filter",
filteredRow:"tr:first",
filterStyleClass:"style",
styleFiltered:{"display":"none"},
styleUnfiltered:{"display":""},
styleFilteredOut:{"display":"none"},
styleUnfilteredOut:{"display":""},
textClear:"clear"
}, o = $.extend({}, defaults, opts),
$this = $(this), length = $this.find(o.filteredRow+" th, "+o.filteredRow+" td").length;
//create insertRow
var insertRow = "<tr class='"+o.classFilterRow+"'>";
for (var i = 0; i < length; i++){
var filterval=o.classFilterCol+i;
insertRow += "<th><input type='hidden' class='"+o.classFilterBy
+"' value='"+filterval+"' /><input type='text' class='"+o.classFilterInput
+"' /><a href='#' class='"+o.classClear+" "+o.classClearAdd+"'>"+o.textClear+"</a></th>";
//attach filterval to each row
$this.find("tr:not("+o.filteredRow+",."+o.classFilterRow+")").each(function(){
$(this).find("td").each(function(j){
if (i === j)
$(this).addClass(filterval);
})
}).addClass(o.classRowToFilter);
}
insertRow += "</tr>";
//insert
$this.find(o.filteredRow).after(insertRow);
//return
return this.each(function(){
var $this = $(this);
$this.find("."+o.classFilterRow+" ."+o.classFilterInput).keyup(function(){
filterValues();
});
//click
$("a."+o.classClear).click(function(){
$(this).parent().find("."+o.classFilterInput).val("");
filterValues();
return false;
});
//function
function filterValues(){
var vals = {};
//get all the current values and store them by filterby:value
$this.find("."+o.classFilterInput).each(function(){
var $finput = $(this), val = $finput.val(), filterval = $finput.parent().find("."+o.classFilterBy).val();
vals[filterval] = val;
});
if (o.ajax){
//ajax will return the latest data from the database and replace our values
alert('ajax');
//this will probably just replace all the rows first then apply css/styles
}
//reveal all hidden rows, then re-apply the hide
var $classRowToFilter = $this.find("."+o.classRowToFilter);
if (o.filter == "filter"){
if (o.filterStyleClass === "class"){
$classRowToFilter.removeClass(o.classFiltered);
} else if (o.filterStyleClass === "style"){
$classRowToFilter.css(o.styleUnfiltered);
}
}
else if (o.filter == "filterOut"){
if (o.filterStyleClass === "class"){
$classRowToFilter.removeClass(o.classFilteredOut);
} else if (o.filterStyleClass === "style"){
$classRowToFilter.css(o.styleUnfilteredOut);
}
}
for (var filterval in vals){
var theVal = vals[filterval];
//this appears to work fine for the filterOut, but not for filter
$this.find("."+o.classRowToFilter+" td."+filterval).each(function(){
var $cur = $(this), $curRow = $cur.parents("."+o.classRowToFilter);
//filter - finds matches
if (o.filter === "filter"){
if (theVal !== "" && ($cur.html().search(theVal) !== -1)){
if (o.filterStyleClass === "class")
$curRow.addClass(o.classFiltered);
else if (o.filterStyleClass === "style")
$curRow.css(o.styleFiltered);
}
}
else if (o.filter === "filterOut"){
//filter out - finds non-matches
if (theVal !== "" && ($cur.html().search(theVal) === -1)){
if (o.filterStyleClass === "class")
$curRow.addClass(o.classFilteredOut);
else if (o.filterStyleClass === "style")
$curRow.css(o.styleFilteredOut);
}
}
});
}
}
});
}
});
})(jQuery);
|
202dbc418fcff82711ae49722fcea46f014d49e7
|
[
"JavaScript"
] | 1 |
JavaScript
|
davidwparker/various-jquery-old
|
598f516e8266c9c1a47a11491cf2097012b7328b
|
64f04f677ce4a2202d95dbc8ba4bec7cbcbdb9b8
|
refs/heads/master
|
<repo_name>chzeng03/CheckIn<file_sep>/js/index.js
const eventlist = document.querySelector('.Events');
const loggedoutlinks = document.querySelectorAll('.logged-out');
const loggedinlinks = document.querySelectorAll('.logged-in');
const accountdetails = document.querySelector('.account-details');
const checkedevent = document.querySelector('.checkedevent');
const setupUI = (user) => {
if (user) {
db.collection('users').doc(user.uid).get().then(doc =>{
const html1 = `
<div> Logged in as ${user.email}</div>
`;
accountdetails.innerHTML = html1;
})
loggedinlinks.forEach(item => item.style.display = 'block');
loggedoutlinks.forEach(item => item.style.display = 'none');
} else {
loggedinlinks.forEach(item => item.style.display = 'none');
loggedoutlinks.forEach(item => item.style.display = 'block');
}
}
//setup events
const setupEvents = (data) => {
let html = '';
data.forEach(doc => {
const event = doc.data();
const li = `
<li>
<div class="collapsible-header grey lighten-4" style="font-weight:bold">${event.Name}</div>
<div class="collapsible-body white">
hosting by ${event.Organization}
<br><br>
${event.Time} at ${event.Location}
<button class="button float-right" onclick="location.href = 'Geofence-master/index.html'">Check IN</button>
</div>
</li>
`;
html += li
});
eventlist.innerHTML = html;
}
// setup materialize componets
document.addEventListener('DOMContentLoaded', function () {
var modals = document.querySelectorAll('.modal');
M.Modal.init(modals);
var items = document.querySelectorAll('.collapsible');
M.Collapsible.init(items);
});
|
fe0e88d5b99831a7a069d450f316c9752de45244
|
[
"JavaScript"
] | 1 |
JavaScript
|
chzeng03/CheckIn
|
ad615b2dfdcc82a663bd6ae9554d3d5043b308e4
|
362d0ee6d56bb48564de6e06669e15293b5dd8a0
|
refs/heads/main
|
<repo_name>bp-mike/lara-vue-addressbook<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\Contact;
Route::group(['middleware' => 'api'],function(){
// get all
Route::get('contacts', function(){
return Contact::latest()->get();
});
Route::get('contacts/{id}', function( $id){
return Contact::findOrFail($id);
});
Route::post('contacts/store', function(Request $request){
return Contact::create(['name'=>$request->input('name'), 'email'=>$request->input('email'), 'phone'=>$request->input('phone')]);
});
Route::patch('contacts/{id}', function(Request $request, $id){
return Contact::findOrFail($id)->update(['name'=>$request->input('name'), 'email'=>$request->input('email'), 'phone'=>$request->input('phone')]);
});
Route::delete('contacts/{id}', function( $id){
return Contact::destroy($id);
});
});
// Route::resource('posts', PostController::class);
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
|
157d5ab47735bcfabfac007d79b133e748259d3c
|
[
"PHP"
] | 1 |
PHP
|
bp-mike/lara-vue-addressbook
|
aec7cefc699a8fd41390801811ff175efa8a1adb
|
9c8b7aae4939e67b7af8306dbb4d94b6e91bc7dd
|
refs/heads/master
|
<repo_name>dewos/Wolfed<file_sep>/src/it/wolfed/model/Edge.java
package it.wolfed.model;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
/**
* Edges are the link elements of the graph model.
*/
abstract public class Edge extends mxCell
{
/**
* {@link Edge} Constructor.
*
* @param parent
* @param id
* @param value
* @param source
* @param target
*/
public Edge(Object parent, String id, Object value,
Object source, Object target)
{
setId(id);
setValue(value);
setEdge(true);
setGeometry(new mxGeometry());
getGeometry().setRelative(true);
}
}<file_sep>/src/it/wolfed/model/Vertex.java
package it.wolfed.model;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
/**
* Vertices are the node elements of the graph model.
*/
abstract public class Vertex extends mxCell
{
/**
* Vertex Constructor.
*
* @param parent
* @param id
* @param value
* @param x
* @param y
* @param width
* @param height
* @param style
*/
public Vertex(Object parent, String id, Object value,
double x, double y, double width, double height, String style)
{
setId(id);
setValue(value);
setGeometry(new mxGeometry(x, y, width, height));
setStyle(style);
setVertex(true);
setConnectable(true);
}
}<file_sep>/src/it/wolfed/operation/ExplicitChoiceOperation.java
package it.wolfed.operation;
import it.wolfed.model.PetriNetGraph;
/**
* ExplicitChoice Operation.
*/
public class ExplicitChoiceOperation extends Operation
{
private PetriNetGraph firstGraph;
private PetriNetGraph secondGraph;
public ExplicitChoiceOperation(PetriNetGraph operationGraph, PetriNetGraph firstGraph, PetriNetGraph secondGraph) throws Exception
{
super(operationGraph);
this.firstGraph = (new IterationPatternOperation(new PetriNetGraph("1"), firstGraph)).getOperationGraph();
this.secondGraph = (new IterationPatternOperation(new PetriNetGraph("2"), secondGraph)).getOperationGraph();
execute();
}
@Override
void process() throws Exception
{
this.operationGraph = (new DefferedChoiceOperation(new PetriNetGraph("ExplicitChoice"), firstGraph, secondGraph)).getOperationGraph();
}
}
<file_sep>/src/it/wolfed/operation/IterationPatternOperation.java
package it.wolfed.operation;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.PlaceVertex;
import it.wolfed.model.TransitionVertex;
import it.wolfed.model.Vertex;
/**
* Sequencing Operation.
*/
public class IterationPatternOperation extends Operation
{
PetriNetGraph firstGraph;
/**
* @param operationGraph
* @param firstGraph
* @throws Exception
*/
public IterationPatternOperation(PetriNetGraph operationGraph, PetriNetGraph firstGraph) throws Exception
{
super(operationGraph);
this.firstGraph = getIfIsWorkFlow(firstGraph);
this.operationGraph = (new FullMergeOperation(operationGraph, firstGraph)).getOperationGraph();
execute();
}
/**
* Iteration Pattern.
*
* firstGraph = P1 -> T1 -> P1
* result = initial* -> T3* -> P1 -> T1 -> P1 -> T4* -> final*
*/
@Override
void process()
{
insertInitialPattern();
insertFinalPattern();
}
/**
* Iteration Initial Pattern.
*
* firstGraph = P1 -> T1 -> P1
* result = initial* -> T3* -> P1 -> T1 -> P1
*/
private void insertInitialPattern()
{
PlaceVertex initialPlace = operationGraph.insertPlace(null);
TransitionVertex initialTransition = operationGraph.insertTransition(null);
PlaceVertex initialPlaceAsFirst = (PlaceVertex) getEquivalentVertex(1, firstGraph.getInitialPlaces().get(0));
operationGraph.insertArc(null, initialPlace, initialTransition);
operationGraph.insertArc(null, initialTransition, initialPlaceAsFirst);
// Remove torkens if any
initialPlaceAsFirst.setTokens(0);
}
/**
* Iteration Final Pattern.
*
* firstGraph = P1 -> T1 -> P1
* result = P1 -> T1 -> P1 -> T4* -> final*
*/
private void insertFinalPattern()
{
PlaceVertex finalPlace = operationGraph.insertPlace(null);
TransitionVertex finalTransition = operationGraph.insertTransition(null);
Vertex finalPlaceAsFirst = getEquivalentVertex(1, firstGraph.getFinalPlaces().get(0));
operationGraph.insertArc(null, finalTransition, finalPlace);
operationGraph.insertArc(null, finalPlaceAsFirst, finalTransition);
}
}<file_sep>/src/it/wolfed/operation/SequencingOperation.java
package it.wolfed.operation;
import it.wolfed.manipulation.GraphManipulation;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.Vertex;
/**
* Sequencing Operation.
*/
public class SequencingOperation extends Operation
{
PetriNetGraph firstGraph;
PetriNetGraph secondGraph;
/**
* @param operationGraph
* @param firstGraph
* @param secondGraph
* @throws Exception
*/
public SequencingOperation(PetriNetGraph operationGraph, PetriNetGraph firstGraph, PetriNetGraph secondGraph) throws Exception
{
super(operationGraph);
this.firstGraph = getIfIsWorkFlow(firstGraph);
this.secondGraph = getIfIsWorkFlow(secondGraph);
this.operationGraph = (new FullMergeOperation(operationGraph, firstGraph, secondGraph)).getOperationGraph();
execute();
}
/**
* Process Sequencing.
*
* FistGraph:
*
* N1_P1 โ โ N1_T1 โ โ N1_P2 โฏ
*
* -------------------------------
*
* SecondGraph:
*
* N2_P1 โ โ N2_T1 โ โ N2_P2 โฏ
*
* -------------------------------
*
* ResultGraph:
*
* N1_P1 โ โ N1_T1 โ -> P* โฏ โ N2_T2 โ โ N2_P2 โฏ
* P* = (N1_P2 + N2_P1)
*/
@Override
void process()
{
Vertex finalPlaceAsFirst = getEquivalentVertex(1, firstGraph.getFinalPlaces().get(0));
Vertex initialPlaceAsSecond = getEquivalentVertex(2, secondGraph.getInitialPlaces().get(0));
GraphManipulation.cloneIncomingEdges(operationGraph, finalPlaceAsFirst, initialPlaceAsSecond);
GraphManipulation.removeVertexAndHisEdges(operationGraph, finalPlaceAsFirst);
// set token to initial place
operationGraph.getInitialPlaces().get(0).setTokens(1);
}
}<file_sep>/src/it/wolfed/operation/CloneGraphOperation.java
package it.wolfed.operation;
import it.wolfed.model.PetriNetGraph;
/**
* Clone Operation.
*/
public class CloneGraphOperation extends Operation
{
PetriNetGraph firstGraph;
/**
* @param operationGraph
* @param firstGraph
* @param secondGraph
* @throws Exception
*/
public CloneGraphOperation(PetriNetGraph operationGraph, PetriNetGraph firstGraph) throws Exception
{
super(operationGraph);
this.operationGraph = (new FullMergeOperation(operationGraph, firstGraph)).getOperationGraph();
execute();
}
@Override
void process()
{
// Nothing
}
}<file_sep>/src/it/wolfed/operation/ZeroOrMoreIterationOperation.java
package it.wolfed.operation;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.TransitionVertex;
/**
* ZeroOrMoreIteration Operation
*/
public class ZeroOrMoreIterationOperation extends Operation
{
public ZeroOrMoreIterationOperation(PetriNetGraph operationGraph, PetriNetGraph iterationGraph) throws Exception
{
super(operationGraph);
this.operationGraph = (new OneOrMoreIterationOperation(operationGraph, iterationGraph)).getOperationGraph();
execute();
}
@Override
void process() throws Exception
{
TransitionVertex zeroTransition = this.operationGraph.insertTransition(null);
getOperationGraph().insertArc(null, this.operationGraph.getInitialPlaces().get(0), zeroTransition);
getOperationGraph().insertArc(null, zeroTransition, this.operationGraph.getFinalPlaces().get(0));
}
}<file_sep>/src/it/wolfed/operation/WrapGraphOperation.java
package it.wolfed.operation;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.PlaceVertex;
import it.wolfed.model.TransitionVertex;
/**
* Wrap Petri Net Graph Operation.
*/
public class WrapGraphOperation extends Operation
{
PetriNetGraph firstGraph;
/**
* @param operationGraph
* @param firstGraph
* @throws Exception
*/
public WrapGraphOperation(PetriNetGraph operationGraph, PetriNetGraph firstGraph) throws Exception
{
super(operationGraph);
this.operationGraph = (new FullMergeOperation(operationGraph, firstGraph)).getOperationGraph();
execute();
}
@Override
void process()
{
if(operationGraph.getInitialPlaces().size() > 1)
{
andSplitPattern();
}
if(operationGraph.getFinalPlaces().size() > 1)
{
andJoinPattern();
}
}
/**
* And-Split for initial places
*/
private void andSplitPattern()
{
// new initial Place i
PlaceVertex initialPlaceI = operationGraph.insertPlace(null);
initialPlaceI.setTokens(1);
// new and-split transition
TransitionVertex andSplitTransition = operationGraph.insertTransition(null);
operationGraph.insertArc(null, initialPlaceI, andSplitTransition);
// for each old initial place i_old, create an Edge (and-split, i_old)
for (PlaceVertex initialPlace : operationGraph.getInitialPlaces())
{
initialPlace.setTokens(0);
operationGraph.insertArc(null, andSplitTransition, initialPlace);
}
}
/**
* And-Join for final places
*/
private void andJoinPattern()
{
// new final place o
PlaceVertex finalPlaceO = this.operationGraph.insertPlace(null);
// new and-join transition
TransitionVertex andJoinTransition = this.operationGraph.insertTransition(null);
this.operationGraph.insertArc(null, andJoinTransition, finalPlaceO);
// for each old final palce o_old, create an Edge (o_old, and-join)
for (PlaceVertex finalPlace : this.operationGraph.getFinalPlaces())
{
this.operationGraph.insertArc(null, finalPlace, andJoinTransition);
}
}
}<file_sep>/README.md
wolfed
======
WOrkflow Light Fast EDitor<file_sep>/src/it/wolfed/operation/Operation.java
package it.wolfed.operation;
import it.wolfed.manipulation.GraphManipulation;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.Vertex;
import it.wolfed.util.Constants;
/**
* Basic Operation Class.
*
* A base class that trigger and execute all operation with some handy
* shortcut methods for all the common editing actions.
*/
abstract public class Operation
{
/**
* Holds the graph to edit.
*/
protected PetriNetGraph operationGraph;
/**
* {@link Operation} Constructor.
*
* @param operationGraph
*/
public Operation(PetriNetGraph operationGraph)
{
this.operationGraph = operationGraph;
}
/**
* Execute the specific operation process.
* @throws Exception
*/
protected void execute() throws Exception
{
operationGraph.getModel().beginUpdate();
try
{
process();
}
finally
{
operationGraph.getModel().endUpdate();
}
}
/**
* Abstract definition for process in subclass.
*/
abstract void process() throws Exception;
/**
* Return the graph if is a Graph is a valid workflow.
*
* @param graph
* @return PetriNetGraph
* @throws Exception
*/
protected PetriNetGraph getIfIsWorkFlow(PetriNetGraph graph) throws Exception
{
if (graph.isWorkFlow() == false)
{
throw new Exception("WorkFlow required! " + graph.getId() + " failed!");
}
return graph;
}
/**
* Returns current operationGraph.
*
* @return PetriNetGraph
*/
public PetriNetGraph getOperationGraph()
{
return operationGraph;
}
/**
* Returns a prefixed id per input net.
*
* @param id
* @return prefixed id
*/
protected String getPrefix(int id)
{
return Constants.OPERATION_PREFIX + id + "_";
}
/**
* Search, in the {@link Operation#operationGraph}, the equivalent vertex from another graph.
*
* @param id input graph prefix (first = 1, second = 2 etc...)
* @param sameVertex vertex to search
* @return
*/
public Vertex getEquivalentVertex(int id, Vertex sameVertex)
{
return operationGraph.getVertexById(getPrefix(id) + sameVertex.getId());
}
/**
* Remove, in {@link Operation#operationGraph}, a vertex and his edges.
*
* @param vertex
*/
protected void removeVertexAndHisEdges(Vertex vertex)
{
GraphManipulation.removeVertexAndHisEdges(operationGraph, vertex);
}
/**
* Clone, in {@link Operation#operationGraph}, all incoming edges from a vertex to another.
*
* @param from
* @param to
*/
protected void cloneIncomingEdges(Vertex from, Vertex to)
{
GraphManipulation.cloneIncomingEdges(operationGraph, from, to);
}
/**
* Clone, in {@link Operation#operationGraph}, all outgoing edges from a vertex to another.
*
* @param from
* @param to
*/
protected void cloneOutgoingEdges(Vertex from, Vertex to)
{
GraphManipulation.cloneOutgoingEdges(operationGraph, from, to);
}
/**
* Clone, in {@link Operation#operationGraph}, all edges from a vertex to another.
*
* @param from
* @param to
*/
protected void cloneEdges(Vertex from, Vertex to)
{
GraphManipulation.cloneEdges(operationGraph, from, to);
}
}<file_sep>/src/it/wolfed/operation/OneServePerTimeOperation.java
package it.wolfed.operation;
import com.mxgraph.model.mxCell;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.PlaceVertex;
import it.wolfed.model.Vertex;
/**
* OneServePerTime Operation
*/
public class OneServePerTimeOperation extends Operation
{
public OneServePerTimeOperation(PetriNetGraph operationGraph, PetriNetGraph iterationGraph) throws Exception
{
super(operationGraph);
this.operationGraph = (new IterationPatternOperation(operationGraph, iterationGraph)).getOperationGraph();
execute();
}
@Override
void process() throws Exception
{
PlaceVertex placeVertex = this.operationGraph.insertPlace(null);
Object[] initialTransitions = this.operationGraph.getOutgoingEdges(this.operationGraph.getInitialPlaces().get(0));
for (Object edgeOjb : initialTransitions)
{
mxCell edge = (mxCell) edgeOjb;
this.operationGraph.insertArc(null, placeVertex, (Vertex) edge.getTarget());
}
Object[] finalTransitions = this.operationGraph.getIncomingEdges(this.operationGraph.getFinalPlaces().get(0));
for (Object edgeOjb : finalTransitions)
{
mxCell edge = (mxCell) edgeOjb;
this.operationGraph.insertArc(null, (Vertex) edge.getSource(), placeVertex);
}
// set tokens
placeVertex.setTokens(1);
this.operationGraph.getInitialPlaces().get(0).setTokens(1);
}
}
|
c3c516a29df3612a0fd9949c3948995449d2e8f7
|
[
"Markdown",
"Java"
] | 11 |
Java
|
dewos/Wolfed
|
e1c7195aa7518a22fd2460b17117a7d4f968965a
|
46804158f585f874b5c5d85459835a26952c06ab
|
refs/heads/master
|
<repo_name>ggayan/zmq_broker_go<file_sep>/broker.go
package main
import (
"flag"
zmq "github.com/alecthomas/gozmq"
"log"
"time"
)
var (
ping_wait int
pub_address string
sub_address string
mon_address string
front_address string
back_address string
ping_channel string
ping_message string
)
func init() {
flag.IntVar(&ping_wait, "ping_wait", 60, "wait seconds between sending each ping")
flag.StringVar(&pub_address, "pub_address", "tcp://*:5556", "address to bind for publishing messages")
flag.StringVar(&sub_address, "sub_address", "tcp://*:5555", "address to bind for receiving messages")
flag.StringVar(&mon_address, "mon_address", "ipc://zmq_broker_monitor.ipc", "address to bind for monitoring messages")
flag.StringVar(&front_address, "front_address", "tcp://*:5559", "address to bind for clients")
flag.StringVar(&back_address, "back_address", "tcp://*:5560", "address to bind for workers")
flag.StringVar(&ping_channel, "ping_channel", "ping", "the channel to send ping messages")
flag.StringVar(&ping_message, "ping_message", "{\"action\": \"ping\"}", "the message to send via ping channel")
flag.Parse()
}
func main() {
ticker := time.NewTicker(time.Second * time.Duration(ping_wait))
ctx, _ := zmq.NewContext()
defer ctx.Close()
log.Println("preparing sockets...")
// setup sockets
pub, _ := ctx.NewSocket(zmq.XPUB)
sub, _ := ctx.NewSocket(zmq.XSUB)
mon, _ := ctx.NewSocket(zmq.SUB)
front, _ := ctx.NewSocket(zmq.ROUTER)
back, _ := ctx.NewSocket(zmq.DEALER)
for _, socket := range []*zmq.Socket{pub, sub, mon, front, back} {
defer socket.Close()
}
initPubSub(pub, sub)
initMonitoring(pub, mon)
initReqRepBroker(front, back)
log.Println("sockets prepared")
log.Println("starting message monitoring")
go startMonitorLoop(mon)
// give time for monitoring socket to prepare
time.Sleep(time.Second)
log.Println("starting ROUTER/DEALER broker")
go startReqRepBroker(front, back)
log.Println("starting XSUB/XPUB broker")
go zmq.Proxy(sub, pub, nil)
log.Println("starting ping messages loop")
startPingLoop(ticker, pub)
}
func initPubSub(pub, sub *zmq.Socket) {
if err := pub.Bind(pub_address); err != nil {
log.Panic(err)
}
if err := sub.Bind(sub_address); err != nil {
log.Panic(err)
}
}
func initMonitoring(pub, mon *zmq.Socket) {
if err := pub.Bind(mon_address); err != nil {
log.Panic(err)
}
mon.SetSubscribe("")
if err := mon.Connect(mon_address); err != nil {
log.Panic(err)
}
}
func initReqRepBroker(front, back *zmq.Socket) {
if err := front.Bind(front_address); err != nil {
log.Panic(err)
}
if err := back.Bind(back_address); err != nil {
log.Panic(err)
}
}
func startMonitorLoop(mon *zmq.Socket) {
for {
channel, _ := mon.Recv(0)
content, _ := mon.Recv(0)
log.Println("publishing message: \"" + string(content) + "\" on channel: \"" + string(channel) + "\"")
}
}
func startPingLoop(t *time.Ticker, pub *zmq.Socket) {
for _ = range t.C {
// log.Println("sending ping message")
pub.SendMultipart([][]byte{[]byte(ping_channel), []byte(ping_message)}, 0)
}
}
func startReqRepBroker(front, back *zmq.Socket) {
// Initialize poll set
toPoll := zmq.PollItems{
zmq.PollItem{Socket: front, Events: zmq.POLLIN},
zmq.PollItem{Socket: back, Events: zmq.POLLIN},
}
for {
_, _ = zmq.Poll(toPoll, -1)
switch {
case toPoll[0].REvents&zmq.POLLIN != 0:
parts, _ := front.RecvMultipart(0)
back.SendMultipart(parts, 0)
case toPoll[1].REvents&zmq.POLLIN != 0:
parts, _ := back.RecvMultipart(0)
front.SendMultipart(parts, 0)
}
}
}
|
82a23c00ee324dabdf644983e9997db6501379c9
|
[
"Go"
] | 1 |
Go
|
ggayan/zmq_broker_go
|
e1a5fc085e84238e389f2278cbab35f029ec3996
|
5423d66eb43ca9ca9d9fec121a030889cae92ec9
|
refs/heads/master
|
<file_sep>package com.log8430.group9.views;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
import org.json.JSONObject;
import com.log8430.group9.commands.Command;
import com.log8430.group9.commands.CommandLoader;
import com.log8430.group9.commands.CommandWatcher;
import com.log8430.group9.utils.ConnectionManager;
import com.log8430.group9.utils.Http;
/**
* Main window of the application.
*@author LOG8430 group9
*/
public class MainWindow extends JFrame implements Observer, ActionListener, TreeSelectionListener {
protected DefaultTreeModel fileSystemModel;
protected JTree tree;
protected JPanel commandPanel;
protected JButton apiSelectionButton;
protected JCheckBox autoRunCheckBox;
protected JButton clearButton;
protected ArrayList<UICommand> commands;
protected FileNode currentFile;
protected String currentAPI;
/**
* Constructor MainWindow.
* <p>
* Construct all the graphical interface and add listeners for buttons.
* </p>
*/
public MainWindow() {
this.commands = new ArrayList<>();
this.currentAPI = "server";
this.currentFile = null;
this.fileSystemModel = new DefaultTreeModel(LazyLoader.load("/", this.currentAPI));
this.setTitle("LOG8430 - groupe 09 - Option 1");
this.setSize(800, 600);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
//this.fileSystemModel.setRoot(new File(System.getProperty("user.home")));
this.tree = new JTree(this.fileSystemModel);
this.tree.addTreeSelectionListener(this);
LazyLoader loader = new LazyLoader();
tree.addTreeWillExpandListener(loader);
this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
JScrollPane treeView = new JScrollPane(this.tree);
this.apiSelectionButton = new JButton("Select an API");
this.apiSelectionButton.addActionListener(this);
JPanel westPanel = new JPanel();
westPanel.setLayout(new BoxLayout(westPanel, BoxLayout.PAGE_AXIS));
westPanel.add(treeView);
westPanel.add(this.apiSelectionButton);
this.commandPanel = new JPanel();
this.commandPanel.setLayout(new BoxLayout(commandPanel, BoxLayout.PAGE_AXIS));
CommandWatcher commandWatcher = new CommandWatcher();
commandWatcher.addObserver(this);
Thread thread = new Thread(commandWatcher);
thread.start();
this.clearButton = new JButton("Clear");
this.clearButton.addActionListener(this);
this.autoRunCheckBox = new JCheckBox("AutoRun");
JPanel optionsPanel = new JPanel();
optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.LINE_AXIS));
optionsPanel.add(this.clearButton);
optionsPanel.add(this.autoRunCheckBox);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
centerPanel.add(this.commandPanel, BorderLayout.CENTER);
centerPanel.add(optionsPanel, BorderLayout.SOUTH);
JLabel southLabel = new JLabel("<NAME> - <NAME> - <NAME>");
southLabel.setHorizontalAlignment(JLabel.CENTER);
this.getContentPane().add(westPanel, BorderLayout.WEST);
this.getContentPane().add(centerPanel, BorderLayout.CENTER);
this.getContentPane().add(southLabel, BorderLayout.SOUTH);
this.loadCommands();
}
/**
* Adds the commands to the command list.
*/
public void loadCommands() {
this.commandPanel.removeAll();
this.commands = new ArrayList<>();
CommandLoader commandLoader = new CommandLoader(CommandLoader.class.getClassLoader());
for(Command command : commandLoader.loadAllCommands()) {
UICommand uiCommand = new UICommand(command);
this.commandPanel.add(uiCommand);
this.commands.add(uiCommand);
}
this.commandPanel.revalidate();
this.commandPanel.repaint();
// to re-initialise correctly all commands and potentially auto-run them
this.setCurrentFile(this.currentFile);
}
/**
* Calls the appropriate method depending of the event source.
*
* @param event
*/
@Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == this.apiSelectionButton) {
this.selectAPI();
} else if(event.getSource() == this.clearButton) {
this.clear();
}
}
/**
* Called when the user select a file or folder on the tree view.
* Replaces the current file by the new file selected.
*
* @param event
*/
@Override
public void valueChanged(TreeSelectionEvent event) {
FileNode file = (FileNode) tree.getLastSelectedPathComponent();
if(file == null)
return;
this.setCurrentFile(file);
}
/**
* Update the current file and the current API for all commands.
* And if the autoRun is checked, executes all the commands.
*
* @param file
*/
private void setCurrentFile(FileNode file) {
this.currentFile = file;
for(UICommand command : commands) {
command.setCurrentFile(file);
command.setCurrentAPI(this.currentAPI);
if(this.autoRunCheckBox.isSelected() && command.isEnabled()) {
command.execute();
}
}
}
/**
* Clears the label of all commands.
*/
private void clear() {
for(UICommand command : commands) {
command.clear();
}
}
public void selectAPI() {
Iterator<String> listeService = ServiceNameLoader.loadServiceNameList();
ArrayList<String> buttons = new ArrayList<>();
while(listeService.hasNext()){
buttons.add(listeService.next());
}
if(buttons.size() == 0){
JOptionPane.showMessageDialog(null, "Aucune API n'est disponible", "Warning", JOptionPane.WARNING_MESSAGE);
}
else{
int returnValue = JOptionPane.showOptionDialog(null, "Select the API you want to use", "Select an API",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, buttons.toArray(), buttons.get(0));
if(returnValue >= 0)
this.currentAPI = buttons.get(returnValue);
if(!ConnectionManager.connect(this.currentAPI)) {
this.currentAPI = "server";
}
for(UICommand command : commands) {
command.setCurrentAPI(this.currentAPI);
}
this.fileSystemModel.setRoot(LazyLoader.load("/", this.currentAPI));
this.fileSystemModel.reload();
}
}
/**
* called when the watcher see changes in the commands files.
*/
@Override
public void update(Observable o, Object arg) {
this.loadCommands();
}
}
<file_sep>package com.log8430.group9.views;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.log8430.group9.utils.ConnectionManager;
import com.log8430.group9.utils.Http;
public class ServiceNameLoader {
public static Iterator<String> loadServiceNameList() {
System.out.println(Http.get(ConnectionManager.apiURL+"/command/listeService",""));
JSONArray json = new JSONArray(Http.get(ConnectionManager.apiURL+"/command/listeService",""));
ArrayList<String> liste = new ArrayList<>();
for(Object child : json){
String service = (String)child;
liste.add(service);
}
return liste.iterator();
}
}
<file_sep>package com.log8430.group9.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* Classe helper permettant d'envoyer des requรชtes HTTP et recevoir la rรฉponse de maniรจre synchrone
* Code en partie copiรฉ de Stack Overflow : http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java
* et http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests
*/
public class Http {
/**
* definition de la requette HTTP get
* @param targetURL url de la requete
* @param urlParameters parametre de la requete
* @return reponse du serveur pour la requete
*/
public static String get(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
URL url = new URL(targetURL + "?" + urlParameters);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
return request(connection);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
/**
* definition de la requete HTTP post
* @param targetURL url de la requete
* @param urlParameters parametres de la requete
* @return la reponse du serveur pour la requete
*/
public static String post(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setDoOutput(true);
//Send request
//urlParameters = URLEncoder.encode(urlParameters,"UTF-8");
OutputStream wr = connection.getOutputStream();
wr.write(urlParameters.getBytes("UTF-8"));
wr.close();
return request(connection);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
/**
* fontion d'envoi des requetes HTTP
* @param connection requete a emettre
* @return reponse du serveur pour la requete
*/
public static String request(HttpURLConnection connection) {
try {
InputStream is;
if (connection.getResponseCode() >= 400) {
is = connection.getErrorStream();
} else {
is = connection.getInputStream();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
}
<file_sep>package com.log8430.group9.tests;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JPanel;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.log8430.group9.commands.Command;
import com.log8430.group9.commands.CommandLoader;
import com.log8430.group9.views.FileNode;
import com.log8430.group9.views.LazyLoader;
import com.log8430.group9.views.UICommand;
public class ClientTest{
private LazyLoader fileLoader = null;
private Command mockCommandFile;
private Command mockCommandDir;
private Command mockCommandFD;
private FileNode fileTest;
private FileNode dossierTest;
private CommandLoader commandLoader;
private ArrayList<UICommand> UICommandsList = new ArrayList<>();
@Before
public void setUp() throws Exception {
//creation des mock compatible fichier, dossier, les deux
mockCommandFile = EasyMock.createMock(Command.class);
mockCommandDir = EasyMock.createMock(Command.class);
mockCommandFD = EasyMock.createMock(Command.class);
ArrayList<Command> commands = new ArrayList<>();
commands.add(mockCommandFile);
commands.add(mockCommandDir);
commands.add(mockCommandFD);
//redefinition du Loader pour fournir les mocks
commandLoader = new CommandLoader(CommandLoader.class.getClassLoader()) {
@Override
public ArrayList<Command> loadAllCommands() {
return commands;
}
};
//creation des elements de tests
this.fileTest = new FileNode("dossierTest/fichierTest", "fichierTest", "dossierTest/fichierTest", false, "server");
this.dossierTest = new FileNode("dossierTest", "dossierTest", "dossierTest", true, "server");
}
@Test
public void loadFile(){
FileNode noeud = LazyLoader.load("root", "server");
ArrayList<String> childrenList = new ArrayList<>();
for(FileNode enfant : noeud.getChilden()){
childrenList.add(enfant.toString());
}
ArrayList<String> expectedChildren = new ArrayList<>();
expectedChildren.add("code");
expectedChildren.add("image");
expectedChildren.add("polymtl");
expectedChildren.add("article.pdf");
Assert.assertEquals("le fichier chargรฉ est incorrect","root",noeud.getPath());
Assert.assertTrue("la liste des enfants est incorrecte", childrenList.containsAll(expectedChildren));
}
//emulation de la creation de composant graphique des commandes avec la technologie SWING
public void createMockUICommand(ArrayList<Command> commands){
for(Command command : commands){
UICommandsList.add(new UICommand(command));
}
}
@Test
public void testNumberOfCommands() {
int retour = 3;
createMockUICommand(commandLoader.loadAllCommands());
Assert.assertEquals("La valeur retournee est invalide", retour, UICommandsList.size());
}
/**
* test si les commandes sont actives ou non ainsi que le fonctionnement de l'execution pour un fichier
*/
@Test
public void testExecutionFOnFile(){
EasyMock.expect(mockCommandFile.fileCompatible()).andReturn(true);
EasyMock.expect(mockCommandFile.getName()).andReturn("commandFile");
EasyMock.expect(mockCommandFile.execute(fileTest.getId(),fileTest.getAPI())).andReturn("fichierTest");
EasyMock.expect(mockCommandDir.fileCompatible()).andReturn(false);
EasyMock.expect(mockCommandDir.getName()).andReturn("commandDir");
EasyMock.expect(mockCommandDir.execute(fileTest.getId(),fileTest.getAPI())).andReturn("dossierTest");
EasyMock.expect(mockCommandFD.fileCompatible()).andReturn(true);
EasyMock.expect(mockCommandFD.getName()).andReturn("commandFD");
EasyMock.expect(mockCommandFD.execute(fileTest.getId(),fileTest.getAPI())).andReturn("fichierTest");
EasyMock.replay(mockCommandFile);
EasyMock.replay(mockCommandDir);
EasyMock.replay(mockCommandFD);
createMockUICommand(commandLoader.loadAllCommands());
ArrayList<Boolean> returnedValues = new ArrayList<>();
returnedValues.add(Boolean.TRUE);
returnedValues.add(Boolean.FALSE);
returnedValues.add(Boolean.TRUE);
for(int i = 0; i< UICommandsList.size();i++){
UICommandsList.get(i).setCurrentFile(fileTest);
UICommandsList.get(i).setCurrentAPI("server");
Assert.assertEquals("La commande n'a pas le comportement adequat ", returnedValues.get(i), UICommandsList.get(i).getButton().isEnabled());
UICommandsList.get(i).execute();
if(UICommandsList.get(i).getButton().isEnabled()){
Assert.assertEquals("La valeur retournรฉ est fausse", "fichierTest", UICommandsList.get(i).getCommandResult());
}
}
}
/**
* test si les commandes sont actives ou non ainsi que le fonctionnement de l'execution pour un dossier
*/
@Test
public void testExecutionOnFolder(){
EasyMock.expect(mockCommandFile.folderCompatible()).andReturn(false);
EasyMock.expect(mockCommandFile.getName()).andReturn("commandFile");
EasyMock.expect(mockCommandFile.execute(dossierTest.getId(),dossierTest.getAPI())).andReturn("fichierTest");
EasyMock.expect(mockCommandDir.folderCompatible()).andReturn(true);
EasyMock.expect(mockCommandDir.getName()).andReturn("commandDir");
EasyMock.expect(mockCommandDir.execute(dossierTest.getId(),dossierTest.getAPI())).andReturn("dossierTest");
EasyMock.expect(mockCommandFD.folderCompatible()).andReturn(true);
EasyMock.expect(mockCommandFD.getName()).andReturn("commandFD");
EasyMock.expect(mockCommandFD.execute(dossierTest.getId(),dossierTest.getAPI())).andReturn("dossierTest");
EasyMock.replay(mockCommandFile);
EasyMock.replay(mockCommandDir);
EasyMock.replay(mockCommandFD);
createMockUICommand(commandLoader.loadAllCommands());
ArrayList<Boolean> returnedValues = new ArrayList<>();
returnedValues.add(Boolean.FALSE);
returnedValues.add(Boolean.TRUE);
returnedValues.add(Boolean.TRUE);
for(int i = 0; i< 1;i++){
UICommandsList.get(i).setCurrentFile(dossierTest);
UICommandsList.get(i).setCurrentAPI("server");
Assert.assertEquals("La commande n'a pas le comportement adequat ", returnedValues.get(i), UICommandsList.get(i).getButton().isEnabled());
UICommandsList.get(i).execute();
if(UICommandsList.get(i).getButton().isEnabled()){
Assert.assertEquals("La valeur retourn๏ฟฝ est fausse", "dossierTest", UICommandsList.get(i).getCommandResult());
}
}
}
}
<file_sep>package com.log8430.group9.api;
import java.net.HttpURLConnection;
import org.json.JSONObject;
import com.log8430.group9.models.APIFile;
/**
* API du service de gestion de fichier GoogleDrive
* @author LOG8430 group9
*
*/
public class APIGoogleDrive extends AbstractAPI implements API {
/**
* clรฉ d'identitรฉ du serveur pour la connexion
*/
private static String apiKey = "21850492540-vrduvcqo1l2airu6u1d02eivddcip48u.apps.googleusercontent.com";
/**
* clรฉ d'authentification du serveur pour la connexion
*/
private static String apiSecret = "<KEY>";
@Override
public String getName() {
return "googledrive";
}
@Override
public boolean isConnected() {
if(this.token == null) {
return false;
} else {
JSONObject json = new JSONObject(this.get("https://www.googleapis.com/drive/v2/files/root/children",""));
if(json.has("items")) {
return true;
} else {
return false;
}
}
}
@Override
public void setAccessToken(String token) {
this.token = token;
}
@Override
public String getAccessToken() {
return this.token;
}
@Override
public void askForToken(String code) {
this.token = null;
String result = this.post("https://accounts.google.com/o/oauth2/token", "grant_type=authorization_code"
+ "&client_id="+apiKey+"&client_secret="+apiSecret
+ "&redirect_uri=http://localhost:8080/api/code?api=googledrive"
+ "&code="+code);
JSONObject json = new JSONObject(result);
if(json.has("access_token")) {
this.token = json.getString("access_token");
}
}
@Override
public void addConnectionProperties(HttpURLConnection connection) {
if(this.token != null) {
connection.setRequestProperty ("Authorization", "Bearer " + this.token);
}
}
@Override
public APIFile metadata(String id) {
String result;
JSONObject json;
boolean isDir;
APIFile apiFile;
if(id.equals("/")) {
apiFile = new APIFile("root", "/", "/", true);
result = this.get("https://www.googleapis.com/drive/v2/files/root/children", "");
} else {
result = this.get("https://www.googleapis.com/drive/v2/files/"+id, "");
json = new JSONObject(result);
isDir = false;
if(json.optString("mimeType") == "application/vnd.google-apps.folder")
isDir = true;
apiFile = new APIFile(id, json.getString("title"), "Not supported in Google Drive", isDir);
// Get the children
result = this.get("https://www.googleapis.com/drive/v2/files/"+id+"/children", "");
}
json = new JSONObject(result);
if(json.optJSONArray("items") != null) {
for(Object obj : json.getJSONArray("items")) {
JSONObject jsonChild = (JSONObject) obj;
String childId = jsonChild.getString("id");
result = this.get("https://www.googleapis.com/drive/v2/files/"+childId, "");
jsonChild = new JSONObject(result);
isDir = false;
if(jsonChild.optString("mimeType").equals("application/vnd.google-apps.folder"))
isDir = true;
apiFile.addChild(new APIFile(childId, jsonChild.getString("title"), "", isDir));
}
}
return apiFile;
}
}
<file_sep>package com.log8430.group9.api;
import java.net.HttpURLConnection;
import com.log8430.group9.models.APIFile;
/**
* Interface decrivant la structure des API des services de gestion de fichier
* @author LOG8430 group9
*
*/
public interface API {
/**
* recuperation du nom du service de gestion de fichier defini par l'API
* @return nom du service
*/
public String getName();
/**
* determine si le serveur est connรฉctรฉ au service
* @return vrai si le serveur est connectรฉ au service
*/
public boolean isConnected();
/**
* accesseur en ecriture du token d'authentification au service
* @param token d'authentification au service
*/
public void setAccessToken(String token);
/**
* accesseur en lecture du token d'authentification au service
* @return le token d'authentification
*/
public String getAccessToken();
/**
* fonction permettant de demander au service de gestion de fichier distant un token d'authentification
* @param code parametre de la requete http de connection au service
*/
public void askForToken(String code);
/**
* permet la recuperation de l'arbre de fichier a partir d'un id decrivant le nom du fichier/dossier a recuperer
* @param id identificateur du dossier a recuperer dans l'arbre de fichier
* @return structure de donnรฉe decrivant un fichier/dossier
*/
public APIFile metadata(String id);
}
<file_sep>package com.log8430.group9.api;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class ServiceLoader extends ClassLoader{
public ServiceLoader(ClassLoader parent) {
super(parent);
}
/**
* Load a class of the commands folder.
*
* @return a Class of the commands folder
*/
public Class loadClass(String name) throws ClassNotFoundException {
if(!name.contains("API") || name.contains("com.log8430.group9.models") || name.equals("com.log8430.group9.api.API") || name.equals("com.log8430.group9.api.AbstractAPI") || name.equals("com.log8430.group9.api.APIFactory")) {
return super.loadClass(name);
}
try {
InputStream input = new FileInputStream("Services/"+name+".class");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int data = input.read();
while(data != -1){
buffer.write(data);
data = input.read();
}
input.close();
byte[] classData = buffer.toByteArray();
return this.defineClass("com.log8430.group9.api."+name, classData, 0, classData.length);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* Create an instance of a API class loaded dynamically.
*
* @param name the file name of the service without extension
* @return an instance of the service Class
*/
public API loadService(String name) {
try {
Class serviceClass = this.loadClass(name);
return (API) serviceClass.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Loads all services located in the Services directory.
*
* @return a list of services instances
*/
public ArrayList<API> loadAllServices() {
ArrayList<API> services = new ArrayList<>();
String filePath = System.getProperty("user.dir")+"/Services";
filePath = filePath.replace("\\", "\\\\");
File commandFolder = new File(filePath);
if(commandFolder.listFiles() != null){
System.out.println("nombre de sousfichier : " + commandFolder.listFiles().length);
for(File commandClassFile : commandFolder.listFiles()) {
if(commandClassFile.getName().contains("API")) {
services.add(this.loadService(commandClassFile.getName().replaceFirst("[.][^.]+$", "")));
}
}
}
return services;
}
}
<file_sep>package com.log8430.group9.main;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import com.log8430.group9.views.MainWindow;
/**
* classe principale de l'application
* @author LOG8430 group9
*
*/
public class Main {
/**
* methode main pour lancer l'application
* @param args
*/
public static void main(String[] args) {
MainWindow window = new MainWindow();
window.setVisible(true);
}
}
<file_sep>package com.log8430.group9.models;
import java.io.File;
import java.util.ArrayList;
/**
* Structure de donnรฉe definissant un fichier
* @author LOG8430 group9
*
*/
public class APIFile {
/**
* identificateur du fichier
*/
private String id;
/**
* nom du fichier
*/
private String name;
/**
* chemin d'acces au fichier
*/
private String path;
/**
* liste des fichiers enfant du fichier courant
*/
private ArrayList<APIFile> children;
/**
* boolean spรฉcifiant si le fichier est un dossier
*/
private boolean directory;
/**
* constructeur de la strucuture
* @param id : identificateur du fichier
* @param name nom du fichier
* @param path chemin d'acces
* @param directory vrai si le fichier est un dossier
*/
public APIFile(String id, String name, String path, boolean directory) {
this.id = id;
this.name = name;
this.path = path;
this.directory = directory;
this.children = new ArrayList<>();
}
/**
* constructeur ne sepcifiant que le nom du fichier
* @param name nom du fichier
*/
public APIFile(String name) {
this("", name, "", false);
}
/**
* constructeur permettant de construire la structure a partir d'un fichier et d'un profondeur pour la recherche de sous-dossier/fichier
* @param file : fichier pour construire la structure
* @param depth profondeur de recherche pour les sous-dossiers/fichiers du fichier courant
*/
public APIFile(File file, int depth) {
this.name = file.getName();
String systemDir = System.getProperty("user.dir");
systemDir = systemDir.replace("\\", "\\\\");
this.path = file.getPath().replaceFirst(systemDir+"/root/?", "/");
this.id = this.path;
this.directory = file.isDirectory();
if(depth > 0 && this.directory) {
this.children = new ArrayList<APIFile>();
for(File child : file.listFiles()) {
this.children.add(new APIFile(child, depth-1));
}
} else {
this.children = null;
}
}
/**
* accesseur en lecture de l'identificateur
* @return l'identificateur du fichier
*/
public String getId() {
return id;
}
/**
* accesseur en lecture du nom du fichier
* @return nom du fichier
*/
public String getName() {
return name;
}
/**
* accesseur en lecture du chemin d'acces
* @return chemin d'acces du fichier
*/
public String getPath() {
return path;
}
/**
* accesseur en lecture de la liste des sous-dossiers/fichiers
* @return liste des sous-dossiers/fichiers du fichier
*/
public ArrayList<APIFile> getChildren() {
return children;
}
/**
* accesseur du parametre directory
* @return vrai si le fichier est un dossier
*/
public boolean isDirectory() {
return directory;
}
/**
* accesseur en ecriture du nom de fichier
* @param name nom du fichier
*/
public void setName(String name) {
this.name = name;
}
/**
* fonction d'ajout a la liste des sous-dossiers/fichiers
* @param child fichier a ajouter a la liste des sous-dossiers/fichiers du fichier courant
*/
public void addChild(APIFile child) {
this.children.add(child);
}
}
<file_sep># LOG8430-TP3 : Mise en Oeuvre d'une Architecture Logicielle - Applications distribuรฉes
## Option 1 : Gestion de fichier
<NAME> - <NAME> - <NAME>
Ce logiciel permet d'exรฉcuter des commandes sur des dossiers et des fichiers. Une arborescence permet ร l'utilisateur de naviguer ร travers les dossiers et les fichiers. Pour pouvoir exรฉcuter une commande l'utilisateur doit prรฉalablement sรฉlectionner un dossier ou un fichier. Initialement, la racine sรฉlectionnรฉe par le logiciel et le rรฉpertoire "Fichier" du serveur. Enfin via l'interface graphique, l'utilisateur peut choisir une autre racine pour l'arborescence entre le serveur, son compte Dropbox ou son compte Google Drive.
Certaines commandes ne peuvent รชtre exรฉcuter que pour des fichiers ou des dossiers. Dans ce cas, l'interface graphique s'adapte et certaines commandes sont "grisรฉes" et dรฉsactivรฉes. Si l'option "AutoRun" est activรฉ, l'exรฉcution des commandes accessibles est automatique dรจs la sรฉlection d'un dossier ou d'un fichier. Enfin, un bouton clear permet d'effacer les diffรฉrents rรฉsultats des commandes.
Les commandes sont chargรฉs automatiquement au lancement du serveur. L'utilisateur peut utiliser l'interface Command.java afin de concevoir ses propres commandes.
Exemple d'une commande retournant le nom d'un fichier :
import java.io.File;
public class FileNameCommand implements Command {
// mรฉthode permettant de dรฉfinir la commande (rรฉsultat de la commande)
@Override
public String execute(File file) {
return file.getName();
}
// mรฉthode dรฉfinissant si la commande est exรฉcutable pour un fichier
@Override
public boolean fileCompatible() {
return true;
}
// mรฉthode dรฉfinissant si la commande est exรฉcutable pour un dossier
@Override
public boolean folderCompatible() {
return false;
}
// mรฉthode dรฉfinissant le nom de la commande apparaissant sur l'inteface graphique
@Override
public String getName() {
return "File name";
}
}
### Have Fun !
<file_sep>package com.log8430.group9.controllers;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.log8430.group9.api.API;
import com.log8430.group9.api.APIFactory;
import com.log8430.group9.models.APIFile;
/**
* Controller pour les commandes utilisateur
* @author LOG8430 group9
*/
@RestController
public class CommandController {
/**
* recuperation du fichier selectionnรฉ par l'utilisateur pour l'execution de la commande
* @param apiName nom du service de gestion de fichier
* @param id identificateur du fichier a charger
* @return strucuture de donnรฉe decrivant le fichier
*/
@RequestMapping("/command/metadata")
public APIFile tree(
@RequestParam(value="api", defaultValue="server") String apiName,
@RequestParam(value="id") String id) {
API api = APIFactory.getInstance().getAPI(apiName);
return api.metadata(id);
}
@RequestMapping("/command/listeService")
public Iterator<String> liste(){
return APIFactory.getInstance().getListeNomsAPI();
}
}
<file_sep>import collections
Antenna = collections.namedtuple('Antenna', ['x', 'y', 'r'])
Point = collections.namedtuple('Point', ['x', 'y'])
import math
# distance (squared) between two positions
def dist2(p1, p2) :
dx = p1.x - p2.x
dy = p1.y - p2.y
return dx * dx + dy * dy
# checking that all antennas are covered
def isCorrect(positions, antennas) :
return all([
any([
dist2(p,a) <= a.r * a.r for a in antennas
]) for p in positions
])
def cost(antennas, K, C) :
return sum([ (K + C * a.r * a.r) for a in antennas ])
# A* state-space search
# for some uncovered positions,
# we recursively search for the best antennas
def searchAStar(positions, K, C) :
if len(positions) == 0 : # if no positions are left
return ( 0, [] ) # no antenna, and no cost needed
if len(positions) == 1 :
p = positions[0];
return ( K + C, [Antenna(p.x,p.y,1)])
# bounds of the positions
minX = min([ p.x for p in positions ])
maxX = max([ p.x for p in positions ])
minY = min([ p.y for p in positions ])
maxY = max([ p.y for p in positions ])
solutions = {};
# for every antenna position
for x in range(minX,maxX+1) :
for y in range(minY,maxY+1) :
antennaPos = Point(x,y)
# we search the min/max radiuses
distances2 = [ dist2( p, antennaPos ) for p in positions ];
maxR = int(math.ceil(math.sqrt(max(distances2))))
minR = max( 1, int(math.ceil(math.sqrt(min(distances2)))) )
# we try all radiuses
for r in range( minR, maxR + 1 ) :
# positions covered by the antenna
covPos = tuple([
positions[i] for i in range(len(positions))
if distances2[i] <= r*r
]);
# if no positions are covered, ignore the antenna
if len(covPos) == 0 : continue
# compare the solution to other sets found
if not covPos in solutions or solutions[covPos].r > r :
solutions[covPos] = Antenna(x,y,r)
# sorting all solutions
solutions = [ (covPos,solutions[covPos]) for covPos in solutions ];
solutions.sort(key = lambda s :
K + C*s[1].r*s[1].r # antenna cost
+ K * (len(positions) - len(s[0])) # heuristic (K * nb of pos left)
)
bestCost = float('inf')
bestSolution = [];
for s in solutions :
a = s[1]
uncovPos = [ # positions uncovered by the antenna
p for p in positions
if dist2(p,a) > a.r*a.r
]
result = searchAStar(uncovPos,K,C)
c = result[0] + K + C*a.r*a.r;
if c < bestCost :
bestCost = c
bestSolution = result[1] + [a]
return (bestCost, bestSolution);
def search(positions, K, C) :
# converting tuples to namedTuples
positions = [ Point(p[0],p[1]) for p in positions ]
solution = searchAStar( positions, K, C )[1]
#print("is correct : " + str(isCorrect(positions, solution)))
#print("cost is " + str(cost(solution,K,C)));
return [(a.x,a.y,a.r) for a in solution];<file_sep>package com.log8430.group9.commands.usercommands;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.json.JSONException;
import org.json.JSONObject;
import com.log8430.group9.commands.Command;
import com.log8430.group9.utils.Http;
public class AbsolutePathCommand implements Command {
@Override
public String execute(String id, String api) {
JSONObject json;
try {
json = new JSONObject(Http.get(urlAPI+"/command/metadata", "api="+api+"&id="+URLEncoder.encode(id,"UTF-8")));
return json.getString("path");
} catch (JSONException | UnsupportedEncodingException e) {
return "Command Failed";
}
}
@Override
public boolean fileCompatible() {
return true;
}
@Override
public boolean folderCompatible() {
return true;
}
@Override
public String getName() {
return "Absolute Path";
}
}
<file_sep>package com.log8430.group9.views;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.tree.TreeNode;
import org.json.JSONObject;
import com.log8430.group9.utils.Http;
/**
* This class is used to have a good display in the JTree.
* @author LOG8430 group9
*
*/
public class FileNode implements TreeNode {
/**
* identificateur du noeud
*/
private String id;
/**
* nom du nom
*/
private String name;
/**
* chemin d'acces au fichier du noeud
*/
private String path;
/**
* liste des noeuds enfants
*/
private ArrayList<FileNode> children;
/**
* boolean specifiant si le noeud represente un dossier
*/
private boolean directory;
/**
* nom du service de gestion de fichier
*/
private String api;
/**
* constructeur du noeud
* @param id identificateur du fichier
* @param filename nom du fichier qui sera egalement le nom du noeud
* @param path chemin d'acces au fichier representรฉ par le noeud
* @param directory definition si le noeud aura des enfants
* @param api nom du service de gestion de fichier
*/
public FileNode(String id, String filename, String path, boolean directory, String api) {
this.id = id;
this.name = filename;
this.path = path;
this.directory = directory;
this.api = api;
this.children = new ArrayList<>();
}
/**
* Replace the default File.toString() method which returns the absolute path.
*
* @return the file/folder name.
*/
@Override
public String toString() {
return this.name;
}
@Override
public TreeNode getChildAt(int childIndex) {
return this.children.get(childIndex);
}
@Override
public int getChildCount() {
return this.children.size();
}
@Override
public int getIndex(TreeNode node) {
return -1;
}
@Override
public boolean getAllowsChildren() {
return true;
}
@Override
public boolean isLeaf() {
return !this.directory;
}
@Override
public Enumeration children() {
return this.children();
}
@Override
public TreeNode getParent() {
return null;
}
/**
* accesseur en lecture du chemin d'acces au fichier
* @return le chemin d'acces au fichier
*/
public String getPath() {
return path;
}
/**
* fonction d'ajout de noeud enfant au noeud courant
* @param child le noeud a ajouter
*/
public void addChild(FileNode child) {
this.children.add(child);
}
/**
* accesseur en lecture au nom de l'API du service de gestion de fichier
* @return le nom de l'API
*/
public String getAPI() {
return this.api;
}
/**
* accesseur en lecture de la liste des noeuds enfants
* @return
*/
public ArrayList<FileNode> getChilden() {
return this.children;
}
/**
* accesseur en ecriture de la liste des noeuds enfants
* @param children liste des noeuds enfants
*/
public void setChildren(ArrayList<FileNode> children) {
this.children = children;
}
/**
* accesseur en lecture de l'identificateur du noeud
* @return identificateur du noeud
*/
public String getId() {
return this.id;
}
}
<file_sep>package com.log8430.group9.commands;
import java.io.File;
import java.util.HashMap;
import java.util.Observable;
/**
* Watches the commands folder and when a file is added, removed or changed,
* tells the window to reload all commands.
*
*/
public class CommandWatcher extends Observable implements Runnable {
protected HashMap<String,Long> files;
public CommandWatcher() {
this.init();
}
/**
* Reset the map and save the current last modification date of the commands files.
*/
public void init() {
this.files = new HashMap<>();
File commandsDir = new File("commands");
if(commandsDir.listFiles() != null) {
for(File file : commandsDir.listFiles()) {
this.files.put(file.getName(), file.lastModified());
}
}
}
/**
* Watch the folder in another thread.
* Checks the number of files and the last modification date of files.
*
* Tells the window to reload commands in case of change.
*/
@Override
public void run() {
while(true) {
File commandsDir = new File("commands");
File[] commandsFile = commandsDir.listFiles();
if(commandsFile != null) {
if(commandsFile.length != files.size()) {
this.setChanged();
this.notifyObservers();
this.init();
} else {
for(File file : commandsFile) {
if(this.files.get(file.getName()) != file.lastModified()) {
this.setChanged();
this.notifyObservers();
this.init();
break;
}
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
<file_sep>
import collections
Antenna = collections.namedtuple('Antenna', ['x', 'y', 'r'])
Point = collections.namedtuple('Point', ['x', 'y'])
from random import randint # random int between two ints (included)
import math
# distance (squared) between a position and an antenna
def dist2(p, a) :
dx = p[0] - a[0]
dy = p[1] - a[1]
return dx * dx + dy * dy
# returns the index of the nearest antenna from a position
def getNearest(pos, antennas) :
return min(range(len(antennas)), # TODO : xrange ?
key=lambda a : dist2(pos,antennas[a]))
# checking that all antennas are covered
def isCorrect(positions, antennas) :
return all([
any([
dist2(p,a) <= a[2] * a[2] for a in antennas
]) for p in positions
])
def cost(antennas, K, C) :
return sum([ (K + C * a[2] * a[2]) for a in antennas ])
# returns an antenna covering all the positions
def baryCenter(posList) :
# TODO : reduce instead
xCenter = sum([p.x for p in posList]) / len(posList)
yCenter = sum([p.y for p in posList]) / len(posList)
xCenter = int(xCenter); yCenter = int(yCenter);
rMax = math.sqrt(max([ dist2(p, Antenna(xCenter,yCenter,1)) for p in posList ]))
rMax = max(1, int(math.ceil(rMax)));
return Antenna(xCenter,yCenter,rMax);
# gets the circumcircle of 3 points
# (be careful when rounding to integers)
def circumCenter(p1,p2,p3) :
ax = p1.x; ay = p1.y;
bx = p2.x; by = p2.y;
cx = p3.x; cy = p3.y;
d = 2*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by));
# is the triangle obtuse ?
obtuse1 = (bx-ax)*(cx-ax) + (by-ay)*(cy-ay) < 0;
obtuse2 = (ax-bx)*(cx-bx) + (ay-by)*(cy-by) < 0;
obtuse3 = (bx-cx)*(ax-cx) + (by-cy)*(ay-cy) < 0;
if d == 0 or obtuse1 or obtuse2 or obtuse3 : # all points are aligned
# finding the 2 most far appart points
d1 = dist2(p1,p2)
d2 = dist2(p1,p3)
d3 = dist2(p2,p3)
if d1 <= d3 and d2 <= d3 :
x = int((p2.x+p3.x)/2)
y = int((p2.y+p3.y)/2)
a = Point(x,y)
r = int(math.ceil(math.sqrt(max([ dist2(p,a) for p in [p1, p2, p3]]))))
return Antenna(x,y,r)
elif d1 <= d2 and d3 <= d2 :
x = int((p1.x+p3.x)/2)
y = int((p1.y+p3.y)/2)
a = Point(x,y)
r = int(math.ceil(math.sqrt(max([ dist2(p,a) for p in [p1, p2, p3]]))))
return Antenna(x,y,r)
elif d2 <= d1 and d3 <= d1 :
x = int((p2.x+p1.x)/2)
y = int((p2.y+p1.y)/2)
a = Point(x,y)
r = int(math.ceil(math.sqrt(max([ dist2(p,a) for p in [p1, p2, p3]]))))
return Antenna(x,y,r)
x = ((ax*ax + ay*ay)*(by-cy)+(bx*bx+by*by)*(cy-ay) + (cx*cx+cy*cy)*(ay-by))/d;
y = ((ax*ax + ay*ay)*(cx-bx)+(bx*bx+by*by)*(ax-cx) + (cx*cx+cy*cy)*(bx-ax))/d;
x = int(x); y = int(y);
a = Point(x,y);
r = int(math.ceil(math.sqrt(max([ dist2(p,a) for p in [p1, p2, p3]]))))
return Antenna(x,y,r);
# returns an antenna covering all the positions, using :
# https://en.wikipedia.org/wiki/Smallest-circle_problem
def covCenter(posList) :
n = len(posList);
if(n >= 3) :
bestAntenna = None;
bestR = float('inf')
for i1 in range(0,n) :
p1 = posList[i1];
for i2 in range(i1+1,n) :
p2 = posList[i2];
for i3 in range(i2+1,n) :
p3 = posList[i3];
a = circumCenter(p1,p2,p3);
if a.r < bestR and all([dist2(a,p) <= a.r*a.r for p in posList]) :
bestR = a.r;
bestAntenna = a;
return bestAntenna;
elif(len(posList) == 2) :
p1 = posList[0];
p2 = posList[1];
x = int((p1.x+p2.x)/2)
y = int((p1.y+p2.y)/2)
a = Point(x,y)
r = int(math.ceil(math.sqrt(max([ dist2(p,a) for p in [p1, p2]]))))
return Antenna( x, y, r );
elif(len(posList) == 1) :
return Antenna( posList[0].x, posList[0].y, 1 )
# Based on the K-Mean algorithm (random start, and hill-climbing)
def search(positions, K, C) :
# converting tuples to namedTuples
positions = [ Point(p[0],p[1]) for p in positions ]
# bounds of the positions
minX = min([ p.x for p in positions ])
maxX = max([ p.x for p in positions ])
minY = min([ p.y for p in positions ])
maxY = max([ p.y for p in positions ])
# best solution found (will be updated)
bestSolution = []
bestCost = float('inf')
for randomStart in range(10 * len(positions)) :
nbAntenna = randint(1, len(positions)) # random number of antennas
antennas = [ # initializing the antennas at random positions
Antenna(randint(minX,maxX), randint(minY,maxY), 1)
for i in range(nbAntenna)
]
# each antenna is a cluster
# we move them until they are the centers
# of their covered positions
stabilized = False # clusters have stabilized
while not stabilized :
# getting the closest antenna (cluster) from each position
clusters = [ getNearest(p,antennas) for p in positions ]
# getting the list of positions from each antenna
coveredPos = [ [] for _ in antennas ]
for i in range(len(clusters)) :
coveredPos[clusters[i]].append(i)
# for each antenna, the new position is the center
# of its covered antennas
stabilized = True # no antenna has moved
for i in range(nbAntenna) :
posList = [ positions[p] for p in coveredPos[i] ];
a = antennas[i]
if len(posList) == 0 :
antennas[i] = Antenna(a.x,a.y,-1) # unused antenna
else :
c = covCenter(posList);
if c.x != a.x or c.y != a.y or c.r != a.r :
stabilized = False
antennas[i] = c
# if final optimisation, trying to move antennas
# around their positions (-1,+1) to reduce radiuses
if stabilized :
for i in range(nbAntenna) :
posList = [ positions[p] for p in coveredPos[i] ];
a = antennas[i]
if len(posList) > 0 and a.r > 1 :
for dx in range(-2,2+1) :
for dy in range(-2,2+1) :
a2 = Antenna(a.x+dx,a.y+dy,a.r-1);
if isCorrect(posList,[a2]) :
antennas[i] = a2
# removing the unused antennas
antennas = [a for a in antennas if a.r >= 0]
c = cost(antennas,K,C)
if c < bestCost :
bestSolution = antennas
bestCost = c
return [(a.x,a.y,a.r) for a in bestSolution]<file_sep>package com.log8430.group9.controllers;
import java.io.File;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.log8430.group9.api.API;
import com.log8430.group9.api.APIDropbox;
import com.log8430.group9.api.APIFactory;
/**
* controller pour les requetes avec les services de gestion de fichier
* @author LOG8430 group9
*
*/
@RestController
public class APIController {
/**
* Cette url est appelรฉe automatiquement par dropbow une fois que l'utilisateur a autorisรฉ l'application.
* Le code fourni permet d'obtenir un token d'accรจs au compte de l'utilisateur.
* Le retour de cette url n'est pas du JSON mais un texte qui est affichรฉ ร l'utilisateur dans son navigateur.
*
* @param code parametre de la requete
* @param apiName nom du service de gestion de fichier
* @return Un message affichรฉ dans le navigateur de l'utilisateur
*/
@RequestMapping("/api/code")
public String code(
@RequestParam(value="api") String apiName,
@RequestParam(value="code") String code) {
API api = APIFactory.getInstance().getAPI(apiName);
api.askForToken(code);
return "Done. You can now return to the application.";
}
/**
* URL pour l'authentification au service de gestion de fichier
* @param apiName nom du service
* @param token jeton d'authentification
* @return Structure contenant l'etat de la connexion et le jeton d'authentification au service
*/
@RequestMapping("/api/auth")
public String auth(
@RequestParam(value="api") String apiName,
@RequestParam(value="token") String token) {
API api = APIFactory.getInstance().getAPI(apiName);
api.setAccessToken(token);
return "{\"connected\": \""+api.isConnected()+"\", \"token\": \""+api.getAccessToken()+"\"}";
}
/**
* recupere l'etat de la connexion au service
* @param apiName nom du service
* @return l'etat de la connexion ainsi que le jeton d'authentification
*/
@RequestMapping("/api/is_connected")
public String isConnected(@RequestParam(value="api", defaultValue="server") String apiName) {
API api = APIFactory.getInstance().getAPI(apiName);
return "{\"connected\": \""+api.isConnected()+"\", \"token\": \""+api.getAccessToken()+"\"}";
}
}
<file_sep>package com.log8430.group9.api;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
/**
* Liste l'ensemble des APIs des services de gestion de fichier gerer par le serveur
* pattern singleton avec systeme de changement comportemental
* @author Alexandre
*
*/
public class APIFactory{
/**
* instance unique de la classe APIFactory
*/
protected static APIFactory instance = null;
/**
* liste des APIs accessibles par la systeme
*/
protected HashMap<String, API> listeAPI = new HashMap<>();
/**
* retourne l'instance de l'API relative au service de gestion de fichier demandรฉ
* @param apiName : nom du service de fichier demandรฉ
* @return l'API du service de gestion de fichier
*/
protected APIFactory(){
this.loadServices();
}
/**
*
* @param apiName
* @return
*/
public API getAPI(String apiName) {
API api = listeAPI.get(apiName);
if(api == null){
api = listeAPI.get("server");
}
return api;
}
public static APIFactory getInstance(){
if(instance == null){
instance = new APIFactory();
}
return instance;
}
/**
* fonction permettant d'ajouter un service de fichier a la liste disponible
* @param api classe implementant l'API du service
* @param nomAPI nom du service
*/
public void addAPI(API api, String nomAPI){
listeAPI.put(nomAPI, api);
}
/**
* permet la recuperation de la liste des noms des services
* @return la liste des noms des service de gestion de fichier
*/
public Iterator<String> getListeNomsAPI(){
return listeAPI.keySet().iterator();
}
/**
* fonction demandant la recuperation de tout les services gestion de fichiers disponible
*/
protected void loadServices() {
listeAPI.clear();
ServiceLoader serviceLoader = new ServiceLoader(ServiceLoader.class.getClassLoader());
for(API service :serviceLoader.loadAllServices()) {
listeAPI.put(service.getName(), service);
}
}
}
<file_sep>package com.log8430.group9.api;
import java.net.HttpURLConnection;
import org.json.JSONObject;
import com.log8430.group9.models.APIFile;
/**
* API du service de gestion de fichier Dropbox
* @author LOG8430 group9
*
*/
public class APIDropbox extends AbstractAPI implements API {
/**
* clรฉ d'identitรฉ du serveur pour la connexion
*/
private static String apiKey = "<KEY>";
/**
* clรฉ d'authentification du serveur pour la connexion
*/
private static String apiSecret = "<KEY>";
@Override
public String getName() {
return "dropbox";
}
@Override
public void askForToken(String code) {
this.token = null;
String result = this.post("https://api.dropboxapi.com/1/oauth2/token", "grant_type=authorization_code"
+ "&client_id="+apiKey+"&client_secret="+apiSecret
+ "&redirect_uri=http://localhost:8080/api/code?api=dropbox"
+ "&code="+code);
JSONObject json = new JSONObject(result);
if(json.has("access_token")) {
this.token = json.getString("access_token");
}
}
@Override
public boolean isConnected() {
if(this.token == null) {
return false;
} else {
JSONObject json = new JSONObject(this.get("https://api.dropboxapi.com/1/account/info",""));
if(json.has("display_name")) {
return true;
} else {
return false;
}
}
}
@Override
public void setAccessToken(String token) {
this.token = token;
}
@Override
public String getAccessToken() {
return this.token;
}
@Override
public void addConnectionProperties(HttpURLConnection connection) {
if(this.token != null) {
connection.setRequestProperty ("Authorization", "Bearer " + this.token);
}
}
@Override
public APIFile metadata(String id) {
String result = this.get("https://api.dropboxapi.com/1/metadata/auto"+id, "list=true");
JSONObject json = new JSONObject(result);
String name;
if(id.equals("/")) {
name = "/";
} else {
String[] tmp = id.split("/");
name = tmp[tmp.length-1];
}
APIFile apiFile = new APIFile(id, name, id, json.getBoolean("is_dir"));
if(json.optJSONArray("contents") != null) {
for(Object obj : json.getJSONArray("contents")) {
JSONObject jsonChild = (JSONObject) obj;
String childPath = jsonChild.getString("path");
String[] tmp2 = childPath.split("/");
String childName = tmp2[tmp2.length-1];
apiFile.addChild(new APIFile(childPath, childName, childPath, jsonChild.getBoolean("is_dir")));
}
}
return apiFile;
}
}
|
62f600477967d7204677ba641643126c0a4fa12d
|
[
"Markdown",
"Java",
"Python"
] | 19 |
Java
|
PolymtlAC/LOG8430-TP3
|
9668a8d2cf814f9745a976b4df753ba530b2a5b0
|
a74ef640f0b12a05d0b78989f3f2983c4ec6df3a
|
refs/heads/master
|
<repo_name>kjmagill/React-Todo<file_sep>/src/components/TodoComponents/TodoList.js
import React from 'react';
import Todo from './Todo';
const TodoList = props => {
return (
<div className="todo-list">
{props.taskList.map(task => (
<Todo
key={task.id}
task={task}
toggleTask={props.toggleTask}
checkmarkBlue={props.checkmarkBlue}
checkmarkGrey={props.checkmarkGrey}
/>
))}
</div>
);
};
export default TodoList;
|
5bc0eba7502fc9dc4f96118a8894a250286a911c
|
[
"JavaScript"
] | 1 |
JavaScript
|
kjmagill/React-Todo
|
d28de7d50381bbad1d2eb24c340109581927a81a
|
6a9ef81eab21783f20c78c3c8cf7c74af90188d8
|
refs/heads/master
|
<repo_name>RachanaBadekar/FlightDataFunnctionApp<file_sep>/README.md
This is a near Real - Time Flight Tracking App using several Azure technologies which tracks all the flights over United States.
I have used Azure Maps to draw the Map Canvas.
In order to get the real time flight information I have created a timer triggered function which pulls the latest flight data from OpenSky
Network Public API. The flight data is then stored in Cosmos Database.
Later a Azure function listens to the Cosmos DB change feed and updates an Azure SignalR hub with all the changes.
I have added some additional functionality where if you hover over a particular flight a pop-up displays all the flight related information
acquired from the OpenSky API in readable format.
In order to run the app clone this repo in after creating a visual studio web project. Once you have the VS project running just run the
index.html file in a browser to see the magic!
References:
https://www.youtube.com/watch?v=w_G3S6q02JE&t=6s
https://davetheunissen.io/real-time-flight-map-w-azure-functions-cosmosdb-signalr/
<file_sep>/FlightDataFunnctionApp/FlightDataPoll.cs
using System;
using System.Net.Http;
using FlightDataFunctionApp;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace FlightDataFunnctionApp
{
public static class FlightDataPoll
{
static HttpClient client = new HttpClient();
[FunctionName("FlightDataPoll")]
public static async System.Threading.Tasks.Task RunAsync(
[TimerTrigger("*/10 * * * * *")]TimerInfo myTimer,
[CosmosDB(
databaseName: "flightdb",
collectionName: "flights",
ConnectionStringSetting = "AzureCosmosDBConnection")]IAsyncCollector<Flight> documents,
ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
var openSkyUrl = "https://opensky-network.org/api/states/all?lamin=25.20&lomin=-124.40&lamax=49.00&lomax=-66.30";
using (HttpResponseMessage res = await client.GetAsync(openSkyUrl))
using (HttpContent content = res.Content)
{
var result = JsonConvert.DeserializeObject<Rootobject>(await content.ReadAsStringAsync());
foreach (var item in result.states)
{
await documents.AddAsync(Flight.CreateFromData(item));
}
log.LogInformation($"Total flights processed{result.states.Length}");
}
}
}
}
|
d3ba414fc685292f9456bc1f92345f205645e165
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
RachanaBadekar/FlightDataFunnctionApp
|
435d10e4950afdc6425096f156be6b27e9ca775d
|
aaf5fd65bf660d45269b8dcc4828a35ab02eb8cc
|
refs/heads/master
|
<repo_name>Admicos/wreplace<file_sep>/wreplacer.js
function replaceTextOnPage(from, to) {
// http://stackoverflow.com/a/18474626
getAllTextNodes().forEach(function(node){
node.nodeValue = node.nodeValue.replace(new RegExp(quote(from), 'gi'), to);
});
function getAllTextNodes(){
var result = [];
(function scanSubTree(node){
if(node.childNodes.length)
for(var i = 0; i < node.childNodes.length; i++)
scanSubTree(node.childNodes[i]);
else if(node.nodeType == Node.TEXT_NODE)
result.push(node);
})(document);
return result;
}
function quote(str){
return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}
}
var rKey = "replacements-" + window.location.hostname;
window.onload = function() {
chrome.storage.sync.get(rKey, function(items) {
var old = "";
var nst = "";
console.log(items);
for (i = 0; i < items[rKey].length; ++i) {
old = items[rKey][i][0];
nst = items[rKey][i][1];
replaceTextOnPage(old, nst);
console.log("%c[WReplacer] " + "%cReplaced '" + old + "' with '" + nst + "'", "color:blue;", "color: orangered;");
};
});
};
<file_sep>/wr-popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tab) {
var url = new URL(tab[0].url);
var domain = url.hostname;
var rKey = "replacements-" + domain;
document.getElementById("cDomain").innerHTML = domain;
window.onload = function() {
chrome.storage.sync.get(rKey, function(items) {
var old = "";
var nst = "";
console.log(items);
for (i = 0; i < items[rKey].length; ++i) {
old = items[rKey][i][0];
nst = items[rKey][i][1];
addToForm(old, nst);
};
});
};
document.getElementById("submit").onclick = function() {
var form = document.getElementById("wr-form");
var c = form.children;
var rArr = [];
for (i = 0; i < c.length; ++i) {
rArr[rArr.length] = [c[i].children[0].value, c[i].children[1].value];
}
var rStor = {};
rStor[rKey] = rArr;
chrome.storage.sync.set(rStor);
alert("Replacements set successfully! Reload all tabs for the replacements to take effect.");
};
});
document.getElementById("new").onclick = function() {
addToForm("", "");
};
function addToForm(old, nst) {
var _tmpEl_g = {};
var _tmpEl_o = {};
var _tmpEl_n = {};
var _tmpEl_r = {};
_tmpEl_o = document.createElement("input");
_tmpEl_o.value = old;
_tmpEl_n = document.createElement("input");
_tmpEl_n.value = nst;
_tmpEl_r = document.createElement("a");
_tmpEl_r.innerHTML = "x";
_tmpEl_r.style = "color: red; text-decoration: none;";
_tmpEl_r.onclick = function(e) {e.srcElement.parentNode.parentNode.removeChild(e.srcElement.parentNode);};
_tmpEl_r.href = "#!";
_tmpEl_g = document.createElement("div");
_tmpEl_g.className = "input-group";
_tmpEl_g.id = "wrg-" + i;
_tmpEl_g.appendChild(_tmpEl_o);
_tmpEl_g.appendChild(_tmpEl_n);
_tmpEl_g.appendChild(_tmpEl_r);
document.getElementById("wr-form").appendChild(_tmpEl_g);
};
|
16d775b577d42675016b41ea7b761d8ec5b50f1f
|
[
"JavaScript"
] | 2 |
JavaScript
|
Admicos/wreplace
|
b1dbca0036dd7079f70814799f3d4d623a2e3e69
|
fc1b70a323fe5b65d93a91a17481a40b08e37e51
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import {HttpClient, HttpClientModule} from '@angular/common/http';
@Component({
selector: 'app-video',
templateUrl: './video.component.html',
styleUrls: ['./video.component.sass']
})
export class VideoComponent implements OnInit {
constructor( private http: HttpClient) {
}
api = '<KEY>';
chanId = 'UCHxEl1YkDIjbWmYuKEm6jow';
result = 5;
obser$;
nextPageToken;
ytvideolist;
ngOnInit() {
const finalURL = "https://www.googleapis.com/youtube/v3/search?key="+this.api+"&channelId="+this.chanId+"&part=snippet,id&order=date&maxResults="+this.result+"";
console.log(finalURL);
this.obser$ = this.http.get(finalURL).subscribe(response => {
console.log('response', response);
const ytresults = response;
console.log(ytresults);
/*console.log(ytresults.nextPageToken);
this.nextPageToken = ytresults.nextPageToken;
ytresults.items.forEach(obj => {
console.log(obj.id.videoId);
this.ytvideolist.push(obj.id.videoId);
});
console.log(this.ytvideolist);*/
});
}
}
<file_sep>export const images = [{
preview: 'https://i2.rozetka.ua/goods/1641787/triumph_7613141551275_images_1641787291.jpg',
big: 'https://i1.rozetka.ua/goods/2581386/obsessive_5901688206744_images_2581386583.jpg',
original: 'https://i1.rozetka.ua/goods/1641786/triumph_7613141551275_images_1641786983.jpg',
id: 1,
width: 2080,
height: 3000
},
{
preview: 'https://i2.rozetka.ua/goods/4479852/triumph_7613136948431_images_4479852120.jpg',
big: 'https://i2.rozetka.ua/goods/2951458/obsessive_5901688207789_images_2951458391.jpg',
original: 'https://i2.rozetka.ua/goods/4479851/triumph_7613136948431_images_4479851624.jpg',
id: 2,
width: 2080,
height: 3000
},
{
preview: 'https://i2.rozetka.ua/goods/1641789/triumph_7613141551275_images_1641789118.jpg',
big: 'https://i2.rozetka.ua/goods/2560221/obsessive_5901688213391_images_2560221799.jpg',
original: '',
id: 3,
width: 0,
height: 0
},
{
preview: 'https://i2.rozetka.ua/goods/1641789/triumph_7613141551275_images_1641789118.jpg',
big: 'https://i1.rozetka.ua/goods/4018662/obsessive_5901688217153_images_4018662744.jpg',
original: '',
id: 4,
width: 0,
height: 0
},
{
preview: 'https://i2.rozetka.ua/goods/1641789/triumph_7613141551275_images_1641789118.jpg',
big: 'https://i1.rozetka.ua/goods/2566235/obsessive_5900308554210_images_2566235055.jpg',
original: '',
id: 5,
width: 0,
height: 0
},
{
preview: 'https://i2.rozetka.ua/goods/1641789/triumph_7613141551275_images_1641789118.jpg',
big: 'https://i2.rozetka.ua/goods/2581502/obsessive_5900308551820_images_2581502183.jpg',
original: '',
id: 6,
width: 0,
height: 0
}];
<file_sep>import {Component, OnInit} from '@angular/core';
import {images} from '../../product';
import { trigger, keyframes, animate, transition } from '@angular/animations';
import * as kf from './keyframes';
@Component({
selector: 'app-image',
templateUrl: './image.component.html',
styleUrls: ['./image.component.sass'],
animations: [
trigger('cardAnimator', [
transition('* => wobble', animate(1000, keyframes(kf.wobble))),
transition('* => swing', animate(1000, keyframes(kf.swing))),
transition('* => jello', animate(1000, keyframes(kf.jello))),
transition('* => zoomOutRight', animate(1000, keyframes(kf.zoomOutRight))),
transition('* => slideOutLeft', animate(1000, keyframes(kf.slideOutLeft))),
transition('* => rotateOutUpRight', animate(1000, keyframes(kf.rotateOutUpRight))),
transition('* => flipOutY', animate(1000, keyframes(kf.flipOutY))),
])
]
})
export class ImageComponent implements OnInit {
photos = images;
selected = this.photos[0];
animationState: string;
startAnimation(state) {
console.log(state);
if (!this.animationState) {
this.animationState = state;
}
}
resetAnimationState() {
this.animationState = '';
this.slide('next');
}
public slide(direction) {
const index = this.photos.indexOf(this.selected);
const array = this.photos.slice();
direction === 'next' ? array.push(array.shift()) : array.unshift(array.pop());
this.selected = array[index];
}
constructor() {
}
ngOnInit() {
}
}
|
f213a1c5acd08a8413fc4935bfbb1151f2b342b2
|
[
"TypeScript"
] | 3 |
TypeScript
|
FibonacciGingerSnap/zoom-for-image
|
8da75ae3ab57d6b15484bff4620f2baddf39d3a8
|
0e3ff4ed988735153ff1f2ad5c7312ebd2d5a4af
|
refs/heads/master
|
<repo_name>PascualHache/ABA-Tech-Frontend-Challenge<file_sep>/README.md
# Tech-Frontend-Challenge Response
This is the result of a technical test for ABA english. The following objectives have been tried to solve:
# Goals/Outcomes/Requirements Facedโ
- To test knowledge of consuming APIs and handling responses
- Loading state and knowing where and how to make multiple API calls efficiently
- Link to the source code, use your favorite repository manager (GitHub, GitLab, ...)
- The app should run on any computer by running npm install , npm test and have a demo online.
- Fetch and display *Released This Week* songs
- Use the API path `new-releases`
- Fetch and display *Featured Playlists*
- Use the API path `featured-playlists`
- Fetch and display *Browse* genres
- Use the API path `categories`
- UX/UI Screenshots reference:


# What have I not solved? โ
- Any test was implemented, so any test was passed. The main reason has been due to a lack of time and knowledge, as it is a long test I have decided to focus my efforts on other points.
- Loading state/UI *(optional, current UX is already clean)*, for the same time reasons explained above.
- Link to the deployed Demo, use your favorite static site hosting platform (surge, github-pages, now, ...). I've been strugglin with the redirection auth process and due the lack of time i've decided not finish that point
# Before run it โ๏ธ
- After npm install, when npm start ensure that the project is runnin on the port 3000. Spotify API is setted to redirect to http://localhost:3000/
- This project is consuming Spotify API so an client ID is required. Is is demanded on the first project screen and if is not correct the project doesnt work. If the client ID isn't provided by me, ask me by email: <EMAIL>
# Theoretical Part ๐
- This part is answered in the root of the repository in a file named TheoreticalPart.pdf
<file_sep>/src/utils/constants.js
export const GET_NEW_RELEASES = 'GET_NEW_RELEASES';
export const GET_FEATURED_PLAYLISTS = 'GET_FEATURED_PLAYLISTS';
export const GET_CATEGORIES = 'GET_CATEGORIES';<file_sep>/src/components/Home.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import config from '../config';
const Home = () => {
const { authUrl, redirectUrl } = config.api;
const [name, setName] = useState("");
const handleSubmit = (evt) => {
evt.preventDefault();
localStorage.setItem('clientID', name)
handleLogin()
}
const handleLogin = () => {
let url = `${authUrl}?client_id=${localStorage.getItem("clientID")}`
url += `&redirect_uri=${redirectUrl}`
url += `&response_type=token&show_dialog=true`;
window.location = url;
};
return (
<div className="login">
<div className="welcomeMsg">
<h1>Welcome</h1>
<p>There's only one way you can acces to this demo and is getting my Spotify <strong>client ID</strong> and pasting it below</p>
<p>Send me an email and I will send you</p>
<a href="mailto:<EMAIL>@" target="_blank" rel="noopener noreferrer"><EMAIL></a>
</div>
<form onSubmit={handleSubmit} className="welcome-form">
<label>
Client ID:
<input
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
</label>
<button type="submit" value="Submit" className="button-login">Login to spotify</button>
</form>
</div>
);
};
export default connect()(Home);<file_sep>/src/reducers/featuredPlaylists.js
import { GET_FEATURED_PLAYLISTS } from './../utils/constants'
const featuredPlaylistsReducer = (state = {}, action) => {
switch (action.type) {
case GET_FEATURED_PLAYLISTS:
return action.playlists;
default:
return state;
}
};
export default featuredPlaylistsReducer;<file_sep>/src/reducers/newReleases.js
import { GET_NEW_RELEASES } from '../utils/constants';
const newReleasesReducer = (state = {}, action) => {
switch (action.type) {
case GET_NEW_RELEASES:
return action.releases;
default:
return state;
}
};
export default newReleasesReducer;<file_sep>/src/actions/result.js
import config from '../config';
import { get } from '../utils/api';
import {
GET_NEW_RELEASES,
GET_FEATURED_PLAYLISTS,
GET_CATEGORIES
} from '../utils/constants';
const { newReleaseUrl, featuredPlaylistsUrl, categoriesUrl } = config.api;
export const getNewReleases = () => (dispatch) => {
return get(newReleaseUrl).then(
(response) => {
dispatch({
type: GET_NEW_RELEASES,
releases: response
});
})
}
export const getFeaturedPlaylists = () => (dispatch) => {
return get(featuredPlaylistsUrl).then(
(response) => {
dispatch({
type: GET_FEATURED_PLAYLISTS,
playlists: response
});
})
}
export const getCategories = () => (dispatch) => {
return get(categoriesUrl).then(
(response) => {
dispatch({
type: GET_CATEGORIES,
categories: response
});
})
}
<file_sep>/src/config.js
export default {
api: {
baseUrl: 'https://api.spotify.com/v1',
authUrl: 'https://accounts.spotify.com/authorize',
clientSecret: '',
redirectUrl: 'http://localhost:3000/redirect',
newReleaseUrl: 'https://api.spotify.com/v1/browse/new-releases',
featuredPlaylistsUrl: 'https://api.spotify.com/v1/browse/featured-playlists',
categoriesUrl: 'https://api.spotify.com/v1/browse/categories'
}
}
|
50b9658a0dc155c7b6237d45eec2d07ae6846397
|
[
"Markdown",
"JavaScript"
] | 7 |
Markdown
|
PascualHache/ABA-Tech-Frontend-Challenge
|
109d0e2fa3c6281ef7d711fc720c4f1660ba1fd8
|
6818fc7910e9b9f9309c32675deefb9937cbe76a
|
refs/heads/master
|
<repo_name>consuelaziza/the-tough-day<file_sep>/routes/Todo.routes.js
const TodoModel = require("../models/Todo.model");
const router = require("express").Router();
// My TODO routes will go here
//Create todo
// Handles GET requests to `/todos/create`
router.get('/todos/create', (req, res, next) => {
// sending an hbs form back to the
res.render('todos/create-form.hbs')
})
// Handles POST requests to `/todos/create`
router.post('/todos/create', (req, res, next) => {
//all the form data will be available inside req.body
console.log( req.body )
const {title, description} = req.body
//Insert the title and description in the DB
//IMPORT YOUR TODOMODEL AT THE TOP OF THE FILE
TodoModel.create({title, description})
.then(() => {
//redirect the user to home page
// redirects it to a certain url path
res.redirect('/')
})
.catch(() => {
next('Todo creation failed')
})
})
// Handles GET requests to `/todo/:somethingDynamic`
router.get('/todo/:todoId', (req, res, next) => {
const {todoId} = req.params
TodoModel.findById(todoId)
.then((todo) => {
//render some HBS file with that todo information
res.render('todos/detail.hbs', {todo})
})
.catch(() => {
next('Single todo fetch failed')
})
})
// Handles GET requests to `/todos/235y38sdf23423/edit
router.get('/todos/:todoId/edit', (req, res, next) => {
const {todoId} = req.params
TodoModel.findById(todoId)
.then((todo) => {
//render some HBS file with that todo information
res.render('todos/edit-form.hbs', {todo})
})
.catch(() => {
next('Single todo fetch failed')
})
})
// Handles POST requests to `/todos/235y38sdf23423/edit
router.post('/todos/:todoId/edit', (req, res, next) => {
//We get this information from the form that the user submits
const {title, description} = req.body
// we grab the dynamic id from the url
const {todoId} = req.params
// Find that specific todo by id and update it
TodoModel.findByIdAndUpdate(todoId, {title, description})
.then(() => {
res.redirect('/')
})
.catch(() => {
next('Todo Edit failed')
})
})
// Handles GET requests to `/todos/235y38sdf23423/delete
router.get('/todos/:todoId/delete', (req, res, next) => {
//grab the todoId from the url
const {todoId} = req.params
// Delete from the database
TodoModel.findByIdAndDelete(todoId)
.then(() => {
//then send the user to the home page
res.redirect('/')
})
.catch(() => {
next('Todo delete failed')
})
})
module.exports = router;
<file_sep>/routes/index.js
const router = require("express").Router();
const TodoModel = require('../models/Todo.model')
/* GET home page */
router.get("/", (req, res, next) => {
TodoModel.find()
.then((todos) => {
res.render("index.hbs", {todos});
})
.catch(() => {
next('Todo find failed')
})
});
module.exports = router;
|
2e9924cc8e739d9c33b841c68be3fd58c9c0cfb4
|
[
"JavaScript"
] | 2 |
JavaScript
|
consuelaziza/the-tough-day
|
04a799463811909c7a6e1c1d9e49fe08386480a9
|
c3c437543eaefae0add8439fc04548a9f9452e6c
|
refs/heads/master
|
<file_sep>import math
import random
import pygame
pygame.init()
pygame.font.init()
SCREEN_WIDTH = 1080
SCREEN_HEIGHT = 720
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
FIRST_P_LETTER = None
SECOND_P_LETTER = None
FIRST_P = None
SECOND_P = None
PLAYING = None
INTRO = None
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
clock.tick(60)
all_sprites = pygame.sprite.Group()
board = ['', '_', '_', '_', '_', '_', '_', '_', '_', '_']
WIN_COMBINATIONS = [
# Horizontal
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
# Vertical
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
# Diagonals
(1, 5, 9),
(3, 5, 7),
]
def get_score(letter, player, depth):
if player == 'X':
scores = {'X': 10 - depth, 'O': -10 + depth, 'Tie': 0}
else:
scores = {'X': -10 + depth, 'O': 10 - depth, 'Tie': 0}
return scores[letter]
def instructions():
print('this is the tic-tac-toe board')
print(board[1], board[2], board[3])
print(board[4], board[5], board[6])
print(board[7], board[8], board[9])
print('each position has a number')
clear_board()
# testing positions
# board[1] = 'O'
# board[2] = 'O'
# board[3] = 'X'
# board[4] = 'X'
# board[6] = 'O'
# board[9] = 'X'
def print_board():
print(board[1], board[2], board[3])
print(board[4], board[5], board[6])
print(board[7], board[8], board[9])
print('/////////////////')
def get_next_move(sprites):
empty_spaces = get_empty_spaces()
next = True
next_move = 0
while next:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
for i in sprites:
if i.rect.collidepoint(pos):
next_move = i.value
next = False
if 0 < next_move <= 9:
if next_move in empty_spaces:
return next_move
else:
continue
else:
continue
def clear_board():
for i in range(1, 10):
board[i] = '_'
def get_empty_spaces():
empty_spaces = []
for i in range(1, len(board)):
if board[i] == '_':
empty_spaces.append(i)
return empty_spaces
def minimax(board, depth, is_maximazing, what_letter, alpha, beta):
result = is_game_over()
if result is not None:
score = get_score(result, what_letter, depth)
return score
if is_maximazing:
best_score = -math.inf
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = what_letter
best_score = max(best_score, minimax(board, depth + 1, False, what_letter, alpha, beta))
board[i] = '_'
alpha = max(alpha, best_score)
if alpha >= beta:
break
return best_score
else:
if what_letter == 'X':
opposite_letter = 'O'
else:
opposite_letter = 'X'
best_score = math.inf
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = opposite_letter
best_score = min(best_score, minimax(board, depth + 1, True, what_letter, alpha, beta))
board[i] = '_'
beta = min(beta, best_score)
return best_score
def get_comp_move(what_turn, what_letter):
alpha = -math.inf
beta = math.inf
best_score = -math.inf
move = 0
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = what_letter
score = minimax(board, 0, False, what_letter, alpha, beta)
board[i] = '_'
if score > best_score:
best_score = score
move = i
return move
def is_game_over():
winner = None
for a, b, c in WIN_COMBINATIONS:
if board[a] == board[b] == board[c] == 'X' or board[a] == board[b] == board[c] == 'O':
winner = board[a]
if winner is None and (len(get_empty_spaces()) == 0):
return 'Tie'
else:
return winner
def add_move_to_board(i, letter):
board[i] = letter
def get_player_letters(first_p):
human_letter = input('Do you want to be X or O \n').upper()
if human_letter == 'X':
comp_letter = 'O'
else:
comp_letter = 'X'
print(f'you are {human_letter} and the computer is {comp_letter}')
if first_p == 'human':
return human_letter, comp_letter
else:
return comp_letter, human_letter
def get_player_turns():
turn = random.randint(1, 2)
if turn == 1:
print(f'you will be {turn}st')
else:
print(f'you will be {turn}nd')
if turn == 1:
return 'human', 'comp'
else:
return 'comp', 'human'
def intro():
global FIRST_P
global SECOND_P
global FIRST_P_LETTER
global SECOND_P_LETTER
button_font = pygame.font.SysFont('comicsans', 30)
button_text = button_font.render('Play', True, (0, 0, 0))
font = pygame.font.SysFont('comicsans', 50)
text = font.render('Do you want to be X or O?', True, (0, 0, 0))
letter_font = pygame.font.SysFont('comicsansms', 100)
letter_x = letter_font.render('X', True, (0, 0, 0))
letter_o = letter_font.render('O', True, (0, 0, 0))
button = Button(500, 450, 100, 50, (103, 174, 171), (137, 235, 232), highlight_border_color=(15, 213, 255))
FIRST_P, SECOND_P = get_player_turns()
intro_running = True
while intro_running:
global FIRST_P_LETTER
global SECOND_P_LETTER
global PLAYING
pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
intro_running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
intro_running = False
if 500 < pos[0] < 600 and 450 < pos[1] < 500:
button.highlighted = True
else:
button.highlighted = False
if event.type == pygame.MOUSEBUTTONDOWN:
# X is selected
if 300 < pos[0] < 300 + letter_x.get_width() and 250 < pos[1] < 250 + letter_x.get_height():
letter_x = letter_font.render('X', True, (255, 255, 255))
letter_o = letter_font.render('O', True, (77, 129, 174))
if FIRST_P == 'comp':
FIRST_P_LETTER = 'O'
SECOND_P_LETTER = 'X'
print(f'the first player is: {FIRST_P} and you selected {SECOND_P_LETTER}')
else:
FIRST_P_LETTER = 'X'
SECOND_P_LETTER = 'O'
print(f'the first player is: {FIRST_P} and you selected {FIRST_P_LETTER}')
# O is selected
if 670 < pos[0] < 670 + letter_o.get_width() and 250 < pos[1] < 670 + letter_o.get_height():
letter_o = letter_font.render('O', True, (255, 255, 255))
letter_x = letter_font.render('X', True, (77, 129, 174))
if FIRST_P == 'comp':
FIRST_P_LETTER = 'X'
SECOND_P_LETTER = 'O'
print(f'the first player is: {FIRST_P} and you selected {SECOND_P_LETTER}')
else:
FIRST_P_LETTER = 'O'
SECOND_P_LETTER = 'X'
print(f'the first player is: {FIRST_P} and you selected {FIRST_P_LETTER}')
try:
if button.highlighted and FIRST_P_LETTER is not None:
intro_running = False
PLAYING = True
except:
pass
screen.fill((31, 112, 174))
# Question text
screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, 100))
# Letter X and O
screen.blit(letter_x, (300, 250))
screen.blit(letter_o, (670, 250))
button.update()
button.draw()
screen.blit(button_text, (int(550 - button_text.get_width() / 2), int(475 - button_text.get_height() / 2)))
pygame.display.update()
class Button:
def __init__(self, x, y, width, height, bg_color, highlight_color, border_color=(0, 0, 0),
highlight_border_color=(0, 0, 0)):
self.x = x
self.y = y
self.width = width
self.height = height
self.bg_color = bg_color
self.highlight_color = highlight_color
self.border_color = border_color
self.highlight_border_color = highlight_border_color
self.highlighted = False
def update(self):
pass
def draw(self):
if self.highlighted:
pygame.draw.rect(screen, self.highlight_color, (self.x, self.y, self.width, self.height))
pygame.draw.rect(screen, self.highlight_border_color, (self.x, self.y, self.width, self.height), 2)
else:
pygame.draw.rect(screen, self.bg_color, (self.x, self.y, self.width, self.height))
pygame.draw.rect(screen, self.border_color, (self.x, self.y, self.width, self.height), 2)
class Cell(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((150, 150))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.value = 0
class CreateText:
def __init__(self, x, y, text, color, size, font_name):
self.text = text
self.color = color
self.size = size
self.x = x
self.y = y
self.font_name = font_name
self.font = pygame.font.SysFont(font_name, 100)
self.text_to_screen = self.font.render(self.text, True, self.color)
def update(self):
pass
def draw(self):
screen.blit(self.text_to_screen, (self.x, self.y))
class ScreenBoard:
def __init__(self):
self.cell = None
self.text = None
def create_screen_board(self):
val = 0
for row in range(3):
for column in range(3):
self.cell = Cell()
val += 1
self.cell.value = val
x = 25 + 175 * row
y = 25 + 175 * column
self.cell.rect.topleft = (y, x)
all_sprites.add(self.cell)
def draw_board(self):
sprite_list = all_sprites.sprites()
for i in range(1, 10):
if board[i] == 'X':
self.text = CreateText(sprite_list[i-1].rect.x, sprite_list[i-1].rect.y, board[i], BLACK, 50, 'comicsansms')
self.text.draw()
elif board[i] == 'O':
self.text = CreateText(sprite_list[i-1].rect.x, sprite_list[i-1].rect.y, board[i], BLACK, 50, 'comicsansms')
self.text.draw()
def game():
global PLAYING
global board
global FIRST_P
global FIRST_P_LETTER
global SECOND_P
global SECOND_P_LETTER
move_count = 1
s_board = ScreenBoard()
s_board.create_screen_board()
s_board.draw_board()
sprite_list = all_sprites.sprites()
while PLAYING:
for event in pygame.event.get():
if event.type == pygame.QUIT:
PLAYING = False
winner = is_game_over()
if winner == 'Tie':
print(f'The game is a {winner}')
PLAYING = False
elif winner:
print(f'The winner is {winner}')
PLAYING = False
else:
if FIRST_P == 'human' and move_count % 2 != 0:
add_move_to_board(get_next_move(sprite_list), FIRST_P_LETTER)
move_count += 1
elif FIRST_P == 'human' and move_count % 2 == 0:
add_move_to_board(get_comp_move(SECOND_P, SECOND_P_LETTER), SECOND_P_LETTER)
move_count += 1
pygame.time.wait(500)
elif FIRST_P == 'comp' and move_count % 2 != 0:
add_move_to_board(get_comp_move(FIRST_P, FIRST_P_LETTER), FIRST_P_LETTER)
move_count += 1
pygame.time.wait(500)
else:
add_move_to_board(get_next_move(sprite_list), SECOND_P_LETTER)
move_count += 1
# Update
all_sprites.update()
# Draw
screen.fill((0, 0, 0))
all_sprites.draw(screen)
s_board.draw_board()
pygame.display.update()
def main():
intro()
if PLAYING:
game()
if __name__ == '__main__':
main()<file_sep># tictactoe
Console game of TicTacToe with Smart AI (Minimax Algorithm)
<file_sep>import math
import random
board = ['', 1, 2, 3, 4, 5, 6, 7, 8, 9]
WIN_COMBINATIONS = [
# Horizontal
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
# Vertical
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
# Diagonals
(1, 5, 9),
(3, 5, 7),
]
def get_score(letter, player, depth):
if player == 'X':
scores = {'X': 10 - depth, 'O': -10 + depth, 'Tie': 0}
else:
scores = {'X': -10 + depth, 'O': 10 - depth, 'Tie': 0}
return scores[letter]
def instructions():
print('this is the tic-tac-toe board')
print(board[1], board[2], board[3])
print(board[4], board[5], board[6])
print(board[7], board[8], board[9])
print('each position has a number')
clear_board()
# testing positions
# board[1] = 'O'
# board[2] = 'O'
# board[3] = 'X'
# board[4] = 'X'
# board[6] = 'O'
# board[9] = 'X'
def print_board():
print(board[1], board[2], board[3])
print(board[4], board[5], board[6])
print(board[7], board[8], board[9])
print('/////////////////')
def get_next_move():
empty_spaces = get_empty_spaces()
while True:
try:
next_move = int(input('what is your move? (a number from 1 to 9)\n'))
if 0 < next_move <= 9:
if next_move in empty_spaces:
return next_move
else:
continue
else:
continue
except:
print('That is not a valid number')
continue
def clear_board():
for i in range(1, 10):
board[i] = '_'
def get_empty_spaces():
empty_spaces = []
for i in range(1, len(board)):
if board[i] == '_':
empty_spaces.append(i)
return empty_spaces
def minimax(board, depth, is_maximazing, what_letter, alpha, beta):
result = is_game_over()
if result is not None:
score = get_score(result, what_letter, depth)
return score
if is_maximazing:
score = -math.inf
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = what_letter
best_score = max(best_score, minimax(board, depth + 1, False, what_letter, alpha, beta))
board[i] = '_'
alpha = max(alpha, best_score)
if alpha >= beta:
break
return best_score
else:
score = math.inf
if what_letter == 'X':
opposite_letter = 'O'
else:
opposite_letter = 'X'
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = opposite_letter
best_score = min(best_score, minimax(board, depth + 1, True, what_letter, alpha, beta))
board[i] = '_'
beta = min(beta, best_score)
return best_score
def get_comp_move(what_turn, what_letter):
alpha = -math.inf
beta = math.inf
best_score = -math.inf
move = 0
alpha = 0
beta = 0
empty_spaces = get_empty_spaces()
for i in empty_spaces:
board[i] = what_letter
score = minimax(board, 0, False, what_letter, alpha, beta)
board[i] = '_'
if alpha >= beta:
move = i
return move
def is_game_over():
winner = None
for a, b, c in WIN_COMBINATIONS:
if board[a] == board[b] == board[c] == 'X' or board[a] == board[b] == board[c] == 'O':
winner = board[a]
if winner is None and (len(get_empty_spaces()) == 0):
return 'Tie'
else:
return winner
def add_move_to_board(i, letter):
board[i] = letter
def get_player_letters(first_p):
human_letter = input('Do you want to be X or O \n').upper()
if human_letter == 'X':
comp_letter = 'O'
else:
comp_letter = 'X'
print(f'you are {human_letter} and the computer is {comp_letter}')
if first_p == 'human':
return human_letter, comp_letter
else:
return comp_letter, human_letter
def get_player_turns():
turn = random.randint(1, 2)
if turn == 1:
print(f'you will be {turn}st')
else:
print(f'you will be {turn}nd')
if turn == 1:
return 'human', 'comp'
else:
return 'comp', 'human'
def main():
game_over = False
instructions()
move_count = 1
first_p, second_p = get_player_turns()
first_p_letter, second_p_letter = get_player_letters(first_p)
while not game_over:
winner = is_game_over()
if winner == 'Tie':
print(f'The game is a {winner}')
game_over = True
elif winner:
print(f'The winner is {winner}')
game_over = True
else:
if first_p == 'human' and move_count % 2 != 0:
add_move_to_board(get_next_move(), first_p_letter)
print_board()
move_count += 1
elif first_p == 'human' and move_count % 2 == 0:
add_move_to_board(get_comp_move(second_p, second_p_letter), second_p_letter)
print_board()
move_count += 1
elif first_p == 'comp' and move_count % 2 != 0:
add_move_to_board(get_comp_move(first_p, first_p_letter), first_p_letter)
print_board()
move_count += 1
else:
add_move_to_board(get_next_move(), second_p_letter)
print_board()
move_count += 1
if __name__ == '__main__':
main()
|
441f5d882495cb552242d452004df85e97d18461
|
[
"Markdown",
"Python"
] | 3 |
Python
|
david12king/tictactoe
|
9775be21fa45aea5a9b4bbc0b143adc420dc8d05
|
5f002680dd22d80a16403b5cae7c8a83034fc338
|
refs/heads/master
|
<repo_name>HiphopSamurai/Sinatra-project<file_sep>/README.md
# Sinatra-project
Flatiron Sinatra Project
<file_sep>/app/controllers/application_controller.rb
require "./config/environment"
#require "./app/models/user"
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
#set :session_secret, "carcollection"
set :session_secret, "auth_demo_lv"
end
#get '/' do
# "This is the start of my Sinatra project!"
#end
get "/" do
erb :index
end
get '/home' do
"This is my home screen"
end
end
|
8a20df3e7d1c484a8c81dddac4f14bd5b341bc8d
|
[
"Markdown",
"Ruby"
] | 2 |
Markdown
|
HiphopSamurai/Sinatra-project
|
5e4cdb2df765ab5b883309b54f5ff9d6e9b3eab4
|
9a11805586f17156cda0a4d8fdacb085e71807ab
|
refs/heads/master
|
<file_sep>/*
* 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 View;
import Client.Controller;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.util.List;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import Client.demo.*;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.io.Writer;
import java.util.Scanner;
import sun.org.mozilla.javascript.internal.xml.XMLLib;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import javax.xml.bind.Validator;
import javax.xml.soap.Node;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author marwa
*/
public class View extends JFrame implements ViewInt {
//layout
JPanel first;
JPanel second;
JTextArea ta;
JTextField tf;
JButton send;
JButton sendFile;
JButton saveFile;
JScrollPane myscroll;
Controller c;
Thread open;
public int xfrom, yto;
public String userFrom, userTo;
public View(Controller cc) {
this.c = cc;
//layout
first = new JPanel();
first.setLayout(new FlowLayout());
second = new JPanel();
second.setLayout(new FlowLayout());
ta = new JTextArea();
tf = new JTextField(30);
send = new JButton("Send");
sendFile = new JButton("SendFile");
saveFile = new JButton("SaveFile");
myscroll = new JScrollPane(ta);
add(myscroll, BorderLayout.CENTER);
//add(first);
add(second, BorderLayout.SOUTH);
second.add(tf);
second.add(send);
second.add(sendFile);
second.add(saveFile);
send.addActionListener(new Myact());
sendFile.addActionListener(new mysendFileListener());
saveFile.addActionListener(new saveFile());
//setDefaultCloseOperation(EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
c.flag = 0;
}
});
}
public void display(String msg) {
ta.append(msg + "\n");
}
public void fun(int idd, int idto) {
xfrom = idd;
yto = idto;
}
public class Myact implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == send) {
String text = tf.getText();
Controller.msgtotellone(text, xfrom, yto);
System.out.println(xfrom + " " + yto);
tf.setText("");
System.out.println();
}
}
}
class mysendFileListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser fC = new JFileChooser();
if (fC.showOpenDialog(View.this) == JFileChooser.APPROVE_OPTION) {
final String path = fC.getSelectedFile().getPath();
try {
open = new Thread(new Runnable() {
@Override
public void run() {
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
int size = fis.available();
byte[] b = new byte[size];
fis.read(b);
System.out.println("seeeeeeeeeeeeeeeend");
Controller.helloref.sendFileToOthers(b, yto);
fis.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
open.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
class saveFile implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser f = new JFileChooser();
JFileChooser fC = new JFileChooser();
if (fC.showSaveDialog(View.this) == JFileChooser.APPROVE_OPTION) {
final String path = fC.getSelectedFile().getPath();
try {
SchemaFactory Factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = Factory.newSchema(new StreamSource(new File("demo.xsd")));
JAXBContext Context = JAXBContext.newInstance("Client.demo");
ObjectFactory factory = new ObjectFactory();
Marshaller marsh = Context.createMarshaller();
marsh.setSchema(schema);
MyMsg Msg = factory.createMyMsg();
Msg.setHeader("file name");
// Msgtype massage = factory.createMsgtype();
// JAXBElement msg = factory.createMsgtype(massage);
// massage.getTo().add("ahmed");
String split[] = null;
int i = 0;
List MyList = null;
MyList = Msg.getMsg();
for (String line : ta.getText().split("\\n")) {
userFrom = Controller.helloref.returnUserofSender(xfrom);
userTo = Controller.helloref.returnUserofSender(yto);
Msgtype massage = factory.createMsgtype();
massage.getTo().add(userTo);
split = line.split("\\:");
massage.setBody(split[i + 1]);
massage.setFrom(userFrom);
split = null;
MyList.add(massage);
}
//Msg.setHeader(marsh);
JAXBElement<MyMsg> element = factory.createMyMsg(Msg);
Marshaller marshaller = Context.createMarshaller();
marsh.marshal(element, new DefaultHandler());
marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml-stylesheet type=\"text/xsl\" href=\"chat.xsl\"?>");
// output pretty printed
marshaller.marshal(element, new FileOutputStream(path + ".xml"));
Scanner file = new Scanner(new File(path + ".xml"));
FileReader fr = new FileReader(path + ".xml");
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
/*
while (lnr.readLine() != null){
linenumber++;
if (linenumber == 2) {
Writer output;
output = new BufferedWriter(new FileWriter(path + ".xml", true)); //clears file every time
output.append("<?xml-stylesheet type=\"text/xsl\" href=\"chat.xsl\"?>");
output.close();
break;
}
}*/
javax.xml.validation.Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(path + ".xml")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
<file_sep>compile.on.save=true
do.depend=false
do.jar=true
file.reference.mysql-connector-java-5.1.6-bin.jar=D:\\JAVA PROJECT\\mysql-connector-java-5.1.6-bin.jar
file.reference.ojdbc14.jar=D:\\JAVA PROJECT\\ojdbc14.jar
javac.debug=true
javadoc.preview=true
user.properties.file=C:\\Users\\Mahmoud\\AppData\\Roaming\\NetBeans\\8.1\\build.properties
|
bb2f3fc2c851987397a121c85d1e91bcf6667c8f
|
[
"Java",
"INI"
] | 2 |
Java
|
mahmoud-abd-elrehim/Chat
|
dbed8a5109919581e5aacb1c5792cb0642ce1a72
|
b0c3a8198f6eb932893f8060b238a42f8aa06788
|
refs/heads/master
|
<repo_name>barshat7/Movie_MS_Project<file_sep>/user-details/src/main/java/com/uservice/controller/UserHomeController.java
package com.uservice.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.uservice.dto.UserDTO;
import com.uservice.model.User;
import com.uservice.service.UserService;
/**
*
* @author brai-a
*
* This controller will:
* 1. Fetch a user by username
* 2. Fetch all the users
* 3. Save a user and generate a user-id(used internally only)
*/
@RestController
@RequestMapping("/user")
public class UserHomeController {
@Autowired
private UserService userService;
@GetMapping
public String home() {
return "User Service Running in localhost";
}
@GetMapping("/{username}")
public UserDTO getUserByName(@PathVariable("username") String username) {
User user = userService.getUserByName(username);
UserDTO userDto = new UserDTO();
if(user!=null) {
userDto.setUsername(user.getUsername());
userDto.setLanguage(user.getLanguage());
userDto.setGender(user.getGender());
}
return userDto;
}
@GetMapping("/all")
public List<UserDTO> getAllUsers(){
return userService.findAll();
}
@PostMapping("/save")
public ResponseEntity<String> saveuser(@RequestBody UserDTO userDto){
User user = new User();
user.setUsername(userDto.getUsername());
user.setLanguage(userDto.getLanguage());
user.setGender(userDto.getGender());
userService.save(user);
return new ResponseEntity<String>(HttpStatus.OK);
}
}
<file_sep>/movie-dashboard/src/main/java/com/dashboard/service/MovieUserService.java
package com.dashboard.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.dashboard.model.UserDTO;
@Service
public class MovieUserService {
@Value("${user_service.api}")
private String userService;
@Autowired
private RestTemplate restTemplate;
public UserDTO getUserByName(String username) {
String url = "http://" + userService + "/" +username;
UserDTO userDto = restTemplate.getForObject(url, UserDTO.class);
// Hystrix fallback required if userDto is not available
return userDto;
}
}
<file_sep>/movie-dashboard/src/main/java/com/dashboard/controller/MovieController.java
package com.dashboard.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dashboard.service.MovieService;
@RestController
@RequestMapping("/movie")
public class MovieController {
@Autowired
private MovieService movieService;
@GetMapping("/{id}")
public String getMovies(@PathVariable("id") String id) {
return movieService.getMovieById(id);
}
}
<file_sep>/eureka-server/src/main/resources/application.properties
server.port=8010
spring.application.name:movie-eureka-server
eureka.client.register-with-eureka=false<file_sep>/movie-dashboard/src/main/java/com/dashboard/service/MovieService.java
package com.dashboard.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class MovieService {
@Value("${themoviedb.api.key}")
private String apiKey;
/*@Autowired
private RestTemplate restTemplate;*/
@HystrixCommand(fallbackMethod="getMovieByIdFallback")
public String getMovieById(String id) {
RestTemplate restTemplate = new RestTemplate();
StringBuilder builder = new StringBuilder("https://api.themoviedb.org/3/movie/");
builder.append(id).append("?api_key=").append(apiKey);
System.out.println("Sending Request: " +builder.toString());
String val = null;
try {
val=restTemplate.getForObject(builder.toString(), String.class);
}catch(Exception ex) {
System.out.println("Exception in getMovieById: " +ex);
throw ex;
}
return val;
}
public String getMovieByIdFallback(String id) {
return "Some Error Occurred..";
}
}
<file_sep>/user-details/src/main/java/com/uservice/controller/UserDTOController.java
package com.uservice.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserDTOController {
}
<file_sep>/movie-dashboard/src/main/java/com/dashboard/controller/HomeController.java
package com.dashboard.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String home() {
return "/movie/{id} for getting movies";
}
}
<file_sep>/movie-user-admin/src/main/java/com/admin/controller/UserAdminController.java
package com.admin.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.admin.model.UserDTO;
import com.admin.service.UserService;
@RestController
@RequestMapping("/user")
public class UserAdminController {
@Autowired
private UserService userService;
@GetMapping("/{username}")
public UserDTO getUserByName(@PathVariable("username") String username) {
return userService.getUserByName(username);
}
@GetMapping("/all")
public List<UserDTO> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping("/save")
public ResponseEntity<String> saveUser(@RequestBody UserDTO user){
userService.saveUser(user);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
<file_sep>/movie-user-admin/src/main/java/com/admin/service/UserService.java
package com.admin.service;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.admin.model.UserDTO;
@FeignClient("user-service")
public interface UserService {
@RequestMapping(value="/user/save",method=RequestMethod.POST)
public void saveUser(@RequestBody UserDTO user);
@RequestMapping(value="/user/{username}",method=RequestMethod.GET)
public UserDTO getUserByName(@PathVariable("username") String username);
@RequestMapping(value="/user/all",method=RequestMethod.GET)
public List<UserDTO> getAllUsers();
}
|
ab3662569ee988f376c081682c58486697fb3365
|
[
"Java",
"INI"
] | 9 |
Java
|
barshat7/Movie_MS_Project
|
00ce4380a3f1d567a3398d3e3122618aaced3b71
|
bd1b8e156c2ed9262044f0285a3043fcb25f0d6e
|
refs/heads/main
|
<repo_name>Cozy228/Go-000<file_sep>/Week04/demoproject/cmd/demo.go
package cmd
import "fmt"
func main() {
fmt.Println("Project entry file")
}
<file_sep>/Week02/errorDemo.go
package main
import (
"database/sql"
"fmt"
"github.com/pkg/errors"
)
func main() {
business(20200607010463)
//another search
business(-1)
}
func dao(id int) (string, error) {
if id < 0 {
//404
//change comment
//่ฟ้ๆฏ่ๅธๅปบ่ฎฎๅฏไปฅๅฎไนๅบ่ชๅทฑ็้่ฏฏ็ ๅฆ code. ErrNoRows ่งฃ่ฆๆ ไพ่ต
return "", errors.Wrapf(sql.ErrNoRows, "404 no data found with id %d", id)
}
//normal logic
return "Ziyu", nil
}
//service
func findNameById(id int) (string, error) {
return dao(id)
}
func business(id int) {
name, err := findNameById(id)
if err != nil {
if errors.Is(errors.Cause(err), sql.ErrNoRows) {
// handle error
//Change comment:
//errors.is ้้ขไธ็จๅตๅฅ errors.Cause(err) ไบ๏ผ ็ดๆฅerrors.is(err,sql.ErrNoRows)ๅฐฑ่ก
//errors.is่ฝ้ๅฝๆพๆ นๅ
fmt.Printf("Error๏ผ%T %v\n", errors.Cause(err), errors.Cause(err))
fmt.Printf("Stacktrace๏ผ\n%+v\n", err)
} else {
// other errors
fmt.Printf("some other error: %+v\n", err)
}
return
}
//handle normal logic
fmt.Println("handle normal logic")
fmt.Printf("Name: %s\n", name)
}
<file_sep>/Week04/demoproject/test/apiTest.go
package test
func apiTest() {
//test api
//response
}
<file_sep>/Week04/demoproject/internal/internal.go
package internal
// code under this package only be used internally
<file_sep>/Week02/README.md
# ๅญฆไน ็ฌ่ฎฐ
## Question
ๆไปฌๅจๆฐๆฎๅบๆไฝ็ๆถๅ๏ผๆฏๅฆ dao ๅฑไธญๅฝ้ๅฐไธไธช sql.ErrNoRows ็ๆถๅ๏ผๆฏๅฆๅบ่ฏฅ Wrap ่ฟไธช error๏ผๆ็ปไธๅฑใไธบไปไน๏ผๅบ่ฏฅๆไนๅ่ฏทๅๅบไปฃ็ ๏ผ
## Answer
Wrap the error at where it happens (low level error should be handled by upper level/business level).
## Learning Material
https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully
## Answer in short:
dao:
```go
return errors.Wrapf(code.NotFound, fmt.Sprintf("sql: %s error: %v", sql, err))
```
business:
```go
if errors.Is(err, code.NotFound} {
}
```<file_sep>/Week04/demoproject/pkg/util.go
package pkg
// code under this package will be exported and be used by other projects.
<file_sep>/Week04/demoproject/api/api.md
# API Definition
##GET /hello
Response: Hello world
##Get /user?id=G20200607010463
Response: Ziyu<file_sep>/Week03/main.go
package main
import (
"context"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
func main() {
ctx := context.Background()
g, cancelCtx := errgroup.WithContext(ctx)
g.Go(func() error {
return listenSignal(cancelCtx)
})
g.Go(func() error {
return startServer(cancelCtx, ":8080")
})
if err := g.Wait(); err != nil {
log.Println("error group return err:", err.Error())
}
log.Println("DONE!")
}
func listenSignal(ctx context.Context) error {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
select {
case <-signalChan:
return errors.New("server close -> close signal received")
case <-ctx.Done():
return errors.New("server close -> context done")
}
}
func startServer(ctx context.Context, addr string) error {
svr := &http.Server{Addr: addr, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "Hello, Ziyu! ID:G20200607010463\n")
})}
go func() {
select {
case <-ctx.Done():
shutdownServer(svr, ctx)
}
}()
log.Println("HTTP Server ready to start...")
return svr.ListenAndServe()
}
func shutdownServer(server *http.Server, ctx context.Context) {
_ = server.Shutdown(ctx)
}
<file_sep>/Week04/demoproject/api/xxapi_gen.go
package api
//auto generated go file
<file_sep>/Week04/README.md
#ๅญฆไน ็ฌ่ฎฐ
## Question
ๆ็
ง่ชๅทฑ็ๆๆณ๏ผๅไธไธช้กน็ฎๆปก่ถณๅบๆฌ็็ฎๅฝ็ปๆๅๅทฅ็จ๏ผไปฃ็ ้่ฆๅ
ๅซๅฏนๆฐๆฎๅฑใไธๅกๅฑใAPI ๆณจๅ๏ผไปฅๅ main ๅฝๆฐๅฏนไบๆๅก็ๆณจๅๅๅฏๅจ๏ผไฟกๅทๅค็๏ผไฝฟ็จ Wire ๆๅปบไพ่ตใๅฏไปฅไฝฟ็จ่ชๅทฑ็ๆ็ๆกๆถใ
## Status
Wire part code is not completed yet..
Due to work overtime till now.
Finished a conference call with colleagues in US just now 23:42.
|
bcc94277f3bddb2fccc9508cc645140e055da936
|
[
"Markdown",
"Go"
] | 10 |
Go
|
Cozy228/Go-000
|
8d9486558951a5e29e29a0b64b21360db7c7cec3
|
ab4a57f063dc44f8258dd32ad3980f2d162997b3
|
refs/heads/master
|
<repo_name>Sprinterzzj/drifter_ml<file_sep>/drifter_ml/classification_tests/classification_tests.py
from sklearn import metrics
import numpy as np
import time
from sklearn import neighbors
from scipy import stats
from sklearn.model_selection import cross_validate, cross_val_predict
from functools import partial
from sklearn.model_selection import KFold
from sklearn.base import clone
class FixedClassificationMetrics():
def __init__(self):
pass
def precision_score(self, y_true, y_pred,
labels=None, pos_label=1, average='binary', sample_weight=None):
y_true = np.array(y_true)
y_pred = np.array(y_pred)
if (y_true == y_pred).all() == True:
return 1.0
else:
return metrics.precision_score(y_true,
y_pred,
labels=labels,
pos_label=pos_label,
average=average,
sample_weight=sample_weight)
def recall_score(self, y_true, y_pred,
labels=None, pos_label=1, average='binary', sample_weight=None):
y_true = np.array(y_true)
y_pred = np.array(y_pred)
if (y_true == y_pred).all() == True:
return 1.0
else:
return metrics.recall_score(y_true,
y_pred,
labels=labels,
pos_label=pos_label,
average=average,
sample_weight=sample_weight)
def f1_score(self, y_true, y_pred,
labels=None, pos_label=1, average='binary', sample_weight=None):
y_true = np.array(y_true)
y_pred = np.array(y_pred)
if (y_true == y_pred).all() == True:
return 1.0
else:
return metrics.f1_score(y_true,
y_pred,
labels=labels,
pos_label=pos_label,
average=average,
sample_weight=sample_weight)
def _prepare_for_per_class_comparison(self, y_true, y_pred):
# this means the per class roc curve can never be zero
# but allows us to do per class classification
if (np.unique(y_true) == 0).all():
y_true = np.append(y_true, [1])
y_pred = np.append(y_pred, [1])
if (np.unique(y_true) == 1).all():
y_true = np.append(y_true, [0])
y_pred = np.append(y_pred, [0])
return y_true, y_pred
def roc_auc_score(self, y_true, y_pred,
labels=None, pos_label=1, average='micro', sample_weight=None):
y_true = np.array(y_true)
y_pred = np.array(y_pred)
if (y_true == y_pred).all() == True:
return 1.0
else:
y_true, y_pred = self._prepare_for_per_class_comparison(y_true, y_pred)
return metrics.roc_auc_score(y_true,
y_pred,
average=average,
sample_weight=sample_weight)
# ToDo: reorganize this class into a bunch of smaller classes that inherit into a main class
class ClassificationTests(FixedClassificationMetrics):
def __init__(self,
clf,
test_data,
target_name,
column_names):
self.clf = clf
self.test_data = test_data
self.column_names = column_names
self.target_name = target_name
self.y = test_data[target_name]
self.X = test_data[column_names]
self.classes = set(self.y)
def get_test_score(self, cross_val_dict):
return list(cross_val_dict["test_score"])
# add cross validation per class tests
def precision_cv(self, cv, average='binary'):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
precision = metrics.make_scorer(precision_score)
result = cross_validate(self.clf, self.X,
self.y, cv=cv,
scoring=(precision))
return self.get_test_score(result)
def recall_cv(self, cv, average='binary'):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
recall = metrics.make_scorer(recall_score)
result = cross_validate(self.clf, self.X,
self.y, cv=cv,
scoring=(recall))
return self.get_test_score(result)
def f1_cv(self, cv, average='binary'):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
f1 = metrics.make_scorer(f1_score)
result = cross_validate(self.clf, self.X,
self.y, cv=cv,
scoring=(f1))
return self.get_test_score(result)
def roc_auc_cv(self, cv, average="micro"):
roc_auc_score = partial(self.roc_auc_score, average=average)
roc_auc = metrics.make_scorer(roc_auc_score)
result = cross_validate(self.clf, self.X,
self.y, cv=cv,
scoring=(roc_auc))
return self.get_test_score(result)
def _cross_val_avg(self, scores, minimum_center_tolerance):
avg = np.mean(scores)
if avg < minimum_center_tolerance:
return False
return True
def _get_per_class(self, y_true, y_pred, metric):
class_measures = {klass: None for klass in self.classes}
for klass in self.classes:
y_pred_class = np.take(y_pred, y_true[y_true == klass].index, axis=0)
y_class = y_true[y_true == klass]
class_measures[klass] = metric(y_class, y_pred_class)
return class_measures
def _per_class_cross_val(self, metric, cv, random_state=42):
kfold = KFold(n_splits=cv, shuffle=True, random_state=random_state)
clf = clone(self.clf)
scores = []
for train, test in kfold.split(self.test_data):
train_data = self.test_data.loc[train]
test_data = self.test_data.loc[test]
clf.fit(train_data[self.column_names], train_data[self.target_name])
y_pred = clf.predict(test_data[self.column_names])
y_true = test_data[self.target_name]
y_true.index = list(range(len(y_true)))
scores.append(self._get_per_class(y_true, y_pred, metric))
return scores
def _cross_val_anomaly_detection(self, scores, tolerance):
avg = np.mean(scores)
deviance_from_avg = [abs(score - avg)
for score in scores]
for deviance in deviance_from_avg:
if deviance > tolerance:
return False
return True
def _cross_val_per_class_anomaly_detection(self, metric, tolerance, cv):
scores_per_fold = self._per_class_cross_val(metric, cv)
results = []
for klass in self.classes:
scores = [score[klass] for score in scores_per_fold]
results.append(self._cross_val_anomaly_detection(scores, tolerance))
return all(results)
def _cross_val_lower_boundary(self, scores, lower_boundary):
for score in scores:
if score < lower_boundary:
return False
return True
def _anomaly_detection(self, scores, tolerance, method):
center, spread = self.describe_scores(scores, method)
for score in scores:
if score < center - (spread * tolerance):
return False
return True
def _per_class(self, y_pred, metric, lower_boundary):
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
if metric(y_class, y_pred_class) < lower_boundary[klass]:
return False
return True
def is_binary(self):
num_classes = len(set(self.classes))
if num_classes == 2:
return True
return False
def roc_auc_exception(self):
if not self.is_binary():
raise Exception("roc_auc is only defined for binary classifiers")
def reset_average(self, average):
if not self.is_binary() and average == 'binary':
return 'micro'
return average
def cross_val_per_class_precision_anomaly_detection(self, tolerance,
cv=3, average='binary'):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
return self._cross_val_per_class_anomaly_detection(precision_score,
tolerance, cv)
def cross_val_per_class_recall_anomaly_detection(self, tolerance,
cv=3, average='binary'):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
return self._cross_val_per_class_anomaly_detection(recall_score,
tolerance, cv)
def cross_val_per_class_f1_anomaly_detection(self, tolerance,
cv=3, average='binary'):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
return self._cross_val_per_class_anomaly_detection(f1_score,
tolerance, cv)
def cross_val_per_class_roc_auc_anomaly_detection(self, tolerance,
cv=3, average="micro"):
self.roc_auc_exception()
roc_auc_score = partial(self.roc_auc_score, average=average)
return self._cross_val_per_class_anomaly_detection(roc_auc_score,
tolerance, cv)
def cross_val_precision_anomaly_detection(self, tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.precision_cv(cv, average=average)
return self._cross_val_anomaly_detection(scores, tolerance)
def cross_val_recall_anomaly_detection(self, tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.recall_cv(cv, average=average)
return self._cross_val_anomaly_detection(scores, tolerance)
def cross_val_f1_anomaly_detection(self, tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.f1_cv(cv, average=average)
return self._cross_val_anomaly_detection(scores, tolerance)
def cross_val_roc_auc_anomaly_detection(self, tolerance, cv=3, average="micro"):
self.roc_auc_exception()
scores = self.roc_auc_cv(cv, average=average)
return self._cross_val_anomaly_detection(scores, tolerance)
def cross_val_precision_avg(self, minimum_center_tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.precision_cv(cv, average=average)
return self._cross_val_avg(scores, minimum_center_tolerance)
def cross_val_recall_avg(self, minimum_center_tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.recall_cv(cv, average=average)
return self._cross_val_avg(scores, minimum_center_tolerance)
def cross_val_f1_avg(self, minimum_center_tolerance, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.f1_cv(cv, average=average)
return self._cross_val_avg(scores, minimum_center_tolerance)
def cross_val_roc_auc_avg(self, minimum_center_tolerance, cv=3, average='micro'):
self.roc_auc_exception()
scores = self.roc_auc_cv(cv, average=average)
return self._cross_val_avg(scores, minimum_center_tolerance)
def cross_val_precision_lower_boundary(self, lower_boundary, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.precision_cv(cv, average=average)
return self._cross_val_lower_boundary(scores, lower_boundary)
def cross_val_recall_lower_boundary(self, lower_boundary, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.recall_cv(cv, average=average)
return self._cross_val_lower_boundary(scores, lower_boundary)
def cross_val_f1_lower_boundary(self, lower_boundary, cv=3, average='binary'):
average = self.reset_average(average)
scores = self.f1_cv(cv, average=average)
return self._cross_val_lower_boundary(scores, lower_boundary)
def cross_val_roc_auc_lower_boundary(self, lower_boundary, cv=3, average='micro'):
self.roc_auc_exception()
scores = self.roc_auc(cv, average=average)
return self._cross_val_lower_boundary(scores, lower_boundary)
def cross_val_classifier_testing(self,
precision_lower_boundary: float,
recall_lower_boundary: float,
f1_lower_boundary: float,
cv=3, average='binary'):
average = self.reset_average(average)
precision_test = self.cross_val_precision_lower_boundary(
precision_lower_boundary, cv=cv, average=average)
recall_test = self.cross_val_recall_lower_boundary(
recall_lower_boundary, cv=cv, average=average)
f1_test = self.cross_val_f1_lower_boundary(
f1_lower_boundary, cv=cv, average=average)
if precision_test and recall_test and f1_test:
return True
else:
return False
def trimean(self, data):
q1 = np.quantile(data, 0.25)
q3 = np.quantile(data, 0.75)
median = np.median(data)
return (q1 + 2*median + q3)/4
def trimean_absolute_deviation(self, data):
trimean = self.trimean(data)
numerator = [abs(elem - trimean) for elem in data]
return sum(numerator)/len(data)
def describe_scores(self, scores, method):
if method == "mean":
return np.mean(scores), np.std(scores)
elif method == "median":
return np.median(scores), stats.iqr(scores)
elif method == "trimean":
return self.trimean(scores), self.trimean_absolute_deviation(scores)
def spread_cross_val_precision_anomaly_detection(self, tolerance,
method="mean", cv=10, average='binary'):
average = self.reset_average(average)
scores = self.precision_cv(cv, average=average)
return self._anomaly_detection(scores, tolerance, method)
def spread_cross_val_recall_anomaly_detection(self, tolerance,
method="mean", cv=3, average='binary'):
average = self.reset_average(average)
scores = self.recall_cv(cv, average=average)
return self._anomaly_detection(scores, tolerance, method)
def spread_cross_val_f1_anomaly_detection(self, tolerance,
method="mean", cv=10, average='binary'):
average = self.reset_average(average)
scores = self.f1_cv(cv, average=average)
return self._anomaly_detection(scores, tolerance, method)
def spread_cross_val_roc_auc_anomaly_detection(self, tolerance,
method="mean", cv=10, average='micro'):
self.roc_auc_exception()
scores = self.roc_auc_cv(cv, average=average)
return self._anomaly_detection(scores, tolerance, method)
def spread_cross_val_classifier_testing(self,
precision_lower_boundary: int,
recall_lower_boundary: int,
f1_lower_boundary: int,
cv=10, average='binary'):
average = self.reset_average(average)
precision_test = self.auto_cross_val_precision_lower_boundary(
precision_lower_boundary, cv=cv, average=average)
recall_test = self.auto_cross_val_recall_lower_boundary(
recall_lower_boundary, cv=cv, average=average)
f1_test = self.auto_cross_val_f1_lower_boundary(
f1_lower_boundary, cv=cv, average=average)
if precision_test and recall_test and f1_test:
return True
else:
return False
# potentially include hyper parameters from the model
# algorithm could be stored in metadata
# Todo: determine if still relevant ^
def precision_lower_boundary_per_class(self, lower_boundary: dict, average='binary'):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
y_pred = self.clf.predict(self.X)
return self._per_class(y_pred, self.precision_score, lower_boundary)
def recall_lower_boundary_per_class(self, lower_boundary: dict, average='binary'):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
y_pred = self.clf.predict(self.X)
return self._per_class(y_pred, recall_score, lower_boundary)
def f1_lower_boundary_per_class(self, lower_boundary: dict, average='binary'):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
y_pred = self.clf.predict(self.X)
return self._per_class(y_pred, f1_score, lower_boundary)
def roc_auc_lower_boundary_per_class(self, lower_boundary: dict, average='micro'):
self.roc_auc_exception()
roc_auc_score = partial(self.roc_auc_score, average=average)
y_pred = self.clf.predict(self.X)
return self._per_class(y_pred, roc_auc_score, lower_boundary)
def classifier_testing(self,
precision_lower_boundary: dict,
recall_lower_boundary: dict,
f1_lower_boundary: dict,
average='binary'):
precision_test = self.precision_lower_boundary_per_class(precision_lower_boundary)
recall_test = self.recall_lower_boundary_per_class(recall_lower_boundary)
f1_test = self.f1_lower_boundary_per_class(f1_lower_boundary)
if precision_test and recall_test and f1_test:
return True
else:
return False
def run_time_stress_test(self, performance_boundary: dict):
for performance_info in performance_boundary:
n = int(performance_info["sample_size"])
max_run_time = float(performance_info["max_run_time"])
data = self.X.sample(n, replace=True)
start_time = time.time()
self.clf.predict(data)
model_run_time = time.time() - start_time
if model_run_time > max_run_time:
return False
return True
class ClassifierComparison(FixedClassificationMetrics):
def __init__(self,
clf_one,
clf_two,
test_data,
target_name,
column_names):
self.clf_one = clf_one
self.clf_two = clf_two
self.column_names = column_names
self.target_name = target_name
self.test_data = test_data
self.y = test_data[target_name]
self.X = test_data[column_names]
self.classes = set(self.y)
def is_binary(self):
num_classes = len(set(self.classes))
if num_classes == 2:
return True
return False
def roc_auc_exception(self):
if not self.is_binary():
raise Exception("roc_auc is only defined for binary classifiers")
def reset_average(self, average):
if not self.is_binary() and average == 'binary':
return 'micro'
return average
def two_model_prediction_run_time_stress_test(self, performance_boundary):
for performance_info in performance_boundary:
n = int(performance_info["sample_size"])
data = self.X.sample(n, replace=True)
start_time = time.time()
self.clf_one.predict(data)
model_one_run_time = time.time() - start_time
start_time = time.time()
self.clf_two.predict(data)
model_two_run_time = time.time() - start_time
# we assume model one should be faster than model two
if model_one_run_time > model_two_run_time:
return False
return True
def precision_per_class(self, clf, average="binary"):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
y_pred = clf.predict(self.X)
precision = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
precision[klass] = precision_score(y_class, y_pred_class)
return precision
def recall_per_class(self, clf, average="binary"):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
y_pred = clf.predict(self.X)
recall = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
recall[klass] = recall_score(y_class, y_pred_class)
return recall
def f1_per_class(self, clf, average="binary"):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
y_pred = clf.predict(self.X)
f1 = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
f1[klass] = f1_score(y_class, y_pred_class)
return f1
def roc_auc_per_class(self, clf, average="micro"):
self.roc_auc_exception()
roc_auc_score = partial(self.roc_auc_score, average=average)
y_pred = clf.predict(self.X)
roc_auc = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
roc_auc[klass] = roc_auc_score(y_class, y_pred_class)
return roc_auc
def _precision_recall_f1_result(self,
precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test):
for klass in precision_one_test:
precision_result = precision_one_test[klass] < precision_two_test[klass]
recall_result = recall_one_test[klass] < recall_two_test[klass]
f1_result = f1_one_test[klass] < f1_two_test[klass]
if precision_result or recall_result or f1_result:
return False
return True
def _precision_recall_f1_roc_auc_result(self,
precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test,
roc_auc_one_test,
roc_auc_two_test):
for klass in precision_one_test:
precision_result = precision_one_test[klass] < precision_two_test[klass]
recall_result = recall_one_test[klass] < recall_two_test[klass]
f1_result = f1_one_test[klass] < f1_two_test[klass]
roc_auc_result = roc_auc_one_test[klass] < roc_auc_two_test[klass]
if precision_result or recall_result or f1_result or roc_auc_result:
return False
return True
def two_model_classifier_testing(self, average="binary"):
average = self.reset_average(average)
precision_one_test = self.precision_per_class(self.clf_one, average=average)
recall_one_test = self.recall_per_class(self.clf_one, average=average)
f1_one_test = self.f1_per_class(self.clf_one, average=average)
precision_two_test = self.precision_per_class(self.clf_two, average=average)
recall_two_test = self.recall_per_class(self.clf_two, average=average)
f1_two_test = self.f1_per_class(self.clf_two, average=average)
if self.is_binary():
if average == 'binary':
average = 'micro'
roc_auc_one_test = self.roc_auc_per_class(self.clf_one, average=average)
roc_auc_two_test = self.roc_auc_per_class(self.clf_two, average=average)
return self._precision_recall_f1_roc_auc_result(precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test,
roc_auc_one_test,
roc_auc_two_test)
else:
self._precision_recall_f1_result(precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test)
def cross_val_precision_per_class(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
precision = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
precision[klass] = precision_score(y_class, y_pred_class)
return precision
def cross_val_recall_per_class(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
recall = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
recall[klass] = recall_score(y_class, y_pred_class)
return recall
def cross_val_f1_per_class(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
f1 = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
f1[klass] = f1_score(y_class, y_pred_class)
return f1
def cross_val_roc_auc_per_class(self, clf, cv=3, average="micro"):
self.roc_auc_exception()
roc_auc_score = partial(self.roc_auc_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
roc_auc = {}
for klass in self.classes:
y_pred_class = np.take(y_pred, self.y[self.y == klass].index, axis=0)
y_class = self.y[self.y == klass]
roc_auc[klass] = roc_auc_score(y_class, y_pred_class)
return roc_auc
def cross_val_per_class_two_model_classifier_testing(self, cv=3, average="binary"):
average = self.reset_average(average)
precision_one_test = self.cross_val_precision_per_class(self.clf_one,
cv=cv, average=average)
recall_one_test = self.cross_val_recall_per_class(self.clf_one,
cv=cv, average=average)
f1_one_test = self.cross_val_f1_per_class(self.clf_one,
cv=cv, average=average)
precision_two_test = self.cross_val_precision_per_class(self.clf_two,
cv=cv, average=average)
recall_two_test = self.cross_val_recall_per_class(self.clf_two,
cv=cv, average=average)
f1_two_test = self.cross_val_f1_per_class(self.clf_two,
cv=cv, average=average)
if self.is_binary():
if average == 'binary':
average = 'micro'
roc_auc_one_test = self.roc_auc_per_class(self.clf_one, average=average)
roc_auc_two_test = self.roc_auc_per_class(self.clf_two, average=average)
return self._precision_recall_f1_roc_auc_result(precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test,
roc_auc_one_test,
roc_auc_two_test)
else:
self._precision_recall_f1_result(precision_one_test,
precision_two_test,
recall_one_test,
recall_two_test,
f1_one_test,
f1_two_test)
def cross_val_precision(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
precision_score = partial(self.precision_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
return precision_score(self.y, y_pred)
def cross_val_recall(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
recall_score = partial(self.recall_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
return recall_score(self.y, y_pred)
def cross_val_f1(self, clf, cv=3, average="binary"):
average = self.reset_average(average)
f1_score = partial(self.f1_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
return f1_score(self.y, y_pred)
def cross_val_roc_auc(self, clf, cv=3, average="micro"):
self.roc_auc_exception()
roc_auc_score = partial(self.roc_auc_score, average=average)
y_pred = cross_val_predict(clf, self.X, self.y, cv=cv)
return roc_auc_score(self.y, y_pred)
def cross_val_two_model_classifier_testing(self, cv=3, average="binary"):
average = self.reset_average(average)
precision_one_test = self.cross_val_precision(self.clf_one,
cv=cv, average=average)
recall_one_test = self.cross_val_recall(self.clf_one,
cv=cv, average=average)
f1_one_test = self.cross_val_f1(self.clf_one,
cv=cv, average=average)
precision_two_test = self.cross_val_precision(self.clf_two,
cv=cv, average=average)
recall_two_test = self.cross_val_recall(self.clf_two,
cv=cv, average=average)
f1_two_test = self.cross_val_f1(self.clf_two,
cv=cv, average=average)
precision_result = precision_one_test < precision_two_test
recall_result = recall_one_test < recall_two_test
f1_result = f1_one_test < f1_two_test
if self.is_binary():
if average == 'binary':
average = 'micro'
roc_auc_one_test = self.cross_val_roc_auc(self.clf_one,
cv=cv, average=average)
roc_auc_two_test = self.cross_val_roc_auc(self.clf_two,
cv=cv, average=average)
roc_auc_result = roc_auc_one_test < roc_auc_two_test
if precision_result or recall_result or f1_result or roc_auc_result:
return False
else:
return True
else:
if precision_result or recall_result or f1_result:
return False
else:
return True
|
d8a0a76ed372eb72ddab2a49a08a9f97ce7d16ed
|
[
"Python"
] | 1 |
Python
|
Sprinterzzj/drifter_ml
|
5a11323618e3aff0a5790d4ad2cdd6132d2655e9
|
f1b7bfaad30960d8f343b12c6a2345db81eb7b2c
|
refs/heads/master
|
<repo_name>d-vandyshev/parser_swisslife-select.de<file_sep>/parser_swisslife-select.de_consultants.rb
#
# Parser data of counsultants from swisslife-select.de and export to csv-file
#
# Created by <NAME>
# email: d.vandyshev (doggy) ya.ru
# skype: d.vandyshev,
# freelancer.com: https://www.freelancer.com/u/vandyshev.html
# odesk/upwork.com: https://www.upwork.com/users/~0171345aa6fedb4083
#
require 'mechanize'
require 'nokogiri'
require 'csv'
require 'rubygems'
exit if Object.const_defined?(:Ocra)
puts 'Start parser data of counsultants from swisslife-select.de and export to csv-file'
BASE_URL = 'http://www.swisslife-select.de'
URL_DATA_CONSULTANTS = 'https://tech.swisslife-select.de/routenplaner/view.jsp?domain=awdde&language=de'
CSV_OUT_FILE = 'swiss_cons.csv'
mech = Mechanize.new { |agent|
agent.user_agent_alias = 'Windows Chrome'
agent.follow_meta_refresh = true
}
puts 'Get page with data of consultants'
content = mech.get(URL_DATA_CONSULTANTS).body.force_encoding('ISO-8859-1').encode!('UTF-8')
items = content.scan /html="([^"]*)";/
Consultant = Struct.new(
:title,
:name,
:address,
:postcode,
:city,
:phone,
:mobile_phone,
:fax,
:email,
:homepage_url,
:image_url,
:contact_url
)
# Consultants
puts 'Get data for each consultant'
cons = []
items.each_with_index do |e, j|
puts "#{j} of #{items.length}"
puts "\t Get data from javascript strings"
c = Consultant.new
# Fields
e[0].split('<br>').each_with_index do |f, i|
next if f.empty?
f.strip!
case i
when 0
if f =~ /Frau|Herr/
c.name = f
next
end
c.title = f
next
when 1
c.name = f if c.name.nil?
next
when 2
unless c.name.nil? && f =~ /^\d{5}/
c.address = f.sub(/\s+/, ' ')
end
when 3
unless f =~ /^\d{5}/ || f == '.' || !c.address.nil?
c.address = f.sub(/\s+/, ' ')
next
end
end
if f =~ /^\d{5}/
c.postcode, *tmp = f.split
c.city = tmp.join ' '
end
n = Nokogiri::HTML f
n.css('a').each do |a|
c.homepage_url = a.attribute('href').text if a.text.include? 'Homepage'
c.contact_url = a.attribute('href').text if a.text.include? 'Kontakt'
end
end
# Get email, mobile phone, image url from homepage
unless c.homepage_url.nil?
puts "\t Get data from homepage #{c.homepage_url}"
begin
page = mech.get c.homepage_url
rescue => e
sleep 2
retry
end
# Address
if c.address.nil?
text_fields = page.parser.xpath('//text()')
text_fields.each_with_index do |t, i|
if t.text.strip =~ /^\d{5}\s/
c.address = text_fields[i-1].text.strip.sub(/\s+/, ' ')
end
end
end
page.parser.xpath('//text()').each do |t|
# a special case
if t.text.include?('Tefefax') && t.text.include?('Mobil')
tmp, c.mobile_phone = t.text.split('Mobil:')
c.mobile_phone.strip!
c.fax = tmp.sub('Tefefax:', '').strip
next
end
# Mobile
c.mobile_phone = t.text.sub('Mobil:', '').strip if t.text.include? 'Mobil'
# Phone
if c.phone.nil? && t.text.include?('Telefon')
c.phone = t.text.sub('Telefon:', '').strip
end
# Fax
if c.fax.nil? && t.text.include?('Telefax')
c.fax = t.text.sub('Telefax:', '').strip
end
end
# Email
page.parser.css('a').each do |a|
href = a.attribute('href')
next if href.nil?
c.email = a.text.strip if href.text.include? 'mailto'
end
c.image_url = BASE_URL + page.at('div.ls-bg img').attribute('src') unless page.at('div.ls-bg img').nil?
end
if c.phone =~ /Stunden/
c.phone = c.email = c.homepage_url = c.contact_url = nil
end
puts "\t" + c.inspect
cons << c.to_a
end
puts 'Export to csv...'
CSV.open(CSV_OUT_FILE, 'wb') do |csv|
csv << %w[title name address postcode city phone mobile_phone fax email homepage_url image_url contact_url]
cons.each { |c| csv << c }
end
puts 'Successfully! Press Enter to exit'
gets
<file_sep>/README.md
# parser_swisslife-select.de
|
e7d8ba893253a17e0337e4e27b00f2e2362c1595
|
[
"Markdown",
"Ruby"
] | 2 |
Ruby
|
d-vandyshev/parser_swisslife-select.de
|
41e91be8d8b010e6d94372c60acca1c9310ae6c4
|
bcfbb142010ef257c51f96c9ad1c0195f8d8ab68
|
refs/heads/master
|
<repo_name>Griffendoors/roadsafe<file_sep>/web.js
var express = require('express');
var pg = require('pg').native;
var connectionString = process.env.DATABASE_URL;
var start = new Date();
var port = process.env.PORT;
var client;
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var password = require('<PASSWORD>');
var path = require('path');
var randtoken = require('rand-token');
client = new pg.Client(connectionString);
client.connect();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.static(__dirname +'/www'));
app.use(cors());
app.post('/logout',function(req,res){
tokenAllowed(req.body.token,function(ok){
if(ok){
doLogOut(req,res);
}
else{
noToken(req,res);
}
});
});
app.get('/seqtok',function(req,res){
tokenAllowed(req.query.token,function(ok){
if(ok){
doseqTok(req,res);
}
else{
noToken(req,res);
}
});
});
app.post('/newUser',function(req,res){
var un = req.body.username;
var pw = req.body.password;
var query = client.query('SELECT COUNT(username) FROM users u WHERE u.username = $1', [un]);
var count;
query.on('row',function(result){
count = result.count;
});
query.on('end',function(){
if(count == 0){
encrypt(pw,function(epw){
var query2 = client.query('INSERT INTO users(username,password) VALUES($1,$2)',[un,epw]);
query2.on('end',function(){
var query3 = client.query('INSERT INTO badges(username,b1,b2,b3,b4) VALUES($1,FALSE,FALSE,FALSE,FALSE)',[un]);
query3.on('end',function(){
res.writeHead(200);
res.write('signup succesful');
res.end();
});
});
});
}
else{
res.write('User with this Username already exists!');
res.end();
}
});
});
app.post('/login',function(req,res){
var un = req.body.username;
var pw = req.body.password;
verifyCredentials(un,pw,function(verified){
if(!verified){
res.write('unauthorized login!');
res.end();
}
else{
var token = giveMeAToken();
var queryTokenInsert = client.query('INSERT INTO validTokens(token) VALUES($1)',[token]);
queryTokenInsert.on('end',function(){
var setUserToken = client.query('UPDATE users SET token = $1 WHERE username = $2',[token,un]);
setUserToken.on('end',function(){
res.writeHead(200);
res.write(token);
res.end();
});
});
}
});
});
/////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
app.get('/testupdate', function (req,res){
res.sendfile('testupdate.html');
});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
app.get('/rank', function (req,res){
query = client.query('SELECT username , totalpoints, points_lvl FROM rank ORDER BY totalpoints DESC') ;
var alluser =[];
query.on('row', function (result){
var user ={
username : "",
totalpoints: 0
} ;
user.username = result.username;
user.totalpoints = result.totalpoints;
user.points_lvl = result.points_lvl ;
alluser.push(user) ;
});
query.on('err', function(err){
res.statusCode = 503 ;
console.log("503 : ERROR "+ err.message );
return res.send( "503 : ERROR");
})
query.on('end', function(){
if(alluser.length < 1 ){
res.statusCode =404 ;
console.log ("404 : NOT FOUND");
res.return ("404 : NOT FOUND");
res.end() ;
}else {
res.statusCode = 200 ;
console.log("SUCCESS RETRIEVING FROM DATABASE");
return res.send(alluser) ;
}
});
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
app.get('/user/:username', function (req,res){
console.log("1");
if(!req.params.username ){console.log("start-----");
console.log("NEED USERNAME");
res.writeHead(400);
res.write('Error 400 : USERNAME not specified');
res.end();
}
console.log("2");
var count =-1 ;
var user ={
username : req.params.username,
totalpoint : 0 ,
points_lvl : [10],
best : [10]
}
query = client.query('SELECT COUNT(*) AS COUNT ,TOTALPOINTS, USERNAME , POINTS_LVL , LVL_BEST FROM RANK WHERE USERNAME=$1 GROUP BY USERNAME',
[user.username]);
query.on('row', function(result){
if(result){console.log("1-----");
count = result.count;
user.totalpoint = result.totalpoints;
user.points_lvl =result.points_lvl;
user.best = result.lvl_best;
console.log("RETRIEVE SUCCESS AT GET USER") ;
console.log(user.toString());
res.writeHead(200);
res.write(user.toString());
res.end();
//res.send(user);
}
});
query.on('err', function(err){
if(err){console.log("2-----");
console.log("ERROR" + err.message);
res.writeHead(503);
res.write("503 : ERROR");
res.end();
}
});
query.on('end', function(){
if(count == -1 ){console.log("3-----");
console.log("USER NOT FOUND");
res.writeHead(404);
res.write("404: USERNOT FOUND");
res.end();
}
res.end() ;
});
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
app.get('/pointsAtlevel/:username/:lvl', function (req, res){
if(!req.params.username || req.params.lvl < 0 || req.params.lvl>10 ){
console.log( "please specify what lvl need") ;
res.writeHead(400);
res.write('Error 400: BAD REQUEST , Post syntax incorrect.');
res.end();
}
var obj = {
username : req.params.username,
};
query = client.query('SELECT POINTS_LVL [$1] AS points, COUNT(username) FROM RANK WHERE username = $2 GROUP BY POINTS_LVL[$1]',[req.params.lvl-1, obj.username]);
var returnPoint = -1 ; var p = -1 ;
query.on('row', function (result){
if (result) {
returnPoint = result.count ;
p = result.points ;
if(p != -1 ) {
console.log("suceess"+ result.points) ;
res.write(""+p) ;
res.end();
}else {
console.log("404 : NOT FOUND");
res.writeHead(404);
res.write("404: CAN NOT FIND USER WITH GIVEN USER NAME");
res.end();
}
}
});
query.on('error', function(err){
console.log(err.message) ;
res.writeHead(503);
res.write("503 : ERROR");
res.end();
});
query.on('end', function(){
if(returnPoint == -1 ) {
console.log("404 : NOT FOUND");
res.writeHead(404);
res.write("404: NOT CANT FIND USERNAME");}
res.end() ;
});
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
app.post('/update/:lvl' , function (req, res){
if(!req.body.hasOwnProperty('username') || !req.body.hasOwnProperty('point') || !req.params.lvl > 0){
console.log( "please specify what lvl need to update") ;
res.writeHead(400);
res.write('Error 400: Post syntax incorrect.');
res.end() ;
}
var obj = {
username : req.body.username,
point : req.body.point,
level : req.params.lvl-1
};
// assuming the username is correct that why it can do the updating
query = client.query('SELECT count(username) , lvl_best[$1] AS best FROM rank WHERE username = $2 GROUP BY lvl_best[$1]',[obj.level, obj.username]);
var count = -1 ; var best = 0 ;
query.on('row', function(result){
count = result.count ;
best = result.best ;
});
query.on('err' , function(err){
console.log( "ERROR : "+ err.message) ;
res.writeHead(503);
res.write("503 : ERROR");
res.end() ;
});
query.on('end', function(){
if(count == -1 ) {
//res.statusCode = 404 ;
console.log ( "404 : USERNAME NOT FOUND") ;
res.write("404 : USERNAME NOT FOUND");
}else {
if(best >= obj.point){res.statusCode=200; console.log("DO NOT NEED TO UPDATE");
res.write("200 : DO NOT NEED TO UPDATE") ; res.end() ;
}
else {
client.query('UPDATE rank SET points_lvl[$1] = $2, lvl_best[$1]=$2 , totalpoints = totalpoints + $3 WHERE username=$4',[obj.level,obj.point,(obj.point-best),obj.username],function (err){
if(err) {console.log( "err :"+err.message) ; res.writeHead(503); res.write("503 : Error at UPDATE" ) ; res.end() ; }
console.log("UPDATED");
res.writeHead(200);
res.write("200 : UPDATE") ;
res.end() ;
});
}
}
//res.end() ;
});
});
app.get('/userBadges',function(req,res){
var un = req.query.username;
// console.log("TTTTTTTTTTTTTTTTTTTTT"+un);
// console.log("y"+req.params.username);
// console.log("r"+req.query.username);
// var ab1,ab2,ab3,ab4;
var bb1,bb2,bb3,bb4;
//var result;
var query = client.query('SELECT b1,b2,b3,b4 FROM badges b WHERE b.username = $1', [un]);
query.on('row', function(row, result) {
// // result.addRow(row);
// ab1 = result.b1;
// ab2 = result.b2;
// ab3 = result.b3;
// ab4 = result.b4;
bb1 = row.b1;
bb2 = row.b2;
bb3 = row.b3;
bb4 = row.b4;
});
query.on('end', function(result) {
//console.log(result.rows.length + ' rows were received');
// console.log("1"+ab1);
// console.log("2"+ab2);
// console.log("3"+ab3);
// console.log("4"+ab4);
// console.log("5"+bb1);
// console.log("6"+bb2);
// console.log("7"+bb3);
// console.log("8"+bb4);
var s1 = bb1.toString();
var string1 = s1.substring(0,1);
var s2 = bb2.toString();
var string2 = s2.substring(0,1);
var s3 = bb3.toString();
var string3 = s3.substring(0,1);
var s4 = bb4.toString();
var string4 = s4.substring(0,1);
var toReturn = ""+string1+string2+string3+string4;
res.writeHead(200);
res.write(toReturn);
res.end();
});
// query.on('end',function(){
// for(key in result){
// console.log(result);
// }
// // var toReturn = ""+b1.toString()+b2.toString()+b3.toString()+b4.toString();
// // res.writeHead(200);
// // res.write(toReturn);
// // res.end();
// res.writeHead(200);
// res.write("");
// res.end();
// });
});
app.post('/newBadge',function(req,res){
var un = req.body.username;
var bid = req.body.bid;
console.log("un"+un);
console.log("b"+bid);
var query;
if(bid==1){
query = client.query('UPDATE badges SET b1 = TRUE WHERE username = $1', [un]);
}
else if(bid==2){
query = client.query('UPDATE badges SET b2 = TRUE WHERE username = $1', [un]);
}
else if(bid==3){
query = client.query('UPDATE badges SET b3 = TRUE WHERE username = $1', [un]);
}
else if(bid==4){
query = client.query('UPDATE badges SET b4 = TRUE WHERE username = $1', [un]);
}
query.on('end',function(){
res.writeHead(200);
res.end();
});
});
///////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function doseqTok(req,res){
var token = giveMeAToken();
var query = client.query('INSERT INTO validTokens(token) VALUES($1)', [token],function(){
res.writeHead(200);
res.write(token);
res.end();
});
query.on('end',function(){
removeActiveToken(req.query.token,function(){
return token;
});
});
}
function encrypt(given,callback){
password(given).hash(function(error, hash) {
if(error){
console.log('given is: '+given)
throw new Error('Something went wrong!');
}
callback(hash);
});
}
function verifyCredentials(givenUsername,givenPassword,callback){
var query = client.query('SELECT password FROM users u WHERE u.username = $1',[givenUsername]);
var storedHash;
query.on('row',function(result){
storedHash = result.password;
//IF !result ??
});
query.on('end',function(){
if(storedHash == null){
callback(false);
}
password(givenPassword).verifyAgainst(storedHash, function(error, verified) {
if(error)
throw new Error('Something went wrong!');
if(!verified) {
callback(false);
} else {
callback(true);
}
});
});
}
function giveMeAToken(given){
var token = randtoken.generate(16);
return token;
}
function tokenAllowed(given,callback){
query = client.query('SELECT COUNT(token) FROM validTokens v WHERE v.token = $1',[given]);
var count = 0;
query.on('row',function(result){
count = result.count;
});
query.on('end',function(){
if(count != 0){
callback(true);
}
else{
callback(false);
}
});
}
function removeActiveToken(given,req,res){
query = client.query('DELETE FROM validTokens WHERE token = $1',[given]);
query.on('end',function(){
var removeUserToken = client.query('UPDATE users SET token = $1 WHERE username = $2',["absent",given]);
removeUserToken.on('end',function(){
res.write('logout succesful');
res.end();
});
});
}
function noToken(req,res){
res.send('Invalid Access token!');
}
function doLogOut(req,res){
removeActiveToken(req.query.token,req,res);
}
// use PORT set as an environment variable
var server = app.listen(process.env.PORT, function() {
console.log('Listening on port %d', server.address().port);
});<file_sep>/validTokensSchema.js
var pg = require('pg').native
, connectionString = process.env.DATABASE_URL
, client
, query;
//CREATE DATABASE CONECTION
client = new pg.Client(connectionString);
client.connect();
//CREATE A SCHEMA - users
query = client.query('DROP TABLE IF EXISTS validTokens;');
query = client.query('CREATE TABLE validTokens(token text PRIMARY KEY)');
//CALLBACK TO END DATABASE CONNECTION
query.on('end', function(result) { client.end(); });<file_sep>/badges.js
var pg = require('pg').native
, connectionString = process.env.DATABASE_URL
, client
, query;
//CREATE DATABASE CONECTION
client = new pg.Client(connectionString);
client.connect();
//CREATE A SCHEMA - users
query = client.query('DROP TABLE IF EXISTS badges;');
query = client.query('CREATE TABLE badges(username text PRIMARY KEY, b1 BOOLEAN, b2 BOOLEAN, b3 BOOLEAN, b4 BOOLEAN)');
query.on('end', function(result) { client.end(); });
|
9d304b8ac69bd6d134ce941769988015c4b330e4
|
[
"JavaScript"
] | 3 |
JavaScript
|
Griffendoors/roadsafe
|
69427473dba7013f99fac70a379f13e00b91807c
|
0edb70f39d400a48b08fe36707980ec905d91d6e
|
refs/heads/master
|
<repo_name>mtarunpr/find-a-friend<file_sep>/README.md
## Website
The Find A Friend web app is hosted at: https://find-a-friend-hackmit.web.app/.
## Description
One of the biggest challenges for students as we navigate through these difficult times is finding and maintaining a sense of community despite the lack of face-to-face contact: it is close to impossible to strike up a conversation with a stranger online as one might do in person. Students have turned to anonymous confessions pages, which have seen a massive rise in popularity of late, to voice their pains and struggles; but such pages are very limited in scope and do not create lasting connections.
Our platform aims to solve this problem by allowing users to chat anonymously with a complete stranger (chosen randomly from among those registered from your school), whether to vent, rant, or simply talk. If you hit it off (and if both participants choose to reveal themselves), you will be notified of the identity of the person you were talking to, along with their contact information to continue the conversation!
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
<file_sep>/src/PageChat.js
import React from 'react';
import { Link, Redirect, withRouter } from 'react-router-dom';
import {
firebaseConnect,
isLoaded,
isEmpty,
populate,
} from 'react-redux-firebase';
import { compose } from 'redux';
import { connect } from 'react-redux';
class PageChat extends React.Component {
constructor(props) {
super(props);
// console.log(this.props.cards[0].front);
this.state = {
message_send: '',
open: false,
reveal: 'Reveal',
};
}
open = () => this.setState({ open: true });
close = () => this.setState({ open: false });
handleChange = event =>
this.setState({ [event.target.name]: event.target.value });
sendMessage = () => {
if (this.state.message_send !== '') {
console.log('sending message ' + this.props.isLoggedIn);
const updates = {};
const newMessage = {
sender_id: this.props.isLoggedIn,
message: this.state.message_send,
};
this.props.chat.messages.push(newMessage);
// console.log(this.props.chat.messages);
updates[
`/chats/${this.props.chatId}/messages`
] = this.props.chat.messages;
// const onComplete = () => alert("sent"); //this.props.history.push(`/chats/${chatId}`);
this.props.firebase.update(`/`, updates);
this.setState({ message_send: '' });
}
};
leaveChat = () => {
const chatId = this.props.chatId;
const chat = this.props.chat;
console.log('leaving ' + this.props.chatId);
const updates = {};
//check is both revealed
const revealed = chat.reveal1 && chat.reveal2;
if (revealed) {
alert(
'You both chose to reveal your identities! Find out who they are in your home page.',
);
// Add friends if this user is the first to leave
if (this.props.chat.sender1 && this.props.chat.sender2) {
updates[
`/users/${this.props.chat.sender1}/friends/${this.props.chat.sender2}`
] = {
id: this.props.chat.sender2,
};
updates[
`/users/${this.props.chat.sender2}/friends/${this.props.chat.sender1}`
] = {
id: this.props.chat.sender1,
};
}
}
// If other user has already left, clear out chat
if (!this.props.chat.sender1 || !this.props.chat.sender2) {
updates[`/chats/${this.props.chatId}`] = {};
} else {
// Otherwise only clear out this user's sender id
if (this.props.chat.sender1 === this.props.isLoggedIn) {
updates[`/chats/${this.props.chatId}/sender1`] = {};
} else if (this.props.chat.sender2 === this.props.isLoggedIn) {
updates[`/chats/${this.props.chatId}/sender2`] = {};
}
// Notify other user of the leaving
const newMessage = {
sender_id: 'Bot',
message: 'Your anonymous friend has left the chat!',
};
this.props.chat.messages.push(newMessage);
updates[
`/chats/${this.props.chatId}/messages`
] = this.props.chat.messages;
}
updates[`/users/${this.props.isLoggedIn}/chat`] = [];
const onComplete = () => this.props.history.push(`/`);
this.props.firebase.update(`/`, updates, onComplete);
};
report = () => {
const reportId = this.props.firebase.push('/reports').key;
const updates = {};
updates[reportId] = {
...this.props.chat,
reporter_id: this.props.isLoggedIn,
};
this.props.firebase.update(`/reports`, updates);
alert('This user has been reported. Please feel free to leave the chat.');
};
reveal = () => {
const sender1 = this.props.chat.sender1;
const sender2 = this.props.chat.sender2;
const updates = {};
if (this.state.reveal === 'Reveal') {
if (this.props.isLoggedIn === sender1) {
updates[`/chats/${this.props.chatId}/reveal1`] = true;
} else {
updates[`/chats/${this.props.chatId}/reveal2`] = true;
}
this.setState({ reveal: 'Conceal' });
} else {
if (this.props.isLoggedIn === sender1) {
updates[`/chats/${this.props.chatId}/reveal1`] = false;
} else {
updates[`/chats/${this.props.chatId}/reveal2`] = false;
}
this.setState({ reveal: 'Reveal' });
}
// const onComplete = () => this.props.history.push(`/`);
this.props.firebase.update(`/`, updates);
};
scrollToBottom = () => {
if (this.messagesEnd) {
this.messagesEnd.scrollIntoView({ behavior: 'smooth' });
}
};
componentDidMount() {
this.scrollToBottom();
}
componentDidUpdate() {
this.scrollToBottom();
}
render() {
console.log(this.props);
if (!isLoaded(this.props.chat)) {
return <div>Loading...</div>;
}
if (!this.props.isLoggedIn) {
return <Redirect to="/login" />;
}
if (isEmpty(this.props.chat)) {
return <div>Page not found!</div>;
}
const messages = this.props.chat.messages.map((message, index) => {
let avatar =
'https://api.adorable.io/avatars/60/' +
message.sender_id +
'@adorable.io.png';
if (message.sender_id === this.props.isLoggedIn) {
return (
<tr key={index}>
<td></td>
<td></td>
<td className="user-one">{message.message}</td>
<td className="propic-one">
<img alt="User one" src={avatar}></img>
</td>
</tr>
);
} else {
return (
<tr key={index}>
<td className="propic-two">
<img alt="User two" src={avatar}></img>
</td>
<td className="user-two">{message.message}</td>
<td></td>
<td></td>
</tr>
);
}
});
return (
<div className="center">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="../">
Find a Friend
</a>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<a className="nav-link" href="../profile">
Profile
</a>
</li>
<li className="nav-item">
<a
className="nav-link"
href="/login"
onClick={() => {
this.props.firebase.logout();
}}
>
Sign Out
</a>
</li>
</ul>
</div>
</nav>
<div className="jumbotron-chat jumbotron jumbotron-fluid">
<div className="container">
<br></br>
<h1>Chat</h1>
<p>
If you both reveal, you'll be able to see each other's profile.
</p>
</div>
</div>
<div className="container chat">
<br></br>
<div className="row align-items-center">
<table>
<colgroup>
<col className="pic" />
<col className="message" />
<col className="message" />
<col className="pic" />
</colgroup>
<tbody>{messages}</tbody>
</table>
</div>
<div
style={{ float: 'left', clear: 'both' }}
ref={el => {
this.messagesEnd = el;
}}
></div>
</div>
<br></br>
<div className="container">
<div className="row text-center">
<div className="col-10">
<textarea
className="form-control"
name="message_send"
onChange={this.handleChange}
onKeyPress={event => {
if (event.key === 'Enter') {
event.preventDefault();
this.sendMessage();
}
}}
placeholder="Send message"
value={this.state.message_send}
/>
</div>
<div className="col-2">
<button
className="btn btn-primary send-chat"
onClick={this.sendMessage}
disabled={!this.state.message_send}
>
Send
</button>
</div>
</div>
{/* Set up a confirmation before leaving the chat */}
<button className="btn btn-primary leave" onClick={this.leaveChat}>
Leave Chat
</button>
<button className="btn btn-danger report" onClick={this.report}>
Report
</button>
<button className="btn btn-primary reveal" onClick={this.reveal}>
{this.state.reveal}
</button>
<br></br>
<br></br>
</div>
</div>
);
}
}
const populates = [
{ child: 'owner', root: 'users' }, // replace owner with user object
];
const mapStateToProps = (state, props) => {
console.log(state);
const chatId = props.match.params.chatId;
const chat = state.firebase.data[chatId];
// const messages = chat && chat.messages;
// console.log(messages)
const res = populate(state.firebase, chatId, populates);
console.log(res);
return {
chat: chat,
chatId: chatId,
isLoggedIn: state.firebase.auth.uid,
res: res,
};
};
export default compose(
withRouter,
firebaseConnect(props => {
// console.log('props',props);
const chatId = props.match.params.chatId;
console.log(chatId);
//const res = populate(props.firebase, deckId, populates)
return [{ path: `/chats/${chatId}`, storeAs: chatId }];
}),
connect(mapStateToProps),
)(PageChat);
<file_sep>/src/PageProfile.js
import React from 'react';
import { firebaseConnect } from 'react-redux-firebase';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { Redirect } from 'react-router-dom';
class PageProfile extends React.Component {
constructor(props) {
super(props);
const {
name = '',
phone = '',
facebook = '',
instagram = '',
} = props.profile;
this.state = {
name,
phone,
facebook,
instagram,
};
}
handleInputChange = event => {
const { name, value } = event.target;
this.setState({ [name]: value });
};
update = async () => {
const profile = {
...this.state,
};
try {
await this.props.firebase.updateProfile(profile);
} catch (error) {
this.setState({ error: error.message });
}
};
goToProfile = ({ url, username }) => (
<a
href={`${url}${username}`}
rel="noopener noreferrer"
target="_blank"
className="btn btn-light profile"
>
Test It
</a>
);
checkChanged = () => {
const { profile } = this.props;
const needCheck = ['name', 'phone', 'facebook', 'instagram'];
let same = needCheck.every(input => this.state[input] === profile[input]);
return same;
};
render() {
if (!this.props.isLoggedIn) {
return <Redirect to="/login" />;
}
const { name = '', phone = '', facebook = '', instagram = '' } = this.state;
var changed = !this.checkChanged();
return (
<div className="center">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="../">
Find a Friend
</a>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ml-auto">
<li className="nav-item active">
<a className="nav-link" href="./profile">
Profile
</a>
</li>
<li className="nav-item">
<a
className="nav-link"
href="/login"
onClick={() => {
this.props.firebase.logout();
}}
>
Sign Out
</a>
</li>
</ul>
</div>
</nav>
<div className="jumbotron jumbotron-fluid">
<div className="container">
<h1>Profile</h1>
</div>
</div>
{this.state.error}
<br />
Email: {this.props.email}
<br />
<br></br>
<i style={{ padding: 10, width: 30 }} className="fa fa-user icon" />
<input
autoComplete="off"
name="name"
onChange={this.handleInputChange}
placeholder="Your name"
type="text"
value={name}
/>
<br />
<i style={{ padding: 10, width: 30 }} className="fa fa-phone icon" />
<input
autoComplete="off"
name="phone"
onChange={this.handleInputChange}
placeholder="Your Phone number"
type="tel"
value={phone}
/>
<br />
<br />
Make online connections with your friends! <br></br>
These links will be available to only the people you match with.
<br />
<br></br>
<i
style={{ padding: 10, width: 30 }}
className="fa fa-instagram icon"
/>
<input
autoComplete="off"
name="instagram"
onChange={this.handleInputChange}
placeholder="Instagram"
type="text"
value={instagram}
/>
<this.goToProfile
url="https://www.instagram.com/"
username={instagram}
/>
<br />
<i style={{ padding: 10, width: 30 }} className="fa fa-facebook icon" />
<input
autoComplete="off"
name="facebook"
onChange={this.handleInputChange}
placeholder="Facebook"
type="text"
value={facebook}
/>
<this.goToProfile url="https://www.facebook.com/" username={facebook} />
<br />
<br></br>
<button
className="btn btn-dark update-profile"
onClick={this.update}
disabled={this.state.name.trim() === ''}
>
Update profile!
</button>
{changed && (
<div style={{ color: 'red' }}>You have unsaved changes.</div>
)}
<br />
<br></br>
<br></br>
</div>
);
}
}
const mapStateToProps = state => {
return {
isLoggedIn: state.firebase.auth.uid,
email: state.firebase.profile.email,
profile: state.firebase.profile,
};
};
export default compose(
firebaseConnect(),
connect(mapStateToProps),
)(PageProfile);
<file_sep>/src/PageHome.js
import React from 'react';
import { Link, Redirect, withRouter } from 'react-router-dom';
import {
firebaseConnect,
isLoaded,
isEmpty,
populate,
} from 'react-redux-firebase';
import { compose } from 'redux';
import { connect } from 'react-redux';
import './index.css';
import ProfileCardView from './ProfileCardView.js';
class PageHome extends React.Component {
constructor(props) {
super(props);
// console.log(this.props.cards[0].front);
this.state = {
message_send: '',
};
}
openChat = () => {
const id = this.props.isLoggedIn;
const profiles = this.props.profiles;
const user = profiles[id];
console.log(user);
const chat = user.chat;
if (!chat) {
console.log('no chat');
this.createChat();
//create new chat
} else {
console.log('existing chat');
const chatId = chat.chatId;
const updates = {};
updates[`joined_chat`] = true;
const onComplete = () => this.props.history.push(`/chat/${chatId}`);
this.props.firebase.update(`/users/${id}/chat`, updates, onComplete);
}
};
createChat = () => {
const id = this.props.isLoggedIn;
const profiles = this.props.profiles;
const user = profiles[id];
//keys of userId
const keys = Object.keys(profiles);
// print all keys
console.log(keys);
// iterate over object
//loop through to find another user without a chat
var secondUser;
var id2;
for (var i = 0; i < keys.length * 4; i++) {
const rand = (Math.random() * keys.length) | 0;
id2 = keys[rand];
secondUser = profiles[id2];
if (!secondUser.chat && id2 !== id) {
break;
}
}
if (secondUser.chat || id2 === id) {
alert(
'Sorry, there are no available matches at the moment. Please wait a hot sec',
);
return;
}
const updates = {};
//create new chat
const chatId = this.props.firebase.push('/chats').key;
//add deck
updates[`/chats/${chatId}`] = {
sender1: id,
sender2: id2,
messages: [{ sender_id: 'Bot', message: 'Hello. Welcome to a new chat' }],
};
updates[`/users/${id}/chat`] = {
user_id: id2,
chatId: chatId,
};
updates[`/users/${id2}/chat`] = {
user_id: id,
chatId: chatId,
joined_chat: false
};
const onComplete = () => this.props.history.push(`/chat/${chatId}`);
this.props.firebase.update(`/`, updates, onComplete);
};
render() {
if (!isLoaded(this.props.profiles)) {
return <div>Loading...</div>;
}
if (!this.props.isLoggedIn) {
return <Redirect to="/login" />;
}
if (isEmpty(this.props.profiles)) {
return <div>Page not found!</div>;
}
const user = this.props.profiles[this.props.isLoggedIn];
var friends;
if (user.friends !== undefined) {
const profiles = this.props.profiles;
friends = Object.keys(user.friends).map(function (keyName, keyIndex) {
console.log(profiles);
const profile = profiles[keyName];
const path = `/profile/${keyName}`;
return <ProfileCardView key={keyName} profile={profile} />;
});
}
return (
<div className="center">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="./">
Find a Friend
</a>
<button
className="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false"
aria-label="Toggle navigation"
>
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<a className="nav-link" href="./profile">
Profile
</a>
</li>
<li className="nav-item">
<a
className="nav-link"
href="/login"
onClick={() => {
this.props.firebase.logout();
}}
>
Sign Out
</a>
</li>
</ul>
</div>
</nav>
<div className="jumbotron jumbotron-fluid">
<div className="container">
<h1>Find a Friend</h1>
<p>
Chat with an anonymous person from your school and reveal to make
friends!
</p>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-sm">
<h3>Friends</h3>
<hr></hr>
{friends}
</div>
<div className="col-sm">
{console.log('Chat', this.props.chat)}
{(this.props.chat && this.props.chat.joined_chat) ? (
<button className="btn btn-success" onClick={this.openChat}>
Continue chatting
</button>
) : (
<button className="btn btn-primary" onClick={this.openChat}>
Create new chat
</button>
)}
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state, props) => {
const userId = state.firebase.auth.uid;
const profiles = state.firebase.data;
const chat = state.firebase.profile.chat;
console.log(profiles.users);
return { isLoggedIn: userId, profiles: profiles.users, chat };
};
export default compose(
withRouter,
firebaseConnect(props => {
//console.log(id);
return [{ path: `/users/`, storeAs: 'users' }];
}),
connect(mapStateToProps),
)(PageHome);
<file_sep>/src/ProfileCardView.js
import React from 'react';
class ProfileCardView extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: false,
};
}
goToProfile = ({ url, username, classname }) => (
<a
href={`${url}${username}`}
rel="noopener noreferrer"
target="_blank"
className={classname}
>
{username}
</a>
);
render() {
return (
<div style={{ border: 'black' }}>
<div onClick={() => this.setState({ selected: !this.state.selected })}>
<i
className={
this.state.selected ? 'fa fa-chevron-down' : 'fa fa-chevron-right'
}
style={{ padding: 10, width: 30 }}
></i>
{this.props.profile.name}
</div>
{this.state.selected && (
<div>
<i
style={{ padding: 10, width: 30 }}
className="fa fa-phone icon"
/>
{this.props.profile.phone}
<br />
<i
style={{ padding: 10, width: 30 }}
className="fa fa-facebook icon"
/>
<this.goToProfile
url="https://www.facebook.com/"
username={this.props.profile.facebook || 'n/a'}
classname="btn btn-outline-primary btn-sm"
/>
{/* {this.props.profile.facebook || 'n/a'} */}
<br />
<i
style={{ padding: 10, width: 30 }}
className="fa fa-instagram icon"
/>
<this.goToProfile
url="https://www.instagram.com/"
username={this.props.profile.instagram || 'n/a'}
classname="btn btn-outline-info btn-sm"
/>
</div>
)}
<br />
</div>
);
}
}
export default ProfileCardView;
<file_sep>/src/PageLogin.js
import React from 'react';
import { firebaseConnect } from 'react-redux-firebase';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router-dom';
import 'firebase/database';
class PageLogin extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
}
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
login = async () => {
const credentials = {
email: this.state.email,
password: <PASSWORD>,
};
try {
await this.props.firebase.login(credentials);
} catch (error) {
this.setState({ error: error.message });
}
};
render() {
if (this.props.isLoggedIn) {
return <Redirect to="/" />;
}
return (
<div className="center">
<div className="jumbotron jumbotron-fluid">
<div className="container">
<h1>Find a Friend</h1>
<p>
Chat with an anonymous person from your school and reveal to make
friends!
</p>
</div>
</div>
<div className="col-md-6 mx-auto">
<br></br>
<h3 className="text-center">Login</h3>
<br></br>
<div>{this.state.error}</div>
<div className="form-group">
<input
name="email"
className="form-control"
onChange={this.handleChange}
placeholder="Email"
value={this.state.email}
/>
</div>
<div className="form-group">
<input
name="password"
type="<PASSWORD>"
className="form-control"
onChange={this.handleChange}
placeholder="<PASSWORD>"
value={this.state.password}
/>
</div>
<br></br>
<button className="btn btn-primary" onClick={this.login}>
Login
</button>
<br></br>
<br></br>
<p>
Don't have an account? <Link to="/register">Register.</Link>
</p>
</div>
</div>
);
}
}
const mapStateToProps = state => {
return { isLoggedIn: state.firebase.auth.uid };
};
export default compose(firebaseConnect(), connect(mapStateToProps))(PageLogin);
|
e36b74a2287f56145b1383feddf03d8cc02ad852
|
[
"Markdown",
"JavaScript"
] | 6 |
Markdown
|
mtarunpr/find-a-friend
|
c2480686a520ff5e27486553da1a8483d3a51be8
|
d1bbaf20867f5e2bb033a9c799e9369d29cf30b1
|
refs/heads/master
|
<repo_name>IsamiYura/TugasAkhir_PraktikumPD2<file_sep>/RandomClass.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 Responsi2;
/**
*
* @author Asus
*/
import java.util.*;
class House implements Comparable<House> {
String index;
int size;
public House(String i, int s) {
index = i;
size = s;
}
@Override
public int compareTo(House o) {
int comparedSize = o.size;
if (this.size > comparedSize) {
return 1;
} else if (this.size == comparedSize) {
return 0;
} else {
return -1;
}
}
public String toString() {
return index;
}
} // membuat objek karakter
public class RandomClass {
public static void main(String[] args) {
LinkedList<House> charaTry = new LinkedList<House>();
charaTry.add(new House("medium", 200));
System.out.println(charaTry.element().size);
charaTry.add(new House("small", 100));
charaTry.add(new House("big", 300));
System.out.println(charaTry);
// sort in ascending order
Collections.sort(charaTry);
System.out.println(charaTry);
// sort in descending order
Collections.sort(charaTry, Collections.reverseOrder());
System.out.println(charaTry);
} //contoh dasar sorting value object
public static void printList(List l) {
for (Object o : l) {
System.out.println(o);
}
} // print LinkedList
}
<file_sep>/README.md
# TugasAkhir_PraktikumPD2
repositori untuk tugas akhir praktikum pd2
|
51841d01d5f034b34d2d2288daa8fdf100d3c852
|
[
"Markdown",
"Java"
] | 2 |
Java
|
IsamiYura/TugasAkhir_PraktikumPD2
|
eba93939e8581ff8f8bf42be949eaf1c830e1774
|
b3a53b93c88fb8afa92b1677a84a8713d5212e1b
|
refs/heads/master
|
<file_sep>import pygame
import requests
WIDTH = 550
bg_color = (251,247,245)
original_grid_element_color= (52,31,151) #To separate the input elements from the elements already provided
buffer=5
response = requests.get("https://sugoku.herokuapp.com/board?difficulty=easy") #pre-fetched api to fill out the boxes initially from this website
grid=response.json()['board']
grid_original = [[grid[x][y] for y in range(len(grid[0]))] for x in range(len(grid))]
def insert(win, position): #function to take input from user
i,j = position[1], position[0]
myfont = pygame.font.SysFont('Comic Sans MS', 35)
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
return
if event.type == pygame.KEYDOWN:
#This leads to 3 cases
#1. user tries to edit default values
if(grid_original[i-1][j-1] != 0): #if the grid element is filled then we simply return
return
#2. user edits his values
if(event.key == 48): #checking with 0 as 0 is 48 in ascii
grid[i-1][j-1] = event.key - 48 #clears the previous input to allow for editing
pygame.draw.rect(win, bg_color, (position[0]*50 + buffer, position[1]*50+ buffer,50 -2*buffer , 50 - 2*buffer)) #superimposing a block with bg color to make it look like the block has been cleared
pygame.display.update()
return
#3. users enters his own values
if(0 < event.key - 48 <10): #Checking for valid input
pygame.draw.rect(win, bg_color, (position[0]*50 + buffer, position[1]*50+ buffer,50 -2*buffer , 50 - 2*buffer))
value = myfont.render(str(event.key-48), True, (0,0,0))
win.blit(value, (position[0]*50 +15, position[1]*50))
grid[i-1][j-1] = event.key - 48
pygame.display.update()
return
return
def main():
pygame.init()
win = pygame.display.set_mode((WIDTH, WIDTH))
pygame.display.set_caption("Sudoku Player")
win.fill(bg_color)
myfont = pygame.font.SysFont('Comic Sans MS', 35)
for i in range(0,10):
if(i%3==0):
pygame.draw.line(win, (0,0,0), (50 + 50*i, 50), (50 + 50*i, 500), 5) #making every third line bold to separate the boxes in the game
pygame.draw.line(win, (0,0,0), (50, 50+50*i), (500, 50 + 50*i), 5)
pygame.draw.line(win, (0,0,0), (50 + 50*i, 50), (50 + 50*i, 500), 2) #drawing the grids
pygame.draw.line(win, (0,0,0), (50, 50+50*i), (500, 50 + 50*i), 2) #drawing the grids
pygame.display.update()
for i in range(0, len(grid[0])):
for j in range (0, len(grid[0])):
if(0<grid[i][j]<10):
value = myfont.render(str(grid[i][j]), True, original_grid_element_color) #adding some values by default
win.blit(value, ((j+1)*50+15, (i+1)*50)) #Specifying the places where the values are to be added
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
pos = pygame.mouse.get_pos()
insert(win, (pos[0]//50, pos[1]//50))
if event.type == pygame.QUIT:
pygame.quit()
return
main()
|
68c1cf49051c1b40c18b7ea740e3980d96c79bb6
|
[
"Python"
] | 1 |
Python
|
Saidath/Sudoku-Python-Project-INT213-
|
b42a76ee89c25d9fc2459ac2b18e50b5661e4229
|
2ef9b41fac00d3be9484e86c9ce89991dcbb9696
|
refs/heads/master
|
<repo_name>jarl-alejandro/redux-sockjs<file_sep>/src/test/e2e/reduxChannel.test.js
import { createStore, combineReducers } from 'redux'
import { startReduxServer } from '../../../server'
import { startReduxClient } from '../../../client'
import defaultHttpServer from '../../server/defaultHttpServer'
describe('startReduxChannel for server and client', function testStartReduxChannel() {
this.slow(1000)
it('emit redux', done => {
const httpServer = defaultHttpServer()
const param = {
ip: '127.0.0.1',
port: 10002,
sockjsPrefix: '/sockjs-redux',
reconnectInterval: 0,
}
const serverChannel = startReduxServer({ ...param, server: httpServer })
const clientChannel = startReduxClient(param)
const clientData = { type: 'abc', payload: 'xxxxx' }
clientChannel.on('open', () => {
clientChannel.send(clientData)
})
serverChannel.receive(data => {
expect(data).toEqual(clientData)
serverChannel.emitter.connection.close()
httpServer.close()
done()
})
})
describe('use store in client and server', () => {
const param = {
ip: '127.0.0.1',
port: 10003,
sockjsPrefix: '/sockjs-redux',
reconnectInterval: 0,
}
it('client send action', done => {
const userReducer = (state = [], action) => {
if (action.type === 'ADD_USER') {
return [...state, action.payload]
}
return state
}
const clientReducer = (state = [], action) => {
if (action.type === 'ADD_CLIENT') {
return [...state, action.payload]
}
return state
}
// const serverStore = createStore(reducer, initialState)
const clientStore = createStore(combineReducers({
user: userReducer,
client: clientReducer,
}))
const httpServer = defaultHttpServer()
const serverChannel = startReduxServer({ ...param, server: httpServer })
const clientChannel = startReduxClient(param)
const clientData = { type: 'ADD_USER', payload: { user: 'tom' } }
clientChannel.on('open', () => {
clientChannel.send(clientData)
})
clientChannel.receive(action => {
clientStore.dispatch(action)
const state = clientStore.getState()
expect(state.user[0].id).toBe(123)
serverChannel.emitter.connection.close()
httpServer.close()
done()
})
serverChannel.receive(action => {
// serverStore.dispatch(action)
// id is generated by server db
serverChannel.send({ ...action, payload: { user: 'tom', id: 123 } })
})
})
})
})
<file_sep>/src/test/client/reduxChannel.test.js
import EventEmitter from 'events'
import ReduxChannel from '../../client/reduxChannel'
import Channel from '../../client/channel'
describe('client/reduxChannel', () => {
let socket
let reduxChannel
beforeEach(() => {
socket = new EventEmitter()
socket.send = () => {}
reduxChannel = new ReduxChannel(socket)
reduxChannel.emitter.emit('open')
})
it('inherite from Channel', () => {
expect(reduxChannel).toBeA(Channel)
expect(reduxChannel.channelName).toBe('redux')
})
it('emit data type should be "redux"', done => {
const data = {
type: 'channel',
channel: 'redux',
data: { type: 'abc', payload: [1, 2, 3] },
}
reduxChannel.receive(msg => {
expect(msg).toEqual(data.data)
done()
})
reduxChannel.emitter.emit('data', data)
})
it('redux channel data if no "data" or no "type" in "data", should throw error', () => {
const data1 = {
type: 'channel',
channel: 'redux',
}
expect(() => {
reduxChannel.emitter.emit('data', data1)
}).toThrow()
const data2 = {
type: 'channel',
channel: 'redux',
data: { name: 'xxx' },
}
expect(() => {
reduxChannel.emitter.emit('data', data2)
}).toThrow()
})
it('ondata receive the data with data.data and data.data.type', () => {
const data = {
type: 'channel',
channel: 'redux',
data: {
type: 'ADD',
payload: 'baby',
},
}
const spy = expect.createSpy()
reduxChannel.receive(spy)
reduxChannel.emitter.emit('data', data)
expect(spy).toHaveBeenCalledWith(data.data)
})
it('send wrong data without data or data.type', () => {
expect(() => {
reduxChannel.send()
}).toThrow()
expect(() => {
reduxChannel.send({})
}).toThrow()
const spy = expect.spyOn(socket, 'send')
reduxChannel.send({
type: 'XXX',
})
expect(spy).toHaveBeenCalled()
})
})
<file_sep>/src/server/emitter.js
import EventEmitter from 'events'
import warn from '../lib/warn'
/* all sockjs should dispatch to instance of this class
* */
const connections = []
class Emitter extends EventEmitter {
constructor(socket) {
super()
this.socket = socket
this.setMaxListeners(100)
this.onconnection = this.onconnection.bind(this)
socket.on('connection', this.onconnection)
}
onconnection(connection) {
connections.push(connection)
this.connection = connection
this.ondata = this.ondata.bind(this)
connection.on('data', this.ondata)
connection.on('close', () => {
connection.removeAllListeners()
connection.close()
const index = connections.findIndex(c => c === connection)
connections.splice(index, 1)
this.destroy()
})
this.emit('open')
}
ondata(message) {
try {
const data = JSON.parse(message)
this.emit('data', data)
} catch (e) {
warn(e)
}
}
/* emit data to connection no eventName, only data */
send(data) {
this.connection.write(JSON.stringify(data))
}
broadcast(data, includeSelf = true) {
connections.forEach(connection => {
if (!includeSelf && this.connection === connection) {
return
}
connection.write(JSON.stringify(data))
})
}
destroy() {
this.removeAllListeners()
}
}
Emitter.connections = connections
export default Emitter
<file_sep>/src/test/action.test.js
// import { createStore, combineReducers } from 'redux'
// import ACTION from '../lib/action'
// import reducer from '../server/reducer'
// import initialState from '../lib/initialState'
// describe('test action', () => {
// it('action', () => {
// const store = createStore(combineReducers({ task: reducer }), initialState)
// let state = store.getState()
// expect(state.task).toEqual(initialState)
// store.dispatch({ type: ACTION.ADD, payload: 123 })
// state = store.getState()
// expect(state.task).toEqual({ list: [123] })
// })
// })
<file_sep>/src/lib/env.js
const env = process.env.NODE_ENV
const isProduction = env === 'production'
export { isProduction, env }
<file_sep>/src/client/actionCreator.js
import uuid from 'uuid'
import EventEmitter from 'events'
const ActionTypes = {
SOCKJS: '@@sockjs',
NOOP_ACTION: '@@sockjs-noop',
}
const actionEmitters = []
/**
* @param {ReduxChannel} ReduxChannel instance
* @param {Number} timeoutInterval, unit milisecond
* @return {Function} action creator that bound to reduxChannel
*/
const reduxActionCreator = (reduxChannel, timeoutInterval = 1000) => {
const actionEmitter = new EventEmitter()
actionEmitters.push(actionEmitter)
actionEmitter.setMaxListeners(100)
const ondataFunc = action => {
const { token } = action
if (token && actionEmitter.listeners(token).length) {
actionEmitter.emit(token, action)
/* for action from other sockjs connection */
} else {
actionEmitter.emit(ActionTypes.SOCKJS, action)
}
}
reduxChannel.receive(ondataFunc)
/* send payload to server
* returnPromise model will return promise
* async will return an empty action that should do nothing by redux store
* */
return (type, returnPromise = false) => {
const createdAction = payload => {
if (returnPromise) {
return new Promise((resolve, reject) => {
const token = uuid.v1()
reduxChannel.send({
type,
payload,
token,
})
let timer = 0
const resolver = action => {
resolve(action)
clearTimeout(timer)
}
timer = setTimeout(() => {
actionEmitter.removeListener(token, resolver)
reject(`type: ${type}, token: ${token}, payload: ${payload} failed because timeout more than ${timeoutInterval}`)
}, timeoutInterval)
actionEmitter.once(token, resolver)
})
}
reduxChannel.send({
type,
payload,
})
return { type: ActionTypes.NOOP_ACTION }
}
createdAction.toString = () => type
return createdAction
}
}
export { ActionTypes, actionEmitters }
export default reduxActionCreator
<file_sep>/src/client/reduxSockjs.js
import { ActionTypes, actionEmitters } from './actionCreator'
/* for action from other sockjs connection */
const middleware = ({ dispatch }) => {
const actionEmitter = actionEmitters.shift()
if (!actionEmitter) {
throw new Error('need createAction(reduxChannel) first to make an actionEmitter')
}
actionEmitter.on(ActionTypes.SOCKJS, action => {
dispatch(action)
})
return next => action => next(action)
}
export default middleware
<file_sep>/src/test/server/emitter.test.js
import stream from 'stream'
import Emitter from '../../server/emitter'
describe('server/emitter', () => {
describe('with auto connection', () => {
let emitter
const conn = new stream.Transform()
conn.close = () => {}
conn.write = () => {}
const socket = new stream.Transform()
beforeEach(() => {
emitter = new Emitter(socket)
socket.emit('connection', conn)
})
afterEach(() => {
conn.emit('close')
emitter.destroy()
})
it('max listener is 100', () => {
const number = emitter.getMaxListeners()
expect(number).toBe(100)
})
it('on parse data', done => {
const data = { sdfas: 3434545 }
emitter.on('data', d => {
expect(d).toEqual(data)
done()
})
conn.emit('data', JSON.stringify(data))
})
it('on parse none json data, warn it', () => {
const spy = expect.spyOn(console, 'warn')
conn.emit('data', 'xxxxxxx')
expect(spy).toHaveBeenCalled()
spy.restore()
})
it('send/on parse json', () => {
const data = { sdfas: 3434545 }
const spy = expect.spyOn(conn, 'write')
emitter.send(data)
expect(spy).toHaveBeenCalledWith(JSON.stringify(data))
spy.restore()
})
it('conn emit close', () => {
expect(emitter.connection.listeners('data').length > 0).toBe(true)
emitter.connection.emit('close')
expect(emitter.connection.listeners('data').length === 0).toBe(true)
})
it('destroy', () => {
emitter.on('close', () => {})
expect(emitter.listeners('close').length > 0).toBe(true)
emitter.destroy()
expect(emitter.listeners('close').length === 0).toBe(true)
})
})
it('broadcast to multiple connection', done => {
const socket = new stream.Transform()
const conn1 = new stream.Transform()
conn1.close = () => {}
conn1.write = () => {}
const conn2 = new stream.Transform()
conn2.close = () => {}
conn2.write = () => {}
const emitter = new Emitter(socket)
socket.emit('connection', conn1)
socket.emit('connection', conn2)
const spy1 = expect.spyOn(conn1, 'write')
const spy2 = expect.spyOn(conn2, 'write')
const data = {
type: 'channel',
data: {
type: 'abc',
},
}
emitter.broadcast(data)
expect(spy1.calls.length).toBe(1)
expect(spy2.calls.length).toBe(1)
expect(spy1).toHaveBeenCalledWith(JSON.stringify(data))
expect(spy2).toHaveBeenCalledWith(JSON.stringify(data))
emitter.broadcast(data)
expect(spy1.calls.length).toBe(2)
expect(spy2.calls.length).toBe(2)
conn1.emit('close')
conn2.emit('close')
emitter.destroy()
done()
})
})
<file_sep>/src/test/init.js
import 'babel-polyfill'
import expect from 'expect'
global.expect = expect
global.sleep = async (time) => new Promise(resolve => {
setTimeout(() => {
resolve()
}, time)
})
<file_sep>/client.js
/*
* sockjs for redux on browser
* (c) 2016 by superwf
* Released under the MIT Liscense.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var SockJS = _interopDefault(require('sockjs-client'));
var EventEmitter = _interopDefault(require('events'));
var uuid = _interopDefault(require('uuid'));
var isAction = (function (action) {
return Boolean(action && action.type);
});
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
/*
* use redux as channelName, and check data must has "type" property
* other usages are same as Channel
* */
var generate = (function (Parent) {
return function (_Parent) {
inherits(ReduxChannel, _Parent);
function ReduxChannel(connection) {
classCallCheck(this, ReduxChannel);
return possibleConstructorReturn(this, (ReduxChannel.__proto__ || Object.getPrototypeOf(ReduxChannel)).call(this, connection, 'redux'));
}
createClass(ReduxChannel, [{
key: 'ondata',
value: function ondata(data) {
if (!isAction(data.data)) {
throw new Error('redux channel data should has redux data and has "type" in redux object ' + JSON.stringify(data));
}
get(ReduxChannel.prototype.__proto__ || Object.getPrototypeOf(ReduxChannel.prototype), 'ondata', this).call(this, data);
}
/* check redux "type" attribute
* and emit with type and channel by this.emitter to browser
* */
}, {
key: 'send',
value: function send(action) {
if (!isAction(action)) {
throw new Error('emit redux data should has "type"');
}
get(ReduxChannel.prototype.__proto__ || Object.getPrototypeOf(ReduxChannel.prototype), 'send', this).call(this, action);
}
}]);
return ReduxChannel;
}(Parent);
});
/* eslint-disable no-console */
var warn = function warn() {
var _console;
return (_console = console).warn.apply(_console, arguments);
};
/* all sockjs should dispatch to instance of this class
* */
var Emitter = function (_EventEmitter) {
inherits(Emitter, _EventEmitter);
function Emitter(connection) {
classCallCheck(this, Emitter);
var _this = possibleConstructorReturn(this, (Emitter.__proto__ || Object.getPrototypeOf(Emitter)).call(this));
_this.connection = connection;
_this.setMaxListeners(100);
_this.onmessage = _this.onmessage.bind(_this);
_this.connection.onopen = function () {
_this.emit('open');
};
_this.connection.onmessage = _this.onmessage;
_this.connection.onclose = function () {
_this.emit('close');
_this.destroy();
};
return _this;
}
createClass(Emitter, [{
key: 'reconnect',
value: function reconnect(connection) {
var _this2 = this;
this.destroy();
this.connection = connection;
this.connection.onopen = function () {
_this2.emit('open');
};
this.connection.onmessage = this.onmessage;
this.connection.onclose = function () {
_this2.emit('close');
_this2.destroy();
};
}
}, {
key: 'onmessage',
value: function onmessage(evt) {
try {
var data = JSON.parse(evt.data);
this.emit('data', data);
} catch (e) {
warn(e);
}
}
/* send data to socket no eventName, only data */
}, {
key: 'send',
value: function send(data) {
this.connection.send(JSON.stringify(data));
}
}, {
key: 'destroy',
value: function destroy() {
this.removeAllListeners();
}
}]);
return Emitter;
}(EventEmitter);
/* multiple channel for single connection */
var generateChannel = (function (Emitter) {
return function (_EventEmitter) {
inherits(Channel, _EventEmitter);
/*
* @param Object instance of server/eventEmitter
* @param String channelName, channel name
* */
function Channel(socket, channelName) {
classCallCheck(this, Channel);
if (!channelName) {
throw new Error('channel must has an channelName');
}
var _this = possibleConstructorReturn(this, (Channel.__proto__ || Object.getPrototypeOf(Channel)).call(this));
_this.socket = socket;
_this.channelName = channelName;
_this._ondataFuncs = new Map();
var emitter = new Emitter(socket);
_this.emitter = emitter;
_this.onopen = _this.onopen.bind(_this);
_this.ondata = _this.ondata.bind(_this);
_this.onclose = _this.onclose.bind(_this);
emitter.on('open', _this.onopen);
emitter.on('data', _this.ondata);
emitter.on('close', _this.onclose);
return _this;
}
createClass(Channel, [{
key: 'onopen',
value: function onopen() {
this.emit('open');
}
/* add func that will invoke when ondata */
}, {
key: 'receive',
value: function receive(func) {
this._ondataFuncs.set(func, func.bind(this));
}
/* remove func that will invoke when ondata */
}, {
key: 'remove',
value: function remove(func) {
this._ondataFuncs.delete(func);
}
}, {
key: 'ondata',
value: function ondata(data) {
if (data && data.type === 'channel' && data.channel === this.channelName) {
this._ondataFuncs.forEach(function (func) {
return func(data.data);
});
}
}
}, {
key: 'onclose',
value: function onclose() {
this.emit('close');
}
/* send with channel by this.emitter to browser
*/
}, {
key: 'send',
value: function send(data) {
this.emitter.send({ type: 'channel', channel: this.channelName, data: data });
}
/* clear all listeners, free memory */
}, {
key: 'destroy',
value: function destroy() {
this.removeAllListeners();
}
}]);
return Channel;
}(EventEmitter);
});
var Channel = generateChannel(Emitter);
var ClientChannel = function (_Channel) {
inherits(ClientChannel, _Channel);
function ClientChannel() {
classCallCheck(this, ClientChannel);
return possibleConstructorReturn(this, (ClientChannel.__proto__ || Object.getPrototypeOf(ClientChannel)).apply(this, arguments));
}
createClass(ClientChannel, [{
key: 'reconnect',
value: function reconnect(interval, maxRetry) {
var _this2 = this;
if (maxRetry) {
this.maxRetry = maxRetry;
this.retryCount = maxRetry;
} else {
this.retryCount -= 1;
}
this.emitter.destroy();
this.socket = new SockJS(this.socket.url);
var emitter = new Emitter(this.socket);
emitter.on('open', this.onopen);
emitter.once('open', function () {
_this2.retryCount = _this2.maxRetry;
});
emitter.on('data', this.ondata);
emitter.on('close', this.onclose);
if (interval > 0 && this.retryCount > 1) {
emitter.on('close', function () {
emitter.destroy();
_this2.emit('reconnecting');
setTimeout(function () {
_this2.reconnect(interval);
}, interval);
});
}
this.emitter = emitter;
}
}]);
return ClientChannel;
}(Channel);
var ReduxChannel = generate(ClientChannel);
var startReduxClient = (function () {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$port = _ref.port;
var port = _ref$port === undefined ? 3000 : _ref$port;
var _ref$domain = _ref.domain;
var domain = _ref$domain === undefined ? '127.0.0.1' : _ref$domain;
var _ref$sockjsPrefix = _ref.sockjsPrefix;
var sockjsPrefix = _ref$sockjsPrefix === undefined ? '/sockjs-redux' : _ref$sockjsPrefix;
var _ref$protocal = _ref.protocal;
var protocal = _ref$protocal === undefined ? 'http' : _ref$protocal;
var _ref$reconnectInterva = _ref.reconnectInterval;
var reconnectInterval = _ref$reconnectInterva === undefined ? 0 : _ref$reconnectInterva;
var _ref$reconnectMax = _ref.reconnectMax;
var reconnectMax = _ref$reconnectMax === undefined ? 0 : _ref$reconnectMax;
var connectUrl = protocal + '://' + domain + ':' + port + sockjsPrefix;
var socket = new SockJS(connectUrl);
var reduxChannel = new ReduxChannel(socket);
if (reconnectInterval > 0 && reconnectMax > 0) {
reduxChannel.once('close', function () {
reduxChannel.reconnect(reconnectInterval, reconnectMax);
});
}
return reduxChannel;
});
var ActionTypes = {
SOCKJS: '@@sockjs',
NOOP_ACTION: '@@sockjs-noop'
};
var actionEmitters = [];
/**
* @param {ReduxChannel} ReduxChannel instance
* @param {Number} timeoutInterval, unit milisecond
* @return {Function} action creator that bound to reduxChannel
*/
var reduxActionCreator = function reduxActionCreator(reduxChannel) {
var timeoutInterval = arguments.length <= 1 || arguments[1] === undefined ? 1000 : arguments[1];
var actionEmitter = new EventEmitter();
actionEmitters.push(actionEmitter);
actionEmitter.setMaxListeners(100);
var ondataFunc = function ondataFunc(action) {
var token = action.token;
if (token && actionEmitter.listeners(token).length) {
actionEmitter.emit(token, action);
/* for action from other sockjs connection */
} else {
actionEmitter.emit(ActionTypes.SOCKJS, action);
}
};
reduxChannel.receive(ondataFunc);
/* send payload to server
* returnPromise model will return promise
* async will return an empty action that should do nothing by redux store
* */
return function (type) {
var returnPromise = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var createdAction = function createdAction(payload) {
if (returnPromise) {
return new Promise(function (resolve, reject) {
var token = uuid.v1();
reduxChannel.send({
type: type,
payload: payload,
token: token
});
var timer = 0;
var resolver = function resolver(action) {
resolve(action);
clearTimeout(timer);
};
timer = setTimeout(function () {
actionEmitter.removeListener(token, resolver);
reject('type: ' + type + ', token: ' + token + ', payload: ' + payload + ' failed because timeout more than ' + timeoutInterval);
}, timeoutInterval);
actionEmitter.once(token, resolver);
});
}
reduxChannel.send({
type: type,
payload: payload
});
return { type: ActionTypes.NOOP_ACTION };
};
createdAction.toString = function () {
return type;
};
return createdAction;
};
};
/**
* @param {Object} reducerMap
* @param {any} initialState
* @return {Function}
*/
var createReducer = function createReducer(reducerMap, initialState) {
return function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var action = arguments[1];
var type = action.type;
// console.log(Object.keys(reducerMap))
if (type in reducerMap) {
return reducerMap[type](state, action);
}
return state;
};
};
/* for action from other sockjs connection */
var middleware = function middleware(_ref) {
var dispatch = _ref.dispatch;
var actionEmitter = actionEmitters.shift();
if (!actionEmitter) {
throw new Error('need createAction(reduxChannel) first to make an actionEmitter');
}
actionEmitter.on(ActionTypes.SOCKJS, function (action) {
dispatch(action);
});
return function (next) {
return function (action) {
return next(action);
};
};
};
exports.startReduxClient = startReduxClient;
exports.actionCreator = reduxActionCreator;
exports.createReducer = createReducer;
exports.reduxSockjs = middleware;<file_sep>/src/lib/remove.js
/* remove item from array
* @param {Array} array
* @param {Any} target
* @return {Boolean}
* */
const remove = (array, target) => {
const index = array.findIndex(item => target === item)
if (index > -1) {
array.splice(index, 1)
return true
}
return false
}
export default remove
<file_sep>/src/test/e2e/channel.test.js
import startServer from '../../server/startChannel'
import startClient from '../../client/startChannel'
describe('start channel for server and client', () => {
it('client channel send data to server', done => {
const param = {
// ip: '127.0.0.1',
// port: 10001,
// sockjsPrefix: '/sockjs-prefix',
channelName: 'channel test name',
reconnectInterval: 0,
}
const { channel: serverChannel, httpServer } = startServer(param)
const clientChannel = startClient(param)
const clientData = { type: 'abc', payload: 'xxxxx' }
serverChannel.receive(data => {
expect(data).toEqual(clientData)
serverChannel.emitter.connection.close()
httpServer.close()
done()
})
clientChannel.on('open', () => {
clientChannel.send(clientData)
})
})
it('different channel channelName', done => {
const param = {
ip: '127.0.0.1',
port: 10001,
sockjsPrefix: '/sockjs-prefix',
channelName: 'channel test name',
reconnectInterval: 0,
}
const { channel: serverChannel, httpServer } = startServer(param)
const clientChannel = startClient({ ...param, channelName: 'other channel' })
const clientData = { type: 'abc', payload: 'xxxxx' }
const spy = expect.createSpy()
serverChannel.receive(spy)
clientChannel.on('open', () => {
clientChannel.send(clientData)
expect(spy).toNotHaveBeenCalled()
serverChannel.emitter.connection.close()
httpServer.close()
done()
})
})
it('server channel send data to client', done => {
const param = {
ip: '127.0.0.1',
port: 10001,
sockjsPrefix: '/sockjs-prefix',
channelName: 'channel test name',
reconnectInterval: 0,
}
const { channel: serverChannel, httpServer } = startServer(param)
const clientChannel = startClient(param)
const serverData = { type: 'abc', payload: 'xxxxx' }
clientChannel.receive(data => {
expect(data).toEqual(serverData)
clientChannel.emitter.connection.close()
httpServer.close()
done()
})
serverChannel.on('open', () => {
serverChannel.send(serverData)
})
})
})
<file_sep>/src/client/index.js
import startReduxClient from './startReduxChannel'
import actionCreator from './actionCreator'
import createReducer from './createReducer'
import reduxSockjs from './reduxSockjs'
export {
startReduxClient,
actionCreator,
createReducer,
reduxSockjs,
}
<file_sep>/src/server/channel.js
import Emitter from './emitter'
import generateChannel from '../lib/channel'
const Channel = generateChannel(Emitter)
class ServerChannel extends Channel {
broadcast(data, includeSelf = true) {
this.emitter.broadcast({ type: 'channel', channel: this.channelName, data }, includeSelf)
}
}
export default ServerChannel
<file_sep>/server.js
/*
* sockjs for redux on server
* (c) 2016 by superwf
* Released under the MIT Liscense.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var sockjs = _interopDefault(require('sockjs'));
var EventEmitter = _interopDefault(require('events'));
var http = _interopDefault(require('http'));
var identity = (function (a) {
return a;
});
var isAction = (function (action) {
return Boolean(action && action.type);
});
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var get = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
var inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
/*
* use redux as channelName, and check data must has "type" property
* other usages are same as Channel
* */
var generate = (function (Parent) {
return function (_Parent) {
inherits(ReduxChannel, _Parent);
function ReduxChannel(connection) {
classCallCheck(this, ReduxChannel);
return possibleConstructorReturn(this, (ReduxChannel.__proto__ || Object.getPrototypeOf(ReduxChannel)).call(this, connection, 'redux'));
}
createClass(ReduxChannel, [{
key: 'ondata',
value: function ondata(data) {
if (!isAction(data.data)) {
throw new Error('redux channel data should has redux data and has "type" in redux object ' + JSON.stringify(data));
}
get(ReduxChannel.prototype.__proto__ || Object.getPrototypeOf(ReduxChannel.prototype), 'ondata', this).call(this, data);
}
/* check redux "type" attribute
* and emit with type and channel by this.emitter to browser
* */
}, {
key: 'send',
value: function send(action) {
if (!isAction(action)) {
throw new Error('emit redux data should has "type"');
}
get(ReduxChannel.prototype.__proto__ || Object.getPrototypeOf(ReduxChannel.prototype), 'send', this).call(this, action);
}
}]);
return ReduxChannel;
}(Parent);
});
/* eslint-disable no-console */
var warn = function warn() {
var _console;
return (_console = console).warn.apply(_console, arguments);
};
/* all sockjs should dispatch to instance of this class
* */
var connections = [];
var Emitter = function (_EventEmitter) {
inherits(Emitter, _EventEmitter);
function Emitter(socket) {
classCallCheck(this, Emitter);
var _this = possibleConstructorReturn(this, (Emitter.__proto__ || Object.getPrototypeOf(Emitter)).call(this));
_this.socket = socket;
_this.setMaxListeners(100);
_this.onconnection = _this.onconnection.bind(_this);
socket.on('connection', _this.onconnection);
return _this;
}
createClass(Emitter, [{
key: 'onconnection',
value: function onconnection(connection) {
var _this2 = this;
connections.push(connection);
this.connection = connection;
this.ondata = this.ondata.bind(this);
connection.on('data', this.ondata);
connection.on('close', function () {
connection.removeAllListeners();
connection.close();
var index = connections.findIndex(function (c) {
return c === connection;
});
connections.splice(index, 1);
_this2.destroy();
});
this.emit('open');
}
}, {
key: 'ondata',
value: function ondata(message) {
try {
var data = JSON.parse(message);
this.emit('data', data);
} catch (e) {
warn(e);
}
}
/* emit data to connection no eventName, only data */
}, {
key: 'send',
value: function send(data) {
this.connection.write(JSON.stringify(data));
}
}, {
key: 'broadcast',
value: function broadcast(data) {
var _this3 = this;
var includeSelf = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
connections.forEach(function (connection) {
if (!includeSelf && _this3.connection === connection) {
return;
}
connection.write(JSON.stringify(data));
});
}
}, {
key: 'destroy',
value: function destroy() {
this.removeAllListeners();
}
}]);
return Emitter;
}(EventEmitter);
Emitter.connections = connections;
/* multiple channel for single connection */
var generateChannel = (function (Emitter) {
return function (_EventEmitter) {
inherits(Channel, _EventEmitter);
/*
* @param Object instance of server/eventEmitter
* @param String channelName, channel name
* */
function Channel(socket, channelName) {
classCallCheck(this, Channel);
if (!channelName) {
throw new Error('channel must has an channelName');
}
var _this = possibleConstructorReturn(this, (Channel.__proto__ || Object.getPrototypeOf(Channel)).call(this));
_this.socket = socket;
_this.channelName = channelName;
_this._ondataFuncs = new Map();
var emitter = new Emitter(socket);
_this.emitter = emitter;
_this.onopen = _this.onopen.bind(_this);
_this.ondata = _this.ondata.bind(_this);
_this.onclose = _this.onclose.bind(_this);
emitter.on('open', _this.onopen);
emitter.on('data', _this.ondata);
emitter.on('close', _this.onclose);
return _this;
}
createClass(Channel, [{
key: 'onopen',
value: function onopen() {
this.emit('open');
}
/* add func that will invoke when ondata */
}, {
key: 'receive',
value: function receive(func) {
this._ondataFuncs.set(func, func.bind(this));
}
/* remove func that will invoke when ondata */
}, {
key: 'remove',
value: function remove(func) {
this._ondataFuncs.delete(func);
}
}, {
key: 'ondata',
value: function ondata(data) {
if (data && data.type === 'channel' && data.channel === this.channelName) {
this._ondataFuncs.forEach(function (func) {
return func(data.data);
});
}
}
}, {
key: 'onclose',
value: function onclose() {
this.emit('close');
}
/* send with channel by this.emitter to browser
*/
}, {
key: 'send',
value: function send(data) {
this.emitter.send({ type: 'channel', channel: this.channelName, data: data });
}
/* clear all listeners, free memory */
}, {
key: 'destroy',
value: function destroy() {
this.removeAllListeners();
}
}]);
return Channel;
}(EventEmitter);
});
var Channel = generateChannel(Emitter);
var ServerChannel = function (_Channel) {
inherits(ServerChannel, _Channel);
function ServerChannel() {
classCallCheck(this, ServerChannel);
return possibleConstructorReturn(this, (ServerChannel.__proto__ || Object.getPrototypeOf(ServerChannel)).apply(this, arguments));
}
createClass(ServerChannel, [{
key: 'broadcast',
value: function broadcast(data) {
var includeSelf = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
this.emitter.broadcast({ type: 'channel', channel: this.channelName, data: data }, includeSelf);
}
}]);
return ServerChannel;
}(Channel);
var ReduxChannel = generate(ServerChannel);
var defaultHttpServer = (function () {
var server = http.createServer();
// server.addListener('upgrade', (req, res) => {
// res.end()
// })
return server;
});
// import store from './store'
var startReduxServer = (function () {
var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var _ref$port = _ref.port;
var port = _ref$port === undefined ? 3000 : _ref$port;
var _ref$ip = _ref.ip;
var ip = _ref$ip === undefined ? '0.0.0.0' : _ref$ip;
var _ref$sockjsPrefix = _ref.sockjsPrefix;
var sockjsPrefix = _ref$sockjsPrefix === undefined ? '/sockjs-redux' : _ref$sockjsPrefix;
var _ref$log = _ref.log;
var log = _ref$log === undefined ? identity : _ref$log;
var server = _ref.server;
var sockserver = sockjs.createServer({
sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js',
log: log
});
var channel = new ReduxChannel(sockserver);
var httpServer = server || defaultHttpServer();
sockserver.installHandlers(httpServer, { prefix: sockjsPrefix });
httpServer.listen(port, ip);
return channel;
});
/**
* @param {Object} reducerMap
* @param {any} initialState
* @return {Function}
*/
var createReducer = function createReducer(reducerMap, initialState) {
return function () {
var state = arguments.length <= 0 || arguments[0] === undefined ? initialState : arguments[0];
var action = arguments[1];
var type = action.type;
// console.log(Object.keys(reducerMap))
if (type in reducerMap) {
return reducerMap[type](state, action);
}
return state;
};
};
exports.startReduxServer = startReduxServer;
exports.createReducer = createReducer;<file_sep>/examples/todos/containers/Todos.js
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Todos from '../components/Todos'
import { create, list, destroy } from '../actions/todo'
export default connect(state => ({
todos: state.todos,
}), dispatch => bindActionCreators({ create, list, destroy }, dispatch)
)(Todos)
<file_sep>/src/lib/isAction.js
export default action => Boolean(action && action.type)
<file_sep>/src/test/lib/isAction.test.js
import isAction from '../../lib/isAction'
describe('lib/isAction', () => {
it('action must has type and payload', () => {
expect(isAction({})).toBe(false)
expect(isAction()).toBe(false)
expect(isAction({ type: 'zbc' })).toBe(true)
expect(isAction({ payload: 'zbc' })).toBe(false)
expect(isAction({ type: 'xxx', payload: 'zbc' })).toBe(true)
})
})
<file_sep>/src/test/server/defaultHttpServer.test.js
// import defaultHttpServer from '../../server/defaultHttpServer'
// import http from 'http'
// describe('server/defaultHttpServer', () => {
// it('is EventEmitter instance', () => {
// const server = defaultHttpServer()
// // expect(server.constructor).toBe(EventEmitter)
// expect(server).toBeA(http.Server)
// expect(server.eventNames()).toInclude('upgrade')
// })
// })
<file_sep>/src/server/reduxChannel.js
import generate from '../lib/reduxChannel'
import Channel from './channel'
export default generate(Channel)
<file_sep>/src/lib/reduxChannel.js
import isAction from './isAction'
/*
* use redux as channelName, and check data must has "type" property
* other usages are same as Channel
* */
export default Parent => class ReduxChannel extends Parent {
constructor(connection) {
super(connection, 'redux')
}
ondata(data) {
if (!isAction(data.data)) {
throw new Error(`redux channel data should has redux data and has "type" in redux object ${JSON.stringify(data)}`)
}
super.ondata(data)
}
/* check redux "type" attribute
* and emit with type and channel by this.emitter to browser
* */
send(action) {
if (!isAction(action)) {
throw new Error('emit redux data should has "type"')
}
super.send(action)
}
}
<file_sep>/examples/todos/webpack.config.js
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackShellPlugin = require('webpack-shell-plugin')
module.exports = {
entry: {
index: './client.js',
},
output: {
path: 'public',
filename: '[name].js',
publicPath: '/',
},
devtool: 'eval-source-map',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
},
],
},
plugins: [
new HtmlWebpackPlugin({
chunks: ['index'],
filename: 'index.html',
template: './index.html',
}),
new webpack.WatchIgnorePlugin([/node_modules/]),
new webpack.SourceMapDevToolPlugin({
exclude: /node_modules/,
}),
new webpack.HotModuleReplacementPlugin(),
new WebpackShellPlugin({
onBuildStart: ['./node_modules/.bin/babel-node server.js'],
})
],
devServer: {
hot: true,
contentBase: './public/',
inline: true,
colors: true,
host: '0.0.0.0',
port: 3000,
},
}
<file_sep>/examples/todos/client.js
import { Provider } from 'react-redux'
import { render } from 'react-dom'
import React from 'react'
import Todos from './containers/Todos'
import store from './store'
import { channel } from './actions/createAction'
channel.on('open', () => {
render(<Provider store={store}><Todos /></Provider>, document.getElementById('main'))
})
<file_sep>/src/test/e2e/realworld.test.js
import { createStore, combineReducers, applyMiddleware } from 'redux'
import EventEmitter from 'events'
import reduxPromise from 'redux-promise'
import uuid from 'uuid'
import { startReduxClient } from '../../../client'
import { startReduxServer } from '../../../server'
import isAction from '../../lib/isAction'
import defaultHttpServer from '../../server/defaultHttpServer'
// import warn from '../../lib/warn'
describe('real world', () => {
it('browser receive initial state from server', async () => {
const httpServer = defaultHttpServer()
const reduxServer = startReduxServer({
server: httpServer,
})
const emitter = new EventEmitter()
const reduxClient = startReduxClient({
reconnectInterval: 0,
})
const timeoutInterval = 1000
/* browser side redux action, reducer, store */
const addUserOnClient = user => {
if (isAction(user)) {
return user
}
return new Promise((resolve, reject) => {
const token = uuid()
const type = 'ADD_USER'
const eventName = `${type}-${token}`
reduxClient.send({
type,
payload: user,
token,
})
let timeout = 0
const resolver = createdUser => {
resolve(createdUser)
clearTimeout(timeout)
}
timeout = setTimeout(() => {
reject(`${type} token ${token} failed because timeout`)
emitter.removeListener(eventName, resolver)
}, timeoutInterval)
emitter.once(eventName, resolver)
})
}
const userReducerOnClient = (state = [], action) => {
if (action.type === 'INITIAL_STATE') {
return action.payload
}
if (action.type === 'ADD_USER') {
return [...state, action.payload]
}
return state
}
const clientStore = createStore(combineReducers({
user: userReducerOnClient,
}), applyMiddleware(reduxPromise))
emitter.on('ADD_USER', user => {
// warn('emititer on ADD_USER', user)
clientStore.dispatch(addUserOnClient(user))
})
reduxClient.receive(action => {
// warn('reduxClient receive', action)
const eventName = `${action.type}-${action.token}`
if (emitter.listeners(eventName).length) {
emitter.emit(eventName, action)
} else {
/* for other user from other connection pub action */
emitter.emit(action.type, action)
}
})
/* server side */
const addUserOnServer = action => {
/* pretend insert user to db and get new user with id */
const payload = (user => ({ ...user, id: 1 }))(action.payload)
return { ...action, payload }
}
const userReducerOnServer = action => {
switch (action.type) {
case 'INITIAL_STATE':
return []
case 'ADD_USER':
return addUserOnServer(action)
default:
return []
}
}
reduxServer.receive(action => {
reduxServer.broadcast(userReducerOnServer(action))
})
await new Promise(resolve => {
reduxClient.on('open', async () => {
await clientStore.dispatch(addUserOnClient({ name: 'from browser 0' }))
resolve()
})
})
expect(clientStore.getState().user).toEqual([{ name: 'from browser 0', id: 1 }])
/* another client connect this channel */
const reduxClient1 = startReduxClient({
reconnectInterval: 0,
})
// warn(reduxServer.socket.listeners('connection').length)
const token1 = uuid()
reduxClient1.on('open', () => {
reduxClient1.send({
type: 'ADD_USER',
payload: { name: '<NAME>' },
token: token1,
})
})
await new Promise(resolve => {
emitter.once(`ADD_USER-${token1}`, user => {
clientStore.dispatch(addUserOnClient(user))
resolve()
})
})
const reduxClient2 = startReduxClient({
reconnectInterval: 0,
})
const token2 = uuid()
reduxClient2.on('open', () => {
reduxClient2.send({
type: 'ADD_USER',
payload: { name: 'another user from reduxClient2' },
token: token2,
})
})
await new Promise(resolve => {
emitter.once(`ADD_USER-${token2}`, user => {
clientStore.dispatch(addUserOnClient(user))
resolve()
})
})
expect(clientStore.getState().user)
reduxServer.emitter.connection.close()
httpServer.close()
})
})
<file_sep>/src/lib/channel.js
import EventEmitter from 'events'
/* multiple channel for single connection */
export default Emitter => class Channel extends EventEmitter {
/*
* @param Object instance of server/eventEmitter
* @param String channelName, channel name
* */
constructor(socket, channelName) {
if (!channelName) {
throw new Error('channel must has an channelName')
}
super()
this.socket = socket
this.channelName = channelName
this._ondataFuncs = new Map()
const emitter = new Emitter(socket)
this.emitter = emitter
this.onopen = this.onopen.bind(this)
this.ondata = this.ondata.bind(this)
this.onclose = this.onclose.bind(this)
emitter.on('open', this.onopen)
emitter.on('data', this.ondata)
emitter.on('close', this.onclose)
}
onopen() {
this.emit('open')
}
/* add func that will invoke when ondata */
receive(func) {
this._ondataFuncs.set(func, func.bind(this))
}
/* remove func that will invoke when ondata */
remove(func) {
this._ondataFuncs.delete(func)
}
ondata(data) {
if (data && data.type === 'channel' && data.channel === this.channelName) {
this._ondataFuncs.forEach(func => func(data.data))
}
}
onclose() {
this.emit('close')
}
/* send with channel by this.emitter to browser
*/
send(data) {
this.emitter.send({ type: 'channel', channel: this.channelName, data })
}
/* clear all listeners, free memory */
destroy() {
this.removeAllListeners()
}
}
<file_sep>/examples/todos/.eslintrc.js
module.exports = {
globals: {
React: true,
},
parser: 'babel-eslint',
plugins: [
'babel',
'react',
],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
extends: ['eslint:recommended', 'plugin:react/recommended'],
}
<file_sep>/README.md
redux with sockjs
=================
[](https://travis-ci.org/superwf/redux-sockjs)
## Test
```bash
npm test
```
## Usage
for es6 project, babel-preset-stage-0 syntax
### on server
```javascript
import { startReduxServer } from 'redux-sockjs/server'
const channel = startReduxServer({
port: 1000, // port should be same with browser
})
channel.receive(action => {
channel.broadcast(action)
})
```
### on browser use webpack or browserify
```javascript
import { startReduxClient, actionCreator, middleware as reduxSockjs, createReducer } from 'redux-sockjs'
/* when use actionCreator, the reduxSockjs must be used and vice versa */
const channel = startReduxClient({
port: 1000, // port should be same with server
})
/* channel must bound to createAction first, then use redux middle to create store */
const createAction = actionCreator(channel)
const createUser = createAction('ADD_USER')
const userReducer = createReducer({
'INITIAL_STATE': (state, action) => action.payload,
'ADD_USER': (state, action) => [...state, action.payload],
}, [])
// use reduxPromise before reduxSockjs
const store = createStore(combineReducers({
user: userReducer,
}), applyMiddleware(reduxPromise, reduxSockjs))
channel.on('open', () => {
store.dispatch(createUser({ name: 'bob' }))
})
// it is async, when data send to server and broadcast to browser
// store.getState().user will be [{ name: 'bob' }]
```
if some server operation take too long, you can use promise action
```javascript
import { startReduxClient, createAction as actionCreator, middleware as reduxSockjs } from 'redux-sockjs'
/* when use actionCreator, the reduxSockjs must be used and vice versa */
const channel = startReduxClient({
port: 1000, // port should be same with server
})
/* channel must bound to createAction first, then use redux middle to create store */
const createAction = actionCreator(channel)
const createUser = createAction('ADD_USER', true)
const userReducer = createReducer({
'INITIAL_STATE': (state, action) => action.payload,
'ADD_USER': (state, action) => [...state, action.payload],
}, [])
/* use reduxPromise before reduxSockjs */
const store = createStore(combineReducers({
user: userReducer,
}), applyMiddleware(reduxPromise, reduxSockjs))
channel.on('open', async () => {
await store.dispatch(createUser({ name: 'bob' }))
console.log(store.getState().user) // [{ name: 'bob' }]
})
// it is async, when data send to server and broadcast to browser
// store.getState().user will be [{ name: 'bob' }]
```
## Server API
### startReduxServer
if no param, just startServer(), it will use default param as below
```javascript
startReduxServer({
port = 3000,
ip = '0.0.0.0',
sockjsPrefix = '/sockjs-redux',
log = () => {}, // a function for log of sockjs, reference from [sockjs-node doc](https://github.com/sockjs/sockjs-node)
server, // server should be http.Server instance, if not defined, will use default server created by http.createServer()
// use https.createServer() when needed
})
```
### reduxChannel instance method
reduxChannel on server inherites nodejs "events", and has some own method as below
* receive(func)
can receive many functions, when receive data, each will be called with data
* remove(func)
remove func from receive data functions
* send(data)
send data to client async
* broadcast(data)
like send, but send data to all connected client
## Client API
### startReduxClient
if no param, just startClient(), it will use default param as below
the protocal should correspond to the server protocal
```javascript
const reduxChannel = startReduxClient({
port = 3000,
domain = '127.0.0.1', // domain or ip
sockjsPrefix = '/sockjs-redux',
protocal = 'http', // http or https
reconnectInterval = 0, // reconnect interval, millisecond
reconnectMax = 0, // reconnect max retry count
})
```
### reduxChannel instance method
reduxChannel on client inherites nodejs "events", and has some own method as below
* reconnect(interval, maxRetry)
when reconnect, it`s emitter property will be replaced new one
* receive(func)
can receive many functions, when receive data, each will be called with data
* remove(func)
remove func from receive data functions
* send(data)
send data to server async
### actionCreator
receive an return value of startReduxClient
return a function to create action
```javascript
const createAction = actionCreator(reduxChannel)
const actionAddTodo = createAction('ADD_TODO')
```
<file_sep>/.eslintrc.js
module.exports = {
root: true,
extends: 'airbnb-base',
parser: 'babel-eslint',
parserOptions: {
ecmascript: 7,
jsx: true,
modules: true
},
plugins: [
'babel',
'json',
'react',
],
env: {
es6: true,
browser: true,
node: true,
mocha: true,
},
globals: {expect: true},
rules: {
semi: [1, 'never'],
'no-console': ['error'],
'max-len': ['error', {ignoreComments: true, code: 200}],
'no-underscore-dangle': ['error', {allowAfterThis: true, allowAfterSuper: true}],
'arrow-parens': [0, 'as-needed'],
'babel/arrow-parens': 0,
'babel/generator-star-spacing': 0,
},
}
<file_sep>/src/server/defaultHttpServer.js
import http from 'http'
export default () => {
const server = http.createServer()
// server.addListener('upgrade', (req, res) => {
// res.end()
// })
return server
}
<file_sep>/src/server/index.js
import startReduxServer from './startReduxChannel'
import createReducer from '../client/createReducer'
export {
startReduxServer,
createReducer,
}
<file_sep>/examples/todos/actions/createAction.js
import { actionCreator, startReduxClient } from 'redux-sockjs'
const channel = startReduxClient({
port: 3010,
sockjsPrefix: '/sockjs-redux',
reconnectInterval: 3000,
reconnectMax: 30,
// protocal: 'https',
})
const createAction = actionCreator(channel)
export { channel, createAction }
<file_sep>/rollup.config.client.js
/* eslint import/no-extraneous-dependencies: 0 */
import babel from 'rollup-plugin-babel'
const banner =
`/*
* sockjs for redux on browser
* (c) 2016 by superwf
* Released under the MIT Liscense.
*/`
module.exports = {
entry: './src/client/index.js',
dest: './client.js',
plugins: [babel()],
format: 'cjs',
moduleName: 'redux-sockjs',
external: ['events', 'sockjs-client', 'uuid'],
banner,
}
<file_sep>/examples/todos/store.js
import { createStore, applyMiddleware, compose } from 'redux'
import reduxPromise from 'redux-promise'
// import { reduxSockjs } from '../../client'
import { reduxSockjs } from 'redux-sockjs'
import reducer from './reducers'
const store = createStore(reducer, compose(
applyMiddleware(reduxPromise, reduxSockjs),
global.devToolsExtension ? global.devToolsExtension() : f => f
))
export default store
<file_sep>/src/test/lib/warn.test.js
import warn from '../../lib/warn'
describe('lib/warn', () => {
it('warn invoke console.warn', () => {
const spy = expect.spyOn(console, 'warn')
expect(spy).toNotHaveBeenCalled()
warn('abc')
expect(spy).toHaveBeenCalledWith('abc')
expect.restoreSpies()
})
})
<file_sep>/src/server/startChannel.js
import sockjs from 'sockjs'
import identity from '../lib/identity'
import Channel from './channel'
import defaultHttpServer from './defaultHttpServer'
// import store from './store'
export default ({
port = 3000,
ip = '0.0.0.0',
sockjsPrefix = '/sockjs',
channelName,
log = identity,
server, // server should be http.Server instance or some instance like express inherite from http.Server
} = {}) => {
const sockserver = sockjs.createServer({
sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js',
log,
})
const channel = new Channel(sockserver, channelName)
const httpServer = server || defaultHttpServer()
sockserver.installHandlers(httpServer, { prefix: sockjsPrefix })
httpServer.listen(port, ip)
return { channel, httpServer }
}
<file_sep>/examples/todos/server.js
import http from 'http'
// import https from 'https'
// import fs from 'fs'
import { isFSA } from 'flux-standard-action'
import remove from 'lodash/remove'
import { startReduxServer } from 'redux-sockjs/server'
function isPromise(promise) {
return promise && promise.then && typeof promise.then === 'function'
}
const server = http.createServer()
// const server = https.createServer({
// key: fs.readFileSync('./cert/privatekey.pem'),
// cert: fs.readFileSync('./cert/certificate.pem'),
// })
const reduxChannel = startReduxServer({
server,
port: 3010,
sockjsPrefix: '/sockjs-redux',
})
/* simulate async db operation */
const database = []
let id = 0
const insert = item => {
item.id = ++id
database.push(item)
return Promise.resolve(item)
}
const list = () => {
return Promise.resolve(database)
}
const destroy = id => {
remove(database, { id })
return Promise.resolve(id)
}
/* when I start this project, I imagine both server and client will use redux
* but write code on server I found that if each time broadcast the whole store by store.getState(),
* that will transfer too many useless data
* so just transfer needed data is ok
* on server, I use half redux mode, only use the action idea of redux
* when there is a redux store on server, only one server process is ok, when use pm2 or cluster, the state between server processes are hard to sync.
* */
const actions = {
ADD_TODO: action => ({ ...action, payload: insert(action.payload) }),
LIST_TODO: action => ({ ...action, payload: list() }),
DESTROY_TODO: action => ({ ...action, payload: destroy(action.payload) }),
}
const broadcast = reduxChannel.broadcast.bind(reduxChannel)
reduxChannel.receive(action => {
// console.log(action)
const result = actions[action.type](action)
if (isPromise(result.payload)) {
result.payload.then(data => {
broadcast({ ...action, payload: data })
})
} else if (isFSA(result)) {
broadcast(result)
}
})
<file_sep>/examples/todos/public/index.js
import { startReduxClient } from 'redux-sockjs';
const clientChannel = startReduxClient({
port: 3000,
sockjsPrefix: '/sockjs-redux',
})
clientChannel.on('open', () => {
console.log('open from client')
})<file_sep>/rollup.config.server.js
/* eslint import/no-extraneous-dependencies: 0 */
import babel from 'rollup-plugin-babel'
const banner =
`/*
* sockjs for redux on server
* (c) 2016 by superwf
* Released under the MIT Liscense.
*/`
module.exports = {
entry: './src/server/index.js',
dest: './server.js',
plugins: [babel()],
format: 'cjs',
moduleName: 'redux-sockjs',
external: ['events', 'sockjs', 'http'],
banner,
}
<file_sep>/examples/todos/reducers/todo.js
import remove from 'lodash/remove'
import { createReducer } from 'redux-sockjs'
import { create, list, destroy } from '../actions/todo'
export default createReducer({
[create]: (state, action) => [...state, action.payload],
[list]: (state, action) => action.payload,
[destroy]: (state, action) => {
const newState = [...state]
remove(newState, todo => todo.id === action.payload.id)
return newState
},
}, [])
<file_sep>/src/test/e2e/middleware.test.js
import { createStore, combineReducers, applyMiddleware } from 'redux'
import reduxPromise from 'redux-promise'
import { startReduxServer } from '../../../server'
import { startReduxClient } from '../../../client'
import actionCreator from '../../client/actionCreator'
import createReducer from '../../client/createReducer'
import reduxSockjs from '../../client/reduxSockjs'
import defaultHttpServer from '../../server/defaultHttpServer'
// import warn from '../../lib/warn'
describe('middle ware', function testMiddleware() {
this.slow(1000)
it('test middleware sync action', async () => {
const httpServer = defaultHttpServer()
const port = 10001
const reduxServer = startReduxServer({
port,
server: httpServer,
})
const reduxClient = startReduxClient({
port,
reconnectInterval: 0,
})
const create = actionCreator(reduxClient)
const createUser = create('ADD_USER', true)
const userReducer = createReducer({
INITIAL_STATE: (state, action) => action.payload,
[createUser]: (state, action) => [...state, action.payload],
}, [])
const clientStore = createStore(combineReducers({
user: userReducer,
}), applyMiddleware(reduxPromise, reduxSockjs))
const addUserOnServer = async (action) => {
/* pretend insert user to db and get new user with id */
const payload = await Promise.resolve({ ...action.payload, id: 1 })
return { ...action, payload }
}
const userReducerOnServer = action => {
switch (action.type) {
case 'INITIAL_STATE':
return []
case 'ADD_USER':
return addUserOnServer(action)
default:
return []
}
}
reduxServer.receive(async (action) => {
// warn(action)
const data = await userReducerOnServer(action)
reduxServer.broadcast(data)
})
await new Promise(resolve => {
reduxClient.on('open', resolve)
})
await clientStore.dispatch(createUser({ name: 'xxx' }))
/* create another client connect from sockjs */
const anotherClient = startReduxClient({ port })
await new Promise(resolve => {
anotherClient.on('open', resolve)
})
anotherClient.send({
type: 'ADD_USER',
payload: { name: '<NAME>' },
})
const anotherClient1 = startReduxClient({ port })
await new Promise(resolve => {
anotherClient1.on('open', resolve)
})
anotherClient1.send({
type: 'ADD_USER',
payload: { name: '<NAME>' },
})
/* wait until last action is received */
await new Promise(resolve => {
reduxClient.receive(action => {
if (action.payload.name === 'another user 1') {
resolve()
}
})
})
const stateUser = clientStore.getState().user
expect(stateUser.length).toBe(3)
expect(stateUser).toInclude({ name: 'xxx', id: 1 })
expect(stateUser).toInclude({ name: '<NAME>', id: 1 })
expect(stateUser).toInclude({ name: '<NAME>', id: 1 })
reduxServer.emitter.connection.close()
httpServer.close()
})
it('test middleware async action', async () => {
const httpServer = defaultHttpServer()
const param = {
port: 10000,
server: httpServer,
reconnectInterval: 0,
}
const reduxServer = startReduxServer(param)
const reduxClient = startReduxClient(param)
const userReducerOnClient = (state = [], action) => {
// warn(action)
if (action.type === 'INITIAL_STATE') {
return action.payload
}
if (action.type === 'ADD_USER') {
return [...state, action.payload]
}
return state
}
const create = actionCreator(reduxClient)
const createUser = create('ADD_USER')
const clientStore = createStore(combineReducers({
user: userReducerOnClient,
}), applyMiddleware(reduxPromise, reduxSockjs))
const addUserOnServer = async (action) => {
/* pretend insert user to db and get new user with id */
const payload = await Promise.resolve({ ...action.payload, id: 1 })
return { ...action, payload }
}
const userReducerOnServer = action => {
switch (action.type) {
case 'INITIAL_STATE':
return []
case 'ADD_USER':
return addUserOnServer(action)
default:
return []
}
}
reduxServer.receive(async (action) => {
// warn(action)
const data = await userReducerOnServer(action)
reduxServer.broadcast(data)
})
await new Promise(resolve => {
reduxClient.on('open', resolve)
})
await clientStore.dispatch(createUser({ name: 'xxx' }))
/* create another client connect from sockjs */
const anotherClient = startReduxClient(param)
await new Promise(resolve => {
anotherClient.on('open', resolve)
})
anotherClient.send({
type: 'ADD_USER',
payload: { name: '<NAME>' },
})
const anotherClient1 = startReduxClient(param)
await new Promise(resolve => {
anotherClient1.on('open', resolve)
})
anotherClient1.send({
type: 'ADD_USER',
payload: { name: '<NAME>' },
})
// await global.sleep(10)
/* wait until last action is received */
await new Promise(resolve => {
reduxClient.receive(action => {
if (action.payload.name === 'another user 1') {
resolve()
}
})
})
const stateUser = clientStore.getState().user
expect(stateUser.length).toBe(3)
expect(stateUser).toInclude({ name: 'xxx', id: 1 })
expect(stateUser).toInclude({ name: '<NAME>', id: 1 })
expect(stateUser).toInclude({ name: 'another user 1', id: 1 })
reduxServer.emitter.connection.close()
httpServer.close()
})
})
|
3c08f86211435511d85dc1a1e86dc5677916a996
|
[
"JavaScript",
"Markdown"
] | 40 |
JavaScript
|
jarl-alejandro/redux-sockjs
|
e3981fb73e34222c23e5e27396a59c1981469a9e
|
daaeb67b1ff93b4aa19a21181715c8885e7cdfdb
|
refs/heads/master
|
<file_sep>const daysEl= document.getElementById("days")
const hoursEl = document.getElementById("hours")
const minsEl= document.getElementById("minutes")
const secondsEl= document.getElementById("seconds")
// const daysEl = document.getElementById("days");
// const hoursEl = document.getElementById("hours");
// const minsEl = document.getElementById("mins");
// const secondsEl = document.getElementById("seconds");
const newYears = `1 Jan 2021`
function countDown(){
const newYearsDate = new Date(newYears);
const currentDate= new Date();
const totalseconds = Math.floor((newYearsDate - currentDate) / 1000)
const daysd = Math.floor(totalseconds / 3600/ 24)
const hoursd = Math.floor( totalseconds / 3600) % 24
const minutesd = Math.floor( totalseconds / 60) % 60
const secondsd = totalseconds % 60
daysEl.innerHTML = daysd
hoursEl.innerHTML = hoursd
minsEl.innerHTML = minutesd
secondsEl.innerHTML = secondsd
// console.log(days,hours,minutes,seconds);
// console.log(Date(newYearsDate - currentDate) );
}
// initial Call
// countDown()
setInterval(countDown,1000)<file_sep>const app = require('./server')
const bodyParser = require('./bodyParser')
// const { }
app.use(bodyParser)
app.createServer(5000)
app.serveDefaultStatic()
app.addGetRoute("/tasks",(req,res) =>{
// res.status(200)
// res.status(200).send("achyuth")
// res.send("achyuth")
res.json({achyuth : "reddy"})
})
app.addGetRoute("/json",(req,res) =>{
console.log("working");
res.status(200)
})<file_sep>const net = require('net')
const client = net.connect({port: 8080}, () =>{
console.log('connected to server!!');
})
client.write('achyuth')
client.on('data',(data) =>{
console.log('data is coming ', data);
console.log(data.toString());
client.end()
})
client.on('end', () =>{
console.log('disconneted from server !!!');
})<file_sep>function status (code){
console.log(" in the status code ");
let resp = `HTTP/1.1 ${code} OK\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: Origin, Content-Type, Accept\r\n`
const date = new Date()
resp += `Date: ${date.toUTCString()}\r\n`
resp += 'Content-Type: *\r\n'
this.resp = resp
return this
}
const code = 200
function send (body,client) {
let resp = `HTTP/1.1 ${code} OK\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: Origin, Content-Type, Accept\r\n`
console.log("coming here OPOPOPOP");
body = JSON.stringify(body)
console.log('body in the response file',body);
this.resp += `Content-Length: ${body.length}\r\n\r\n`
this.resp += body
console.log('resp', this.resp);
client.write(resp)
// return this.resp
}
const response = {
send : send,
status : status
}
module.exports = response<file_sep>// const express = require('express')
// const socketIO = require('socket.io')
// const http = require('http')
// const port = process.env.PORT || 3000
// let app = express()
// let server = http.createServer(app)
// let io = socketIO(server)
// io.on('connection', (socket)=>{
// console.log('New user connected');
// socket.emit('newMessage', {
// from:'jen<EMAIL>',
// text:'hepppp',
// createdAt:123
// });
// socket.on('createMessage', (newMessage)=>{
// console.log('newMessage', newMessage);
// });
// socket.on('disconnect', ()=>{
// console.log('disconnected from user');
// });
// });
// server.listen(port)
// const express=require('express');
// const socketIO=require('socket.io');
// const http=require('http')
// const port=process.env.PORT||3000
// var app=express();
// var io=socketIO(server);
// // make connection with user from server side
// io.on('connection', (socket)=>{
// console.log('New user connected');
// //emit message from server to user
// socket.emit('newMessage', {
// from:'jen<EMAIL>',
// text:'hepppp',
// createdAt:123
// });
// // listen for message from user
// socket.on('createMessage', (newMessage)=>{
// console.log('newMessage', newMessage);
// });
// // when server disconnects from user
// socket.on('disconnect', ()=>{
// console.log('disconnected from user');
// });
// });
// server.listen(port);
const net = require('net')
const server = net.createServer()
server.listen(8000, console.log('i am listening!!'))
server.on('connection',(client) =>{
console.log('client connected !!!');
client.on('data', (data) =>{
client.write('hello from the server')
client.write(data)
client.end()
client.on('end',() =>{
console.log('socket connection ended');
})
client.on('error', err =>{
console.log(err);
})
})
})
<file_sep># webserver
Web Server created using sockets and net module of Node.js. Having all the basic functionalities of the server as provided by the express framework.
<file_sep>const net = require('net')
const server = net.createServer()
server.listen(8080,() =>{
console.log('opened server on', server.address());
console.log(' server is working !!!!');
})
server.on('connection', (client) => {
const address = `${client.remoteAddress} : remote port is ${client.remotePort}`
console.log(`connection established !!!`,address);
console.log('A Client connected')
// client.write('Hello, from the echo server!\n\n')
client.on('data', (data) => {
console.log(data.toString());
client.write('Hello, from the echo server!\n\n')
client.write(data)
client.end()
client.on('end', () => {
console.log('Socket connection ended')
})
client.on('error', (err) => {
console.log(err)
})
})
})
// server.on()
// const server = net.createServer((socket) => {
// socket.end('goodbye\n');
// }).on('error', (err) => {
// // Handle errors here.
// throw err;
// });
// // Grab an arbitrary unused port.
// server.listen(() => {
// console.log('opened server on', server.address());
// });<file_sep>const fs = require('fs')
const mimeType = {
'.html':'text/html',
'.css': 'text/css',
'.js':'text/javascript',
'.json':'application.json',
'.jpg':'image/jpeg',
'jpeg':'image/jpeg',
'.png':'image/png'
}
const servestaticfiles = (reques,folder ) =>{
console.log('request', reques);
console.log('Folder',folder);
console.log("headers first here ", reques['headers'].url);
let path = reques['headers'].url
let res = ''
let responseHeader;
res += responseHeader
// return res
if(path === '/'){
try {
body = fs.readFileSync(`./${folder}/index.html`)
responseHeader = `HTTP/1.1 200 OK
Content-Type : ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection : keep-alive
Content-Length: ${body.toString().length}
\r\n\r\n`
} catch {
body = fs.readFileSync(`./${folder}/404.html`);
// implement the error function!!!
responseHeader = `HTTP/1.1 404 OK
Content-Type : ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection : keep-alive
Content-Length: ${body.toString().length}
\r\n\r\n`
}
let response = Buffer.concat([Buffer.from(responseHeader),body])
return response
}else{
try {
let data = fs.readFileSync(`./${folder}/${path}`)
responseHeader = `HTTP/1.1 200 OK
Content-Type : ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection : keep-alive
Content-Length: ${data.toString().length}
\r\n\r\n`
let response = Buffer.concat([Buffer.from(responseHeader),data])
return response
} catch {
// console.log('coming here',path,path.slice(path.lastIndexOf('.')) , mimeTypes['.html']);
if (path.slice(path.lastIndexOf('.')) == '.html' ){
body = fs.readFileSync(`./${folder}/404.html`);
responseHeader = `HTTP/1.1 404 OK
Content-Type : ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection : keep-alive
Content-Length: ${body.toString().length}
\r\n\r\n`
let response = Buffer.concat([Buffer.from(responseHeader),body])
return response
} //else return null
}
}
// console.log('headers :::', headers['method-path-protocol'] );
// const [protocol, path, status ] = headers['method-path-protocol'].split(' ')
// console.log('type of header::::',(headers.Accept));
// let type_of_doc = (headers.Accept).trim().slice(0,headers.Accept.indexOf(','))
// console.log('type_of_doc:',type_of_doc,typeof(type_of_doc));
// switch (type_of_doc){
// // case 'text/html,':
// // let body
// // if (path === '/'){
// // }
// // else{
// // try {
// // body = fs.readFileSync(`./staticfiles/${path}`)
// // } catch (error) {
// // body = fs.readFileSync(`./staticfiles/404.html`)
// // }
// // }
// case 'text/css,':
// console.log('css file working !!!',path);
// const bodycss = fs.readFileSync(`./staticfiles/${path}`)
// // console.log('body',res);
// res += `Content-Length: ${bodycss.toString().length}\r\n\r\n`
// res += bodycss
// return res
// default:
// try
// {const defaultFile = fs.readFileSync(`./staticfiles/${path}`)
// console.log('###### ' , defaultFile );
// res += `Content-Length: ${defaultFile.length}\r\n\r\n`
// res += defaultFile
// return res }
// catch{
// console.log(`${path}`);
// }
// }
}
module.exports = servestaticfiles<file_sep>const fs = require('fs');
const bodyParser = require('./bodyParser');
const mimeType = {
'.html' : 'text/html',
'.css' : 'text/css',
'.js' : 'application/javascript',
'.json' : 'application/json',
'.txt' : 'text/plain',
'.jpg' : 'image/jpeg',
'.jpeg' : 'image/jpeg',
'.png' : 'image/png'
}
const routeController = async (request, getRoutes, postRoutes,middlewares,client) =>{
const response = {
send : send,
json : json,
status : status
}
for (const middleware of middlewares){
request = middleware(request)
}
path = (request.headers.path);
console.log('path in routecontroller', path);
if(getRoutes.hasOwnProperty(path)){
getRoutes[path](request,response,client)
}
if(postRoutes.hasOwnProperty(path)){
postRoutes[path](request,response,client)
}
function status (code){
console.log(" in the status code ");
let resp = `HTTP/1.1 ${code} OK\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Headers: Origin, Content-Type, Accept\r\n`
const date = new Date()
resp += `Date: ${date.toUTCString()}\r\n`
resp += 'Content-Type: *\r\n'
client.write(Buffer.from(resp), function(err) { client.end() })
// client.end()
}
function json(body2){
const body = JSON.stringify(body2);
let responseHeaders =
`HTTP/1.1 200 OK
Content-Type: ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection: keep-alive
Content-Length: ${body.length}
Date: ${new Date().toUTCString()}
\r\n\r\n`
client.write(Buffer.from(responseHeaders + body), function(err) { client.end() })
// client.end()
}
function send(controller) {
const body = JSON.stringify(controller)
let responseHeaders =
`HTTP/1.1 200 OK
Content-Type: ${mimeType[path.slice(path.lastIndexOf('.'))]}
Connection: keep-alive
Content-Length: ${body.length}
Date: ${new Date().toUTCString()}
\r\n\r\n`
client.write(Buffer.from(responseHeaders + body + '\r\n'), function(err) { client.end() })
// client.end()
}
}
module.exports = routeController
function statusHeader(statusCode){
const httpStatus = {
'200':'OK',
'400': 'Bad request',
}
let responseHeader = `HTTP/1.1 ${statusCode} ${httpStatus[statusCode]}
Connection: keep-alive
Date: ${new Date()}
\r\n`
return responseHeader
}<file_sep>
const bodyParser = (req) =>{
const contentType = req['Content-Type']
if(!req.body){
return req
}
console.log('before', req.body);
switch (contentType){
case 'application/json':
req.body = JSON.parse(req.body.toString())
case 'test/plain':
req.body = req.body.toString()
}
return req
}
module.exports = bodyParser
|
55f62f6101d52b8d9ae23d9e8739f6e34f870f31
|
[
"JavaScript",
"Markdown"
] | 10 |
JavaScript
|
achyuthreddyi/webserver
|
75313bb292c10ef6d2365680d2277b847b7a8bb3
|
cf73394339d3e61df0063dc3c7ae9519979e7781
|
refs/heads/master
|
<repo_name>yretes/Weekly1<file_sep>/Weekly1/Weekly1.cpp
#include <iostream>
#include <string>
#include <stdlib.h>
std::string Fullname = "";
char Initial;
int age;
char Confirmation;
bool yesno = false;
bool likesCoffee;
long phonenr = 00000000;
std::string Birthday = "";
int borderSize;
int task;
int favDrink;
// A function to check for answers for yes or no questions. Basically transforms Y/N to True/false.
void confirm() {
if (Confirmation == 'y') {
yesno = true;
}
else if ( Confirmation == 'n') {
yesno = false;
}
else {
std::cout << "I'm sorry, I don't understand. Please answer my question (y/n)\n";
std::cin >> Confirmation;
confirm();
}
}
// A function that counts how many characters there are in a string. This is to make the border in the end.
void stringCount() {
borderSize = Fullname.length();
}
void Task1() {
bool Phone = true;
std::cout << "Welcome to task 1! Please enter your full name\n";
std::cin.ignore();
std::getline (std::cin, Fullname);
std::cout << "Great to meet you, " << Fullname << "! Now, what is the initial of your first name?\n";
std::cin.clear();
std::cin >> Initial;
std::cout << "Got it! Your name is " << Fullname << ", and your first initial is " << Initial << std::endl;
std::cout << "so, " << Initial << ", How old are you?\n";
std::cin.clear();
std::cin >> age;
if (age >= 20) {
std::cout << "Excellent. You are " << age << " years old.\n";
}
else if (age < 13) {
std::cout << "Oh my... You're very young.\n";
}
else if (age < 20) {
std::cout << "So you're a teenager? Ok!\n";
}
std::cout << "Right, so, is it ok if I ask for your phone number? (y/n)\n";
std::cin.clear();
std::cin >> Confirmation;
confirm();
if (yesno == true) {
std::cout << "Great! Please enter your phone number:\n";
std::cin >> phonenr;
std::cout << "Got it! Your phone number is " << phonenr << std::endl;
Phone = true;
}
else {
std::cout << "I'm sorry to hear that, but so be it.\n";
Phone = false;
}
std::cout << "So, when is your birthday?\n";
std::cin >> Birthday;
stringCount();
std::cout << "Okay, " << Initial << ", does this look right to you?\n";
std::cout << std::string(borderSize, '-') + "-----------\n";
std::cout << "| Name |" << Fullname << std::endl;
std::cout << "| Initial |" << Initial << std::endl;
std::cout << "| Age |" << age << std::endl;
std::cout << "| Phone no|";
if (Phone == false) {
std::cout << "NOT RECIEVED\n";
}
else {
std::cout << phonenr << std::endl;
}
std::cout << "| Birthday|" << Birthday << std::endl;
std::cout << std::string(borderSize, '-') + "-----------\n";
std::cout << "Is the information above correct? (y/n)" << std::endl;
std::cin.clear();
std::cin >> yesno;
confirm();
if (yesno == true) {
std::cout << "Amazing. Thank you, " << Fullname << ". See you around! Bye!";
}
else {
std::cout << "Oh dear. I'm sorry. Please restart the program, and we'll try again.";
}
}
void Task2() {
std::cin.clear();
std::cout << "Hello. I am CoffeeTron 2000. Please input your name:\n";
std::cin >> Fullname;
std::cout << "Affirmative. Your name is " << Fullname << ". Please input your age.\n";
std::cin >> age;
std::cout << "Affirmative. You are " << age << " years old. Do you like coffee, " << Fullname << "? (y/n)\n";
std::cin >> Confirmation;
confirm();
if (yesno == true) {
std::cout << "It seems you like coffee.\n";
likesCoffee = true;
}
if (yesno == false) {
std::cout << "Oh you don't like coffee.\n";
likesCoffee = false;
}
std::cout << "\n \nYour name is " << Fullname << "\n \n You are " << age << " years old. \n \n";
if (likesCoffee == true) {
std::cout << "Seems you like coffee.\n";
}
if (likesCoffee == false) {
std::cout << "Seems you don't like coffee... \n \n Please leave. \n \n";
}
}
void Task3() {
std::cout << "Hi there, how old are you?\n";
std::cin >> age;
if (age < 20) {
std::cout << "You are young.\n";
}
else if (age < 40) {
std::cout << "You are a grown up.\n";
}
else if (age < 59) {
std::cout << "You are old.\n";
}
else if (age > 59) {
std::cout << "You are REALLY old.\n";
}
}
void Task4() {
std::cin.clear();
std::cout << "Hey man, could I ask you what your favourite drink is? \n 1. Coffee \n 2. Tea \n 3. Coca Cola \n\n Select between 1 to 3\n";
std::cin >> favDrink;
if (favDrink == 1) {
std::cout << "Coffee is delicious.\n";
}
else if (favDrink == 2) {
std::cout << "Tea gives peace of mind.\n";
}
else if (favDrink == 3) {
std::cout << "Coke will give you a white smile.\n";
}
else {
std::cout << "Please select between 1 to 3.\n";
Task4();
}
}
void Task5() {
std::cin.clear();
int x;
int y;
int xCounter = 0;
int yCounter = 0;
std::cout << "Please input X size(max 25):\n";
std::cin >> x;
if (x > 25) {
std::cout << "I'm sorry. I can't let you do that.\n \n";
Task5();
}
std::cout << "Please input Y size (max 25):\n";
std::cin >> y;
if (y > 25) {
std::cout << "I'm sorry. I can't let you do that.\n \n";
Task5();
}
while (yCounter < y) {
while (xCounter <x) {
std::cout << " [" << xCounter + 1 << "]";
xCounter = xCounter + 1;
}
xCounter = 0;
std::cout << std::endl;
yCounter = yCounter + 1;
}
std::cout << std::endl;
}
int main()
{
std::cout << "Welcome! This is the first weekly assignment. Please select which task you want to test:\n '1' Who are you? \n '2' Do you like coffee? \n";
std::cout << " '3' Age checker \n '4' Drink preference \n '5' Grid \n";
std::cin.clear();
std::cin >> task;
if (task == 1) {
Task1();
}
if (task == 2) {
Task2();
}
if (task == 3) {
Task3();
}
if (task == 4) {
Task4();
}
if (task == 5) {
Task5();
}
std::cout << "\nThanks for testing that one, feel free to try another!\n";
}
|
c682bedeb949f40f40207d55e7dacd9d11d9d0ed
|
[
"C++"
] | 1 |
C++
|
yretes/Weekly1
|
cb63bfe36f6a6a5c72a7a5cf643290281577777f
|
3a580e010aa9fb2b630eeb3fdd510b2352b2005b
|
refs/heads/master
|
<repo_name>mtirtapradja/learn-DDD-concept<file_sep>/pertemuan-4/Controllers/UserController.cs
๏ปฟusing pertemuan_4.Handlers;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Controllers
{
public class UserController
{
public static string CheckUsername(string username)
{
string response = "";
if (username == "")
{
response = "Username must be filled";
}
else if (username.Length < 5)
{
response = "Username must be at least 5 characters";
}
return response;
}
public static string CheckRegister(string username, string password, string confirmPassword, DateTime dob)
{
string response = CheckUsername(username);
if (response == "")
{
if (password.Equals(""))
{
response = "Password must be filled";
}
else if (!confirmPassword.Equals(password))
{
response = "Confirm password must be the same as password";
}
else if (dob.Date == DateTime.MinValue)
{
response = "DOB must be chosen";
}
else
{
if (UserHandler.InsertNewUser(username, password, dob))
{
response = "";
}
else
{
response = "Failed to register!";
}
}
}
return response;
}
public static string CheckLogin(string username, string password)
{
string response = "";
User currentUser = UserHandler.Login(username, password);
if (currentUser == null)
{
response = "User not found!";
}
return response;
}
public static User GetUser(string username, string password)
{
return UserHandler.GetUser(username, password);
}
}
}<file_sep>/projek_WebService/Repository/ProductRepository.cs
๏ปฟusing projek_WebService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebServices.Repository
{
public class ProductRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static Product FindByProductId(int productId)
{
db.Configuration.ProxyCreationEnabled = false;
return (from x in db.Products where x.Id == productId select x).FirstOrDefault();
}
}
}<file_sep>/pertemuan-4/Utils/JsonHandler.cs
๏ปฟusing Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace pertemuan_4.Utils
{
public class JsonHandler
{
private static JavaScriptSerializer jss = new JavaScriptSerializer();
// Object -> JSON
public static string Encode(object data)
{
return JsonConvert.SerializeObject(data);
}
// JSON -> Object
public static T Decode<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
}
}<file_sep>/pertemuan-4/Factories/TransactionHeaderFactory.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Factories
{
public class TransactionHeaderFactory
{
public static TransactionHeader Create(int userId)
{
TransactionHeader transactionHeader = new TransactionHeader();
transactionHeader.UserId = userId;
transactionHeader.TransactionDate = DateTime.Now;
return transactionHeader;
}
}
}<file_sep>/pertemuan-4/Views/ManageProductPage.aspx.cs
๏ปฟusing pertemuan_4.Handlers;
using pertemuan_4.Controllers;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace pertemuan_4.Views
{
public partial class ManageProductPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
{
Response.Redirect("LoginPage.aspx");
}
else
{
User currentUser = (User)Session["user"];
if (currentUser.Role != "Admin")
{
Response.Redirect("HomePage.aspx");
}
else
{
FillGrid();
}
}
}
protected void FillGrid()
{
gvProduct.DataSource = ProductController.GetProductList();
gvProduct.DataBind();
}
protected void btnInsert_Click(object sender, EventArgs e)
{
string name = txtName.Text;
string str_price = txtPrice.Text;
string str_quantity = txtQuantity.Text;
string response = ProductController.CheckInsert(name, str_price, str_quantity);
if (response == "")
{
lblError.Text = "";
FillGrid();
}
else
{
lblError.Text = response;
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
int id = int.Parse(txtID.Text);
string name = txtName.Text;
string str_price = txtPrice.Text;
string str_quantity = txtQuantity.Text;
string response = ProductController.CheckUpdate(id, name, str_price, str_quantity);
if (response == "")
{
lblError.Text = "";
FillGrid();
}
else
{
lblError.Text = response;
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
int id = int.Parse(txtID.Text);
string response = ProductController.CheckDelete(id);
if (response == "")
{
lblError.Text = "";
FillGrid();
}
else
{
lblError.Text = response;
}
}
protected void linkHome_Click(object sender, EventArgs e)
{
Response.Redirect("HomePage.aspx");
}
}
}<file_sep>/pertemuan-4/Controllers/CartController.cs
๏ปฟusing pertemuan_4.Handlers;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Controllers
{
public class CartController
{
public static string CheckInsert(int userId, string str_productId, string str_quantity)
{
string response = "";
if (str_productId == "")
{
response = "Product ID must be filled";
}
else if (str_quantity == "")
{
response = "Quantity must be filled";
}
else
{
int productId = int.Parse(str_productId);
int quantity = int.Parse(str_quantity);
if (!CartHandler.InsertCart(userId, productId, quantity))
{
response = "Failed to order product";
}
}
return response;
}
public static List<Cart> GetThisUserCart(int id)
{
return CartHandler.GetThisUserCart(id);
}
public static string Checkout(int userId)
{
string response = "";
if (CartHandler.Checkout(userId))
{
response = "";
}
else
{
response = "You haven't ordered anything";
}
return response;
}
}
}<file_sep>/pertemuan-4/Factories/TransactionDetailFactory.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Factories
{
public class TransactionDetailFactory
{
public static TransactionDetail Create(int headerId, int productId, int quantity)
{
TransactionDetail transactionDetial = new TransactionDetail();
transactionDetial.TransactionId = headerId;
transactionDetial.ProductId = productId;
transactionDetial.Quantity = quantity;
return transactionDetial;
}
}
}<file_sep>/pertemuan-4/Controllers/ProductController.cs
๏ปฟusing pertemuan_4.Handlers;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Controllers
{
public class ProductController
{
public static List<Product> GetProductList()
{
return ProductHandler.GetProductList();
}
public static string CheckInsert(string name, string str_price, string str_quantity)
{
string response = "";
if (name == "")
{
response = "Name must be filled!";
}
else if (str_price == "")
{
response = "Price must be filled!";
}
else
{
int price = int.Parse(str_price);
int quantity;
// TryParse bakal cobain parse argument pertama,
// kalo berhasil dia bakal di masukin ke quarntyty
if (int.TryParse(str_quantity, out quantity))
{
ProductHandler.InsertNewProduct(name, price, quantity);
}
else
{
ProductHandler.InsertNewProductWithDefaultQuantity(name, price);
}
}
return response;
}
public static string CheckUpdate(int id, string name, string str_price, string str_quantity)
{
string response = "";
if (name == "")
{
response = "Name must be filled!";
}
else if (str_price == "")
{
response = "Price must be filled!";
}
else
{
int price = int.Parse(str_price);
int quantity;
// TryParse bakal cobain parse argument pertama,
// kalo berhasil dia bakal di masukin ke quarntyty
if (int.TryParse(str_quantity, out quantity))
{
if (!ProductHandler.UpdateProduct(id, name, price, quantity))
{
response = "Product not found!";
}
}
else
{
if (!ProductHandler.UpdateProductWithDefaultQuantity(id, name, price))
{
response = "Product not found!";
}
}
}
return response;
}
public static string CheckDelete(int id)
{
string response = "";
if (!ProductHandler.DeleteProductById(id))
{
response = "Product not found!";
}
return response;
}
}
}<file_sep>/pertemuan-4/Views/LoginPage.aspx.cs
๏ปฟusing pertemuan_4.Models;
using pertemuan_4.Handlers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using pertemuan_4.Controllers;
namespace pertemuan_4.Views
{
public partial class LoginPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] != null)
{
Response.Redirect("HomePage.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = txtUsername.Text;
string password = <PASSWORD>.Text;
string response = UserController.CheckLogin(username, password);
if (response == "")
{
Session["user"] = UserController.GetUser(username, password);
Response.Redirect("HomePage.aspx");
}
}
protected void linkRegister_Click(object sender, EventArgs e)
{
Response.Redirect("RegisterPage.aspx");
}
}
}<file_sep>/projek_WebService/Handlers/TransactionHandler.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebServices.Factories;
using WebServices.Repository;
using projek_WebService.Models;
using projek_WebService.Handlers;
namespace WebServices.Handlers
{
public class TransactionHandler
{
private static object jsonHandler;
public static string FindByUserId(int userId)
{
List<TransactionHeader> result = new List<TransactionHeader>();
var headers = TransactionRepository.FindByUserId(userId);
if (headers.Count < 1)
{
return "";
}
else
{
foreach(var header in headers)
{
List<TransactionDetail> finalDetail = new List<TransactionDetail>();
List<TransactionDetail> transactionDetails = TransactionRepository.FindDetailByHeaderId(header.Id);
foreach(var detail in transactionDetails)
{
Product product = ProductRepository.FindByProductId(detail.ProductId);
finalDetail.Add(TransactionFactory.CreateDetail(header.Id, product, detail.Quantity));
}
TransactionHeader finalHeader = TransactionFactory.CreateHeader(header.Id, header.UserId, header.TransactionDate, finalDetail);
result.Add(finalHeader);
}
return JsonHandler.Encode(result);
}
}
}
}<file_sep>/pertemuan-4/Handlers/UserHandler.cs
๏ปฟusing pertemuan_4.Models;
using pertemuan_4.Repository;
using pertemuan_4.Factories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Handlers
{
public class UserHandler
{
public static User Login(string username, string password)
{
return UserRepository.GetUser(username, password);
}
public static User GetUser(string username, string password)
{
return UserRepository.GetUser(username, password);
}
public static bool InsertNewUser(string username, string password, DateTime DOB)
{
User currentUser = UserFactory.Create(username, password, DOB);
return UserRepository.InsertUser(currentUser);
}
}
}<file_sep>/pertemuan-4/Services/TransactionService.cs
๏ปฟusing pertemuan_4.WebService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Services
{
public class TransactionService
{
private static MainService service = null;
// Constructor
private TransactionService() { }
public static MainService GetInstance()
{
if (service == null)
{
service = new MainService();
}
return service;
}
}
}<file_sep>/pertemuan-4/Repository/TransactionDetailRepository.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Repository
{
public class TransactionDetailRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static bool InsertTransactionDetail(TransactionDetail transactionDetail)
{
if (transactionDetail != null)
{
db.TransactionDetails.Add(transactionDetail);
db.SaveChanges();
return true;
}
return false;
}
public static List<TransactionDetail> GetTransactionDetails(int transactionId)
{
return (from x in db.TransactionDetails where x.TransactionId == transactionId select x).ToList();
}
}
}<file_sep>/pertemuan-4/Factories/UserFactory.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Factories
{
public class UserFactory
{
public static User Create(string username, string password, DateTime DOB)
{
User newUser = new User();
newUser.Username = username;
newUser.Password = <PASSWORD>;
newUser.DOB = DOB;
newUser.Role = "User";
return newUser;
}
}
}<file_sep>/pertemuan-4/Views/ReportPage.aspx.cs
๏ปฟusing pertemuan_4.Datasets;
using pertemuan_4.Models;
using pertemuan_4.Reports;
using pertemuan_4.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace pertemuan_4.Views
{
public partial class ReportPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GroupingReport transactionReport = new GroupingReport();
transactionReport.SetDataSource(GetData());
crvTransaction.ReportSource = transactionReport;
}
protected DataSet GetData()
{
List<TransactionHeader> headers = TransactionHeaderRepository.GetAllTransactions();
DataSet ds = new DataSet();
var ds_header = ds.TransactionHeader;
var ds_detail = ds.TransactionDetail;
foreach (var header in headers)
{
var newRow = ds_header.NewRow();
newRow["Id"] = header.Id;
newRow["UserId"] = header.UserId;
newRow["Date"] = header.TransactionDate;
ds_header.Rows.Add(newRow);
List<TransactionDetail> details = TransactionDetailRepository.GetTransactionDetails(header.Id);
foreach (var detail in details)
{
var newRowDetail = ds_detail.NewRow();
newRowDetail["TransactionId"] = detail.TransactionId;
newRowDetail["ProductId"] = detail.ProductId;
newRowDetail["ProductName"] = ProductRepository.GetProductById(detail.ProductId).Name;
newRowDetail["Price"] = ProductRepository.GetProductById(detail.ProductId).Price;
newRowDetail["Quantity"] = ProductRepository.GetProductById(detail.ProductId).Quantity;
ds_detail.Rows.Add(newRowDetail);
}
}
return ds;
}
protected void linkHome_Click(object sender, EventArgs e)
{
Response.Redirect("HomePage.aspx");
}
}
}<file_sep>/pertemuan-4/Views/HomePage.aspx.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace pertemuan_4.Views
{
public partial class HomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
{
Response.Redirect("LoginPage.aspx");
}
else
{
User currentUser = (User)Session["user"];
lblWelcome.Text = "Welcome, " + currentUser.Username;
if (currentUser.Role != "Admin")
{
btnManageProduct.Visible = false;
}
else
{
btnManageProduct.Visible = true;
}
}
}
protected void btnLogout_Click(object sender, EventArgs e)
{
Session["user"] = null;
Session.Abandon();
Response.Redirect("LoginPage.aspx");
}
protected void btnManageProduct_Click(object sender, EventArgs e)
{
Response.Redirect("ManageProductPage.aspx");
}
protected void btnOrderProduct_Click(object sender, EventArgs e)
{
Response.Redirect("OrderProductPage.aspx");
}
protected void btnHistory_Click(object sender, EventArgs e)
{
Response.Redirect("TransactionHistoryPage.aspx");
}
protected void btnReport_Click(object sender, EventArgs e)
{
Response.Redirect("ReportPage.aspx");
}
}
}<file_sep>/pertemuan-4/Views/TransactionHistoryPage.aspx.cs
๏ปฟusing pertemuan_4.Models;
using pertemuan_4.Utils;
using pertemuan_4.WebService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace pertemuan_4.Views
{
public partial class TransactionHistoryPage : System.Web.UI.Page
{
private MainService service = new MainService();
protected static List<TransactionHeader> transactionHeaders = new List<TransactionHeader>();
protected void FillGrid()
{
gvTransactionHistory.DataSource = transactionHeaders;
gvTransactionHistory.DataBind();
List<TransactionDetail> transactionDetails = new List<TransactionDetail>();
foreach(var header in transactionHeaders)
{
foreach(var detail in header.TransactionDetails)
{
transactionDetails.Add(detail);
}
}
gvDetail.DataSource = transactionDetails;
gvDetail.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
{
Response.Redirect("LoginPage.aspx");
}
else
{
User currentUser = (User)Session["user"];
string json = service.GetTransaction(currentUser.Id);
transactionHeaders = JsonHandler.Decode<List<TransactionHeader>>(json);
FillGrid();
}
}
protected void linkHome_Click(object sender, EventArgs e)
{
Response.Redirect("HomePage.aspx");
}
}
}<file_sep>/pertemuan-4/Repository/UserRepository.cs
๏ปฟusing pertemuan_4.Factories;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Repository
{
public class UserRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static bool InsertUser(User currentUser)
{
if (currentUser != null)
{
db.Users.Add(currentUser);
db.SaveChanges();
return true;
}
return false;
}
public static User GetUser(string username, string password)
{
User currentUser = (from x in db.Users where x.Username.Equals(username) &&
x.Password.Equals(password) select x)
.FirstOrDefault();
return currentUser;
}
}
}<file_sep>/pertemuan-4/Handlers/ProductHandler.cs
๏ปฟusing pertemuan_4.Models;
using pertemuan_4.Factories;
using pertemuan_4.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Handlers
{
public class ProductHandler
{
public static List<Product> GetProductList()
{
// Ngebalikin semua data di db dari repo
return ProductRepository.GetAllProducts();
}
public static bool InsertNewProduct(string name, int price, int quantity)
{
// Bikin object pake Factory
Product newProduct = ProductFactory.Create(name, price, quantity);
// Masukin object nya ke db lewat repo
return ProductRepository.InsertProduct(newProduct);
}
public static bool InsertNewProductWithDefaultQuantity(string name, int price)
{
// Bikin object pake Factory
Product newProduct = ProductFactory.Create(name, price);
// Masukin object nya ke db lewat repo
return ProductRepository.InsertProduct(newProduct);
}
public static bool UpdateProduct(int id, string name, int price, int quantity)
{
// Cari produk yang mau di update lewat repo, karena cuma repo yang bisa
// berhubungan sama db
Product currentProduct = ProductRepository.GetProductById(id);
if (currentProduct != null)
{
currentProduct.Name = name;
currentProduct.Price = price;
currentProduct.Quantity = quantity;
return ProductRepository.UpdateProduct(currentProduct);
}
return false;
}
public static bool UpdateProductWithDefaultQuantity(int id, string name, int price)
{
// Cari produk yang mau di update lewat repo, karena cuma repo yang bisa
// berhubungan sama db
Product currentProduct = ProductRepository.GetProductById(id);
if (currentProduct != null)
{
currentProduct.Name = name;
currentProduct.Price = price;
return ProductRepository.UpdateProduct(currentProduct);
}
return false;
}
public static bool DeleteProductById(int id)
{
// Cari produk yang mau di delete lewat repo, karena cuma repo yang bisa
// berhubungan sama db
Product currentProduct = ProductRepository.GetProductById(id);
return ProductRepository.DeleteProduct(currentProduct);
}
}
}<file_sep>/pertemuan-4/Repository/ProductRepository.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Repository
{
public class ProductRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static List<Product> GetAllProducts()
{
return (from x in db.Products select x).ToList();
}
public static bool InsertProduct(Product newProduct)
{
if (newProduct != null)
{
db.Products.Add(newProduct);
db.SaveChanges();
return true;
}
return false;
}
public static Product GetProductById(int id)
{
return (from x in db.Products where x.Id.Equals(id) select x)
.FirstOrDefault();
}
public static bool UpdateProduct(Product currentProduct)
{
if (currentProduct != null)
{
db.SaveChanges();
return true;
}
return false;
}
public static bool DeleteProduct(Product currentProduct)
{
if (currentProduct != null)
{
db.Products.Remove(currentProduct);
db.SaveChanges();
return true;
}
return false;
}
}
}<file_sep>/pertemuan-4/Repository/CartRepository.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Repository
{
public class CartRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static bool InsertCart(Cart newCart)
{
if (newCart != null)
{
db.Carts.Add(newCart);
db.SaveChanges();
return true;
}
return false;
}
public static List<Cart> GetThisUserCart(int id)
{
return (from x in db.Carts where x.UserId == id select x).ToList();
}
public static bool RemoveCart(Cart cart)
{
if (cart != null)
{
db.Carts.Remove(cart);
db.SaveChanges();
return true;
}
return false;
}
}
}<file_sep>/pertemuan-4/Views/OrderProductPage.aspx.cs
๏ปฟusing pertemuan_4.Controllers;
using pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace pertemuan_4.Views
{
public partial class OrdcerProductPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FillGrid();
}
protected void FillGrid()
{
int userId = ((User)Session["user"]).Id;
gvCart.DataSource = CartController.GetThisUserCart(userId);
gvCart.DataBind();
gvProducts.DataSource = ProductController.GetProductList();
gvProducts.DataBind();
}
protected void btnOrder_Click(object sender, EventArgs e)
{
string str_productId = txtProductID.Text;
string str_quantity= txtQuantity.Text;
// Dari session di cast ke User terus diambil Id nya
int userId = ((User)Session["user"]).Id;
string response = CartController.CheckInsert(userId, str_productId, str_quantity);
if (response == "")
{
lblError.Text = "";
FillGrid();
}
else
{
lblError.Text = response;
}
}
protected void btnCheckout_Click(object sender, EventArgs e)
{
int userId = ((User)Session["user"]).Id;
string response = CartController.Checkout(userId);
if (response == "")
{
lblError.Text = "";
FillGrid();
}
else
{
lblError.Text = response;
}
}
protected void linkHome_Click(object sender, EventArgs e)
{
Response.Redirect("HomePage.aspx");
}
}
}<file_sep>/pertemuan-4/Handlers/CartHandler.cs
๏ปฟusing pertemuan_4.Factories;
using pertemuan_4.Models;
using pertemuan_4.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Handlers
{
public class CartHandler
{
public static bool InsertCart(int userId, int productId, int quantity)
{
Cart newCart = CartFactory.Create(userId, productId, quantity);
return CartRepository.InsertCart(newCart);
}
public static List<Cart> GetThisUserCart(int id)
{
return CartRepository.GetThisUserCart(id);
}
public static bool Checkout(int userId)
{
List<Cart> carts = GetThisUserCart(userId);
if (carts.Count == 0)
{
return false;
}
else
{
TransactionHeader transactionHeader = TransactionHeaderFactory.Create(userId);
if (TransactionHeaderRepository.InsertTransactionHeader(transactionHeader))
{
int headerId = transactionHeader.Id;
for (int i = 0; i < carts.Count(); i++)
{
TransactionDetail transactionDetail = TransactionDetailFactory.Create(headerId, carts[i].ProductId, carts[i].Quantity);
TransactionDetailRepository.InsertTransactionDetail(transactionDetail);
}
for (int i = 0; i < carts.Count(); i++)
{
CartRepository.RemoveCart(carts[i]);
}
return true;
}
return false;
}
}
}
}<file_sep>/pertemuan-4/Repository/TransactionHeaderRepository.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Repository
{
public class TransactionHeaderRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static bool InsertTransactionHeader(TransactionHeader transactionHeader)
{
if (transactionHeader != null)
{
db.TransactionHeaders.Add(transactionHeader);
db.SaveChanges();
return true;
}
return false;
}
public static List<TransactionHeader> GetAllTransactions()
{
return db.TransactionHeaders.ToList();
}
}
}<file_sep>/projek_WebService/Factories/TransactionFactory.cs
๏ปฟusing projek_WebService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebServices.Factories
{
public class TransactionFactory
{
public static TransactionHeader CreateHeader(int headerId, int userId, DateTime date, List<TransactionDetail> details)
{
return new TransactionHeader()
{
Id = headerId,
UserId = userId,
TransactionDate = date,
TransactionDetails = details
};
}
public static TransactionDetail CreateDetail(int headerId, Product product, int quantity)
{
return new TransactionDetail()
{
TransactionId = headerId,
ProductId = product.Id,
Quantity = quantity,
};
}
}
}<file_sep>/pertemuan-4/Factories/ProductFactory.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Factories
{
public class ProductFactory
{
public static Product Create(String name, int price, int quantity)
{
Product product = new Product();
product.Name = name;
product.Price = price;
product.Quantity = quantity;
return product;
}
public static Product Create(String name, int price)
{
Product product = new Product();
product.Name = name;
product.Price = price;
product.Quantity = 100;
return product;
}
}
}<file_sep>/WebServices/Repository/TransactionRepository.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebServices.Repository
{
public class TransactionRepository
{
private static DatabaseEntities db = new DatabaseEntities();
public static List<TransactionHeader> FindByUserId(int userId)
{
db.configuration.ProxyCreationEnabled = false;
return (from x in db.TransactionHeaders where x.UserId == userId select x).toList();
}
public static List<TransactionDetail> FindDetailByHeaderId(int headerId)
{
db.configuration.ProxyCreationEnabled = false;
return (from x in db.TransactionDetails where x.TransactionId == headerId select x).toList();
}
}
}<file_sep>/pertemuan-4/Factories/CartFactory.cs
๏ปฟusing pertemuan_4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace pertemuan_4.Factories
{
public class CartFactory
{
public static Cart Create(int userId, int productId, int quantity)
{
Cart c = new Cart();
c.UserId = userId;
c.ProductId = productId;
c.Quantity = quantity;
return c;
}
}
}
|
21d624a1f7c81c4dfac399a0142fdf42d5ed62c8
|
[
"C#"
] | 28 |
C#
|
mtirtapradja/learn-DDD-concept
|
319e2bf88f66fc666a37f5fbe630b797916b35cf
|
d79a2cb689a4a2c0c3acb5fc4cf051a4fd6b55e5
|
refs/heads/master
|
<file_sep>brian
=====
WDI BriannDFIshy
<file_sep>require 'bcrypt'
PASSWORD_RESET_EXPIRES = 4
class User
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :image, ImageUploader
attr_accessor :password, :password_confirmation
field :email
field :salt
field :fish
field :reset_code
field :reset_expires_at, type: Time
field :admin, type: Boolean, default: false
has_many :forms, validate: false, dependent: :delete, autosave: true
before_create :set_random_password, unless: :password
before_save :encrypt_password, if: :password
before_save :downcase_attributes
validates :email, presence: true, uniqueness: {case_sensitive: false}
validates :password, confirmation: true
def self.authenticate(email, password)
user = User.find_by email: email
user if user and user.authenticate(password)
end
def self.find_by_code(code)
if user = User.find_by({:reset_code => code, :reset_expires_at => {"$gte" => Time.now.gmtime}})
user.set_expiration
end
user
end
def authenticate(password)
self.fish == BCrypt::Engine.hash_secret(password, self.salt)
end
def update_info(params)
self.update_attributes(params)
end
def set_reset_code
self.reset_code = SecureRandom.urlsafe_base64
set_expiration
end
def reset_password(params)
if self.update_attributes(params)
self.update_attributes(params.merge( reset_code: nil, reset_expires_at: nil ))
end
end
def set_expiration
self.reset_expires_at = PASSWORD_RESET_EXPIRES.hours.from_now
self.save!
end
protected
def downcase_attributes
self.email.downcase!
end
def set_salt
self.salt = BCrypt::Engine.generate_salt
end
def set_random_password
if self.fish.blank?
self.fish = BCrypt::Engine.hash_secret(SecureRandom.base64(32), set.salt)
end
end
def encrypt_password
self.fish = BCrypt::Engine.hash_secret(password, set.salt)
true
end
end
<file_sep>require 'spec_helper'
describe User do
# before :each do
# @invalid_user = User.new
# @valid_user = User.new(
# email: <EMAIL>
# )
# end
# it "is valid with an email" do
# user = User.new(
# email: '<EMAIL>'
# )
# expect(user).to be_valid
# end
it "is invalid without email" do
user = User.new
expect(user).to be_invalid
end
it "is a valid email" do
user = User.new(
email: "<EMAIL>"
)
expect(user.email).to match /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/
end
it "is an invalid email" do
user = User.new(
email: "s*^()(&^"
)
expect(user.email).not_to match /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/
end
it "is invalid with a duplicate email address" do
User.create(
email: "<EMAIL>"
)
user = User.new(
email: "<EMAIL>"
)
expect(user).to have(1).errors_on(:email)
end
it "is saved with the password match with password confirmation" do
user = User.new(
email: '<EMAIL>',
password_confirmation: '<PASSWORD>',
password: '<PASSWORD>'
)
result = user.save
expect(result).to be_false
end
it "is invalid if it can't be authenticated" do
User.create(
email: "<EMAIL>",
password: "<PASSWORD>"
)
user = User.find_by email: "<EMAIL>"
result = user.authenticate "12345"
expect(result).to be_false
end
it "get the code when password is reset"
User.create(
email: "<EMAIL>"
)
#1. hash manually
#2. get code when password reset
end
<file_sep>class FormController < ApplicationController
before_action :is_authenticated?, only: [:new, :create, :edit, :update, :destroy]
before_action :set_message, only: [:show, :edit, :update, :destroy]
def index
@forms = Form.desc(:created_at).entries
@family = @forms.select{|x| x.relationship == "family"}
@friends = @forms.select{|x| x.relationship == "friends"}
end
def new
@user = current_user
@form = @user.forms.new
end
def create
@user = current_user
@form = @user.forms.new(form_params)
if @form.save
redirect_to root_url, notice: "You have successfully send your love."
else
error_message = @form.errors.full_messages.join('\n')
flash.now[:alert] = error_message
render :new
end
end
def show
end
def edit
end
def update
if
@form.update(params[:form].permit(:name, :relationship, :message, :year, :image))
redirect_to @form
else
render :edit
end
end
def destroy
@form.destroy
redirect_to root_url, notice: "Your form has been deleted."
end
private
def form_params
params.require(:form).permit(:user_id, :id, :name, :relationship, :message, :year, :image)
end
def set_message
@form = Form.find(params[:id])
end
end<file_sep>class Name
include Mongoid::Document
embedded_in :form
field :prefix
field :name
field :middle
field :family
field :suffix
validates :name, :family, presence: true
def full
[
self.prefix,
self.name,
self.middle,
self.family,
self.suffix,
].compact.join(" ")
end
def full_reversed
[
self.family,
[
self.prefix,
self.name,
self.middle,
].compact.join(" "),
self.suffix
].compact.join(", ")
end
def simple
[ self.name, self.middle, self.family ].compact.join(" ")
end
def simple_reversed
[
self.family,
[ self.name, self.middle ].compact.join(" ")
].compact.join(", ")
end
def reversed
[ self.family, self.name ].compact.join(" ")
end
end<file_sep>class UserNotifier < ActionMailer::Base
CODED_RESET_LINK_SUBJECT = "[BriannFishy] Reset your credentials"
PASSWORD_WAS_RESET_SUBJECT = "[BriannFishy] Your password was reset successfully"
default from: "BriannFishy <<EMAIL>"
def coded_password_reset_link(user)
@user = user
mail to: @user.email, subject: CODED_RESET_LINK_SUBJECT
end
def password_was_reset(user)
@user = user
mail to: @user.email, subject: PASSWORD_WAS_RESET_SUBJECT
end
end<file_sep>class UserController < ApplicationController
def new
end
def create
@user = User.new(user_params)
if @user.save
log_user_in(@user, "You have successfully signed up!")
else
render :new
end
end
private
def user_params
params.require(:user).permit(:id, :email, :password, :password_confirmation, forms_attributes: [:id, :name, :message, :relationship, :year, :image])
end
end<file_sep># Be sure to restart your server when you modify this file.
Brian::Application.config.session_store :cookie_store, key: '_brian_session'
<file_sep>class UserAuthenticator
AUTH_FAILED = %{
Unable to log you into the system, please try again
}.squish
def initialize(session, flash)
@flash = flash
@session = session
end
def authenticate_user(user_params)
#email and password
unless @user = User.authenticate(
user_params[:email],
user_params[:password])
@flash.now[:alert] = AUTH_FAILED
end
@user
end
end<file_sep>class Form
include Mongoid::Document
include Mongoid::Timestamps
RELATIONSHIP = ["Family", "Friends"]
mount_uploader :image, ImageUploader
field :name
field :relationship
field :message
field :year
validates :name, :relationship, :message, :year, :image, presence: true
belongs_to :user
end
<file_sep>Brian::Application.routes.draw do
resources :user
resources :form
root 'form#index'
get 'signup' => 'user#new'
post 'signup' => 'user#create'
get 'login' => 'session#new', as: :login_form
post 'login' => 'session#create', as: :log_in
delete 'logout' => 'session#destroy'
# get 'logout' => 'session#destroy'
get 'privacy' => 'site#privacy'
get 'terms' => 'site#terms'
get 'reset/:code' => '<PASSWORD>', as: :reset_password
put 'reset/:code' => '<PASSWORD>'
patch 'reset/:code' => '<PASSWORD>'
get 'wdi' => 'site#wdi'
end
<file_sep>Time::DATE_FORMATS[:mail_timestamp] = "%a %-d %b %Y %-I:%M %p"
|
3ccf0ea1462349d49c84603edd9c8ebfc98ce7f6
|
[
"Markdown",
"Ruby"
] | 12 |
Markdown
|
JulesWiz/brian
|
cf1374052fca649d59b5f779f4392296b0e9b1eb
|
174b1b0225632c6cc69b70a6a831104d930267c3
|
refs/heads/master
|
<repo_name>cjtitus/sst-hw<file_sep>/sst_hw/__init__.py
import os
from pkg_resources import get_distribution, DistributionNotFound
"""
Style imitated shamelessly from qtpy: https://github.com/spyder-ide/qtpy/blob/master/qtpy/__init__.py
"""
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
SST_API = "SST_HW"
REAL_API = ["real"]
SIM_API = ["sim"]
binding_specified = SST_API in os.environ
os.environ.setdefault(SST_API, 'real')
API = os.environ[SST_API].lower()
initial_api = API
assert API in (REAL_API + SIM_API)
REAL = True
SIM = False
if API in REAL_API:
try:
from sst_hw_real import __version__ as REAL_HW_VERSION
except ImportError:
API = os.environ[SST_API] = 'sim'
if API in SIM_API:
try:
from sst_hw_sim import __version__ as SIM_HW_VERSION
REAL = False
SIM = True
except ImportError:
raise RuntimeError("No SST HW packages found")
<file_sep>/sst_hw/detectors.py
from . import REAL, SIM
if REAL:
from sst_hw_real.detectors import *
elif SIM:
from sst_hw_sim.detectors import *
<file_sep>/sst_hw/shutters.py
from . import REAL, SIM
if REAL:
from sst_hw_real.shutters import *
elif SIM:
from sst_hw_sim.shutters import *
<file_sep>/sst_hw/motors.py
from . import REAL, SIM
if REAL:
from sst_hw_real.motors import *
elif SIM:
from sst_hw_sim.motors import *
|
bbf84d680a6286b752f2d6fbb154bb459d2075fc
|
[
"Python"
] | 4 |
Python
|
cjtitus/sst-hw
|
de92df76dc34aa0d935fe82f18f916a1bad37867
|
c8bd69df8a460664bc0e7a393abfc8a8ddf35f5d
|
refs/heads/master
|
<repo_name>circlespainter/quorum-web3j-raw-priv<file_sep>/build.gradle
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.30'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
implementation 'org.web3j:quorum:4.0.6'
runtime 'ch.qos.logback:logback-classic:1.1.3'
}
compileKotlin {
kotlinOptions {
jvmTarget = '1.8'
}
}
application {
mainClassName = 'com.dtcs.demo.dlt.quorumweb3j.rawpriv.MainKt'
}<file_sep>/contract/private-Counter.js
a = eth.accounts[0]
web3.eth.defaultAccount = a;
// abi and bytecode generated from Counter.sol:
// > solcjs --bin --abi Counter.sol
var abi = [{"constant":false,"inputs":[],"name":"inc","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getCount","outputs":[{"name":"","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"dec","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
var bytecode = "0x60806040526000805534801561001457600080fd5b50610101806100246000396000f3fe6080604052600436106053576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063371303c0146058578063a87d942c14606c578063b3bcfa82146094575b600080fd5b348015606357600080fd5b50606a60a8565b005b348015607757600080fd5b50607e60ba565b6040518082815260200191505060405180910390f35b3<KEY>"
var simpleContract = web3.eth.contract(abi);
var simple = simpleContract.new(42, {from:web3.eth.accounts[0], data: bytecode, gas: 0x47b760, privateFor: ["QfeDAys9MPDs2XHExtc84jKGHxZg/aj52DTh0vtA3Xc="]}, function(e, contract) {
if (e) {
console.log("err creating contract", e);
} else {
if (!contract.address) {
console.log("Contract transaction send: TransactionHash: " + contract.transactionHash + " waiting to be mined...");
} else {
console.log("Contract mined! Address: " + contract.address);
console.log(contract);
}
}
});
<file_sep>/src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/Main.kt
package com.dtcs.demo.dlt.quorumweb3j.rawpriv
import org.web3j.abi.TypeReference
import org.web3j.abi.datatypes.Function
import org.web3j.abi.datatypes.Int
import org.web3j.crypto.WalletUtils
import java.io.File
import java.math.BigInteger
fun main() {
val qs = QuorumService(PRIVATE_FOR_FROM_NODE_PUBK)
val tmpDir = System.getProperty("java.io.tmpdir")
val fn = WalletUtils.generateNewWalletFile("pwd", File(tmpDir))
val filePath = "$tmpDir/$fn"
File(filePath).deleteOnExit()
val wallet = WalletUtils.loadCredentials("pwd", filePath)
val nonce = BigInteger.ZERO // Always new account
val func = Function("inc", emptyList(), emptyList())
val sendTransaction = qs.signAndSendFunctionCallTx(
wallet,
CONTRACT_ADDR,
func,
nonce,
DEFAULT_GAS_LIMIT,
PRIVATE_FOR_TO_NODE_PUBK
).get()
val hash = sendTransaction.transactionHash
println("TX HASH: $hash")
if (sendTransaction.error != null)
println("TX ERROR: ${sendTransaction.error.message}")
val queryFunc = Function("getCount", emptyList(), listOf(object : TypeReference<Int>(){}))
val res = qs.call(wallet.address, queryFunc, CONTRACT_ADDR).get()
if (res.error != null)
println("QUERY ERROR: ${res.error.message}")
else
println("COUNTER: ${res.value}")
qs.shutdown()
}<file_sep>/src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/Consts.kt
package com.dtcs.demo.dlt.quorumweb3j.rawpriv
import java.math.BigInteger
internal const val CONTRACT_ADDR = "0x36d15cc4f755c74d347376876ebc6730b4243dfa" // Private for node 1 and 2
internal const val PRIVATE_FOR_FROM_NODE_PUBK = "<KEY>
internal const val PRIVATE_FOR_TO_NODE_PUBK = "<KEY>
internal const val QUORUM_FROM_NODE_URL = "http://localhost:22000"
internal const val TESSERA_URL = "http://localhost"
internal const val TESSERA_PORT = 9081
internal const val DEFAULT_SLEEP_DURATION_IN_MILLIS = 2000L
internal const val DEFAULT_MAX_RETRY = 30
internal val DEFAULT_GAS_LIMIT = BigInteger.valueOf(100000)<file_sep>/src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/QuorumService.kt
package com.dtcs.demo.dlt.quorumweb3j.rawpriv
import org.web3j.abi.FunctionEncoder
import org.web3j.abi.datatypes.Function
import org.web3j.crypto.Credentials
import org.web3j.crypto.RawTransaction
import org.web3j.crypto.TransactionEncoder
import org.web3j.protocol.core.DefaultBlockParameterName
import org.web3j.protocol.core.methods.request.Transaction
import org.web3j.protocol.core.methods.response.EthCall
import org.web3j.protocol.core.methods.response.EthSendTransaction
import org.web3j.protocol.http.HttpService
import org.web3j.quorum.Quorum
import org.web3j.quorum.enclave.Tessera
import org.web3j.quorum.enclave.protocol.EnclaveService
import org.web3j.quorum.tx.QuorumTransactionManager
import org.web3j.utils.Numeric
import java.math.BigInteger
import java.util.concurrent.CompletableFuture
internal class QuorumService(
private val fromNodePK: String,
quorumUrl: String = QUORUM_FROM_NODE_URL,
tesseraUrl: String = TESSERA_URL,
tesseraPort: Int = TESSERA_PORT
) {
fun signAndSendFunctionCallTx(
creds: Credentials,
contractAddr: String,
func: Function,
nonce: BigInteger,
gasLimit: BigInteger,
vararg privateFor: String
): CompletableFuture<EthSendTransaction> {
val encodedFunc = FunctionEncoder.encode(func)
val rawTx = RawTransaction.createTransaction(nonce, BigInteger.ZERO, gasLimit, contractAddr, encodedFunc)
return if (privateFor.isNotEmpty()) {
// quorum.ethSendRawPrivateTransaction(hexEncodedSignedRawTx, privateFor.toList())
val qrtxm = QuorumTransactionManager(quorum, creds, fromNodePK, privateFor.asList(), enclave)
CompletableFuture.supplyAsync { qrtxm.signAndSend(rawTx) }
} else {
val signedRawTx = TransactionEncoder.signMessage(rawTx, creds)
val hexEncodedSignedRawTx = Numeric.toHexString(signedRawTx)
quorum.ethSendRawTransaction(hexEncodedSignedRawTx).sendAsync()
}
}
fun call(from: String, func: Function, contractAddr: String): CompletableFuture<EthCall> =
quorum.ethCall(
Transaction.createEthCallTransaction(from, contractAddr, FunctionEncoder.encode(func)),
DefaultBlockParameterName.LATEST
).sendAsync()
fun shutdown() {
quorum.shutdown()
}
private val web3Service = HttpService(quorumUrl)
internal val quorum = Quorum.build(web3Service)
private val enclaveService = EnclaveService(tesseraUrl, tesseraPort)
internal val enclave = Tessera(enclaveService, quorum)
}<file_sep>/README.md
# Private raw transaction demo with [web3j/quorum](https://github.com/web3j/quorum)
## Intro
These small Kotlin applications demonstrate how to use [web3j/quorum](https://github.com/web3j/quorum) to send private
raw transactions to a Quorum node, both with the AST API and with the Java contract wrappers
[generated using the web3j command line tools](https://docs.web3j.io/smart_contracts.html#smart-contract-wrappers).
They call a simple `Counter.sol` Solidity smart contract and perform an `inc()` operation privately between
two nodes (a "from" node and a "to" node); they also retrieve and print the updated counter value through `getCount()`.
### Running
[Setup the 7nodes examples locally](https://github.com/jpmorganchase/quorum-examples#setting-up-locally): build the
latest release tag, use Raft and remember to run with Tessera as Constellation is not supported locally. If you want
you can reduce the number of nodes to e.g. 3 (preferred) or 2.
[Proceed with the private transaction demo](https://github.com/jpmorganchase/quorum-examples/blob/master/examples/7nodes/README.md)
up to the smart contract deployment but use [`private-Counter.js`](./contract/private-Counter.js) instead of
`private-contract.js`.
Check that the contract has been deployed correctly and note the contract address via the transaction receipt.
You'll also need to note the public key of the "from" (first node) and "to" nodes that you can obtain e.g. with
`cat qdata/c1/tm.pub` from the 7nodes example directory after starting them.
If you're using [`quorum-maker` 2.6.2](https://github.com/synechron-finlabs/quorum-maker/tree/V2.6.2) you can deploy the
contract and copy the contract address more comfortably through the UI.
Now replace the values in [`Consts.kt`](./src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/Consts.kt) as follows:
- `CONTRACT_ADDR` has to be set to the contract's Ethereum address obtained from the receipt of the deployment transaction.
- `PRIVATE_FOR_FROM_NODE_PUBK` has to be set to the public key of the "from" node.
- `PRIVATE_FOR_TO_NODE_PUBK` has to be set to the public key of the "to" node.
- `QUORUM_FROM_NODE_URL` has to be set to the JSON-RPC URL of the Quorum node you want to connect to.
- `TESSERA_URL` has to be set to 3rd-party API Tessera URL (see the notes below about the Tessera configuration) _without the port_.
- `TESSERA_PORT` has to be set to 3rd-party API Tessera URL's _port_ (see the notes below about the Tessera configuration).
You shouldn't need to change anything else if you're using the 7nodes setup and the "from" node as first node.
If you're using [`quorum-maker` 2.6.2](https://github.com/synechron-finlabs/quorum-maker/tree/V2.6.2) take the keys and
address information from the UI; on Linux the URLs will be similar to the following values (see the notes below about
the Tessera configuration):
```kotlin
internal const val QUORUM_FROM_NODE_URL = "http://10.50.0.2:22000"
internal const val TESSERA_URL = "http://10.50.0.2"
internal const val TESSERA_PORT = 22006
```
Finally run `./gradlew run` and check the `getCount()` value in the various nodes, similar to the 7nodes demo. You
can run multiple times to increase the counter further.
As an alternative you can also run `MainWithWrapper` that uses the
[`Counter.java`](./src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/Counter.java) contract wrapper
[generated using the web3j command line tools](https://docs.web3j.io/smart_contracts.html#smart-contract-wrappers) like so:
```bash
$ web3j solidity generate -a Counter.abi -o . -p mypackage
```
### Notes
- Tessera 0.8 is required with the [Third Party API](https://github.com/jpmorganchase/tessera/wiki/Interface-&-API#third-party---public-api)
enabled in the configuration as the `web3j/quorum` library [invokes the `storeraw` API](https://github.com/web3j/quorum/blob/v4.0.6/src/main/kotlin/org/web3j/quorum/tx/QuorumTransactionManager.kt#L52).
- The Tessera Third Party API is enabled by default in 7nodes but not yet in [`quorum-maker` 2.6.2](https://github.com/synechron-finlabs/quorum-maker/tree/V2.6.2)
that uses Tessera 0.8 but the legacy 0.7 configuration format; if you want to use `quorum-maker` you'll need to
manually convert and overwrite the nodes' Tessera configuration after setting up the nodes but before running them
(configuration examples for Linux and macOS with Docker are provided in [`examples/conf`](./examples/conf)).
- Unfortunately there is no `quorum-maker` version that works with Tessera 0.9.x and Quorum 2.2.4 as of 20190704.
- The contract is compiled with `solcjs --bin --abi Counter.sol` using `[email protected]` and both the ABI and bytecode are provided;
beware that later version of `solc` might produce bytecode that is invalid for your specific Quorum version;
the Quorum node log usually provides insight on why a transaction was unsuccessful (e.g. gas or invalid bytecode).<file_sep>/src/main/kotlin/com/dtcs/demo/dlt/quorumweb3j/rawpriv/MainWithWrapper.kt
package com.dtcs.demo.dlt.quorumweb3j.rawpriv
import org.web3j.crypto.WalletUtils
import org.web3j.quorum.tx.QuorumTransactionManager
import java.io.File
import java.math.BigInteger
fun main() {
val qs = QuorumService(PRIVATE_FOR_FROM_NODE_PUBK)
val tmpDir = System.getProperty("java.io.tmpdir")
val fn = WalletUtils.generateNewWalletFile("pwd", File(tmpDir))
val filePath = "$tmpDir/$fn"
File(filePath).deleteOnExit()
val wallet = WalletUtils.loadCredentials("pwd", filePath)
val qrtxm = QuorumTransactionManager(
qs.quorum,
wallet,
PRIVATE_FOR_FROM_NODE_PUBK,
listOf(PRIVATE_FOR_TO_NODE_PUBK),
qs.enclave,
DEFAULT_MAX_RETRY,
DEFAULT_SLEEP_DURATION_IN_MILLIS
)
val counter = Counter.load(CONTRACT_ADDR, qs.quorum, qrtxm, BigInteger.valueOf(0), DEFAULT_GAS_LIMIT)
val sendTransaction = counter.inc().send()
val hash = sendTransaction.transactionHash
println("TX HASH: $hash")
val res = counter.count.send()
println("COUNTER: $res")
qs.shutdown()
}
|
a169869aee5c1d6affc15a509acd2b8d76bf435a
|
[
"JavaScript",
"Kotlin",
"Markdown",
"Gradle"
] | 7 |
Gradle
|
circlespainter/quorum-web3j-raw-priv
|
098d47643d8d6f1d7a190e9d82819fb5203e7c6c
|
61e4227e9c2dfd35d06d22eac6efa8ddd6039ee1
|
refs/heads/main
|
<file_sep>package day11.demo2;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Testing MathUtils ")
public class MathUtilsTest {
@Test
@DisplayName("Addition testing for MathUtils")
public void additionTest() {
MathUtils maths = new MathUtils();
// Client Expectation : 30
int actualOutput = maths.addition(10, 20);
// verify
assertEquals(30, actualOutput);
}
@Test
@DisplayName("Subtration testing for MathUtils")
public void subtractionTest() {
MathUtils maths = new MathUtils();
// CLIENT :: 5
int output = maths.subtraction(10, 5);
assertEquals(5, output, "Client expectation is 5");
}
@Test
@DisplayName("Negation Testing for Division")
public void divideTest() {
MathUtils maths = new MathUtils();
// CLIENT Expectatation :: ArithmeticException
assertThrows(ArithmeticException.class, () -> maths.divide(10, 0));
}
}
<file_sep>package te1.demo1;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class AppUtilsTest {
private AppUtils app;
@BeforeEach
public void init() {
app = new AppUtils();
}
@AfterEach
public void destroy() {
app = null;
}
@Test
@DisplayName("Welcome Greeting Test!")
public void greetingTest() {
assertEquals("helloworld", app.greetings(), ()-> "This must return hello world!!");
}
@Test
@DisplayName("Parametrized Greeting Test!")
public void greetingParamTest() {
assertEquals("hello rohit", app.greetings("rohit"), ()-> "This must return hello rohit!!");
}
@Test
@DisplayName("Divide test with Zero!!")
public void divideTest() {
assertThrows(ArithmeticException.class, () -> app.divide(12, 0), ()-> "Must throw arithmetic exception!");
}
@Test
@RepeatedTest(value = 5)
public void validateMobileLength() {
assertTrue(() -> app.validateMobileNumber("1234567891"), ()-> "String length must be equal to 10.");
}
@ParameterizedTest
@ValueSource(strings = {"1234567891", "1234567891"})
public void validateMobileNumber(String mobile) {
assertTrue(() -> app.validateMobileNumber(mobile) );
}
@ParameterizedTest
@CsvSource(value = {"1234567891", "1234567891"})
public void validateMobileNumberV1(String mobile) {
assertTrue(() -> app.validateMobileNumber(mobile) );
}
@Test
@DisplayName("Multiple add test!")
public void multipleAddTest() {
assertAll(
() -> assertEquals(5, app.add(3, 2), "The sum must be 5."),
() -> assertEquals(5, app.add(3, 2), "The sum must be 5."),
() -> assertEquals(5, app.add(3, 2), "The sum must be 5.")
);
}
@Test
public void cipherTest() {
assertEquals("bcd", app.cipherText("abc"));
}
@Nested
class MathUtils{
@Test
public void addPostiveTest() {
assertEquals(5, app.add(3, 2), "The sum must be 5.");
}
@Test
public void addNegativeTest() {
assertEquals(-5, app.add(-2, -3), "The sum must be -5.");
}
}
}
|
c7bddeed367f27b8ffe93667ef59e20495518a0f
|
[
"Java"
] | 2 |
Java
|
cg-201/day11
|
c299c1d656a741615f45f423ce0039f1c5c02f7a
|
2574a685a08bdb68eb135b3ef89c026d1ba8eba3
|
refs/heads/master
|
<repo_name>RobertDober/lab42-config<file_sep>/README.md
# lab42-config
My config files + deployment
## Basic idea
keep the config files in sync thx to git, add the following features
* Use Branches to deploy for different "profiles"
* Add deploy scripts in Ruby
## Layout
As this is after all a Ruby project we use the established ruby conventions
.
โโโ assets # config files to be deployed
โโโ lib
โย ย โโโ lab42-config
โโโ README.md
โโโ spec
## Basic Example
Let us assume that we have a bunch of zsh files we want to load with our .zshrc and that they are to be deployed
into $HOME/etc/
The files themselves are located in `assets/__home__/etc/**` and the deploy script will simply
* copy them into $HOME if nothing is clobbered
* not clobbering anything but continuing to copy other assets (default mode)
* only deploy if nothing is clobbered at all (safe mode)
* ask for clobbering if deployment is in interactive mode
* clobber if deployment is in force mode
<file_sep>/features/step_definitions/file_steps.rb
# Given(/^an asset file named "(.*?)"$/) do | fn |
# @af_content ||= 0
# step "a file named #{File.join(
# end
<file_sep>/bin/check_aruba_in_process
#!/usr/bin/env ruby
require 'lab42/config/deploy'
Deploy.new(ARGV.dup).execute!
<file_sep>/features/support/env.rb
require 'aruba/cucumber'
require 'aruba/in_process'
$:.unshift( File.expand_path( "../../lib", __FILE__ ) )
require 'lab42/config/deploy'
Aruba::InProcess.main_class = Lab42::Config::Deploy
Aruba.process = Aruba::InProcess
<file_sep>/TODO.md
# NEXT
## Create fn specs for the failing feature
## Create unit specs for rinning the failing fn spec
## Make unit spec pass
<file_sep>/features/step_definitions/deployment_steps.rb
require 'yaml'
When(/^I deploy the application with the following params:$/) do |string|
params = YAML.parse string
args = params.to_ruby.inject([]){| a, (k, v) | a << "#{k}: #{v}"}
step "I run `bin/lab42_config_deploy #{args.join " "}`"
end
<file_sep>/lib/lab42/config/deploy.rb
module Lab42
module Config
class Deploy
def execute!
@kernel.exit( 42 )
end
private
def initialize argv, stdin=$stdin, stdout=$stdout, stderr=$stderr, kernel=Kernel
@argv, @stdin, @stdout, @stderr, @kernel = argv, stdin, stdout, stderr, kernel
end
end # class Deploy
end # module Config
end # module Lab42
<file_sep>/features/step_definitions/environment_steps.rb
Given(/^env var \$(\w+) has value (.*)$/) do | var_name, var_value |
@env ||= {}
@env[var_name] = var_value
end
|
bbd3e8d6fc591d1605c9142cc8b33709c0054c75
|
[
"Markdown",
"Ruby"
] | 8 |
Markdown
|
RobertDober/lab42-config
|
9d06752cd52ae6501ee2061e7f19501a0d30eb44
|
79de765e3bb07bc96dc1d832f77d41a4d9ea0742
|
refs/heads/master
|
<repo_name>deathtumble/neopixel<file_sep>/src/main/java/opc/OpcClient.java
package opc;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
/**
* Represents a client connection to one FadeCandy server. The idea is to
* replicate the interface provided by Adafruit's Neopixel library for the
* Arduino.
*
* @see https://github.com/scanlime/fadecandy
* @see https://github.com/adafruit/Adafruit_NeoPixel
*/
public class OpcClient implements AutoCloseable {
private final static Logger LOGGER = Logger.getLogger(OpcClient.class);
public static final int BLACK = 0x000000;
private final List<OpcDevice> devices;
private final String host;
private final int port;
private Socket socket;
private OutputStream output;
private final Map<Byte, byte[]> packetDataMap;
/**
* Construct a new OPC Client.
*
* @param hostname
* Host name or IP address.
* <version>${spring-boot.version}</version>
*
* @param portNumber
* Port number
*/
public OpcClient(String hostname, int portNumber) {
this.host = hostname;
this.port = portNumber;
packetDataMap = Collections.synchronizedMap(new HashMap<Byte, byte[]>());
devices = new ArrayList<OpcDevice>();
}
/**
* Reset all pixels on this strip to black.
*/
public void clear() {
for (OpcDevice device : devices) {
device.clear();
}
}
/**
* Push all pixel changes to the strip.
*/
public void show() {
for (OpcDevice device : devices) {
device.show();
}
}
public int getMaxPixelCount(byte channel) {
int maxPixelCount = 0;
for (OpcDevice device : devices) {
maxPixelCount = Math.max(device.getMaxPixelCount(channel), maxPixelCount);
}
return maxPixelCount;
}
/**
* Add one new Fadecandy device.
*/
public void addDevice(OpcDevice opcDevice) {
if (!devices.contains(opcDevice)) {
devices.add(opcDevice);
}
}
/**
* Push a pixel buffer out the socket to the Fadecandy.
*/
public void writePixels(byte channel, int startPixel, byte[] colorData) {
if (colorData == null || colorData.length == 0) {
LOGGER.info("writePixels: no packet data");
} else {
byte[] packetData = getPacketData(channel);
System.arraycopy(colorData, 0, packetData, 4 + startPixel, colorData.length);
int numBytes = packetData.length - 4;
packetData[0] = (byte) channel;
packetData[1] = 0; // Command (Set pixel colors)
packetData[2] = (byte) (numBytes >> 8);
packetData[3] = (byte) (numBytes & 0xFF);
writePacketData(packetData);
}
}
private byte[] getPacketData(byte channel) {
byte[] packetData;
synchronized (packetDataMap) {
if (packetDataMap.containsKey(channel)) {
packetData = packetDataMap.get(channel);
} else {
packetData = new byte[getMaxPixelCount(channel) + 4];
packetDataMap.put(channel, packetData);
}
}
return packetData;
}
/**
* Send a control message to the Fadecandy server setting up proper
* interpolation and dithering.
*/
public void sendFirmwareConfigPacket(byte channel, byte firmwareConfig) {
byte[] packet = new byte[9];
packet[0] = (byte) channel; // Channel (reserved)
packet[1] = (byte) 0xFF; // Command (System Exclusive)
packet[2] = 0; // Length high byte
packet[3] = 5; // Length low byte
packet[4] = 0x00; // System ID high byte
packet[5] = 0x01; // System ID low byte
packet[6] = 0x00; // Command ID high byte
packet[7] = 0x02; // Command ID low byte
packet[8] = firmwareConfig;
writePacketData(packet);
}
private void writePacketData(byte[] packetData) {
synchronized (this) {
if (output == null) {
open();
}
}
try {
synchronized (output) {
output.write(packetData);
output.flush();
}
} catch (IOException e) {
close("Exception writing pixels", e);
}
}
/**
* Open a socket connection to the Fadecandy server.
*/
private void open() {
try {
socket = new Socket(host, port);
socket.setTcpNoDelay(true);
output = socket.getOutputStream();
} catch (IOException e) {
close("Exception opening socket", e);
}
}
private void close(String message, IOException e) {
LOGGER.error(message, e);
close();
throw new OpcException(message, e);
}
@Override
public void close() {
synchronized (this) {
try {
closeStream();
} finally {
closeSocket();
}
}
}
private void closeSocket() {
try {
if (socket != null && !socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
LOGGER.error("Exception closing socket", e);
} finally {
socket = null;
}
}
private void closeStream() {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
LOGGER.error("Exception closing stream", e);
} finally {
output = null;
}
}
}
<file_sep>/src/main/java/opc/Layer.java
package opc;
public class Layer {
private int size;
private int[] colorData;
private int[] alpha;
public Layer(int size) {
super();
this.size = size;
colorData = new int[size * 3];
alpha = new int[size];
reset();
}
public void setColorData(int pixelNo, int red, int green, int blue, int alpha) {
colorData[pixelNo * 3] = red;
colorData[pixelNo * 3 + 1] = green;
colorData[pixelNo * 3 + 2] = blue;
this.alpha[pixelNo] = alpha;
}
public void mergeLayer(Layer otherLayer) {
for (int i = 0; i < size; i++) {
float otherAlpha = 1.0f * otherLayer.alpha[i] / 255;
int otherRed = otherLayer.colorData[i * 3 + 0];
int otherGreen = otherLayer.colorData[i * 3 + 1];
int otherBlue = otherLayer.colorData[i * 3 + 2];
float currentAlpha = 1.0f * alpha[i] / 255;
int currentRed = colorData[i * 3 + 0];
int currentGreen = colorData[i * 3 + 1];
int currentBlue = colorData[i * 3 + 2];
float newAlpha = otherAlpha + currentAlpha * (1 - otherAlpha);
int newRed;
int newGreen;
int newBlue;
if (newAlpha > 0.0f) {
newRed = Math.round((1 / newAlpha) * ((otherRed * otherAlpha) + currentRed * currentAlpha * (1 - otherAlpha)));
newGreen = Math.round((1 / newAlpha) * ((otherGreen * otherAlpha) + currentGreen * currentAlpha * (1 - otherAlpha)));
newBlue = Math.round((1 / newAlpha) * ((otherBlue * otherAlpha) + currentBlue * currentAlpha * (1 - otherAlpha)));
} else {
newRed = 0;
newGreen = 0;
newBlue = 0;
}
colorData[i * 3 + 0] = newRed;
colorData[i * 3 + 1] = newGreen;
colorData[i * 3 + 2] = newBlue;
alpha[i] = Math.round(newAlpha * 255);
if (i == 9) {
alpha[i] = Math.round(newAlpha * 255);
}
}
}
public void reset() {
for (int i = 0; i < size; i++) {
alpha[i] = (byte) 0;
colorData[i * 3] = (byte) 0;
colorData[i * 3 + 1] = (byte) 0;
colorData[i * 3 + 2] = (byte) 0;
}
}
public byte[] getColorData() {
byte[] colorByteData = new byte[size * 3];
for (int i = 0; i < size * 3; i++) {
colorByteData[i] = (byte) colorData[i];
}
return colorByteData;
}
}
<file_sep>/src/main/java/com/murraytait/actuator/Main.java
package com.murraytait.actuator;
import opc.OpcClient;
import opc.OpcDevice;
import opc.PixelStrip;
public class Main {
public static final Color RED = new Color(128, 0, 0);
public static void main(String[] args) throws Exception {
String FC_SERVER_HOST = "localhost";
int FC_SERVER_PORT = 7890;
OpcClient client = new OpcClient(FC_SERVER_HOST, FC_SERVER_PORT);
client.clear();
client.show();
OpcDevice fadeCandy = new OpcDevice(client);
fadeCandy.setDithering(true);
fadeCandy.setInterpolation(true);
PixelStrip strip = new PixelStrip(fadeCandy, 0, 0, 0, 64);
for (int i = 0; i < 64; i++) {
if (i % 2 == 0 || (i / 8) % 2 == 0) {
strip.setPixelColor(0, i, Color.BLACK, 255);
} else {
strip.setPixelColor(0, i, RED, 255);
}
}
Breath breath = new Breath(strip, 64);
breath.start();
Thread.sleep(60000);
breath.setRunning(false);
breath.join();
client.clear();
client.show();
client.close();
}
}
<file_sep>/src/main/java/opc/OpcUtil.java
package opc;
public class OpcUtil {
public static final int BLACK = OpcUtil.makeColor(0, 0, 0);
/**
* Package red/green/blue values into a single integer.
*/
final public static int makeColor(int red, int green, int blue) {
int r = red & 0x000000FF;
int g = green & 0x000000FF;
int b = blue & 0x000000FF;
return (r << 16) | (g << 8) | (b) ;
}
/**
* Extract the red component from a color integer.
*/
final public static int getRed(int color) {
return (color >> 16) & 0x000000FF;
}
/**
* Extract the green component from a color integer.
*/
final public static int getGreen(int color) {
return (color >> 8) & 0x000000FF;
}
/**
* Extract the blue component from a color integer.
*/
final public static int getBlue(int color) {
return color & 0x000000FF;
}
}
|
a717bdd3e97491cb31064065f6f52257a4d634ed
|
[
"Java"
] | 4 |
Java
|
deathtumble/neopixel
|
8b8e63e3d43d1861159214eee9f86c281a8ca4ed
|
f56714895e0d56e75a6190ffba70db4de41bbaba
|
refs/heads/master
|
<repo_name>SmithSamuelM/sophy<file_sep>/README.md
<a href="http://sphia.org"><img src="http://media.charlesleifer.com/blog/photos/sophia-logo.png" width="215px" height="95px" /></a>
`sophy`, fast Python bindings for [Sophia Database](http://sphia.org), v2.1.
Features:
* Append-only MVCC database
* ACID transactions
* Consistent cursors
* Compression
* Multi-part keys
* Multiple databases per environment
* Ordered key/value store
* Fast Range searches
* Read-only, point-in-time Views
* Prefix searches
* Python 2.x only at the moment, but 3.x is coming.
Limitations:
* Not tested on Windoze.
The source for `sophy` is [hosted on GitHub](https://github.com/coleifer/sophy)
If you encounter any bugs in the library, please [open an issue](https://github.com/coleifer/sophy/issues/new), including a description of the bug and any related traceback.
## Installation
The [sophia](http://sophia.systems) sources are bundled with the `sophy` source code, so the only thing you need to install is [Cython](http://cython.org). You can install from [GitHub](https://github.com/coleifer/sophy) or from [PyPI](https://pypi.python.org/pypi/sophy/).
Pip instructions:
```console
$ pip install Cython sophy
```
Git instructions:
```console
$ pip install Cython
$ git clone https://github.com/coleifer/sophy
$ cd sophy
$ python setup.py build
$ python setup.py install
```
## Overview
Sophy is very simple to use. It acts like a Python `dict` object, but in addition to normal dictionary operations, you can read slices of data that are returned efficiently using cursors. Similarly, bulk writes using `update()` use an efficient, atomic batch operation. Reading and writing data to Sophy is a lot like working with a regular Python dictionary.
Despite the simple APIs, Sophia has quite a few advanced features. Sophia supports multiple key/value stores per environment. Key/value stores support multi-part keys, mmap, a cache mode, in-memory mode, LRU mode (bounded size), AMQ filters to reduce disk seeks, compression, read-only point-in-time views, and more. There is too much to cover everything in this document, so be sure to check out the official [Sophia storage engine documentation](http://sophia.systems/v2.1/index.html).
The next section will show how to perform common actions with `sophy`.
## Using Sophy
To begin, I've opened a Python terminal and instantiated a Sophia environment with one database (an environment can have multiple databases, though). When I called `create_database()` I specified my key/value store's name and index type, `"string"`.
```pycon
>>> from sophy import Sophia
>>> env = Sophia('/path/to/data-dir')
>>> db = env.create_database('mydb', 'string') # Create a new KV store.
```
The `db` object can now be used to store and retrieve data. Our keys will be strings, as will the values. Values are always treated as strings in `sophy`, but depending on the index type the key may be either: a 32-bit unsigned int, a 64-bit unsigned int, a string, or any combination of the above as a multi-part key.
We can set values individually or in groups:
```pycon
>>> db['k1'] = 'v1'
>>> db.update(k2='v2', k3='v3', k4='v4') # Efficient, atomic.
```
You can also use transactions:
```pycon
>>> with db.transaction() as txn: # Same as .update()
... txn['k1'] = 'v1-e'
... txn['k5'] = 'v5'
...
```
We can read values individually or in groups. When requesting a slice, the third parameter (`step`) is used to indicate the results should be returned in reverse. Alternatively, if the first key is higher than the second key in a slice, `sophy` will interpret that as ordered in reverse.
Here we're reading a single value, then iterating over a range of keys. When iterating over slices of the database, both the keys and the values are returned.
```pycon
>>> db['k1']
'v1-e'
>>> [item for item in db['k2': 'k444']]
[('k2', 'v2'), ('k3', 'v3'), ('k4', 'v4')]
```
Slices can also return results in reverse, starting at the beginning, end, or middle.
```pycon
>>> list(db['k3':'k1']) # Results are returned in reverse.
[('k3', 'v3'), ('k2', 'v2'), ('k1', 'v1-e')]
>>> list(db[:'k3']) # All items from lowest key up to 'k3'.
[('k1', 'v1-e'), ('k2', 'v2'), ('k3', 'v3')]
>>> list(db[:'k3':True]) # Same as above, but ordered in reverse.
[('k3', 'v3'), ('k2', 'v2'), ('k1', 'v1-e')]
>>> list(db['k3':]) # All items from k3 to highest key.
[('k3', 'v3'), ('k4', 'v4'), ('k5', 'v5')]
```
Values can also be deleted singly or in groups. To delete multiple items atomically use the `transaction()` method.
```pycon
>>> del db['k3']
>>> db['k3'] # 'k3' no longer exists.
Traceback (most recent call last):
...
KeyError: 'k3'
>>> with db.transaction() as txn:
... del txn['k2']
... del txn['k5']
... del txn['kxx'] # No error raised.
...
>>> list(db)
[('k1', 'v1-e'), ('k4', 'v4')]
```
### Transactions
```pycon
>>> with db.transaction() as txn:
... txn['k2'] = 'v2-e'
... txn['k1'] = 'v1-e2'
...
>>> list(db[::True])
[('k4', 'v4'), ('k2', 'v2-e'), ('k1', 'v1-e2')]
```
You can call `commit()` or `rollback()` inside the transaction block itself:
```pycon
>>> with db.transaction() as txn:
... txn['k1'] = 'whoops'
... txn.rollback()
... txn['k2'] = 'v2-e2'
...
>>> list(db.items())
[('k1', 'v1-e2'), ('k2', 'v2-e2'), ('k4', 'v4')]
```
If an exception occurs in the wrapped block, the transaction will automatically be rolled back.
### Cursors
Sophia is an ordered key/value store, so cursors will by default iterate through the keyspace in ascending order. To iterate in descending order, you can specify this using the slicing technique described above. For finer-grained control, however, you can use the `cursor()` method.
The `Database.cursor()` method supports a number of interesting parameters:
* `order`: either `'>='` (default), `'<='` (reverse), `'>'` (ascending not including endpoint), `'<'` (reverse, not including endpoint).
* `key`: seek to this key before beginning to iterate.
* `prefix`: perform a prefix search.
* `keys`: include the database key while iterating (default `True`).
* `values`: include the database value while iterating (default `True`).
To perform a prefix search, for example, you might do something like:
```pycon
>>> db.update(aa='foo', abc='bar', az='baze', baz='nugget')
>>> for item in db.cursor(prefix='a'):
... print item
...
('aa', 'foo')
('abc', 'bar')
('az', 'baze')
```
### Configuration
Sophia supports a huge number of [configuration options](http://sophia.systems/v2.1/conf/sophia.html), most of which are exposed as simple properties on the `Sophia` or `Database` objects. For example, to configure `sophy` with a memory limit and to use mmap and compression:
```pycon
>>> env = Sophia('my/data-dir', auto_open=False)
>>> env.memory_limit = 1024 * 1024 * 1024 # 1GB
>>> db = env.create_database('test-db', index_type=('string', 'u64'))
>>> db.mmap = True
>>> db.compression = 'lz4'
>>> env.open()
```
You can also force checkpointing, garbage-collection, and other things using simple methods:
```pycon
>>> env.scheduler_checkpoint()
>>> env.scheduler_gc()
```
Some properties are read-only:
```pycon
>>> db.index_count
10
>>> len(db)
10
>>> db.status
'online'
>>> db.memory_used
69
```
Take a look at the [configuration docs](http://sophia.systems/v2.1/conf/database.html) for more details.
### Multi-part keys
In addition to string keys, Sophy supports uint32, uint64, and any combination of the above. So, if I had a database that had a natural index on a timestamp (stored as an unsigned 64-bit integer) and a string, I could have a fast, multi-part key that stored both.
To use multi-part keys, just use tuples where you would otherwise use strings or ints.
```pycon
>>> db = env.create_database('multi', ('string', 'u64'))
>>> db[('hello', 100)] = 'sophy'
>>> print db[('hello', 100)]
sophy
```
Multi-part keys support slicing, and the ordering is derived from left-to-right.
### Specifying databases on startup
Because Sophia does not store any schema information, every time your app starts up you will need to provide it with the databases to connect to.
`Sophy` supports a very simple API for telling a database environment what key/value stores are present and should be loaded up:
```python
db_list = [
('users', 'string'),
('clicks', ('string', 'u64')),
('tweets', ('string', 'u64')),
]
env = Sophia('/var/lib/sophia/my-app', databases=db_list)
# After creating the environment, we can now access our data-stores.
user_db = env['users']
click_db = env['clicks']
tweet_db = env['tweets']
```
### Views
Views provide a read-only, point-in-time snapshot of the database. Views cannot be written to nor deleted from, but they support all the familiar reading and iteration APIs. Here is an example:
```pycon
>>> db.update(k1='v1', k2='v2', k3='v3')
>>> view = db.view('view-1')
>>> print view['k1']
'v1'
```
Now we'll make modifications to the database, and observe the view is not affected:
```pycon
>>> db['k1'] = 'v1-e'
>>> db['k3'] = 'v3-e'
>>> del db['k2']
>>> print [item for item in view] # Values in view are unmodified.
[('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]
```
When you are done with a view, you can call `view.close()`.
<file_sep>/tests.py
import os
import shutil
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
from sophy import Sophia
DB_NAME = 'db-test'
TEST_DIR = 'sophia-test'
class BaseTestCase(unittest.TestCase):
_index_type = 'string'
def setUp(self):
if os.path.exists(TEST_DIR):
shutil.rmtree(TEST_DIR)
self.sophia = self.create_env()
self.db = self.get_db()
def tearDown(self):
self.sophia.close()
if os.path.exists(TEST_DIR):
shutil.rmtree(TEST_DIR)
def create_env(self):
return Sophia(TEST_DIR, [(DB_NAME, self._index_type)])
def get_db(self):
return self.sophia[DB_NAME]
class TestConfiguration(BaseTestCase):
def test_version(self):
v = self.sophia.version
self.assertEqual(v, '2.1.1')
class BaseSophiaTestMethods(object):
def setUp(self):
super(BaseSophiaTestMethods, self).setUp()
self.k1, self.k2, self.k3, self.k4 = self.get_keys()
def get_keys(self):
raise NotImplementedError
def set_key_vars(self):
raise NotImplementedError
def set_key_range(self):
self.set_key_vars()
self.db.update({
self.r1: 'r1',
self.r2: 'r2',
self.r3: 'r3',
self.r4: 'r4',
self.r5: 'r5',
self.r6: 'r6',
self.r7: 'r7'})
def test_kv(self):
self.db[self.k1] = 'v1'
self.assertEqual(self.db[self.k1], 'v1')
self.db[self.k1] = 'v1-e'
self.assertEqual(self.db[self.k1], 'v1-e')
del self.db[self.k1]
self.assertRaises(KeyError, lambda: self.db[self.k1])
self.assertEqual(len(self.db), 0)
self.db[self.k2] = 'v2'
self.db[self.k3] = 'v3'
self.assertFalse(self.k1 in self.db)
self.assertTrue(self.k2 in self.db)
self.assertEqual(len(self.db), 2)
def test_open_close(self):
self.db[self.k1] = 'v1'
self.db[self.k2] = 'v2'
db_ptr = id(self.db)
self.sophia.close()
self.sophia.open()
db = self.sophia[self.db.name]
self.assertTrue(db_ptr != id(db))
self.assertEqual(db[self.k1], 'v1')
self.assertEqual(db[self.k2], 'v2')
db[self.k2] = 'v2-e'
self.sophia.close()
self.assertIsNone(db.status)
with self.sophia as env:
db = env[self.db.name]
self.assertEqual(db.status, 'online')
self.assertEqual(db[self.k1], 'v1')
self.assertEqual(db[self.k2], 'v2-e')
def test_collections(self):
self.db[self.k1] = 'v1'
self.db[self.k2] = 'v2'
self.db[self.k3] = 'v3'
self.assertEqual(list(self.db.keys()), [self.k1, self.k2, self.k3])
self.assertEqual(list(self.db.values()), ['v1', 'v2', 'v3'])
self.assertEqual(list(self.db.items()), [
(self.k1, 'v1'),
(self.k2, 'v2'),
(self.k3, 'v3')])
self.assertEqual(len(self.db), 3)
self.assertEqual(list(self.db), list(self.db.items()))
def test_update(self):
self.db.update({self.k1: 'v1', self.k2: 'v2', self.k3: 'v3'})
self.assertEqual(list(self.db.items()), [
(self.k1, 'v1'),
(self.k2, 'v2'),
(self.k3, 'v3')])
self.db.update({self.k1: 'v1-e', self.k3: 'v3-e', self.k4: 'v4'})
self.assertEqual(list(self.db.items()), [
(self.k1, 'v1-e'),
(self.k2, 'v2'),
(self.k3, 'v3-e'),
(self.k4, 'v4')])
def test_txn(self):
self.db[self.k1] = 'v1'
self.db[self.k2] = 'v2'
with self.db.transaction() as txn:
self.assertEqual(txn[self.k1], 'v1')
txn[self.k1] = 'v1-e'
del txn[self.k2]
txn[self.k3] = 'v3'
self.assertEqual(self.db[self.k1], 'v1-e')
self.assertRaises(KeyError, lambda: self.db[self.k2])
self.assertEqual(self.db[self.k3], 'v3')
def test_rollback(self):
self.db[self.k1] = 'v1'
self.db[self.k2] = 'v2'
with self.db.transaction() as txn:
self.assertEqual(txn[self.k1], 'v1')
txn[self.k1] = 'v1-e'
del txn[self.k2]
txn.rollback()
txn[self.k3] = 'v3'
self.assertEqual(self.db[self.k1], 'v1')
self.assertEqual(self.db[self.k2], 'v2')
self.assertEqual(self.db[self.k3], 'v3')
def test_cursor(self):
self.db.update({
self.k1: 'v1',
self.k2: 'v2',
self.k3: 'v3',
})
curs = self.db.cursor()
self.assertEqual(
list(curs),
[(self.k1, 'v1'), (self.k2, 'v2'), (self.k3, 'v3')])
curs = self.db.cursor(order='<')
self.assertEqual(
list(curs),
[(self.k3, 'v3'), (self.k2, 'v2'), (self.k1, 'v1')])
def assertRange(self, l, lo, hi, reverse=False):
expected = [
(getattr(self, 'r%d' % idx), 'r%d' % idx)
for idx in range(lo, hi + 1)]
if reverse:
expected.reverse()
self.assertEqual(list(l), expected)
return expected
def test_assert_range(self):
self.set_key_range()
expected = self.assertRange(self.db[:self.r4], 1, 4)
self.assertEqual(expected, [
(self.r1, 'r1'),
(self.r2, 'r2'),
(self.r3, 'r3'),
(self.r4, 'r4')])
expected = self.assertRange(self.db[self.r4::True], 4, 7, True)
self.assertEqual(expected, [
(self.r7, 'r7'),
(self.r6, 'r6'),
(self.r5, 'r5'),
(self.r4, 'r4')])
def test_range_endpoints(self):
self.set_key_range()
# everything to 'dd'.
self.assertRange(self.db[:self.r4], 1, 4)
# everything to 'dd' but reversed.
self.assertRange(self.db[:self.r4:True], 1, 4, True)
# everthing from 'dd' on.
self.assertRange(self.db[self.r4:], 4, 7)
# everthing from 'dd' on but reversed.
self.assertRange(self.db[self.r4::True], 4, 7, True)
# everything.
self.assertRange(self.db[:], 1, 7)
# everything reversed.
self.assertRange(self.db[::True], 1, 7, True)
def test_ranges(self):
self.set_key_range()
# Everything from aa to bb.
self.assertRange(self.db[self.r1:self.r2], 1, 2)
# Everything from aa to bb but reversed.
self.assertRange(self.db[self.r1:self.r2:True], 1, 2, True)
# Everything from bb to aa (reverse implied).
self.assertRange(self.db[self.r2:self.r1], 1, 2, True)
# Everything from bb to aa (reverse specified).
self.assertRange(self.db[self.r2:self.r1:True], 1, 2, True)
# Missing endpoint.
self.assertRange(self.db[self.r2:self.r5_1], 2, 5)
# Missing endpoint reverse.
self.assertRange(self.db[self.r5_1:self.r2], 2, 5, True)
self.assertRange(self.db[self.r2:self.r5_1:True], 2, 5, True)
# Missing startpoint.
self.assertRange(self.db[self.r3_1:self.r6], 4, 6)
# Missing startpoint reverse.
self.assertRange(self.db[self.r6:self.r3_1], 4, 6, True)
self.assertRange(self.db[self.r3_1:self.r6:True], 4, 6, True)
# Missing both.
self.assertRange(self.db[self.r3_1:self.r5_1], 4, 5)
# Missing both reverse.
self.assertRange(self.db[self.r5_1:self.r3_1], 4, 5, True)
self.assertRange(self.db[self.r3_1:self.r5_1:True], 4, 5, True)
def test_view(self):
self.db.update(dict(zip(
self.get_keys(),
('v1', 'v2', 'v3', 'v4'))))
del self.db[self.k4]
v = self.db.view('view1')
self.assertEqual(v[self.k1], 'v1')
self.assertEqual(v[self.k2], 'v2')
self.assertEqual(v[self.k3], 'v3')
self.db[self.k1] = 'v1-e'
self.db[self.k3] = 'v3-e'
v2 = self.db.view('view2')
self.db[self.k3] = 'v3-e2'
self.db[self.k4] = 'v4'
self.assertEqual(self.db[self.k1], 'v1-e')
self.assertEqual(self.db[self.k3], 'v3-e2')
self.assertEqual(self.db[self.k4], 'v4')
self.assertEqual(v[self.k1], 'v1')
self.assertEqual(v[self.k2], 'v2')
self.assertEqual(v[self.k3], 'v3')
self.assertRaises(KeyError, lambda: v[self.k4])
self.assertEqual(v2[self.k1], 'v1-e')
self.assertEqual(v2[self.k2], 'v2')
self.assertEqual(v2[self.k3], 'v3-e')
self.assertRaises(KeyError, lambda: v2[self.k4])
v.close()
v2.close()
def test_iter_view(self):
self.db.update(dict(zip(
self.get_keys(),
('v1', 'v2', 'v3', 'v4'))))
v = self.db.view('v1')
# Make some changes.
self.db[self.k1] = 'v1-e'
self.db[self.k3] = 'v3-e'
del self.db[self.k4]
# Iterate through the view.
view_items = list(v)
self.assertEqual(
list(v),
list(zip(self.get_keys(), ('v1', 'v2', 'v3', 'v4'))))
self.assertEqual(list(self.db), [
(self.k1, 'v1-e'),
(self.k2, 'v2'),
(self.k3, 'v3-e')])
# Do a little slicing to make sure.
self.assertEqual(list(v[self.k1:self.k2]), [
(self.k1, 'v1'),
(self.k2, 'v2')])
self.assertEqual(list(v[self.k2:self.k1]), [
(self.k2, 'v2'),
(self.k1, 'v1')])
self.assertEqual(list(v[:self.k2]), [
(self.k1, 'v1'),
(self.k2, 'v2')])
self.assertEqual(list(v[self.k2::True]), [
(self.k4, 'v4'),
(self.k3, 'v3'),
(self.k2, 'v2')])
v.close()
def test_multiple_dbs(self):
db_foo = self.sophia.create_database('foo')
db_bar = self.sophia.create_database('bar')
db_foo['k1'] = 'foo'
db_bar['k1'] = 'bar'
self.assertEqual(db_foo['k1'], 'foo')
self.assertEqual(db_bar['k1'], 'bar')
self.sophia.close()
self.sophia.open()
db_foo = self.sophia['foo']
db_bar = self.sophia['bar']
self.assertEqual(db_foo['k1'], 'foo')
self.assertEqual(db_bar['k1'], 'bar')
class TestStringIndex(BaseSophiaTestMethods, BaseTestCase):
_index_type = 'string'
def get_keys(self):
return ('k1', 'k2', 'k3', 'k4')
def set_key_vars(self):
self.r1 = 'aa'
self.r2 = 'bb'
self.r3 = 'bbb'
self.r4 = 'dd'
self.r5 = 'ee'
self.r6 = 'gg'
self.r7 = 'zz'
self.r3_1 = 'cc'
self.r5_1 = 'ff'
def test_key(self):
self.db['aa'] = 'v1'
self.db['ab'] = 'v2'
self.db['aab'] = 'v3'
self.db['abb'] = 'v4'
self.db['bab'] = 'v5'
self.db['baa'] = 'v6'
curs = self.db.cursor(key='ab')
self.assertEqual(list(curs), [
('ab', 'v2'),
('abb', 'v4'),
('baa', 'v6'),
('bab', 'v5'),
])
curs = self.db.cursor(key='abb', order='<')
self.assertEqual(list(curs), [
('ab', 'v2'),
('aab', 'v3'),
('aa', 'v1'),
])
curs = self.db.cursor(key='c')
self.assertEqual(list(curs), [])
curs = self.db.cursor(key='a', order='<')
self.assertEqual(list(curs), [])
def test_prefix(self):
self.db['aaa'] = '1'
self.db['aab'] = '2'
self.db['aba'] = '3'
self.db['abb'] = '4'
self.db['baa'] = '5'
curs = self.db.cursor(order='>=', prefix='a')
self.assertEqual(list(curs), [
('aaa', '1'),
('aab', '2'),
('aba', '3'),
('abb', '4')])
curs = self.db.cursor(order='>=', prefix='ab')
self.assertEqual(list(curs), [
('aba', '3'),
('abb', '4')])
class TestU32Index(BaseSophiaTestMethods, BaseTestCase):
_index_type = 'u32'
def get_keys(self):
return (
0,
1,
10,
11)
def set_key_vars(self):
self.r1 = 0
self.r2 = 3
self.r3 = 8
self.r4 = 10
self.r5 = 14
self.r6 = 16
self.r7 = 70
self.r3_1 = 9
self.r5_1 = 15
class TestU64Index(TestU32Index):
_index_type = 'u64'
class TestMultiIndex(BaseSophiaTestMethods, BaseTestCase):
_index_type = ('string', 'string', 'string')
def get_keys(self):
return (
('foo', 'bar', 'baz'),
('foo', 'bar', 'nug'),
('foo', 'nug', 'baz'),
('nug', 'bar', 'baz'))
def set_key_vars(self):
self.r1 = ('cc', 'bb', 'aa')
self.r2 = ('cc', 'bb', 'bb')
self.r3 = ('cc', 'bb', 'bbb')
self.r4 = ('cc', 'cc', 'aa')
self.r5 = ('dd', 'cc', 'aa')
self.r6 = ('ee', 'aa', 'bb')
self.r7 = ('ee', 'zz', 'aa')
self.r3_1 = ('cc', 'bc', 'bb')
self.r5_1 = ('de', 'ad', 'da')
def runOne(test):
test = BasicTestCase(test)
suite = unittest.TestSuite([test])
unittest.TextTestRunner(verbosity=2).run(suite)
def runSome():
tests = []
names = [
'test_version',
]
tests.extend(map(TestConfiguration, names))
names = [
'set_key_vars',
]
tests.extend(map(TestStringIndex, names))
suite = unittest.TestSuite(tests)
unittest.TextTestRunner(verbosity=2).run(suite)
def runTestConfiguration():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestConfiguration))
unittest.TextTestRunner(verbosity=2).run(suite)
def runTestStringIndex():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestStringIndex))
unittest.TextTestRunner(verbosity=2).run(suite)
def runTestU32Index():
suite = unittest.TestSuite()
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestU32Index))
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__' and __package__ is None:
runTestConfiguration() #run unitests from
runTestU32Index()
#runTestStringIndex()
#runAll() #run all unittests
#runSome()#only run some
#runOne('testCodes')
#if __name__ == '__main__':
#unittest.main(argv=sys.argv)
|
473ede82fe2662f4914f48cfe64a16e264577803
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
SmithSamuelM/sophy
|
2f9c86d598b41e551d298c4e7d77671a27757d83
|
14dc993fa18232eaa81d9ac6171bb807669c1801
|
refs/heads/master
|
<file_sep># CTI-110
# M7HW1_TestGrades_RobertDeLaney.py
# <NAME>
# 12-4-17
# Write a program that ask the user to calculate the
# test average and grade of five test scores
# conversion is total of five test scores /5
test1 = int(input('Enter score 1: '))
test2 = int(input('Enter score 2: '))
test3 = int(input('Enter score 3: '))
test4 = int(input('Enter score 4: '))
test5 = int(input('Enter score 5: '))
total =(test1 + test2 + test3 + test4 + test5)
# CalculateAverage
def calc_average(total):
return total / 5
#Grade
def determine_score(grade):
if 90 <= grade <= 100:
return 'A'
elif 80 <= grade <= 89:
return 'B'
elif 70 <= grade <= 79:
return 'C'
elif 60 <= grade <= 69:
return 'D'
else:
return 'F'
grade = total
avg = calc_average(total)
abc_grade = determine_score(grade)
print("That's a(n): " + str(abc_grade))
print('Average grade is: ' + str(avg))
<file_sep>def snowFlake(times,length=200.00):
t.penUp()
t.rotateTurtle(180)
t.moveForward(300)
t.rotateTurtle(-90)
t.moveForward(170)
t.rotateTurtle(-90)
t.penDown()
pattern = "MRMRM"
for i in range(times):
pattern =pattern.replace("M","MLMRMLM")
for j in pattern:
if j=="M":moveForward(length / (3.00 **(times - 1)))
elif j=="L": t.rotateTurtle(60)
elif j=="R": t.rotateTurtle(-120)
t.rotateTurtle(-120)
<file_sep># CTI-110
# M6HW2_Delaney.py
# <NAME>
# 12-1-17
total=0
for i in range(5):
newNumber = int (input('Enter a number:' ))
total += newNumber
print('The total is:',total)
total = 0 + 80
total = 80+ 90
total = 170+ 100
total =270 + -1
<file_sep># CTI-110
# M6T2Lab_DeLaney.py
# <NAME>
# 12-1-17
# Set total = 0
# for each of 7 days:
# Input bugs collected for a day
# Add Bugs collected to total
#
# Initialize the accumulator
total = 0
# Get the bugs collected for each day.
for day in range (1,8):
#Prompt the user
print('Enter the bugs collected on day', day)
#Input the number of bugs
bugs = int(input('How many bugs were collected on this day? '))
#Add bug to total
total = total + bugs
#Display the total bugs.
print ('You collected a total of', total, 'bugs. ')
<file_sep># CTI-110
# M6T1-Turtle Lab
# <NAME>
# 11-29-17
import turtle
win = turtle.Screen()
r = turtle.Turtle()
for x in range(2):
r.forward(100)
r.left(120)
r.forward (100)
r.penup()
r.forward (100)
r.pendown()
for x in range(4):
r.forward(50) # Tell alex to move forward by 50 units
r.left(90)
win.mainloop()
<file_sep># CTI-110
# M7T1_Delaney.py Kilometer Converter
# <NAME>
# 12-4-17
# Write a program that ask the user to enter a distance
# in Kilometers, and then converts that distance to miles
# Formula Miles = Kilometers * 0.6214
def askUserForKilometer():
userKilometers = float(input('Enter distance in kilometers. '))
return userKilometers
def convertKilometersToMiles (userKilometers ):
miles = userKilometers * 0.6214
return miles
def main():
userTypedKilometers = askUserForKilometer()
convertedMiles = convertKilometersToMiles (userTypedKilometers )
print(userTypedKilometers,'Kilometers converted to miles is',\
format (convertedMiles, '.2f') + 'miles. ')
main()
<file_sep># CTI-110
# M6LAB_DeLaney.py
# <NAME>
# 12-1-17
# Draw a traiangle using nested loops
baseSize = 8
for r in range (baseSize,1,-1):
for c in range (r - l):
print('*', end= '')
print()
<file_sep># CTI-110
# M6HW1_DeLaney.py
# <NAME>
# 12-1-17
# What is the speed of the vehicle in mph?
# How many hours did the vehicle travel?
# List the Distance Traveled for each hour traveled.
speed = int (input ('What is your speed? '))
startHour = (1)
endHour = int (input ('How long has the vehicle been traveling? '))
endHour = endHour + 1
#Print the table headings
print ('Hour\tDistance Traveled')
print ('------------------------')
distance = 0
# Print the distance traveled for each hour
for hours in range (startHour, endHour):
distance = speed * hours
print (hours, '\t', distance)
<file_sep># CTI-110
# M5HW1_AgeClassifier_DeLaney
# <NAME>
# 13-11-17
# ask the persons age
age = int(input('The persons age.'))
# if the person is 1 or younger
if age <= 1:
print ('The person is an infant.' )
# if the person is older than 1 but younger than 13
elif age > 1 and age < 13:
print ('The person is a child.' )
# if a person is at least 13, but less than 20
elif age >=13 and age < 20:
print ('The person is a teenager.' )
else:
print ('The person is an adult.' )
<file_sep># CTI-110
# M5HW2_SoftwareSales_DeLaney
# <NAME>
# 13-11-17
# Get number of packages
total = int(input('Enter number of packages purchased' ))
# if subtotal = $99 * number of packages
if total > 10:
print ('$99 * 10 packages purchased' )
print ('Discount is 10%' )
if total > 20:
print ('$99 * 20 packages purchased' )
print ('Discount is 20%' )
if total > 30:
print ('$99 * 50 packages purchased')
print ('Discount is 30%' )
if total > 100:
print ('$99 * 100 packages purchased' )
print ('Discount is 40% ')
else:
print ('$99 * 9 packages purchased' )
print ('Discount is 0' )
<file_sep># CTI-110
# M6T1B: Initials
# <NAME>
# 11-29-17
import turtle
wn=turtle.Screen()
R = turtle.Turtle()
#add display options
R.pensize(3)
R.pencolor("green")
R.shape("turtle")
R.left(90)
R.forward(50)
R.right(90)
R.forward(50)
R.right(90)
R.forward(25)
R.right(90)
R.forward(40)
R.left(90)
R.left(45)
R.forward(35)
# Move to New Spot
R.penup()
R.right(125)
R.backward(145)
R.left(180)
R.pendown()
# Draw Second Initial
R.right(90)
R.forward(100)
R.left(90)
R.circle(50,180)
R.hideturtle()
# end command
wn.mainloop()
<file_sep># CTI-110
# M7T2_FeetToInches_RobertDeLaney.py
# <NAME>
# 12-4-17
# Write a program that ask the user to enter a number
# feet, and then converts that number to inches
# conversion formula is one foot equals 12 inches
def askUserForFeet():
userFeet = float(input('Enter distance in feet. '))
return userFeet
def convertFeetToInches (userFeet ):
inches = userFeet * 12
return inches
def main():
userTypedFeet = askUserForFeet()
convertedInches = convertFeetToInches (userTypedFeet )
print(userTypedFeet,'Feet converted to inches is',\
format (convertedInches, '.2f') + 'inches. ')
main()
<file_sep># CTI-110
# M5LAB_DeLaney.py
# <NAME>
# 19-11-17
# Get students grade.
grade = int(input('Enter your grade: '))
# Did the student pass?
if grade >= 90:
print('Your grade is A.')
elif grade >= 80:
print('Your grade is B.')
elif grade >= 70:
print('Your grade is C.')
elif grade >= 60:
print('Your grade is D.')
else:
print('Your grade is F.')
<file_sep># CTI-110
# M6T1CLAB_DeLaney.py
# <NAME>(bonus)
# 12-1-17
import turtle
wn =turtle.Screen()
d =turtle.Turtle()
# add some display options
#d.pensize(3)
d.pencolor("Orange")
d.shape("turtle")
# Create my shape
for i in range (20):
for i in range(2):
d.forward(100)
d.right(60)
d.forward(100)
d.right(120)
# Rotate
d.right(18)
wn.exitonclick()
<file_sep># CTI-110
# M6LAB_DeLaney.py
# <NAME>
# 12-1-17
# Write a program that uses nested loops to draw this pattern:
# *******
# ******
# *****
# ****
# ***
# **
# *
for currentRow in range (7, 0, -1):
for currentColumn in range( currentRow ):
print( "*", end=" " )
print("")
<file_sep># CTI-110
# M4HW2 - Tip Tax Total
# <NAME>
# 08-11-17
# Enter the charge for food
tipRate=0.18
taxRate=0.07
# Get the cost of the meal
mealcost = float(input('How much was the cost of your meal? '))
# Calculate the amount of tip
tip = mealcost * tipRate
# Calculate the amount of tax
tax = mealcost * taxRate
#Display the total cost of the meal
total = mealcost + tax + tip
print('Mealcost' , format(mealcost, '0.02f'))
print('Tax total', format(tax, '0.2f'))
print('Tip total', format(tip, '0.2f'))
print('Meal total',format(total,'0.2f'))
<file_sep># CTI-110
# M4HW1 -Distance Traveled
# RobertDeLaney
# 08-11-17
# A car is traveling at 70 miles per hour
print ('A car is traveling at 70 miles per hour ')
speed=70
#The distance the car will travel in 6hours
time = 6
distance = speed * time
print ('The distance the car will travel ', distance, 'miles in 6 hours' )
#The distance the car will travel in 10 hours
time = 10
distance = speed * time
print ('The distance the car will travel ', distance, 'miles in 10 hours')
#The distance the car will travel in 15 hours
time = 15
distance = speed * time
print ('The distance the car will travel ', distance, 'miles in 15 hours')
<file_sep># CTI-110
# M7HW2_GuessingGame_RobertDeLaney.py
#<NAME>
# 12-4-17
# Write a program that ask the user to guess
# the random number between 0-50 if the answer is false
# the program will instruct the user to try again higher or lower
# if user guess is true the program will print ("Well Done")
# and print("End of program") will end the session
import random
randomNumber = random.randrange (0,50)
print('Random number has been generated')
guessed = False
while guessed==False:
userInput = int(input('Your guess please: '))
if userInput==randomNumber:
guessed = True
print('Well done!!')
elif userInput>50:
print('Our guess range is between 0 and 50, try a little lower')
if userInput<0:
print('Our guess range is between 0 and 50, try a little higher')
elif userInput>randomNumber:
print('Try again, a little lower')
elif userInput<randomNumber:
print('Try again, a little higher')
print ('End of program')
<file_sep># CTI110 Repository
Created for M2LAB2
DeLaney
October 31, 2017
|
e84a1738415b01d613429ad9247ca1b2634327c6
|
[
"Markdown",
"Python"
] | 19 |
Python
|
robertdelaney/CTI110
|
97a6a8ef8cdd33b61574564d20d357d22dc1d557
|
60b1f5e5948ab4bc6c4964e91277d89ccc2880c1
|
refs/heads/master
|
<file_sep>var List = function(options) {
this.id = Math.floor((Math.random()*1000)+1),
this.listName = options.listName,
this.tasks = options.tasks,
this.addTask = function(taskObj) {
this.tasks.push(taskObj);
};
};
var Task = function(name) {
this.id = Math.floor((Math.random()*2000)+1000),
this.name = name,
this.completed = false
// this.done = function() {
// this.completed = true;
// };
};
//tests
// var newList = new List ({
// listName: "todo",
// tasks: []
// });
// var newTask = new Task("walk the pups");
// var newTask2 = new Task("get milk");
// newList.addTask(newTask);
// newList.addTask(newTask2);
// console.log("updated list", newList);<file_sep>$(document).ready(function() {
var list1 = new List ({
listName: "Today's todo",
tasks: [ {id: 2001, name: "Walk the pups", completed: false}]
});
$('#add_todo').on('click', function() {
var userInput = $('input').val();
$('ul').append('<li>'+userInput+'</li>');
$('input').val('').focus();
var task = new Task(userInput);
list1.addTask(task);
console.log(list1);
});
$('section').on('click', 'li', function() {
var complete = 'completed';
$(this).addClass(complete);
var name = $(this).text();
var taskList = list1.tasks;
for (var i=0; i < taskList.length; i++) {
if (taskList[i].name === name) {
taskList[i].completed = true;
}
}
});
});
|
7f6cc7d16a4b9ef85b3bf40a0f662dec1d3204e8
|
[
"JavaScript"
] | 2 |
JavaScript
|
vkraucunas/simple-todo-list
|
ffb6c65acdabb0c0afad8a97af233e5abc4b560f
|
f1b321515aa57e702792d4518e558383ac32bd19
|
refs/heads/master
|
<repo_name>AmritaDas/RProf<file_sep>/README.md
# RProf
R proficiency
<file_sep>/QA1.R
##Q1#######
fun1 <- function(x){
y <- 0
if(x%%2 == 0){
print('eeny')
y <- 1
}
if(x%%3 == 0){
print('meeny')
y <- 1
}
if(x%%5 == 0){
print('miny')
y <- 1
}
if(y == 0){
print('moe')
}
}
##ex:
fun1(60)
fun1(59)
fun1(25)
##Q2#######
fun2 <- function(v){
c <- apply(v, 2, function(x) x%%2 == 0)
print(sum(c == TRUE))
}
##ex:
v <- cbind(10,4,6,9,8)
fun2(v)
##Q3#######
fun3 <- function(l){
c <- apply(l, 2, function(x) substring(x, 1, 1)=='R'||substring(x, 1, 1)=='r')
print(sum(c == TRUE))
}
##ex:
l <- cbind(7, 'Ret', 'io', 89.9, 'ryu')
fun3(l)
##Q4#######
fun4 <- function(w,x,y,z){
mat1 <- matrix(w, nrow=x, ncol=y)
mat2 <- matrix(z, nrow=y, ncol=x)
mat <- rbind(mat1, t(mat2))
return(mat)
}
##ex:
x1 <- fun4(1,2,3,4)
x1
##Q5#######
fun_diamonds <- function(diamonds){
count <- sum(diamonds$cut == "Ideal")
cutset <- subset(diamonds, cut == "Ideal")
sum <- sum(cutset$price)
return(sum/count)
}
##ex:
setwd("C:/Users/amrita/Desktop/ABI papers/R.Proficiency.Test")
diamonds <- read.table("diam.txt", header=TRUE)
fun_diamonds(diamonds)
##Q6#######
#6.1
temp_hist <- function(temperatures){
hist(temperatures$temp, breaks = 5, xlab = "Temperatures", main = "Histogram of temperatures")
}
#6.2
temp_boxplot <- function(temperatures){
boxplot(temperatures$temp, xlab = "Temperatures", main = "Boxplot of temperatures")
}
##ex:
temps <- read.table("temp.txt", header=TRUE)
temp_hist(temps)
temp_boxplot(temps)
##Q7#######
library(ggplot2)
fun_plot <- function(dat1, dat2, dat3){
ggplot() + geom_point(data=dat1, aes(x=dat1$x, y=dat1$y), color='red', shape=1, size=4) +
geom_point(data=dat2, aes(x=dat2$x, y=dat2$y), color='black', shape=5, size=4) +
geom_point(data=dat3, aes(x=dat3$x, y=dat3$y), color='blue', shape=4, size=4) +
xlab("x") + ylab("y") + ggtitle("Plot of three datasets")
}
##ex:
dat1 <- read.table("dat1.txt", header=TRUE)
dat2 <- read.table("dat2.txt", header=TRUE)
dat3 <- read.table("dat3.txt", header=TRUE)
fun_plot(dat1, dat2, dat3)
<file_sep>/QA2.R
##Q8#######
#8.1
library(plyr)
read_data <- function(x1, y1){
df1 <- read.csv(x1, header=TRUE, na.strings=c(""," ","NA"))
df2 <- read.csv(y1, header=TRUE, na.strings=c(""," ","NA"))
if(ncol(df1) < ncol(df2)){
k <- 1
x <- df1
y <- df2
} else if(ncol(df1) > ncol(df2)){
k <- 1
x <- df2
y <- df1
} else{
k <- 0
x <- df1
y <- df2
}
nc <- colnames(x)
nc1 <- colnames(y)
nc1 <- nc1[!nc1 %in% nc]
df_merged <- y
for(i in 1:nrow(x)){
row <- x[i,]
if(row$id %in% y$id){
r2 <- df_merged[df_merged$id == row$id,]
df_merged <- df_merged[df_merged$id != row$id,]
for(j in 1:length(nc)){
if(is.numeric(row[[nc[j]]])){
if(row[nc[j]] != r2[nc[j]]){
r2[nc[j]] <- NA
}
}
}
if(k == 1){
for(l in 1:length(nc1)){
r2[nc1[l]] <- NA
}
}
df_merged <- rbind.fill(df_merged, r2)
} else{
df_merged <- rbind.fill(df_merged, row)
}
}
write.csv(df_merged, file = "student_data_merged.csv", row.names = FALSE)
return(df_merged)
}
#8.2
compute_mean_median <- function(df_merged){
mean <- c()
median <- c()
for(i in 1:nrow(df_merged)){
row <- df_merged[i,]
m <- c()
for(j in 6:ncol(row)){
m <- rbind(m, row[[j]])
}
m <- sort(m)
mean <- rbind(mean, summary(m)[["Mean"]])
median <- rbind(median, summary(m)[["Median"]])
}
df_merged_new <- cbind(df_merged, Average_grade=mean)
df_merged_new <- cbind(df_merged_new, Median_grade=median)
return(df_merged_new)
}
#8.3
compute_mean_gender <- function(df_merged_new){
male <- c()
female <- c()
for(i in 1:nrow(df_merged_new)){
row <- df_merged_new[i,]
if(row$gender == 'M'){
male <- rbind(male, row$Average_grade)
} else if(row$gender == 'F'){
female <- rbind(female, row$Average_grade)
}
}
male <- sort(male)
female <- sort(female)
print(paste("Male students have a mean grade of",summary(male)[["Mean"]]))
print(paste("Female students have a mean grade of",summary(female)[["Mean"]]))
}
#8.4
compute_letter_grades <- function(df_merged_new){
df_letters <- df_merged_new[,1:16]
letters <- c()
for(i in 1:nrow(df_merged_new)){
num <- df_merged_new[i,]$Average_grade
if(num >= 90 && num <= 100){
letters <- rbind(letters, "A")
} else if(num >= 80 && num <= 89){
letters <- rbind(letters, "B")
} else if(num >= 70 && num <= 79){
letters <- rbind(letters, "C")
} else if(num < 70){
letters <- rbind(letters, "F")
}
}
df_letters <- cbind(df_letters, Letter_grade=letters)
return(df_letters)
}
#8.5
count_letter_grades <- function(df_letters){
lev <- levels(df_letters$Letter_grade)
for(i in 1:length(lev)){
print(paste("Count of Grade",lev[i], "-", sum(df_letters$Letter_grade == lev[i])))
}
}
##ex:
df_merged <- read_data("student_data_01.csv", "student_data_02.csv")
df_merged_new <- compute_mean_median(df_merged)
compute_mean_gender(df_merged_new)
df_letters <- compute_letter_grades(df_merged_new)
count_letter_grades(df_letters)
|
41cb392343bfe1a3e9467e080e0dd2298985dd0f
|
[
"Markdown",
"R"
] | 3 |
Markdown
|
AmritaDas/RProf
|
5c9c6582f48907d78329b611775fdbddbd5d5bcc
|
b777b5b2482dd324bca4cba0db52fb69aec3edc3
|
refs/heads/master
|
<file_sep>void readfile(FILE *f);
void process_request(FILE *f);
<file_sep>/* A simple database */
#include <stdio.h>
#include <string.h>
#include "readfile.h"
int main (int argc , char *argv[])
{
char * filename = argv[1];
printf("%s" , filename);
FILE *f = fopen(filename, "r+");/*opening the file in read and write mode*/
if (f != NULL)
{
readfile(f); /*passes this pointer to the readfromfle function*/
process_request(f); /*passes this pointer to the process_request function*/
}
else
{
printf("Error opening file\n");
}
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "prompt.h"
#define MAX_DEPARTMENT_LENGTH 6
#define MAX_COURSE_NUMBER_LENGTH 5
#define MAX_COURSE_LOCATION_LENGTH 12
#define MAX_NO_CLASSES 100
#define MAX_LINE_LENGTH 100
struct class
{
char department [MAX_DEPARTMENT_LENGTH];
char number [MAX_COURSE_NUMBER_LENGTH];
char location [MAX_COURSE_LOCATION_LENGTH];
};
void readfile(FILE *f);/*A function prototype*/
void process_request(FILE *f);
static struct class* classes[MAX_NO_CLASSES]; /*An array that holds pointer to 100 struct classes*/
static int no_of_classes; /*The no classes in the file*/
void readfile(FILE *f)
{
int i = 0;
fscanf(f , "%d" , &no_of_classes); /* Reading the first-line which is an int*/
/*This will move the file pointer to nextline */
char pseudo[MAX_LINE_LENGTH];
fgets(pseudo , MAX_LINE_LENGTH , f);
char line[MAX_LINE_LENGTH]; /*Stores a new class from the file*/
while (i < no_of_classes)
{
fgets(line , MAX_LINE_LENGTH , f);
classes[i] = (struct class*) malloc(sizeof(struct class)); /*Dynamically creating memory for structs*/
strcpy(classes[i] -> department , strtok(line , ":"));
strcpy(classes[i] -> number , strtok(NULL , ":"));
strcpy(classes[i] -> location , strtok(NULL , ":"));
i++;
}
}
void process_request(FILE *f)
{
int init_classes = no_of_classes;
int val; /* val controls the execution of switch statement*/
char input[MAX_LINE_LENGTH];
char value[MAX_LINE_LENGTH];
while (1) /*Loops repeatedly until the user wants to exit*/
{
display_prompt(); /*A call to the display_prompt function from the displayprompt module*/
fgets(input , MAX_LINE_LENGTH, stdin); /*gets input from the user and checks with the below conditions*/
if (strcmp(input , "list\n") == 0)
{
val = 1;
}
else if (strcmp(input , "add\n") == 0)
{
val = 2;
}
else if (strstr(input , "remove") != NULL)
{
val = 3;
}
else if (strcmp(input , "exit\n") == 0)
{
val = 4;
}
else
{
val = 5;
}
switch(val)
{
case 1: /*Lists the structs*/
{
int l;
for(l = 0; l < no_of_classes; l++)
{
printf("%d%s%s%s%s%s\n", (l+1), ":", classes[l] -> department, classes[l] -> number, "-", classes[l]-> location);
}
}
break;
case 2: /*Adds a new struct*/
{
classes[no_of_classes] = (struct class*) malloc(sizeof(struct class)); /*creating a space for additional struct*/
printf("Enter department:\n");
fgets(value , MAX_DEPARTMENT_LENGTH , stdin);
value[strlen(value) - 1] = '\0';
strcpy(classes[no_of_classes] -> department , value);
printf("Enter no. of class:\n");
fgets(value , MAX_COURSE_NUMBER_LENGTH , stdin);
value[strlen(value) - 1] = '\0';
strcpy(classes[no_of_classes] -> number , value);
printf("Enter location:\n");
fgets(value , MAX_COURSE_LOCATION_LENGTH , stdin);
value[strlen(value) - 1] = '\0';
strcpy(classes[no_of_classes] -> location , value);
no_of_classes++;
}
break;
case 3: /*Removes the struct*/
{
char substring [MAX_LINE_LENGTH];
strtok(input , " \n");
strcpy(substring , strtok (NULL , " \n")); /*the substring is the substring to be checked*/
printf("%s\n" , substring);
int j;
int k;
for (j = 0 ; j < no_of_classes ; j++) /*substring is checked for all fields of each class below*/
{
if ((strstr(classes[j] -> department , substring) != NULL) || (strstr(classes[j] -> number , substring) != NULL))
{
free(classes[j]);
for(k = j ; k < no_of_classes - 1; k++)
{
classes[k] = classes[k + 1]; /*Replacing the pointers*/
}
no_of_classes--; /*no_of_snippets decrease*/
if (j > 0)
{
--j;
}
}
}
}
break;
case 4: /*Writes the modified struct count and new Struct back to the file*/
{
if(no_of_classes != init_classes) /*There was a change in the number of classes*/
{
fseek(f, 0, SEEK_SET); /*Setting the pointer to begining of the file just to be sure*/
int i;
fprintf(f , "%d\n" , no_of_classes); /*If there is a change in the number of classes then writing to the file*/
for (i = 0; i < no_of_classes; i++)
{
fprintf(f , "%s:%s:%s\n" , classes[i] -> department , classes[i] -> number,
classes[i] -> location);
}
}
exit(0);
}
default: /*handles the case for wrong input*/
printf("Input mismatch with the prompt!! Try again.");
}
}
}
<file_sep>void display_prompt();
<file_sep>/*This module is responsible to get the input from the user*/
#include <stdio.h>
void display_prompt();
void display_prompt() /*gets a line from the user, stores it in array, and makes the entire line a string*/
{
printf("\n1.Type \"list\"to list all the structs\n2.Type \"add\" to add a struct\n");
printf("3.Type \"remove\" and a string to remove all the struct that contains the string as a substring\n");
printf("4.Type \"exit\" to terminate the program\n");
}
<file_sep>db : db.o readfile.o prompt.o
gcc -o db db.o readfile.o prompt.o
db.o : db.c readfile.h
gcc -c db.c
readfile.o : readfile.c prompt.h
gcc -c readfile.c
prompt.o : prompt.c
gcc -c prompt.c
all : db
clean :
rm -f db db.o readfile.o prompt.o
tarball : db db.c readfile.c readfile.h prompt.c prompt.h make
tar -c -f db.tar readfile.c readfile.h prompt.c prompt.h make makefile db db.c
|
01b50e0d46b5075d1d9829d6a3bb8a3f5f694109
|
[
"C",
"Makefile"
] | 6 |
C
|
ashimupd/Database-System
|
cb40d0cdc6247f67af7ae83153bc2447ed5920f1
|
3a85b1ac8d171d51f8e9618087fbd547cfa5cbbf
|
refs/heads/main
|
<file_sep>
export class Satellite {
name: string;
orbitType: string;
type: string;
operational: boolean;
launchDate: string;
constructor (name: string, type: string, launchDate: string, orbitType: string, operational: boolean)
{
this.name = name;
this.type = type;
this.launchDate = launchDate;
this.orbitType = orbitType;
this.operational = operational;
}
shouldShowWarning(): boolean {
return this.type.toLowerCase() === "space debris";
}
}
|
db85a05f2345da582f174cc0f9672135111771f3
|
[
"TypeScript"
] | 1 |
TypeScript
|
vn50a3v/Orbit-Report
|
e59dbcb8edda93ea859a9ef4a3b578e44f383af0
|
f8decc20561fc2f5f89bc30a6e58590d05a3b6c9
|
refs/heads/master
|
<file_sep>text="""Mary Noun Name
loves Verb No-Name
John Noun Name
. Punct No-Name
John Noun Name
loves Verb No-Name
Mary Noun Name
. Punct No-Name"""
from itertools import takewhile
sentences = []
split = iter(text.splitlines())
print split
while True:
sentence = list(takewhile(bool, split))
print "Hello"
print sentence
if not sentence:
break
types = set(el.split()[1] for el in sentence)
words = [el.split(' ', 1)[0] for el in sentence]
sentences.append(
{
'sentence': sentence,
'types': types,
'words': words
}
)
print sum(1 for el in sentences if 'Noun' in el['types']), 'sentences contain Noun'
print sentences[0]['words']
<file_sep>import csv
import sys
f = open(sys.argv[1], 'rt')
try:
csv_object = csv.reader(f)
text = []
XCoord = []
YCoord = []
for row in csv_object:
text.append(row[0])
XCoord.append(row[1])
YCoord.append(row[2])
finally:
f.close()
print len(text)
print len(XCoord)
print len(YCoord)
<file_sep>import sys
coord = (1.23, 4.56)
#The X an Y co-ordinates,(1.23,4.56) must yield strings โ1_4โ, โ12_45โ, โ123_456โ
def get_coord(coord):
coord_str = map(lambda x: str(x).replace('.', ''), coord)
for level in range(1, len(coord_str[0])+1):
yield reduce(lambda x, y: (x[:level]+'_'+y[:level]), coord_str)
print list(get_coord(coord))
<file_sep>import re
str = "<customer>1</customer>"
data = re.search('<([a-z])+>(.*)</\1>',str)
print data.group(1) + ": " + data.group(2)
<file_sep>import random
from geoindex import *
#create object of class GeoGridIndex
geo_index = GeoGridIndex(precision=2)
#Populate the geo_index with Latitudes and Longitudes Information
for _ in range(10000):
lat = random.random()*180 - 90
lng = random.random()*360 - 180
geo_index.add_point(GeoPoint(lat, lng))
#Center Point
center_point = GeoPoint(37.7772448, -122.3955118)
print geo_index.__dict__.keys()
for distance, point in geo_index.get_nearest_points(center_point, 10,'km'):
print("We found {0} in {1} km".format(point, distance))
<file_sep>import re
str = "Edureka"
m = re.match('(..)+',str)
print m.group(1)
print m.group(0)
<file_sep>import re
import string
def posting(corpus):
posting = []
tokens = tokenize(corpus)
for index, token in enumerate(tokens):
posting.append([token, (index+1)])
return posting
def posting_list(corpus):
posting_list = {}
tokens = tokenize(corpus)
for index, token in enumerate(tokens):
if token not in posting_list:
posting_list[token] = [(index + 1)]
else:
posting_list[token].append(index + 1)
return posting_list
def tokenize(corpus):
assert type(corpus) is str, 'Corpus must be a string of characters.'
# split
tokenized = corpus.split()
# normalize
for index, token in enumerate(tokenized):
tokenized[index] = re.sub('\W\Z', '', tokenized[index])
tokenized[index] = re.sub('\A\W', '', tokenized[index])
return tokenized
def readFile(fileName):
f = open(fileName,'r')
data = f.read()
return data
if __name__ == "__main__":
test_corpus = readFile("geo.csv")
posting_ = posting(test_corpus)
posting_list_ = posting_list(test_corpus)
print(posting_list_)
<file_sep># Spatial-Hashing
---
Encoding geo-locations as spatial-indices for simultaneous text and location searching
1. Read data from CSV
* Each row is article text (string), X coord (double), Y coord (double)
* Store rows as objects
2. Create mapping from words to articles
* Words are tokens from article text, as well as strings corresponding to location E.g., (1.23,4.56) yields strings โ1_4โ, โ12_45โ, โ123_456โ
* Use stop words, stemming rules (code for Porter stemmer is readily available)
* Mapping should be in the form of skip lists from words to list of articles (โposting listsโ)
3. Implement search engine: inputs is location and words
* Return articles that are near that location and contain those words
* Key computation: intersect posting lists
|
aaf09d92bb900115f4b73380d91b7d3fc8d053db
|
[
"Markdown",
"Python"
] | 8 |
Python
|
domarps/Spatial_Hashing
|
345db01e7c8a8cdbd8653b86f698742acef999e6
|
7d11eae66851bdcfabf3e025342e43668bd58117
|
refs/heads/master
|
<repo_name>Derek-zd/CI-demo<file_sep>/README.md
# cicd-demo
## ๅ่ฝๅฎ็ฐ
- [x] ๅบๅ`stage`, `prod`, `test`็ฏๅข
- [x] ่ชๅจๅ`CD` & `CI`
## ๆต้ๅๅๅพ
> ๅฆๆๅพไธ่ฝๆญฃๅธธๆพ็คบ, ๅฏไปฅๅฐๆฌ้กน็ฎ็ `resource`็ฎๅฝๆฅ็.

## ๆต้ๅๅฒๆ่ทฏ
่ฟ้ๆๅไบไธไธ็ๆๆฏ้ๅ:
- traefik(k8s ingress broker)
- istio(L7ๅฑๆต้ๅๅฒๆงๅถ)
> ไธ็ดๆฅ็จ istio-gateway-ingress ๆฏๅ ไธบๆๆฒก้ฑไนฐ `ELB VIP`. ๐ข
<file_sep>/Dockerfile
FROM golang
WORKDIR /go/src/app
COPY . .
CMD ["/go/src/app/cicd-demo"]
<file_sep>/main.go
package main
import (
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world 2\n \r"))
hostname := os.Getenv("HOSTNAME")
w.Write([]byte("HOSTNAME:" + hostname + "\r \n"))
cookies, err := r.Cookie("env")
if err != nil {
// emm ๆฒก่ฎพ็ฝฎcookies ้ฃๅฐฑ ่ฏปdev confๅง
config, err := ioutil.ReadFile("./configs/dev.json") // just pass the file name
if err != nil {
w.Write([]byte("\n \r"))
w.Write([]byte(err.Error()))
}
w.Write(config)
return
}
cookiesEnv := cookies.Value
config, err := loadConfig(cookiesEnv)
if err != nil {
w.Write([]byte("\n \r"))
w.Write([]byte(err.Error()))
return
}
w.Write([]byte("\n \r"))
w.Write(config)
})
log.Println("run at :8801")
http.ListenAndServe(":8801", nil)
}
func loadConfig(cookiesEnv string) ([]byte, error) {
var path string
switch cookiesEnv {
case "test":
path = "./configs/test.json"
case "prod":
path = "./configs/prod.json"
case "stage":
path = "./configs/stage.json"
default:
path = "./configs/dev.json"
}
b, err := ioutil.ReadFile(path) // just pass the file name
if err != nil {
return nil, err
}
return b, nil
}
<file_sep>/Makefile
#!/bin/bash
build-dev:
docker build . -f DockerfileDev -t motecshine:dev
run-dev:
docker run -p 8801:8801 motecshine:dev
|
c9c3aa73a9f27d9628ac3ac2a5023fe3aa042887
|
[
"Markdown",
"Go",
"Dockerfile",
"Makefile"
] | 4 |
Markdown
|
Derek-zd/CI-demo
|
c766e5c7379ebcb7cc75d24e5bda8f902d169726
|
0567fba7c7bdafdf67a2140e99c6198e4fb15498
|
refs/heads/master
|
<repo_name>timothee-florian/test<file_sep>/final/implementations.py
import numpy as np
from functions import *
from proj1_helpers import *
def least_squares_GD(y, x, initial_w, max_iters, gamma):
"""Gradient descent algorithm."""
w = initial_w
for n_iter in range(max_iters):
dw = compute_gradient_mse(y, x, w)
w = w - gamma * dw
loss = compute_error(y, x, w, 'mse')
return w, loss
def least_squares_SGD(y, x, initial_w, max_iters, gamma):
"""Stochastic gradient descent."""
# Define parameters to store w and loss
w = initial_w
for n_iter in range(max_iters):
for y_batch, tx_batch in batch_iter(y, x, batch_size=1, num_batches=1):
# compute a stochastic gradient and loss
dw = compute_gradient_mse(y_batch, tx_batch, w)
# update w through the stochastic gradient update
w = w - gamma * dw
# calculate loss
loss = compute_error(y, x, w, 'mse')
return w, loss
def least_squares(y, x):
"""calculate the least squares solution"""
a = x.T.dot(tx)
b = x.T.dot(y)
w = np.linalg.solve(a, b)
loss = compute_error(y, x, w, 'mse')
return w , loss
def ridge_regression(y, x, lambda_):
"""implement ridge regression."""
aI = 2 * x.shape[0] * lambda_ * np.identity(x.shape[1])
a = x.T.dot(x) + aI
b = x.T.dot(y)
w = np.linalg.solve(a, b)
loss = compute_error(y, x, w, 'mse')
return w , loss
def logistic_regression(y, x, initial_w, max_iters, gamma):
"""Gradient descent algorithm."""
w = initial_w
for n_iter in range(max_iters):
dw = grad_logistic(y, x, w, lambda_1=0, lambda_2=0)
w = w - gamma * dw
loss = compute_logi_loss(y, x, w)
return w, loss
def reg_logistic_regression(y, x, lambda_, initial_w, max_iters, gamma):
"""Gradient descent algorithm."""
w = initial_w
for n_iter in range(max_iters):
dw = grad_logistic(y, x, w, lambda_1=0, lambda_2=lambda_)
w = w - gamma * dw
loss = compute_logi_loss(y, x, w)
return w, loss
<file_sep>/final/notebooks/combinatory.py
import numpy as np
def combinationsUniques(items,n):
"return all unique combinations of n elements"
if n==0:
yield[]
else:
for i in range(len(items) - n+1):
for j in combinationsUniques(items[i+1:],n-1):
yield[items[i]]+j
def combinationsUnique(items):
"return all unique combination"
res = []
for n in range(1,len(items)+1):
res+=combinationsUniques(items,n)
return res <file_sep>/final/run.py
import numpy as np
import matplotlib.pyplot as plt
from proj1_helpers import *
from functions import *
from implementations import *
y, x, ids = load_csv_data('train.csv')
columns_to_keep = [0,1,2,3,4,5,6,10,11,12,13,22,24]
x1 = x[:, columns_to_keep]
y1=y
#remove -999 and put them close to the rest of the data
min_ = x1[x1!=-999].min()-1
x1[x1<=-998]= min_
# remove outliers
x1 = x1
y1 = y1
threshold = []
for i in range(x1.shape[1]):
# get value of each column of the 99 percentile
threshold += [np.percentile(x1[:,i], 99)]
for i in range(x1.shape[1]):
y1 = y1[x1[:,i]<=threshold[i]]
x1 = x1[x1[:,i]<=threshold[i]]
# print('{} % of the data was removed'.format(int(100*(1-len(x1)/len(x)))))
degree =12
x_train, x_test, y_train, y_test = split_data(x1, y1, ratio=0.8, seed =2)
x_train, mean_x, std_x= standardize(x_train)
x_test = (x_test-mean_x)/std_x
x_train = build_poly(x_train, degree=degree)
x_test = build_poly(x_test, degree=degree)
w, loss = ridge_regression(y_train, x_train, lambda_=10**-7)
y_p = predict_labels(w, x_test)
accuracy = np.mean(y_p == y_test)
error_tr = compute_error(y_train, x_train, w, 'mse')
error_te = compute_error(y_test, x_test, w, 'mse')
# print('Train error: {}, \ntest error: {},\naccuracy: {}'.format(error_tr, error_te, accuracy))
y_t, x_t, ids = load_csv_data('test.csv')
x_t1 = x_t[:,columns_to_keep]
x_t1[x_t1==-999]= min_
x_t2 = (x_t1-mean_x)/std_x
x_t2 = build_poly(x_t2, degree=degree)
y_p = predict_labels(w, x_t2)
create_csv_submission(ids, y_p, 'prediction_ridge_regression.csv')<file_sep>/final/notebooks/functions.py
import numpy as np
from plots import cross_validation_visualization
from proj1_helpers import *
#functions
def standardize(x):
"""Standardize the original data set."""
mean_x = np.mean(x, axis=0)
x = x - mean_x
std_x = np.std(x, axis=0)
x = x / std_x
return x, mean_x, std_x
def build_poly(x, degree):
"""polynomial basis functions for input data x, for j=0 up to j=degree."""
poly = np.ones((len(x), 1))
for deg in range(1, degree+1):
poly = np.c_[poly, np.power(x, deg)]
return poly
def sigmoid(x):
return 1/(1+np.exp(-x))
def compute_mse(e):
"""Calculate the mse for vector e."""
return 1/2*np.mean(e**2)
def compute_gradient_mse(y, x, w):
"""Compute the mse gradient."""
N= x.shape[0]
e = y - np.matmul(x, w)
return -1 * np.dot(x.T, e) /N
def compute_mae(e):
"""Calculate the mae for vector e."""
return np.mean(np.abs(e))
def compute_logi_loss(y, x, w):
"""Compute the logistic loss of"""
y_t = sigmoid(x.dot(w))
N= len(y)
loss1 = y.T.dot(np.log(y_t+10**-18))
loss2 = (1- y).T.dot(np.log(1-y_t+10**-18))
return -1/N*(loss1+loss2)
def compute_error(y, x, w, error):
if error == 'mse':
e = y - x.dot(w)
return compute_mse(e)
elif error == 'mae':
e = y - x.dot(w)
return compute_mae(e)
def grad_logistic(y, x, w, lambda_1, lambda_2):
"""Compute de gradient for logistic regression with regularization L1 and L2"""
# N= x.shape[0]
z = sigmoid(x.dot(w))
return x.T.dot(z-y) + np.sign(w) * lambda_1 + w * lambda_2
# def least_squares(y, tx):
# """calculate the least squares solution"""
# a = tx.T.dot(tx)
# b = tx.T.dot(y)
# w = np.linalg.solve(a, b)
# return w
def ridge_regression_solu(y, x, lambda_):
"""implement ridge regression."""
aI = 2 * x.shape[0] * lambda_ * np.identity(x.shape[1])
a = x.T.dot(x) + aI
b = x.T.dot(y)
return np.linalg.solve(a, b)
def split_data(x, y, ratio, seed=1):
"""split the dataset based on the split ratio."""
# set seed
np.random.seed(seed)
# generate random indices
num_row = len(y)
indices = np.random.permutation(num_row)
index_split = int(np.floor(ratio * num_row))
index_tr = indices[: index_split]
index_te = indices[index_split:]
# create split
x_tr = x[index_tr]
x_te = x[index_te]
y_tr = y[index_tr]
y_te = y[index_te]
if len(x_tr.shape)<2:
return x_tr.reshape(-1,1), x_te.reshape(-1,1), y_tr.reshape(-1,1), y_te.reshape(-1,1)
return x_tr, x_te, y_tr.reshape(-1,1), y_te.reshape(-1,1)
def gradient_descent(y, x, initial_w, max_iters, gamma, lambda_1, lambda_2,\
compute_gradient, compute_loss):
"""Gradient descent algorithm."""
w = initial_w
for n_iter in range(max_iters):
dw = compute_gradient(y, x, w, lambda_1, lambda_2)
w = w - gamma * dw
loss = compute_loss(y, x, w)
return w, loss
def stochastic_gradient_descent(y, x, initial_w, batch_size, max_iters, gamma,\
lambda_1, lambda_2, compute_gradient, compute_loss, return_last=True):
"""Stochastic gradient descent."""
# Define parameters to store w and loss
ws = [initial_w]
losses = []
w = initial_w
for n_iter in range(max_iters):
for y_batch, tx_batch in batch_iter(y, x, batch_size=batch_size, num_batches=1):
# compute a stochastic gradient and loss
dw = compute_gradient(y_batch, tx_batch, w, lambda_1, lambda_2)
# update w through the stochastic gradient update
w = w - gamma * dw
# calculate loss
loss = compute_loss(y, x, w)
# store w and loss
ws.append(w)
losses.append(loss)
#uncomment to see the loss progression
# print("SGD({bi}/{ti}): loss={l}".format(bi=n_iter, ti=max_iters - 1, l=loss))
if return_last:
return ws[-1] , losses[-1]
return ws, losses
def build_k_indices(y, k_fold, seed):
"""build k indices for k-fold."""
num_row = y.shape[0]
interval = int(num_row / k_fold)
np.random.seed(seed)
indices = np.random.permutation(num_row)
k_indices = [indices[k * interval: (k + 1) * interval]
for k in range(k_fold)]
return np.array(k_indices)
def cross_validation(y, x, k_indices, k, lambda_, degree, regression):
"""return the loss of ridge regression or logistic regression"""
# ***************************************************
# select training and testing sets
y_test = y[k_indices[k]].reshape(-1,1)
x_test =x[k_indices[k]]
k_indices=np.delete(k_indices, k)
y_train = y[k_indices].reshape(-1,1)
x_train =x[k_indices]
# ***************************************************
# standardize the set
x_train, mean_x, std_x= standardize(x_train)
x_test = (x_test-mean_x)/std_x
x_train = build_poly(x_train, degree)
x_test = build_poly(x_test, degree)
# ***************************************************
# train the chosen model
print(y_train.shape)
print(regression)
if regression == 'ridge_regression':
w = ridge_regression_solu(y_train, x_train, lambda_)
# compute and return the losses
loss_tr = compute_error(y_train, x_train, w, 'mse')
loss_te = compute_error(y_test, x_test, w, 'mse')
else:
print(y_train.shape)
y_train[y_train<0]=0
y_test[y_test<0]=0
w_initial = np.zeros(x_train.shape[1],1)
w, loss = gradient_descent(y_train, x_train, w_initial, max_iters= 200, gamma=0.001, lambda_1=0,
lambda_2=lambda_, compute_gradient=grad_logistic, compute_loss = compute_logi_loss)
# compute and return the losses
loss_tr = compute_logi_loss(y_train, x_train, w)
loss_te = compute_logi_loss(y_test, x_test, w)
return loss_tr, loss_te
def cross_validation_accross_lambdas(x, y, regression, degree = 3, k_fold = 4, lambdas = np.logspace(-5, 3, 8)):
seed = 2
# split data in k fold
k_indices = build_k_indices(y, k_fold, seed)
# define lists to store the loss of training data and test data
mean_losses_tr = []
mean_losses_te = []
# ***************************************************
for lambda_ in lambdas:
loss_train = 0
loss_test = 0
for k in range(k_fold):
loss_tr, loss_te = cross_validation(y, x, k_indices, k, lambda_, degree, regression)
loss_train += loss_tr
loss_test += loss_te
#append the losses
mean_losses_tr += [loss_train/k_fold]
mean_losses_te += [loss_test/k_fold]
# ***************************************************
cross_validation_visualization(xs=lambdas, mse_tr= mean_losses_tr, mse_te=mean_losses_te, x_name='lambda')
return mean_losses_tr, mean_losses_te
def cross_validation_accross_degrees(x, y, regression, degrees = range(1,10), k_fold = 4, lambda_ = 0):
seed = 2
# split data in k fold
k_indices = build_k_indices(y, k_fold, seed)
# define lists to store the loss of training data and test data
mean_losses_tr = []
mean_losses_te = []
# ***************************************************
for degree in degrees:
loss_train = 0
loss_test = 0
for k in range(k_fold):
loss_tr, loss_te = cross_validation(y, x, k_indices, k, lambda_, degree, regression)
loss_train += loss_tr
loss_test += loss_te
#append the losses with the mean error
mean_losses_tr += [loss_train/k_fold]
mean_losses_te += [loss_test/k_fold]
# ***************************************************
cross_validation_visualization(xs=degrees, mse_tr= mean_losses_tr, mse_te=mean_losses_te, x_name='degree', xscale='lin')
return mean_losses_tr, mean_losses_te<file_sep>/final/README.md
# Identification of physical particles from a dataset
The aim of the code provided is to create a model based on a train set of physical particles and their parameters in order to differentiate Higgs Boson in a test set.
## Sections
### Helper for the project
Name : proj1_helpers.py
This section help with the basic work for exploiting the data (reading the data, writing new data,...).
#### Methods
- load_csv_data(data_path, sub_sample=False) : Load the data from a csv file and have 3 returns : one column containing 1 for an Higgs boson and -1 for the background, a numpy array of 30 columns with a value for each parameters and the indexes.
data_path : the path where the data is stored
sub_sample=True : create a sub sample of size one fifth of the original data, taking data every five rows
-predict_labels(weights, data) : One column of predictions is calculated (1 and -1).
weights : weight coefficients of the model chosen
data : numpy array containing values for differents parameters
-create_csv_submission(ids, y_pred, name) : Create a csv file containing the index and the prediction.
ids : index of the prediction
y_pred : prediction containing 1 or -1 values
name : name of the csv created
### Functions
Name : functions.py
This section gives all the building blocks that is needed for running the implementation methods along with the cross validation techniques. Furthermore, it calculates the loss of the prediction evaluated.
### Implementation
Name : implementations.py
This section contains all the important method used to give a good prediction while always returning the weights coefficients of the chosen model and the loss between the real value and the predicted one. These methods will help a lot to enhance the results that we have.
### Polynomial regression
Name : functions_for_polynomial.py
This section gives all the methods to make polynome regression using different techniques. Calculation of the degree with minimal error for each of the column and testing with different columns and differents degree to take the best combination.
### Plotting
Name : plot.py
This section gives a plot of the loss in function of either the number of degree for the polynomial regression or the hyperparameter lambda for the ridge regression.
## Notebook
### Combinatory
Name : combinatory.py
### Evaluation of the prediction
Name : evaluation_function.py
This section help to have a better understanding of the prediction not just the result in percent but as well for the quantity of 1 and -1 and the false positive and negative.
<file_sep>/final/notebooks/functions_for_polynomial.py
import numpy as np
from functions import *
from combinatory import *
from evaluation_function import *
from proj1_helpers import *
import matplotlib.pyplot as plt
def build_indices_ratio(y, ratio, seed):
"""build indices for splitting the original train sample"""
nb_row = y.shape[0]
np.random.seed(seed)
indices = np.random.permutation(nb_row)
nb_split = int(nb_row*ratio)
ind_train = indices[nb_split:]
ind_test = indices[:nb_split]
return ind_train, ind_test
def polynomial_regressions(poly,y):
# least squares applied to polynom
w = ridge_regression(y,poly, 0)
return w
def build_poly(x, degree):
"""polynomial basis functions for input data x, for j=0 up to j=degree"""
poly = np.ones((len(x), 1))
for deg in range(1, degree+1):
poly = np.c_[poly, np.power(x, deg)]
return poly
def compute_losses_pos_neg(y, tx, w):
"""Calculate the loss MSE separately for bosons and the other particles"""
e = y - np.dot(tx, w)
e_pos = e[y>0]
e_neg = e[y<0]
pos= len(e_pos)
neg= len(e_neg)
return np.sum(e_pos * e_pos)/ (2 * pos),np.sum(e_neg * e_neg)/ (2 *neg)
def bias_variance_demo_poly(x_c,label,ratio,degrees):
"""Bias variance decomposition, for the values of a given feature we want to
to find the polynom (until degree 20) that allows to get the best prediction"""
# define parameters
seeds = range(10)
adapted_degree=[]
# define list to store the variable
rmse_tr = np.empty((len(seeds), len(degrees)))
rmse_te = np.empty((len(seeds), len(degrees)))
for index_seed, seed in enumerate(seeds):
ind_train, ind_test = build_indices_ratio(label, ratio, seed)
y_train = label[ind_train].reshape(-1,1)
x_train =x_c[ind_train]
y_test = label[ind_test].reshape(-1,1)
x_test =x_c[ind_test]
rmse_tr_p =[]
rmse_tr_n =[]
rmse_te_p =[]
rmse_te_n =[]
for index_degree, degree in enumerate(degrees):
poly_train = build_poly(x_train, degree)
poly_test = build_poly(x_test, degree)
w= polynomial_regressions(poly_train,y_train)
loss_tr_p, loss_tr_neg = compute_losses_pos_neg(y_train, poly_train, w)
loss_te_p,loss_te_neg = compute_losses_pos_neg(y_test, poly_test, w)
rmse_tr_p.append(loss_tr_p)
rmse_tr_n.append(loss_tr_neg)
rmse_te_p.append(loss_te_p)
rmse_te_n.append(loss_te_neg)
rmse_tr_p=normalize_vect(rmse_tr_p)
rmse_tr_n=normalize_vect(rmse_tr_n)
rmse_te_p=normalize_vect(rmse_te_p)
rmse_te_n=normalize_vect(rmse_te_n)
rmse_tr_f = sum_vector(rmse_tr_p,rmse_tr_n)
rmse_te_f = sum_vector(rmse_te_p,rmse_te_n)
for j in range (0,len(rmse_tr_p)):
rmse_tr[index_seed,j] = rmse_tr_f[j]
rmse_te[index_seed,j] = rmse_te_f[j]
return rmse_tr,rmse_te
def bias_variance_decomposition_visualization(degrees, rmse_tr, rmse_te):
"""visualize the bias variance decomposition."""
rmse_tr_mean = np.expand_dims(np.mean(rmse_tr, axis=0), axis=0)
rmse_te_mean = np.expand_dims(np.mean(rmse_te, axis=0), axis=0)
plt.plot(
degrees,
rmse_tr.T,
'b',
linestyle="-",
color=([0.7, 0.7, 1]),
label='train',
linewidth=0.3)
plt.plot(
degrees,
rmse_te.T,
'r',
linestyle="-",
color=[1, 0.7, 0.7],
label='test',
linewidth=0.3)
plt.plot(
degrees,
rmse_tr_mean.T,
'b',
linestyle="-",
label='train',
linewidth=3)
plt.plot(
degrees,
rmse_te_mean.T,
'r',
linestyle="-",
label='test',
linewidth=3)
plt.xlabel("degree")
plt.ylabel("error")
plt.title("Bias-Variance Decomposition")
plt.savefig("bias_variance")
def normalize_vect(a):
"normalize a vector with the max"
maxi = max(a)
for i in range (0,len(a)):
a[i]=a[i]/maxi
return a
def sum_vector(a,b):
"sum and averages two vectors termby term"
c=[]
for i in range (0,len(a)):
c.append(a[i]+b[i]/2)
return c
def best_degree_of_polynom(rmse_tr,rmse_te,degrees):
"""after the biased variance decomposition, this function do the average of the errors for the train and the test
and it returns the degree for which the test error is minimised"""
rmse_tr_mean = np.expand_dims(np.mean(rmse_tr, axis=0), axis=0)
rmse_te_mean = np.expand_dims(np.mean(rmse_te, axis=0), axis=0)
list_rmse_tr_mean=rmse_tr_mean.tolist()
list_rmse_te_mean=rmse_te_mean.tolist()
return degrees[list_rmse_te_mean[0].index(min(list_rmse_te_mean[0]))]
def release_best_degree_by_feature(x,y,ratio,degrees):
"return the list of degree of polynom that allows the best polynomial regression for all the 30 fetaures"
adapted_degree=[]
for j in range (0,30):
rmse_tr,rmse_te = bias_variance_demo_poly(x[:,j],y,ratio,degrees)
best_degree=best_degree_of_polynom(rmse_tr,rmse_te,degrees)
adapted_degree.append(best_degree)
print("for feature: ",j,"the best degree is:,",best_degree)
return adapted_degree
def poly_regression_with_adapted_degree(x,y,num,adapted_degree,ratio):
"""returns the predictions for the feature applied in argument (num=[0,1], means we want to test features 0 and 1).
polynomial regresion is applied on these features with the best degree for each feature, this degree was determined
with the function release_best_degree_by_feature
"""
les_pred = []
seed =1
ind_train, ind_test = build_indices_ratio(y, ratio, seed)
y_train = y[ind_train]
x_train =x[ind_train]
y_test = y[ind_test]
x_test =x[ind_test]
for i in num:
poly_train = build_poly(x_train[:,i], adapted_degree[i])
w= polynomial_regressions(poly_train,y_train)
poly_test = build_poly(x_test[:,i], adapted_degree[i])
y_pred = predict_labels(w, poly_test)
les_pred.append(y_pred)
return les_pred,y_test
def final_poly_regression_with_adapted_degree(x,y,test,num,adapted_degree):
"""returns the predictions for the feature applied in argument (num=[0,1], means we want to test features 0 and 1).
polynomial regresion is applied on these features with the best degree for each feature, this degree was determined
with the function release_best_degree_by_feature
"""
les_pred = []
for i in num:
poly = build_poly(x[:,i], adapted_degree[i])
w= polynomial_regressions(poly,y)
poly_test = build_poly(test[:,i], adapted_degree[i])
y_pred = predict_labels(w, poly_test)
les_pred.append(y_pred)
return les_pred
def evaluation_all_polynomial_regression(x,y,adapted_degree):
ratio =0.7
the_best_feature=[]
print("feature",",","Boson (-1)",",","Others (+1)",",","Global evaluation")
for j in range (0,30):
num =[j]
les_pred,y_test = poly_regression_with_adapted_degree(x,y,num,adapted_degree,ratio)
prediction=les_pred[0]
neg=evaluation_neg(prediction,y_test)
pos =pos=evaluation_pos(prediction,y_test)
print("feature",j,",",neg,",",pos,",",evaluation_glob(prediction,y_test))
if (pos>0.3):
the_best_feature.append(j)
return the_best_feature
def test_combinations(the_best_features,x,y,adapted_degrees):
"""tests all combinations of three elements for features that gave the best result for polynomial regression
and returns the best combination"""
list_combi =combinationsUniques(the_best_features,3)
best_result=0
best_combi=[]
for num in list_combi:
ratio=0.7
les_pred,y_test =poly_regression_with_adapted_degree(x,y,num,adapted_degrees,ratio)
final=evaluate_the_predictions_moins(les_pred)
print(num)
print(evaluation(final,y_test))
glob=evaluation_glob(final,y_test)
print(glob)
if (glob>best_result):
best_result=glob
best_combi=num
return best_combi
def final_prediction(x,y,test,best_combi,list_degrees):
les_pred=final_poly_regression_with_adapted_degree(x,y,test,best_combi,list_degrees)
final=evaluate_the_predictions_moins(les_pred)
return final
<file_sep>/final/notebooks/evaluation_function.py
import numpy as np
def evaluation_glob(final,y_te):
""""gives the proportion of correct predictions"""
sum=0
for j in range (0, len(final)):
if (y_te[j]==final[j]):
sum =sum +1
return (sum/(len(y_te)))
def evaluation(final,y_te):
""""evaluation of the proportion of boson (-) that are predicted as boson(-1) and other particles (+1)
that are predicted as other particles"""
real_pos =0
real_neg =0
pos=0
neg=0
for j in range (0, len(final)):
if (y_te[j]==1):
real_pos = real_pos + 1
if (y_te[j]==final[j]):
pos = pos +1
else:
real_neg = real_neg + 1
if (y_te[j]==final[j]):
neg = neg +1
return (pos/real_pos, neg/real_neg)
def evaluation_pos(final,y_te):
""""evaluation of the proportion of bosons (-1)
that are predicted as bosons"""
real_pos =0
real_neg =0
pos=0
neg=0
for j in range (0, len(final)):
if (y_te[j]==1):
real_pos = real_pos + 1
if (y_te[j]==final[j]):
pos = pos +1
else:
real_neg = real_neg + 1
if (y_te[j]==final[j]):
neg = neg +1
return pos/real_pos
def evaluation_neg(final,y_te):
""""evaluation of the proportion of bosons (-1)
that are predicted as bosons"""
real_pos =0
real_neg =0
pos=0
neg=0
for j in range (0, len(final)):
if (y_te[j]==1):
real_pos = real_pos + 1
if (y_te[j]==final[j]):
pos = pos +1
else:
real_neg = real_neg + 1
if (y_te[j]==final[j]):
neg = neg +1
return neg/real_neg
def evaluate_the_predictions_moins(les_pred):
"""for 3 results of prediction from polynomial regression, this function return the most dominant prediction"""
final = []
for i in range (0,len(les_pred[0])):
pos = 0
neg = 0
for vect in les_pred:
if(vect[i]==-1):
neg = neg + 1
else:
pos = pos + 1
if(pos>1):
final.append(1)
else:
final.append(-1)
return final
|
393d68e5d8a7cf27ca15811509c2f1471bb4a5fa
|
[
"Markdown",
"Python"
] | 7 |
Python
|
timothee-florian/test
|
cac0c1c36386c1a16fe477a02d688fcf51b81d4f
|
b9f28baa79cd743904527aed3dcb1da3881dd816
|
refs/heads/master
|
<file_sep># Works, but there is a bug in which it says "aesthetic :Unknown command" but prints the text regardless. /shrug
# Licensed under the Copyfree Open Innovation License, which can be found in the next comment.
# http://copyfree.org/content/standard/licenses/coli/license.txt
import hexchat
__module_name__ = 'aesthetic'
__module_author__ = 'Breadinator'
__module_version__ = '0.1'
__module_description__ = 'Make your text more a e s t h e t i c'
def strToAesthetic(word, word_eol, userdata):
ugly = word_eol[1]
aesthetic = ""
for n, i in enumerate(ugly):
if n == len(ugly) - 1:
aesthetic += str(i).lower() + " "
else:
aesthetic += str(i).lower() + " "
hexchat.command("say " + aesthetic)
hexchat.hook_command('aesthetic', strToAesthetic, help="/aesthetic <string>")
hexchat.prnt(__module_name__ + " by " + __module_author__ + " loaded.")<file_sep># Licensed under the Copyfree Open Innovation License, which can be found in the next comment.
# http://copyfree.org/content/standard/licenses/coli/license.txt
# (Doesn't really need a license, but #YOLO am i rite?)
import sys
def strToAesthetic(ugly): #pass in a string
aesthetic = ""
for n, i in enumerate(ugly):
if n == len(ugly) - 1:
aesthetic += str(i).lower() + " "
else:
aesthetic += str(i).lower() + " "
return aesthetic
if __name__ == "__main__":
ret = ""
for n, i in enumerate(sys.argv):
if n == 0:
continue
ret += strToAesthetic(sys.argv[n])
print(ret)<file_sep># aesthetic
Turn text a e s t h e t i c with a single command! Works via terminal and hexchat.
## Usage
### Command line (linux)
python3 ./aesthetic.py <string to make a e s t h e t i c>
## Hexchat
Loading:
/load <file location>
Using:
/aesthetic <string to make a e s t h e t i c>
## Bugs
### Hexchat
It says the command is not found but performs it anyways.
|
faaadf74b0753af86049e2b4b9866e30d895bb87
|
[
"Markdown",
"Python"
] | 3 |
Python
|
Breadinator/aesthetic
|
b1bdf14451309cd1925f0602b80c6438df1038ab
|
17514e8eaa60f97511ec924273a7a4b79a2d0ce3
|
refs/heads/master
|
<repo_name>daisy-link/eccube2-sandbox<file_sep>/.env.example
# ใใผใฟใใผในๅ
DB_DATABASE=eccube
# ใใผใฟใใผในใในใฏใผใ
DB_PASSWORD=<PASSWORD>
# Webใตใผใใผ ๅค้จใใผใ (docker-compose)
WEB_PORT=80
# Webใตใผใใผ ใใฆใณใใขใผใ (docker-compose/Macใงใฏใณใกใณใใขใฆใใ่งฃ้ค)
#WEB_VOLUME_CONSISTENCY=cached
# xdebug.remote_host (docker-compose)
#XDEBUG_HOST=host.docker.internal
# xdebug.remote_port (docker-compose)
XDEBUG_PORT=9000
# Xdebug PHP_IDE_CONFIG (docker-compose)
PHP_IDE_CONFIG=serverName=localhost
<file_sep>/.docker/app/Dockerfile
FROM php:5.6-apache AS base
RUN set -x \
&& apt-get update \
&& apt-get install -y \
iproute2 \
sudo \
&& apt-get clean \
&& rm -rf /tmp/*
RUN \
apt-get update \
&& apt-get install -y \
libfreetype6-dev \
libjpeg-dev \
libmcrypt-dev \
libpng-dev \
libzip-dev \
&& docker-php-ext-configure gd \
--with-freetype-dir=/usr/include/ \
--with-jpeg-dir=/usr/include/ \
--with-png-dir=/usr/include/ \
&& docker-php-ext-install \
gd \
mcrypt \
mysql \
pdo_mysql \
zip
COPY ./base.ini /usr/local/etc/php/conf.d/base.ini
COPY ./entrypoint-base.sh /entrypoint-base.sh
ENTRYPOINT ["/entrypoint-base.sh"]
CMD ["apache2-foreground"]
FROM base AS dev
RUN \
pecl install xdebug-2.5.5 \
&& docker-php-ext-enable \
xdebug \
&& rm -rf /tmp/*
COPY ./dev.ini /usr/local/etc/php/conf.d/dev.ini
COPY ./entrypoint-dev.sh /entrypoint-dev.sh
ENTRYPOINT ["/entrypoint-dev.sh"]
CMD ["apache2-foreground"]
<file_sep>/docker-compose.yml
version: "3.4"
services:
app:
build:
context: ./.docker/app
target: dev
volumes:
- "./src:/var/www/html:${WEB_VOLUME_CONSISTENCY:-consistent}"
ports:
- "${WEB_PORT:-80}:80"
environment:
- HOST_UID
- HOST_GID
- XDEBUG_HOST
- "XDEBUG_PORT=${XDEBUG_PORT:-9000}"
db:
image: mysql:5.6
command: mysqld --character-set-server=utf8 --collation-server=utf8_unicode_ci
environment:
- "MYSQL_DATABASE=${DB_DATABASE}"
- "MYSQL_ROOT_PASSWORD=${DB_PASSWORD}"
ports:
- "${DB_PORT:-3306}:3306"
|
620ccf4376569861ef3fbfcfa5a9b3d637e3618d
|
[
"Dockerfile",
"YAML",
"Shell"
] | 3 |
Shell
|
daisy-link/eccube2-sandbox
|
b40942fc9ff4bc4def1710236d4053d81da33dbc
|
ec8b7841e5287cacaaff4cfb11f41b4b67f56ed5
|
refs/heads/master
|
<repo_name>leopaul29/spring-gallery<file_sep>/src/main/java/com/example/gallery/service/AlbumConsumerService.java
package com.example.gallery.service;
import com.example.gallery.data.Album;
import java.util.List;
public interface AlbumConsumerService {
List<Album> processAlbumDataFromAlbumArray();
Album processAlbumDataFromAlbum(Long id);
}
<file_sep>/README.md
# gallery
> In this project, I made a webapp to consume a gallery API (album and photos).
In this webapp we can
- [x] show a list of albums
- [x] show a single albums with multiple photos
- [x] show a signle photo
- [ ] import file photo
- [ ] manage cache settings
- [ ] test restclientapi
## Style
/* Color Theme Swatches in Hex */
.Illustration-1-hex { color: #F20587; }
.Illustration-2-hex { color: #F2059F; }
.Illustration-3-hex { color: #F22ED2; }
.Illustration-4-hex { color: #BF8360; }
.Illustration-5-hex { color: #F2F2F2; }
/* Color Theme Swatches in RGBA */
.Illustration-1-rgba { color: rgba(242, 4, 135, 1); }
.Illustration-2-rgba { color: rgba(242, 4, 159, 1); }
.Illustration-3-rgba { color: rgba(242, 46, 209, 1); }
.Illustration-4-rgba { color: rgba(191, 130, 95, 1); }
.Illustration-5-rgba { color: rgba(242, 242, 242, 1); }
/* Color Theme Swatches in HSLA */
.Illustration-1-hsla { color: hsla(326, 96, 48, 1); }
.Illustration-2-hsla { color: hsla(320, 96, 48, 1); }
.Illustration-3-hsla { color: hsla(309, 88, 56, 1); }
.Illustration-4-hsla { color: hsla(22, 42, 56, 1); }
.Illustration-5-hsla { color: hsla(0, 0, 95, 1); }
## Usefull link
- https://jsonplaceholder.typicode.com/albums
- https://jsonplaceholder.typicode.com/albums
- https://spring.io/guides/gs/consuming-rest/
- https://www.thymeleaf.org/documentation.html
- https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
- https://howtodoinjava.com/spring-boot2/resttemplate/spring-restful-client-resttemplate-example/
- https://www.baeldung.com/spring-resttemplate-json-list
- https://www.baeldung.com/rest-template
- https://fonts.google.com/specimen/Dancing+Script?preview.text_type=custom<file_sep>/src/main/java/com/example/gallery/data/Photo.java
package com.example.gallery.data;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Photo {
public Long albumId;
public Long id;
public String title;
public String url;
public String thumbnailUrl;
public Photo() {}
public Long getAlbumId() {
return albumId;
}
public void setAlbumId(Long albumId) {
this.albumId = albumId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
@Override
public String toString() {
return "Photo{" +
"albumId=" + albumId +
", id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
", thumbnailUrl='" + thumbnailUrl + '\'' +
'}';
}
}
<file_sep>/src/main/java/com/example/gallery/controller/HomeController.java
package com.example.gallery.controller;
import com.example.gallery.data.Album;
import com.example.gallery.data.Photo;
import com.example.gallery.service.AlbumConsumerService;
import com.example.gallery.service.AlbumConsumerServiceImpl;
import com.example.gallery.service.PhotoConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@Controller
public class HomeController {
private static final Logger log = LoggerFactory.getLogger(HomeController.class);
@Autowired
private AlbumConsumerService albumConsumerService;
@Autowired
private PhotoConsumerService photoConsumerService;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@RequestMapping(path = {"/", "/albums"})
public String home(Model model) {
List<Album> albumList = albumConsumerService.processAlbumDataFromAlbumArray();
model.addAttribute("albumList", albumList);
return "home";
}
@RequestMapping("/albums/{id}")
public String album(Model model, @PathVariable Long id) {
Album album = albumConsumerService.processAlbumDataFromAlbum(id);
model.addAttribute("album", album);
List<Photo> photos = photoConsumerService.processPhotoDataFromAlbum(id);
model.addAttribute("photos", photos);
return "album";
}
}
|
aaa64a830b20ba48f0f756c7bfb3b2a1f3ae2398
|
[
"Markdown",
"Java"
] | 4 |
Java
|
leopaul29/spring-gallery
|
50ba522a941b518e220728c69f89d08a6239812a
|
6eadf57d38fabe04b23919c6b6598f9d2204bb8f
|
refs/heads/main
|
<repo_name>Twf1421/SideWalk<file_sep>/SideWalk/src/com/chalk/sidewalk/Main.java
//Leo (')>
package com.chalk.sidewalk;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);// brings in our keyboard
System.out.println("Hello, User"); // hello, user
// creating students
Student tj = new Student("TJ LastName", 3.9, "Green Light", 5, "Present");
//tj.printStu();
Student leo = new Student("Leo LastName", 3.7, "Red Light", 2, "Absent");
//leo.printStu();
Student becca = new Student("Becca", 2.9, "Green Light", 1, "Present");
Student tim = new Student("Tim", 3.2, "Red Light", 3, "Absent");
Student victoria = new Student("Victoria", 3.8, "Yellow Light", 4, "Present");
Student ethan = new Student("Ethan", 3.0, "Green Light", 6, "Present");
//creating a roster
Roster newRos = new Roster("CSC331", 6);
newRos.addStu(tj);
/*newRos.addStuTo(leo, leo.getSeat());
newRos.addStuTo(becca, becca.getSeat());
newRos.addStuTo(tim, tim.getSeat());
newRos.addStuTo(victoria, victoria.getSeat());
newRos.addStuTo(ethan, ethan.getSeat());*/
Student temp = newRos.getStu(0);
temp.printStu();
/*for (int i = 0; i < newRos.size(); i++)
{
Student temp = newRos.getStu(i);
temp.printStu();
}*/
// changing student stuff and printing
/*leo.setName("<NAME>");
leo.setGpa(3.2);
leo.setBeh("Yellow Light");
leo.setSeat(6);
leo.setAtt("Present");
leo.printStu();*/
// making a custom student using kb. can prolly be done better
/*Student custom = new Student();
custom.createStu();
custom.printStu();*/
/* while(selectionMenu)
{
System.out.println("");
System.out.println("");
System.out.println("-----------------------------------------------------");
System.out.println("Please Enter the number of the option you would like!");
System.out.println("-----------------------------------------------------");
System.out.println("1: Under Construction");
System.out.println("2: Under Construction");
System.out.println("3: Under Construction");
System.out.println("4: Add another Student");
System.out.println("5: Exit Program");
System.out.println("-----------------------------------------------------");
teacherChoice = keyboard.nextInt() - 1;
switch(teacherChoice)
{
case 0:
System.out.println("Please Enter a Different Option");
break;
case 1:
System.out.println("Please Enter a Different Option");
break;
case 2:
System.out.println("Please Enter a Different Option");
break;
case 3: //Creates a new student
Student custom = new Student();
custom.createStu();
custom.printStu();
break;
case 4: //Closes the Application
selectionMenu = false;
break;
default:
System.out.println("Please Enter a Different Option");
break;
}
}*/
}
}
|
6176ce3b43a9f681e4858a7d9e4a6ac0a31826cd
|
[
"Java"
] | 1 |
Java
|
Twf1421/SideWalk
|
e5590f600049c6788bde41639a411528a072de92
|
61589d1b8e6c6aa3727e5d8bb8fb7d81de9ddf44
|
refs/heads/master
|
<file_sep>'use strict'
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
const port = process.env.port || process.env.npm_config_port || 80 // ็ซฏๅฃ
// vue.config.js ้
็ฝฎ่ฏดๆ
//ๅฎๆนvue.config.js ๅ่ๆๆกฃ https://cli.vuejs.org/zh/config/#css-loaderoptions
// ่ฟ้ๅชๅไธ้จๅ๏ผๅ
ทไฝ้
็ฝฎๅ่ๆๆกฃ
module.exports = {
// ้จ็ฝฒ็ไบง็ฏๅขๅๅผๅ็ฏๅขไธ็URLใ
// ้ป่ฎคๆ
ๅตไธ๏ผVue CLI ไผๅ่ฎพไฝ ็ๅบ็จๆฏ่ขซ้จ็ฝฒๅจไธไธชๅๅ็ๆ น่ทฏๅพไธ
// ไพๅฆ https://www.ruoyi.vip/ใๅฆๆๅบ็จ่ขซ้จ็ฝฒๅจไธไธชๅญ่ทฏๅพไธ๏ผไฝ ๅฐฑ้่ฆ็จ่ฟไธช้้กนๆๅฎ่ฟไธชๅญ่ทฏๅพใไพๅฆ๏ผๅฆๆไฝ ็ๅบ็จ่ขซ้จ็ฝฒๅจ https://www.ruoyi.vip/admin/๏ผๅ่ฎพ็ฝฎ baseUrl ไธบ /admin/ใ
publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
// ๅจnpm run build ๆ yarn build ๆถ ๏ผ็ๆๆไปถ็็ฎๅฝๅ็งฐ๏ผ่ฆๅbaseUrl็็ไบง็ฏๅข่ทฏๅพไธ่ด๏ผ๏ผ้ป่ฎคdist๏ผ
outputDir: 'dist',
// ็จไบๆพ็ฝฎ็ๆ็้ๆ่ตๆบ (jsใcssใimgใfonts) ็๏ผ๏ผ้กน็ฎๆๅ
ไนๅ๏ผ้ๆ่ตๆบไผๆพๅจ่ฟไธชๆไปถๅคนไธ๏ผ
assetsDir: 'static',
// ๆฏๅฆๅผๅฏeslintไฟๅญๆฃๆต๏ผๆๆๅผ๏ผture | false | 'error'
lintOnSave: process.env.NODE_ENV === 'development',
// ๅฆๆไฝ ไธ้่ฆ็ไบง็ฏๅข็ source map๏ผๅฏไปฅๅฐๅ
ถ่ฎพ็ฝฎไธบ false ไปฅๅ ้็ไบง็ฏๅขๆๅปบใ
productionSourceMap: false,
// webpack-dev-server ็ธๅ
ณ้
็ฝฎ
devServer: {
host: '0.0.0.0',
port: port,
open: true,
proxy: {
'/api': {
target: `http://ysyz.xczxb.com`,
changeOrigin: true,
pathRewrite: {
'^/api' : '/api'
}
}
},
},
configureWebpack: {
resolve: {
alias: {
'@': resolve('src')
}
}
},
css: {
loaderOptions: {
postcss: {
plugins: [
require("postcss-px-to-viewport")({
unitToConvert: "px", //้่ฆ่ฝฌๆข็ๅไฝ๏ผ้ป่ฎคไธบ"px"
viewportWidth: 750, // ่ง็ช็ๅฎฝๅบฆ๏ผๅฏนๅบ็ๆฏๆไปฌ่ฎพ่ฎก็จฟ็ๅฎฝๅบฆ๏ผไธ่ฌๆฏ750
unitPrecision: 3, //ๅไฝ่ฝฌๆขๅไฟ็็็ฒพๅบฆ
propList: [ //่ฝ่ฝฌๅไธบvw็ๅฑๆงๅ่กจ
"*"
],
viewportUnit: "vw", // ๅธๆไฝฟ็จ็่งๅฃๅไฝ
fontViewportUnit: "vw", //ๅญไฝไฝฟ็จ็่งๅฃๅไฝ
selectorBlackList: ['van'], //้่ฆๅฟฝ็ฅ็CSS้ๆฉๅจ๏ผไธไผ่ฝฌไธบ่งๅฃๅไฝ๏ผไฝฟ็จๅๆ็px็ญๅไฝใ
minPixelValue: 1, //่ฎพ็ฝฎๆๅฐ็่ฝฌๆขๆฐๅผ๏ผๅฆๆไธบ1็่ฏ๏ผๅชๆๅคงไบ1็ๅผไผ่ขซ่ฝฌๆข
mediaQuery: false, //ๅชไฝๆฅ่ฏข้็ๅไฝๆฏๅฆ้่ฆ่ฝฌๆขๅไฝ
replace: true, //ๆฏๅฆ็ดๆฅๆดๆขๅฑๆงๅผ๏ผ่ไธๆทปๅ ๅค็จๅฑๆง
exclude: /(\/|\\)(node_modules)(\/|\\)/, //ๅฟฝ็ฅๆไบๆไปถๅคนไธ็ๆไปถๆ็นๅฎๆไปถ๏ผไพๅฆ 'node_modules' ไธ็ๆไปถ
})
]
}
}
}
}
<file_sep>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
import { Button,Icon,Toast,Dialog} from 'vant';
Vue.use(Button).use(Icon).use(Toast).use(Dialog)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
|
72a7aedaf379ef82f2ff311601ff1a31a1b5c69b
|
[
"JavaScript"
] | 2 |
JavaScript
|
huangxiucai/VUECLI-H5
|
87741a4ac667552e0eb9fe64bc16acea3bcd1db8
|
224513be5caef7f6a7fb91cf0da9bf945d4f9290
|
refs/heads/main
|
<file_sep>import java.lang.reflect.*;
class private {
// private variables
private String name;
// private method
private void display() {
System.out.println("The name is " + name);
}
}
class Main {
public static void main(String[] args) {
try {
// create an object of Test
Test test = new Test();
// create an object of the class named Class
Class obj = test.getClass();
// access the private variable
Field field = obj.getDeclaredField("name");
// make private field accessible
field.setAccessible(true);
// set value of field
field.set(test, "Test");
// get value of field
// and convert it in string
String value = (String)field.get(test);
System.out.println("Name: " + value);
// access the private method
Method[] methods = obj.getDeclaredMethods();
System.out.println("Method Name: " + methods[0].getName());
int modifier = methods[0].getModifiers();
System.out.println("Access Modifier: " + Modifier.toString(modifier));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
/* Output:
Name: Test (because we set it as this. check line 30 to change it.)
Method Name: display
Access Modifier: private
*/
/*
Here, we have a private field named name and a private method named display().
We are using the reflection to access the private fields and methods of the class private.
View a Java Reflection article to learn more.
*/
|
77c0f9b0d0c5406c882a50afe708bf4857f1737f
|
[
"Java"
] | 1 |
Java
|
appliers/private.java
|
2b1a551bff1b34ee47a03777c828792556f57b4a
|
a74518282ec7c72495f1b63716ed5d7f4aefefb1
|
refs/heads/master
|
<file_sep>########################################################################
# Helper file for ExportTools
# This one handles global constants
########################################################################
# APP specific stuff
VERSION = ' V2.0.0.4'
APPNAME = 'ExportTools'
NAME = APPNAME + VERSION
DESCRIPTION = 'Export Plex libraries to csv-files or xlsx-files'
ART = 'art-default.jpg'
ICON = 'icon-default.png'
PREFIX = '/applications/ExportTools'
APPGUID = '7608cf36-742b-11e4-8b39-00af17210b2'
PLAYLIST = 'playlist.png'
DEFAULT = 'N/A'
# How many items we ask for each time, when accessing a section
CONTAINERSIZEMOVIES = 30
CONTAINERSIZETV = 20
CONTAINERSIZEEPISODES = 30
CONTAINERSIZEAUDIO = 10
CONTAINERSIZEPHOTO = 20
# For slow PMS HW, we might need to wait some time here
PMSTIMEOUT = Prefs['TimeOut']
|
ecd6ceb5e597895cdfaef9b6e3a61a97e4d6079c
|
[
"Python"
] | 1 |
Python
|
jayd2446/ExportTools.bundle
|
192a250c16f03e479183b99e72c4e9b765d02d98
|
4195905b363f345cf2d71c674dccdbd8323b149d
|
refs/heads/master
|
<file_sep>from gamestate import GameState
from actions import Action
import socket
import json
from datetime import datetime, timedelta
import warnings
import os
import random
import logging
import time
import sys
import config
class GameConnection:
socketpath = config.socketpath
crawl_socketpath = config.crawl_socketpath
#crawl_socketpath = '/home/dustin/crawl/crawl-ref/source/rcs/midca:test.sock'
def __init__(self):
self.crawl_socket = None
self.game_state = GameState()
self.msg_buffer = None
self.recent_msg_data_raw = None
self.recent_msg_data_decoded = None
self.num_times_to_try_pressing_enter_read_msg = 5
self.num_times_pressed_enter_read_msg = 0
@staticmethod
def json_encode(value):
return json.dumps(value).replace("</", "<\\/")
def connect(self):
try:
os.unlink(GameConnection.socketpath)
except OSError:
if os.path.exists(GameConnection.socketpath):
raise
if self.ready_to_connect():
primary = True
self.crawl_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.crawl_socket.settimeout(10)
self.crawl_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if (self.crawl_socket.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) < 2048):
self.crawl_socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
if (self.crawl_socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF) < 212992):
self.crawl_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 212992)
msg = GameConnection.json_encode({
"msg": "attach",
"primary": primary
})
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.crawl_socket.bind(GameConnection.socketpath)
self._send_message(msg)
self._read_msgs()
def ready_to_connect(self):
return os.path.exists(GameConnection.crawl_socketpath) and not os.path.exists(GameConnection.socketpath)
def close(self):
if self.crawl_socket:
print("Closing socket...")
self.crawl_socket.close()
# socketpathobj.close()
os.unlink(GameConnection.socketpath)
crawl_socket = None
def _send_message(self, data):
start = datetime.now()
try:
self.crawl_socket.sendto(data.encode('utf-8'), GameConnection.crawl_socketpath)
except socket.timeout:
# self.logger.warning("Game socket send timeout", exc_info=True)
print("ERROR: in send_message() - Game socket send timeout")
self.close()
return
end = datetime.now()
if end - start >= timedelta(seconds=1):
print("Slow socket send: " + str(end - start))
# self.logger.warning("Slow socket send: " + str(end - start))
def _control_input(self, c):
self._send_message(GameConnection.json_encode({'msg': 'key', 'keycode': ord(c) - ord('A') + 1}))
def _send_input(self, input_str):
for c in input_str:
self._send_message(GameConnection.json_encode({'msg': 'key', 'keycode': ord(c)}))
def _read_msg(self):
try:
self.recent_msg_data_raw = self.crawl_socket.recv(128 * 1024, socket.MSG_DONTWAIT)
self.num_times_pressed_enter_read_msg = 0
except socket.timeout:
# first try to send and receive 'r' since the game might just be waiting with lots of messages
if self.num_times_pressed_enter_read_msg <= self.num_times_to_try_pressing_enter_read_msg:
self.send_and_receive_str('\r')
self.num_times_pressed_enter_read_msg += 1
else:
print("ERROR: in read_msg() - Game socket send timeout")
self.close()
return ''
if isinstance(self.recent_msg_data_raw, bytes):
self.recent_msg_data_decoded = self.recent_msg_data_raw.decode("utf-8")
if self.msg_buffer is not None:
self.recent_msg_data_decoded = self.msg_buffer + self.recent_msg_data_decoded
if self.recent_msg_data_decoded[-1] != "\n":
# All messages from crawl end with \n.
# If this one doesn't, it's fragmented.
self.msg_buffer = self.recent_msg_data_decoded
else:
self.msg_buffer = None
return self.recent_msg_data_decoded
return ''
def _handle_msgs(self, msgs):
self.game_state.update(msgs)
def get_gamestate(self):
return self.game_state
def _read_msgs(self):
msgs = []
data = self._read_msg()
# TODO: This doesn't seem to be the correct way to determine the end of the messages
while "flush_messages" not in data:
if len(data) > 0 and not data.startswith("*"):
msgs.append(json.loads(data))
# game_state.update(msgs[-1])
elif data.startswith("*"):
server_msg = json.loads(data[1:])
# TODO: Handle server messages (client_path,flush_messages,dump,exit_reason)
data = self._read_msg()
self._handle_msgs(msgs)
return msgs
def _send_command(self, command):
self._send_message(GameConnection.json_encode(Action.get_execution_repr(command)))
def send_and_receive_dict(self, input_dict):
logging.debug("Sending {}".format(input_dict))
self._send_message(GameConnection.json_encode(input_dict))
msgs = self._read_msgs()
self._handle_msgs(msgs)
def send_and_receive_str(self, input_str):
logging.debug("Sending {}".format(input_str))
self._send_input(input_str)
msgs = self._read_msgs()
self._handle_msgs(msgs)
def send_and_receive_command(self, command, sleep_secs=0.05):
logging.debug("Sending {}".format(command.name))
self._send_command(command)
if sleep_secs > 0:
time.sleep(sleep_secs)
msgs = self._read_msgs()
self._handle_msgs(msgs)
<file_sep>from gamestate import GameState
from actions import Command, Action
import subprocess
import random
class Agent:
def __init__(self):
pass
def get_game_mode_setup_actions(self):
raise NotImplementedError()
def get_action(self, gamestate: GameState):
raise NotImplementedError()
class SimpleRandomAgent(Agent):
"""
Agent that takes random cardinal actions to move/attack.
"""
def do_sprint(self):
# select sprint and character build
return [{'msg': 'key', 'keycode': ord('a')},
{'msg': 'key', 'keycode': ord('b')},
{'msg': 'key', 'keycode': ord('h')},
{'msg': 'key', 'keycode': ord('b')}
]
def do_dungeon(self):
# select dungeon and character build
return [{'msg': 'key', 'keycode': ord('b')},
{'msg': 'key', 'keycode': ord('h')},
{'msg': 'key', 'keycode': ord('b')},
]
def get_game_mode_setup_actions(self):
return self.do_dungeon()
def get_action(self, gamestate):
simple_commands = [Command.MOVE_OR_ATTACK_N,
Command.MOVE_OR_ATTACK_S,
Command.MOVE_OR_ATTACK_E,
Command.MOVE_OR_ATTACK_W,
Command.MOVE_OR_ATTACK_NE,
Command.MOVE_OR_ATTACK_NW,
Command.MOVE_OR_ATTACK_SW,
Command.MOVE_OR_ATTACK_SE]
return random.choice(simple_commands)
class TestAllCommandsAgent(Agent):
"""
Agent that serves to test all commands are working. Cycles through commands in actions.Command enum.
"""
def __init__(self):
super().__init__()
self.next_command_id = 1
def do_dungeon(self):
# select dungeon and character build
return [{'msg': 'key', 'keycode': ord('b')},
{'msg': 'key', 'keycode': ord('h')},
{'msg': 'key', 'keycode': ord('b')},
]
def get_game_mode_setup_actions(self):
return self.do_dungeon()
def get_action(self, gamestate):
problematic_actions = [Command.REST_AND_LONG_WAIT, # some kind of message delay issue
Command.WAIT_1_TURN, # some kind of message delay issue
Command.FIND_ITEMS, # gets stuck on a prompt
]
try:
next_command = Command(self.next_command_id)
except IndexError:
self.next_command_id = 1
next_command = Command(self.next_command_id)
self.next_command_id += 1
# skip any known problematic actions for now
while next_command in problematic_actions:
next_command = self.get_action(gamestate)
return next_command
class FastDownwardPlanningAgent(Agent):
"""
Agent that uses fast downward to solve planning problems to explore a floor. Ignores monsters.
"""
pddl_domain_file = ""
def __init__(self):
super().__init__()
self.current_game_state = None
self.next_command_id = 1
self.plan_domain_filename = "models/fastdownwardplanningagent_domain.pddl"
self.plan_current_pddl_state_filename = "models/fdtempfiles/gamestate.pddl"
self.plan_result_filename = "models/fdtempfiles/dcss_plan.sas"
self.plan = []
def do_dungeon(self):
# select dungeon and character build
return [{'msg': 'key', 'keycode': ord('b')},
{'msg': 'key', 'keycode': ord('h')},
{'msg': 'key', 'keycode': ord('b')},
]
def get_game_mode_setup_actions(self):
return self.do_dungeon()
def get_random_nonvisited_nonwall_playerat_goal(self):
available_cells = []
cells_visited = 0
for cell in self.current_game_state.get_cell_map().get_xy_to_cells_dict().values():
if cell.has_player_visited:
cells_visited += 1
elif not cell.has_wall and not cell.has_player and not cell.has_statue and not cell.has_lava and not cell.has_plant and not cell.has_tree and cell.g:
#print("added {} as an available cell, it's g val is {}".format(cell.get_pddl_name(), cell.g))
available_cells.append(cell)
else:
pass
goal_cell = random.choice(available_cells)
print("Visited {} cells - Goal is now {}".format(cells_visited, goal_cell.get_pddl_name()))
return "(playerat {})".format(goal_cell.get_pddl_name())
def get_plan_from_fast_downward(self, goals):
# step 1: write state output so fastdownward can read it in
if self.current_game_state:
self.current_game_state.write_pddl_current_state_to_file(filename=self.plan_current_pddl_state_filename,
goals=goals)
else:
print("WARNING current game state is null when trying to call fast downward planner")
return
# step 2: run fastdownward
# fast_downward_process_call = ["./FastDownward/fast-downward.py",
# "--plan-file {}".format(self.plan_result_filename),
# "{}".format(self.plan_domain_filename),
# "{}".format(self.plan_current_pddl_state_filename),
# "--search \"astar(lmcut())\""]
fast_downward_process_call = [
"./FastDownward/fast-downward.py --plan-file {} {} {} --search \"astar(lmcut())\"".format(
self.plan_result_filename,
self.plan_domain_filename,
self.plan_current_pddl_state_filename), ]
#print("About to call fastdownward like:")
#print(str(fast_downward_process_call))
subprocess.run(fast_downward_process_call, shell=True, stdout=subprocess.DEVNULL)
# step 3: read in the resulting plan
plan = []
with open(self.plan_result_filename, 'r') as f:
for line in f.readlines():
line = line.strip()
if ';' not in line:
if line[0] == '(':
pddl_action_name = line.split()[0][1:]
command_name = pddl_action_name.upper()
plan.append(Command[command_name])
else:
# we have a comment, ignore
pass
#for ps in plan:
# print("Plan step: {}".format(ps))
self.plan = plan
def get_action(self, gamestate: GameState):
self.current_game_state = gamestate
if len(self.plan) == 0:
goals = [self.get_random_nonvisited_nonwall_playerat_goal()]
self.get_plan_from_fast_downward(goals=goals)
next_action = None
if len(self.plan) > 0:
next_action = self.plan.pop(0)
else:
print("warning - no plan!")
return next_action
<file_sep>socketpath = '/var/tmp/crawl_socket'
agent_name = 'aiagent'
crawl_socketpath = 'crawl/crawl-ref/source/rcs/'+agent_name+':test.sock'<file_sep># AI Wrapper for Dungeon Crawl Stone Soup

(Demo of an agent taking random actions to play DCSS in the terminal)
# About
**dcss-ai-wrapper** aims to create an API for Dungeon Crawl Stone Soup for Artificial Intelligence research. This effort started with the following paper:
*<NAME>., <NAME>., <NAME>., <NAME>. [Dungeon Crawl Stone Soup as an Evaluation Domain for Artificial Intelligence.](https://arxiv.org/pdf/1902.01769) Workshop on Games and Simulations for Artificial Intelligence. Thirty-Third AAAI Conference on Artificial Intelligence. Honolulu, Hawaii, USA. 2019.*
If you use this repository in your research, please cite the above paper.
If you'd like to contribute to the research effort aligned with this project, see [Research Effort](contribute/ResearchEffort.md)
# Development Community
Join the chat at https://gitter.im/dcss-ai-wrapper/community
# Installation
## Pre-requisites
This guide has been tested on Ubuntu 18.04 LTS and assumes you have the following installed:
- git | `sudo apt-get install git`
- python2 | `sudo apt-get install python2.7`
- pip2 | `sudo apt-get install python-pip`
- python3 | `sudo apt-get install python3.6`
- pip3 | `sudo apt-get install python3-pip`
- A variety of packages required by Dungeon Crawl Stone Soup
`sudo apt-get install build-essential libncursesw5-dev bison flex liblua5.1-0-dev libsqlite3-dev libz-dev pkg-config python-yaml libsdl2-image-dev libsdl2-mixer-dev libsdl2-dev libfreetype6-dev libpng-dev ttf-dejavu-core`
## Installing Dungeon Crawl Stone Soup
While this API is likely to work with the current dcss master branch, it has been tested with the 23.1 version, which
is the recommended version of crawl to use with this API. We recommend installing a local version of crawl inside this
project's folder.
1. Make sure you have cloned this repository (dcss-ai-wrapper)
2. Grab a copy of the 23.1 version of crawl, by cloning the repo and then resetting to the 23.1 version
`cd ~/dcss-ai-wrapper/` (assuming this is the directory where you cloned this project - dcss-ai-wrapper)
`git clone https://github.com/crawl/crawl.git`
`cd ~/dcss-ai-wrapper/crawl/`
`git reset --hard <PASSWORD>`
`git submodule update --init`
3. Compile crawl with the following flags
`cd ~/dcss-ai-wrapper/crawl/crawl-ref/source/`
`sudo make install prefix=/usr/local/ WEBTILES=y`
__Note for installing on Ubuntu 20.04:__
If you get an error saying "/usr/bin/env cannot find python", then one possible fix is to the do the following (but beware this may change the default python on your system)
`sudo ln --symbolic \usr\bin\python2.7 \usr\bin\python`
4. Check that the `crawl/crawl-ref/source/.rcs' folder exists, if not create it:
`mkdir crawl/crawl-ref/source/rcs`
# How to Run a simple agent in the terminal
1. Open a new terminal, cd into dcss-ai-wrapper/ and run:
First time running the following script may require: `chmod +x start_crawl_terminal_dungeon.sh`
`./start_crawl_terminal_dungeon.sh`
Note that nothing will happen until an agent connects.
The terminal that runs this command must be a minimum width, so try enlarging the terminal if it doesn't work and you are using a small monitor/screen. (Only try changing the width if the next step fails).
2. Open a new terminal, cd into dcss-ai-wrapper/ and run:
`python3 main.py`
3. You should now be able to watch the agent in the terminal as this script is running, as shown in the demo gif at the top of this readme.
# Run the fastdownward planning agent for simple goal exploration
1. Download and compile the [fastdownward planner](http://www.fast-downward.org/ObtainingAndRunningFastDownward) and put it in a folder under dcss-ai-wrapper so the folder structure looks like this:
`dcss-ai-wrapper/FastDownward/fast-downward.py`
2. Switch the agent in `main.py` to be the `FastDownwardPlanningAgent` agent, like:
`agent = FastDownwardPlanningAgent()`
3. Run main.py and it should work. There's a chance that the fastdownward planner will fail to find a plan because of a missing feature of our api. Since the dungeon is procedurally generated, try a few times before troubleshooting fastdownward. If you do need to troubleshoot, start by displaying fastdownward's output. This can be done by removing the `stdout=subprocess.DEVNULL` option when calling FastDownward via subprocess.
## Web browser setup (see ISSUE #8)
The following instructions need to be updated - see issue 8.
The following steps enable the API to connect to DCSS running on a webserver on the local host, which means you can watch
your AI agent play DCSS in the tile version that runs in the web browser.
1. Install requirements to run the webserver version of the game
`sudo pip2 install tornado==3.0.2`
`sudo pip3 install asyncio`
`sudo pip3 install websockets`
2. Test that the browser version of the game is working
`cd ~/dcss-ai-wrapper/crawl/crawl-ref/source/`
`python2 webserver/server.py`
Now open your web browser and go to http://localhost:8080/
Click register at the top right (not necessary to enter an email).
Then after logging in, click the leftmost link under "Play now:" which is "DCSS trunk".
You should then go to a menu where you choose your character configuration (i.e. species > background > weapon)
Once you proceed through the menus you should find yourself in a newly generated world. If you've reached this
step (and can see the tiles) you have successfully installed the game.
# Troubleshooting
Problem: Errors during compiling
Solution: Double check you installed all the packages listed at the
beginning that crawl needs. These come from the install instructions
for crawl itself.
Problem: No images showing up and getting errors from the webserver like:
'HTTPOutputError: Tried to write X number of bytes but error with content length'
Solution: Make sure you are using tornado 3.0 (not the version that installs by default)
# Running the webserver
----------
Note these instructions may be outdated - they need to be double checked.
## Start webserver
`cd crawl_18/crawl/crawl-ref/source/`
`python2 webserver/server.py`
## now check to see if its up using a browser at localhost:8080
### If this is the first time you are running this on your machine,
you will need to register an account on the webserver (in the
browser). Keep track of the username and password, as you will enter
this into the code file, which the agent will use to connect to the
server.
## In a new terminal, go back to top level dir
## run the test_interface script using python3 (sidenote: installing asyncio
on python2.x will initially work but then you get errors when trying
to import it)
`python3 main.py`
# Watching the Agent Play
1. Navigate your browser to localhost:8080
2. You should see a list of agents playing, click on the agent's name to spectate (note, you do not need to log in for this). If you don't see the agent on the list, try refreshing the page.
<file_sep>'''
This file stores the gamestate class that is used to keep track of
the current state of the dcss game
'''
import actions
import logging
import re
import time
import string
import random
from enum import Enum
class ItemProperty(Enum):
"""
See crawl wiki for lists of these:
weapons: http://crawl.chaosforge.org/Brand
armour: http://crawl.chaosforge.org/Ego
"""
NO_PROPERTY = 0
# Melee Weapon Brands
Antimagic_Brand = 1
Chaos_Brand = 2
Disruption_Brand = 3
Distortion_Brand = 4
Dragon_slaying_Brand = 5
Draining_Brand = 6
Electrocution_Brand = 7
Flaming_Brand = 8
Freezing_Brand = 9
Holywrath_Brand = 10
Pain_Brand = 11
Necromancy_Brand = 12
Protection_Brand = 13
Reaping_Brand = 14
Speed_Brand = 15
Vampiricism_Brand = 16
Venom_Brand = 17
Vorpal_Brand = 18
# Thrown weapon brands
Dispersal_Brand = 19
Exploding_Brand = 20
Penetration_Brand = 21
Poisoned_Brand = 22
Returning_Brand = 23
Silver_Brand = 24
Steel_Brand = 25
# Needles
Confusion_Brand = 26
Curare_Brand = 27
Frenzy_Brand = 28
Paralysis_Brand = 29
Sleeping_Brand = 30
# Armour Properties (Egos)
Resistance_Ego = 31
Fire_Resistance_Ego = 32
Cold_Resistance_Ego = 33
Poison_Resistance_Ego = 34
Positive_Energy_Ego = 35
Protection_Ego = 36
Invisibility_Ego = 37
Magic_Resistance_Ego = 38
Strength_Ego = 39
Dexterity_Ego = 40
Intelligence_Ego = 41
Running_Ego = 42
Flight_Ego = 43
Stealth_Ego = 44
See_Invisible_Ego = 45
Archmagi_Ego = 46
Ponderousness_Ego = 47
Reflection_Ego = 48
Spirit_Shield_Ego = 49
Archery_Ego = 50
class CellRawStrDatum(Enum):
""" These are the types of data that may appear in a raw str description of a cell from the server. """
x = 0
f = 1
y = 2
g = 3
t = 4
mf = 5
col = 6
class Cell:
'''
Stores a cell of the map, not sure what all the information means yet
'''
def __init__(self, vals):
'''
Vals is a dictionary containing attributes, key must be a CellRawStrDatum
'''
self.raw = vals
self.x = None
self.f = None
self.y = None
self.g = None
self.t = None
self.mf = None
self.col = None
self.has_wall = False
self.has_player = False
self.has_stairs_down = False
self.has_stairs_up = False
self.has_closed_door = False
self.has_open_door = False
self.has_statue = False
self.has_player_visited = False
self.has_lava = False
self.has_plant = False
self.has_tree = False
self.set_vals(vals)
def set_vals(self, vals):
if 'x' in vals.keys():
self.x = vals['x']
if 'f' in vals.keys():
self.f = vals['f']
if 'y' in vals.keys():
self.y = vals['y']
if 'g' in vals.keys():
self.g = vals['g']
if self.g == '#':
self.has_wall = True
if self.g == '>':
self.has_stairs_down = True
if self.g == '<':
self.has_stairs_up = True
if self.g == '@':
self.has_player = True
self.has_player_visited = True
else:
self.has_player = False
if self.g == '+':
self.has_closed_door = True
self.has_closed_door = False
if self.g == '\'':
self.has_closed_door = False
self.has_open_door = True
if self.g == '8':
self.has_statue = True
if self.g == 'โ' or self.g == 'ยง':
self.has_lava = True
if self.g == 'P':
self.has_plant = True
if self.g == 'โ':
self.has_tree = True
if 't' in vals.keys():
self.t = vals['t']
if 'mf' in vals.keys():
self.mf = vals['mf']
if 'col' in vals.keys():
self.col = vals['col']
self.raw = vals
def get_pddl_name(self):
return "cellx{}y{}".format(self.x, self.y)
def get_cell_vector(self):
"""Do something similar to get_item_vector"""
# cell vector should contain:
# corpse? 0 or 1
# monster? (can only be one monster on a tile) - monster vector with
# monster vector
# current health? (may be in the form of weak, almost dead, bloodied, etc)
# maximum health?
# monster name
# is unique?
# items?
# special tile features (like water, lava, wall, door, etc)
def get_pddl_facts(self):
pddl_facts = []
if self.has_wall:
pddl_facts.append('(wall {})'.format(self.get_pddl_name()))
if self.has_closed_door:
pddl_facts.append('(closeddoor {})'.format(self.get_pddl_name()))
if self.has_player:
pddl_facts.append('(playerat {})'.format(self.get_pddl_name()))
if self.has_statue:
pddl_facts.append('(statue {})'.format(self.get_pddl_name()))
if self.has_lava:
pddl_facts.append('(lava {})'.format(self.get_pddl_name()))
if self.has_plant:
pddl_facts.append('(plant {})'.format(self.get_pddl_name()))
if self.has_tree:
pddl_facts.append('(tree {})'.format(self.get_pddl_name()))
return pddl_facts
def __str__(self):
if self.g and len(self.g) >= 1:
return self.g
else:
return " "
class CellMap:
"""
Data structure that maintains the set of all cells currently seen in the game.
"""
def __init__(self):
self.min_x = None
self.min_y = None
self.max_x = None
self.max_y = None
self.num_cells = 0
self.x_y_to_cells = {} # key is an (x,y) tuple, val is the cell at that spot
self.agent_x = None
self.agent_y = None
# unknown_vals = {k:None for k in CellRawStrDatum} # test this
# self.unknown_cell = Cell(
def add_or_update_cell(self, x, y, vals):
#print("vals={}".format(str(vals)))
if 'x' not in vals.keys():
vals['x'] = x
elif x != vals['x']:
print("WARNING potential issue with coordinates, x={} and vals[x]={}".format(x, vals['x']))
if 'y' not in vals.keys():
vals['y'] = x
elif y != vals['y']:
print("WARNING potential with coordinates, y={} and vals[y]={}".format(y, vals['y']))
if (x, y) in self.x_y_to_cells.keys():
#print("updating existing cell x={},y={}".format(x,y))
#print("previous vals={}, new vals={}".format(self.x_y_to_cells[(x, y)].raw, vals))
self.x_y_to_cells[(x, y)].set_vals(vals=vals)
else:
#print("adding new cell x={},y={} with vals={}".format(x, y, vals))
self.x_y_to_cells[(x, y)] = Cell(vals=vals)
if self.min_x is None or x < self.min_x:
self.min_x = x
if self.max_x is None or x > self.max_x:
self.max_x = x
if self.min_y is None or y < self.min_y:
self.min_y = y
if self.max_y is None or y > self.max_y:
self.max_y = y
if 'g' in vals.keys() and '@' in vals['g']:
self.agent_x = x
self.agent_y = y
def draw_cell_map(self):
s = "agent=({},{})\nminx={},maxx={},miny={},maxy={}\n".format(self.agent_x, self.agent_y,
self.min_x, self.max_x, self.min_y, self.max_y)
non_empty_cells = []
for curr_y in range(self.min_y, self.max_y + 1):
for curr_x in range(self.min_x, self.max_x + 1):
if (curr_x, curr_y) in self.x_y_to_cells.keys():
cell = self.x_y_to_cells[(curr_x, curr_y)]
s += str(cell)
if cell.g != "." and cell.g != "#" and cell.g is not None:
non_empty_cells.append(cell)
else:
s += " "
s += '\n'
#print("non-empty cells are:")
#for c in non_empty_cells:
# print("X={},Y={}, Cell is: {}".format(c.x, c.y, c.g))
return s
def print_radius_around_agent(self, r=8):
x_min = self.agent_x - r
x_max = self.agent_x + r
y_min = self.agent_y - r
y_max = self.agent_y - r
s = ""
for curr_y in range(y_min, y_max + 1):
for curr_x in range(x_min, x_max + 1):
if (curr_x, curr_y) in self.x_y_to_cells.keys():
s += str(self.x_y_to_cells[(curr_x, curr_y)])
else:
s += " "
s += '\n'
return s
def get_cell_map_pddl(self, goals):
object_strs = []
fact_strs = []
for curr_y in range(self.min_y, self.max_y + 1):
for curr_x in range(self.min_x, self.max_x + 1):
if (curr_x, curr_y) in self.x_y_to_cells.keys():
cell = self.x_y_to_cells[(curr_x, curr_y)]
object_strs.append(cell.get_pddl_name())
for f in cell.get_pddl_facts():
fact_strs.append(f)
#print('cellxy = {}, cellname is {}'.format(str((curr_x, curr_y)), cell.get_pddl_name()))
northcellxy = (cell.x, cell.y - 1)
#print("northcellxy = {}".format(northcellxy))
if northcellxy in self.x_y_to_cells.keys():
northcell = self.x_y_to_cells[northcellxy]
#print("northcell = {}".format(northcell.get_pddl_name()))
fact_strs.append("(northof {} {})".format(cell.get_pddl_name(), northcell.get_pddl_name()))
southcellxy = (cell.x, cell.y + 1)
if southcellxy in self.x_y_to_cells.keys():
southcell = self.x_y_to_cells[southcellxy]
fact_strs.append("(southof {} {})".format(cell.get_pddl_name(), southcell.get_pddl_name()))
westcellxy = (cell.x-1, cell.y)
if westcellxy in self.x_y_to_cells.keys():
westcell = self.x_y_to_cells[westcellxy]
fact_strs.append("(westof {} {})".format(cell.get_pddl_name(), westcell.get_pddl_name()))
eastcellxy = (cell.x + 1, cell.y)
if eastcellxy in self.x_y_to_cells.keys():
eastcell = self.x_y_to_cells[eastcellxy]
fact_strs.append("(eastof {} {})".format(cell.get_pddl_name(), eastcell.get_pddl_name()))
northeastcellxy = (cell.x + 1, cell.y - 1)
if northeastcellxy in self.x_y_to_cells.keys():
northeastcell = self.x_y_to_cells[northeastcellxy]
fact_strs.append("(northeastof {} {})".format(cell.get_pddl_name(), northeastcell.get_pddl_name()))
northwestcellxy = (cell.x - 1, cell.y - 1)
if northwestcellxy in self.x_y_to_cells.keys():
northwestcell = self.x_y_to_cells[northwestcellxy]
fact_strs.append(
"(northwestof {} {})".format(cell.get_pddl_name(), northwestcell.get_pddl_name()))
southeastcellxy = (cell.x + 1, cell.y + 1)
if southeastcellxy in self.x_y_to_cells.keys():
southeastcell = self.x_y_to_cells[southeastcellxy]
fact_strs.append(
"(southeastof {} {})".format(cell.get_pddl_name(), southeastcell.get_pddl_name()))
southwestcellxy = (cell.x - 1, cell.y + 1)
if southwestcellxy in self.x_y_to_cells.keys():
southwestcell = self.x_y_to_cells[southwestcellxy]
fact_strs.append(
"(southwestof {} {})".format(cell.get_pddl_name(), southwestcell.get_pddl_name()))
object_strs = list(set(object_strs))
fact_strs = list(set(fact_strs))
pddl_str = "(define (problem dcss-test-prob)\n(:domain dcss)\n(:objects \n"
for obj in object_strs:
pddl_str+= " {}\n".format(obj)
pddl_str += ")\n"
pddl_str += "(:init \n"
for fact in fact_strs:
pddl_str+= " {}\n".format(fact)
pddl_str += ")\n"
pddl_str += "(:goal \n (and \n"
for goal in goals:
pddl_str += " {}\n".format(goal)
pddl_str += ")\n"
pddl_str += ")\n\n)"
return pddl_str
def get_xy_to_cells_dict(self):
return self.x_y_to_cells
class InventoryItem:
ITEM_VECTOR_LENGTH = 5
def __init__(self, id_num, name, quantity, base_type=None):
self.id_num = int(id_num)
self.name = name
self.quantity = quantity
self.base_type = base_type
self.item_bonus = 0
self.properties = []
if self.name:
if '+' in self.name or '-' in self.name:
m = re.search('[+-][1-9][1-9]?', self.name)
if m:
self.item_bonus = int(m.group(0))
else:
self.item_bonus = 0
else:
print(
"\n\nself.name is None, not sure why...args to InventoryItem were id_num={}, name={}, quantity={}, base_type={}\n\n".format(
id_num, name, quantity, base_type))
exit(1)
# TODO - figure out how to know if item is equipped
self.equipped = False
def set_base_type(self, base_type):
self.base_type = base_type
def get_base_type(self):
return self.base_type
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
def set_quantity(self, quantity):
self.quantity = quantity
def get_quantity(self):
return self.quantity
def set_num_id(self, id_num):
self.id_num = int(id_num)
def get_num_id(self):
return self.id_num
def get_letter(self):
return string.ascii_letters[self.id_num]
def get_item_bonus(self):
return self.item_bonus
def is_item_equipped(self):
return self.equipped
def get_item_type(self):
"""
Since 0 is a valid value, increase all by 1, so 0 means an empty value
"""
return 1 + self.base_type
def get_property_i(self, i):
if i < len(self.properties):
return self.properties[i]
else:
return ItemProperty.NO_PROPERTY
def get_item_vector(self):
"""
* Indicates that item vector value may be repeated, if more than one property.
Index Information Contained
----- ---------------------
0 Item Type (Armour, Weapon, etc)
1 Item Count
2 Item Bonus ("+x" value)
3 Item Equipped
4 Property* (Fire resist, stealth, venom, etc)
"""
item_vector = []
item_vector.append(self.get_item_type())
item_vector.append(self.get_quantity())
item_vector.append(self.get_item_bonus())
item_vector.append(self.is_item_equipped())
item_vector.append(self.get_property_i(0))
assert len(item_vector) == InventoryItem.ITEM_VECTOR_LENGTH
# Note: If this assert fails, update
# InventoryItem.ITEM_VECTOR_LENGTH to be the correct value
return item_vector
@staticmethod
def get_empty_item_vector():
item_vector = [0 for i in range(InventoryItem.ITEM_VECTOR_LENGTH)]
return item_vector
def __eq__(self, other):
return self.name == other.name
def __str__(self):
return "{}({}) - {} (#={}, base_type={})".format(self.get_letter(), self.id_num, self.get_name(),
self.get_quantity(), self.get_base_type())
class TileFeatures:
'''
Contains feature data used per tile
Returns a factored state representation of the tiles around the player:
Example w/ radius of 1
- 9 tiles including the player's current position and all adjacent tiles in every cardinal direction
- each tile is represented as a factored state:
<objType,monsterLetter,hasCorpse,hereBefore>
* objType = 0 is empty, 1 is wall, 2 is monster
* monsterLetter = 0-25 representing the alpha index of the first letter of mon name (0=a, etc)
* hasCorpse = 0 if no edible corpse, 1 if edible corpse
* hereBefore = 0 if first time player on this tile, 1 if player has already been here
'''
absolute_x = None
absolute_y = None
has_monster = 0
last_visit = None # None if never visited, 0 if currently here, otherwise >1 representing
# number of actions executed since last visit
class GameState:
ID = 0
def __init__(self):
# state is just a dictionary of key value pairs
self.state = {}
# only state information we care about
self.state_keys = ['hp', 'hp_max', 'depth', 'light', 'god', 'mp', 'species', 'dex', 'inv', 'cells', 'species']
self.letter_to_number_lookup = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
# when the agent starts, it is in the center of its mental map
# as it moves N,S,E,W, the coordinates of its mental map will shift
self.agent_x = 0
self.agent_y = 0
self.agent_z = 0 # which floor of the dungeon the agent is on
self.map_obj_player_x = None # this is the x of the map_obj where the player is
self.map_obj_player_y = None # this is the y of the map_obj where the player is
self.map_obj = []
self.map_dim = 24
self.map_middle = 12
self.cellmap = CellMap()
self.inventory_by_id = {}
self.last_recorded_movement = ''
self.asp_str = '' # facts that don't change when an action is executed
self.asp_comment_str = '' # comments associated with asp
self.player_cell = None
self.training_asp_str = '' # facts that do change
self.all_asp_cells = None # number of cell objects
self.messages = {} # key is turn, value is list of messages received on this turn in order,
# where first is oldest message
# initialize values of state variables
for k in self.state_keys:
self.state[k] = None
self.died = False # becomes true if agent has died
self.more_prompt = False # becomes true when there is more messages before the agent can act
# and therefore must press enter to receive for messages
self.too_terrified_to_move = False # idk what to do here, but agent can't move
self.cannot_move = False # agent can't move for some reason, no use trying move actions
self.just_gained_level = False
self.id = GameState.ID
GameState.ID += 1
def update(self, msg_from_server):
try:
# print(str(self.state))
logging.info(str(msg_from_server))
self._process_raw_state(msg_from_server)
# self.draw_map()
# self.compute_asp_str()
# print(self.training_asp_str)
# print(self.background_asp_str)
except Exception as e:
raise Exception("Something went wrong" + e)
def record_movement(self, dir):
self.last_recorded_movement = dir
print('last recorded movement is ' + str(self.last_recorded_movement))
if dir in actions.key_actions.keys():
if dir is 'move_N':
self.shift_agent_y(-1)
elif dir is 'move_S':
self.shift_agent_y(1)
elif dir is 'move_E':
self.shift_agent_x(1)
elif dir is 'move_W':
self.shift_agent_x(-1)
else:
pass # do nothing if the agent didn't move
pass # do nothing if the agent didn't move
def shift_agent_x(self, change):
'''
Performs an addition
'''
self.agent_x += change
def shift_agent_y(self, change):
'''
Performs an addition
'''
self.agent_y += change
def get_cell_map(self):
return self.cellmap
def _process_raw_state(self, s, last_key=''):
# print("processing {}\n\n".format(s))
if isinstance(s, list):
for i in s:
self._process_raw_state(i)
elif isinstance(s, dict):
for k in s.keys():
if k == 'cells':
self.get_cell_objs_from_raw_data(s[k])
# self.update_map_obj(cells_x_y_g_data_only)
# self.update_map_obj()
last_key = k
if k == 'messages':
self.process_messages(s[k])
if k == 'inv':
self.process_inv(s[k])
if k in self.state_keys:
self.state[k] = s[k]
# print("Just stored {} with data {}".format(k,s[k]))
elif isinstance(s[k], list):
for i in s[k]:
self._process_raw_state(i)
elif isinstance(s[k], dict):
self._process_raw_state(s[k])
else:
pass
else:
pass
def _process_items_agent_location(self, message):
items = message.split(';')
print("Found {} items, they are:".format(len(items)))
for i in items:
print(" {}".format(i))
def process_messages(self, data):
# begin: this is just for html stripping
from html.parser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.strict = False
self.convert_charrefs = True
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
# end: html stripping code
last_message_is_items_here = False
for m in data:
turn = m['turn']
message_only = strip_tags(m['text'])
if turn in self.messages.keys():
self.messages[turn].append(message_only)
else:
self.messages[turn] = [message_only]
if 'You die...' in message_only:
self.died = True
if len(self.messages[turn]) >= 8:
self.more_prompt = True
if 'too terrified to move' in message_only:
self.too_terrified_to_move = True
if 'You cannot move' in message_only:
self.cannot_move = True
if 'You have reached level' in message_only:
self.just_gained_level = True
if last_message_is_items_here:
self._process_items_agent_location(message_only)
last_message_is_items_here = False
if 'Things that are here' in message_only:
last_message_is_items_here = True
if 'Unknown command.' in message_only:
print("Error with last command - game did not recognize it... sleeping for 30 seconds")
time.sleep(30)
print("Just added message for turn {}: {}".format(turn, message_only))
def get_pddl_current_state(self, goals):
return self.cellmap.get_cell_map_pddl(goals)
def write_pddl_current_state_to_file(self, filename, goals):
"""Filename is assumed to be a relevant filename from the folder that the main script is running"""
with open(filename.format(), 'w') as f:
f.write(self.get_pddl_current_state(goals))
return True
def has_agent_died(self):
return self.died
def is_agent_too_terrified(self, reset=True):
agent_terrified = self.too_terrified_to_move
if reset:
self.too_terrified_to_move = False
return agent_terrified
def agent_cannot_move(self, reset=True):
cannot_move = self.cannot_move
if reset:
self.cannot_move = False
return cannot_move
def agent_just_leveled_up(self, reset=True):
leveled_up = self.just_gained_level
if reset:
self.just_gained_level = False
return leveled_up
def game_has_more_messages(self, reset=False):
more_prompt = self.more_prompt
if reset:
self.more_prompt = False
return more_prompt
def process_inv(self, data):
print("Data is {}".format(data))
for inv_id in data.keys():
name = None
quantity = None
base_type = None
if 'name' in data[inv_id].keys():
name = data[inv_id]['name']
if 'quantity' in data[inv_id].keys():
quantity = int(data[inv_id]['quantity'])
if 'base_type' in data[inv_id].keys():
base_type = data[inv_id]['base_type']
if inv_id not in self.inventory_by_id.keys():
# new item
inv_item = InventoryItem(inv_id, name, quantity, base_type)
self.inventory_by_id[inv_id] = inv_item
print("***** Adding new item {}".format(inv_item))
else:
# existing item
inv_item = self.inventory_by_id[inv_id]
print("***** Updating item {}".format(inv_item))
prev_quantity = inv_item.get_quantity()
if quantity is not None and quantity <= prev_quantity:
if quantity == 0:
print(" **** Deleting item {} because quantity = 0".format(inv_item))
del self.inventory_by_id[inv_id]
else:
print(" **** Reducing item {} quantity from {} to {}".format(inv_item, prev_quantity, quantity))
self.inventory_by_id[inv_id].set_quantity(quantity)
def get_cell_objs_from_raw_data(self, cells):
only_xyg_cell_data = []
curr_x = None
curr_y = None
g_var = None
num_at_signs = 0
if cells:
# Note: in the first iteration of this loop, x and y will exist in cell_dict.keys()
for cell_dict in cells:
# either x and y appear to mark the start of a new row, or ...
if 'x' in cell_dict.keys() and 'y' in cell_dict.keys():
curr_x = cell_dict['x']
curr_y = cell_dict['y']
else: # ... just increment x, keeping y the same
curr_x += 1
#print("x={},y={}".format(curr_x, curr_y))
vals = {}
# store any other datums we have access to
for datum_key in CellRawStrDatum:
if datum_key.name in cell_dict.keys():
#input("datum_key {} is in cell_dict {} with value {}".format(datum_key.name, cell_dict, cell_dict[datum_key.name]))
vals[datum_key.name] = cell_dict[datum_key.name]
else:
pass
# input("datum_key {} is NOT in cell_dict {}".format(datum_key.name, cell_dict))
if 'x' not in vals.keys():
vals['x'] = curr_x
if 'y' not in vals.keys():
vals['y'] = curr_y
self.cellmap.add_or_update_cell(curr_x, curr_y, vals=vals)
def update_map_obj(self):
'''
If we already have a map data, and we have new map data from the player moving,
shift the map and update the cells
:param cell_data_raw:
:param player_move_dir:
'''
# print("cells data is {}".format(cell_data_raw))
# todo - left off here, figure out how to update the global cells as the player moves
# todo - do we need to shift cells? or only change the player's current x and y? The latter
# todo - would be ideal.
at_sign_count = 0 # we should only see the @ in one location
# If map object isn't created yet, then initialize
if len(self.map_obj) == 0:
for i in range(self.map_dim):
row = [' '] * self.map_dim
self.map_obj.append(row)
if not cell_data_raw:
# We don't always get cell data, if so, return
return
if cell_data_raw:
print("Raw cells data:")
prev_x = None
prev_y = None
for cell_raw_str in cell_data_raw:
# x, y, g = cell_raw_str['x']
print(" {}".format(cell_raw_str))
for xyg_cell in cell_data_raw:
x = int(xyg_cell[0])
y = int(xyg_cell[1])
g = xyg_cell[2]
map_obj_x = self.map_middle + x
map_obj_y = self.map_middle + y
if '@' == g:
# print("player x,y is " + str(x) + ',' + str(y) + " from cell data")
# print("player x,y in gamestate is " + str(map_obj_x) + ',' + str(map_obj_y) + " from cell data")
self.map_obj_player_x = map_obj_x
self.map_obj_player_y = map_obj_y
at_sign_count += 1
if at_sign_count > 1:
print("Error, multiple @ signs - let's debug!")
time.sleep(1000)
# boundary conditions
if map_obj_y < len(self.map_obj) and \
map_obj_x < len(self.map_obj[map_obj_y]) and \
map_obj_x > 0 and \
map_obj_y > 0:
self.map_obj[map_obj_y][map_obj_x] = g
def print_map_obj(self):
while self.lock:
# wait
time.sleep(0.001)
self.lock = True
try:
for r in self.map_obj:
print(str(r))
self.lock = False
except:
raise Exception("Oh man something happened")
finally:
self.lock = False
def get_player_xy(self):
return (self.map_obj_player_x, self.map_obj_player_y)
def get_asp_str(self):
return self.asp_str
def get_asp_comment_str(self):
return self.asp_comment_str
def get_training_asp_str(self):
return self.training_asp_str
def get_player_cell(self):
return self.player_cell
def get_tiles_around_player_radius(self, radius=1):
'''
A radius of 0 is only the players tile
A radius of 1 would be 9 tiles, including
- players tile
- all tiles 1 away (including diagonal) of the player's tile
A radius of 2 would be 16+8+1 = 25 tiles (all tiles <= distance of 2 from player)
etc...
Returns a factored state representation of the tiles around the player:
Example w/ radius of 1
- 9 tiles including the player's current position and all adjacent tiles in every cardinal direction
- tiles are ordered in a clockwise orientation, starting with N, then NE, then E, etc
- inner layers come before outer layers
- each tile is represented as a factored state:
<objType,monsterLetter,hasCorpse,hereBefore>
* objType = 0 is empty, 1 is wall, 2 is monster
* monsterLetter = 27 if noMonster, 0-26 representing the alpha index of the first letter of mon name
* hasCorpse = 0 if no edible corpse, 1 if edible corpse
* hereBefore = 0 if first time player on this tile, 1 if player has already been here
:param radius: Int
:return: a factored state representation of the tiles around the player
'''
tiles = []
curr_radius = 0
# agent's tile
tiles.append(self.map_obj[self.map_obj_player_y][self.map_obj_player_x])
# N tile
tiles.append(self.map_obj[self.map_obj_player_y - 1][self.map_obj_player_x])
# NE tile
tiles.append(self.map_obj[self.map_obj_player_y - 1][self.map_obj_player_x + 1])
# E tile
tiles.append(self.map_obj[self.map_obj_player_y][self.map_obj_player_x + 1])
# SE tile
tiles.append(self.map_obj[self.map_obj_player_y + 1][self.map_obj_player_x + 1])
# S tile
tiles.append(self.map_obj[self.map_obj_player_y + 1][self.map_obj_player_x])
# SW tile
tiles.append(self.map_obj[self.map_obj_player_y + 1][self.map_obj_player_x - 1])
# W tile
tiles.append(self.map_obj[self.map_obj_player_y][self.map_obj_player_x - 1])
# NW tile
tiles.append(self.map_obj[self.map_obj_player_y - 1][self.map_obj_player_x - 1])
return tiles
def draw_map(self):
# print("in draw map!")
s = ''
top_row_indexes = None
for row in self.map_obj:
row_s = ''
if top_row_indexes is None:
# not sure what I was doing here?
pass
for spot in row:
if len(spot) != 0:
row_s += (str(spot))
else:
row_s += ' '
# remove any rows that are all whitespace
if len(row_s.strip()) > 0:
s += row_s + '\n'
print(s)
def draw_cell_map(self):
print(self.cellmap.draw_cell_map())
def print_inventory(self):
print(" Inventory:")
for inv_item in sorted(self.inventory_by_id.values(), key=lambda i: i.get_num_id()):
print(" {} - {} (#={}, base_type={})".format(inv_item.get_letter(), inv_item.get_name(),
inv_item.get_quantity(), inv_item.get_base_type()))
print(" Vector: {}".format(inv_item.get_item_vector()))
def get_inventory_vector(self):
pass
def _pretty_print(self, curr_state, offset=1, last_key=''):
if not isinstance(curr_state, dict):
print(' ' * offset + str(curr_state))
else:
for key in curr_state.keys():
last_key = key
if isinstance(curr_state[key], dict):
print(' ' * offset + str(key) + '= {')
self._pretty_print(curr_state[key], offset + 2, last_key)
print(' ' * offset + '}')
elif isinstance(curr_state[key], list):
if last_key == 'cells':
# don't recur
self.print_x_y_g_cell_data(curr_state[key])
# for i in curr_state[key]:
# print(' '*offset+str(i))
# pass
else:
print(' ' * offset + str(key) + '= [')
for i in curr_state[key]:
self._pretty_print(i, offset + 2, last_key)
print(' ' * offset + "--")
print(' ' * offset + ']')
else:
print(' ' * offset + str(key) + "=" + str(curr_state[key]))
def printstate(self):
# print("self.state="+str(self.state))
# print('-'*20+" GameState "+'-'*20)
# self._pretty_print(self.state)
pass
def get_map_obj(self):
return self.map_obj
def convert_cells_to_map_obj(self, cells_str):
'''
cells is the data of the map and nearby monsters and enemies received from the server
'''
map_dim = 200
map_middle = 100
for i in range(map_dim):
row = [' '] * map_dim
self.map_obj.append(row)
curr_x = -1
for cell in cells_str:
# create Cell object
new_cell = Cell(cell)
# put into right location into map
if new_cell.x and new_cell.y and new_cell.g:
curr_x = new_cell.x
self.map_obj[new_cell.y + map_middle][new_cell.x + map_middle] = new_cell.g
# map_obj[abs(new_cell.x)][abs(new_cell.y)] = new_cell.g
# elif new_cell.y and new_cell.g and curr_x >= 0:
# map_obj[new_cell.y+map_middle][curr_x] = new_cell.g
# map_obj[curr_x][abs(new_cell.y)] = new_cell.g
def print_map_obj(self):
for row in self.map_obj:
for spot in row:
print(str(spot), end='')
print('')
class FactoredState():
'''
Represents a factored state for use for q-learning.
State Information:
- 9 tiles including the player's current position and all adjacent tiles in every cardinal direction
- each tile is represented as a factored state:
<objType,monsterLetter,hasCorpse,hereBefore>
* objType = 0 is empty, 1 is wall, 2 is monster
* monsterLetter = -1 if noMonster, 0-26 representing the alpha index of the first letter of mon name
* hasCorpse = 0 if no edible corpse, 1 if edible corpse
* hereBefore = 0 if first time player on this tile, 1 if player has already been here
- player's health, enums of [none,verylow,low,half,high,veryhigh,full]
- player's hunger, enums of [fainting,starving,very hungry, hungry, not hungry, full, very full, engorged]
'''
tiles = []
health = None
hunger = None
def __init__(self, gs):
map_obj = gs.get_map_obj()
if __name__ == '__main__':
example_json_state_string_1 = {'msgs': [{'msg': 'map', 'clear': True, 'cells': [
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1847}, 'x': -6, 'mf': 2, 'y': -1},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1847}, 'x': -6, 'mf': 2, 'y': 0},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 9, 'ov': [2202, 2204]}},
{'f': 33, 'g': '$', 'mf': 6, 'col': 14,
't': {'doll': None, 'ov': [2204], 'fg': 947, 'mcache': None, 'bg': 1048585, 'base': 0}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4, 'ov': [2204]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 2, 'ov': [2204]}}, {'f': 33, 'g': '0', 'mf': 6, 'col': 5,
't': {'doll': None, 'ov': [2204],
'fg': 842, 'mcache': None, 'bg': 2,
'base': 0}},
{'f': 33, 'g': '@', 'mf': 1, 'col': 87,
't': {'mcache': None, 'doll': [[3302, 32], [3260, 32], [3372, 32], [3429, 32], [4028, 32], [3688, 32]],
'bg': 7, 'ov': [2204], 'fg': 527407}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5, 'ov': [2204]}}, {'f': 33, 'g': '$', 'mf': 6, 'col': 14,
't': {'doll': None, 'ov': [2204],
'fg': 947, 'mcache': None,
'bg': 1048580, 'base': 0}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6, 'ov': [2204, 2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1848}, 'x': -6, 'mf': 2, 'y': 1},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3, 'ov': [2202]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4, 'ov': [2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1846}, 'x': -6, 'mf': 2, 'y': 2},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3, 'ov': [2202]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 9}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 2}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3, 'ov': [2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1846}, 'x': -6, 'mf': 2, 'y': 3},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4, 'ov': [2202]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 6}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 2, 'ov': [2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1845}, 'x': -6, 'mf': 2, 'y': 4},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7, 'ov': [2202]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 9}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 7}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 8}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 8, 'ov': [2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1845}, 'x': -6, 'mf': 2, 'y': 5},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3, 'ov': [2202]}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 3}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 2}},
{'f': 60, 'g': '<', 'mf': 12, 'col': 9, 't': {'bg': 2381, 'flv': {'f': 6, 's': 50}}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}}, {'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 5}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 2}},
{'f': 33, 'g': '.', 'mf': 1, 'col': 7, 't': {'bg': 4, 'ov': [2206]}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1847}},
{'f': 9, 'col': 1, 'g': '#', 't': {'bg': 1847}, 'x': -6, 'mf': 2, 'y': 6},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1846}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1845}},
{'f': 9, 'g': '#', 'mf': 2, 'col': 1, 't': {'bg': 1848}}], 'player_on_level': True, 'vgrdc': {'y': 0, 'x': 0}}]}
example_json_state_string_2 = "{'msgs': [{'msg': 'input_mode', 'mode': 0}, {'msg': 'player', 'turn': 12, 'time': 120, 'pos': {'y': 1, 'x': -1}}, {'msg': 'map', 'cells': [{'col': 7, 'y': 0, 'g': '.', 't': {'mcache': None, 'doll': None, 'fg': 0}, 'x': 0}, {'col': 87, 'y': 1, 'g': '@', 't': {'mcache': None, 'doll': [[3302, 32], [3260, 32], [3372, 32], [3429, 32], [4028, 32], [3688, 32]], 'fg': 527407}, 'x': -1}], 'vgrdc': {'y': 1, 'x': -1}}, {'msg': 'input_mode', 'mode': 1}]}"
gs1 = GameState()
gs1.update(example_json_state_string_1)
'''
int:4
species:Minotaur
equip:{'0': 0, '15': -1, '8': -1, '1': -1, '12': -1, '9': -1, '11': -1, '18': -1, '17': -1, '4': -1, '3': -1, '7': -1, '16': -1, '14': -1, '10': -1, '6': 1, '2': -1, '5': -1, '13': -1}
dex_max:9
unarmed_attack:Nothing wielded
penance:0
form:0
int_max:4
poison_survival:16
turn:1114
str_max:21
place:Dungeon
name:midca
dex:9
ev:12
hp_max:20
real_hp_max:20
mp_max:0
unarmed_attack_colour:7
piety_rank:1
mp:0
xl:1
ac:2
title:the Skirmisher
hp:16
'''
'''
def _process_raw_state3(self, dict_struct):
if isinstance(dict_struct, list):
new_li = []
for li in dict_struct:
new_li.append(self._process_raw_state(li))
return new_li
elif not isinstance(dict_struct, dict):
return dict_struct
else:
curr_state = {}
ignore_list = ['cell','html','content','skip','text']
skip_bc_ignore = False
for key in dict_struct.keys():
for ignore in ignore_list:
if ignore in key:
skip_bc_ignore = True
if skip_bc_ignore:
skip_bc_ignore = False
pass
# process if list
elif isinstance(dict_struct[key], list):
new_list = []
for li in dict_struct[key]:
new_list.append(self._process_raw_state(li))
curr_state[key] = li
# else:
# curr_state[key] = dict_struct[key]
# process if dict
elif isinstance(dict_struct[key], dict):
curr_state[key] = self._process_raw_state(dict_struct[key])
else:
curr_state[key] = dict_struct[key]
return curr_state
'''
<file_sep>'''
This file contains messages for key actions and text inputs to be
sent to webserver, including:
* moving around
* accessing the inventory
* using items
* ... etc
These keycodes were identified manually be testing commands using
Chrome's develop tools and observing the communications sent through
the websockets.
'''
from enum import Enum
class Command(Enum):
'''
These are taken from the in-game manual of crawl.
'''
# Movement
MOVE_OR_ATTACK_SW = 1
MOVE_OR_ATTACK_S = 2
MOVE_OR_ATTACK_SE = 3
MOVE_OR_ATTACK_W = 4
MOVE_OR_ATTACK_E = 5
MOVE_OR_ATTACK_NW = 6
MOVE_OR_ATTACK_N = 7
MOVE_OR_ATTACK_NE = 8
# Rest
REST_AND_LONG_WAIT = 9
WAIT_1_TURN = 10
# Extended Movement
AUTO_EXPLORE = 11
INTERLEVEL_TRAVEL = 12
FIND_ITEMS = 13
SET_WAYPOINT = 14
LONG_WALK_SW = 15
LONG_WALK_S = 16
LONG_WALK_SE = 17
LONG_WALK_W = 18
LONG_WALK_E = 19
LONG_WALK_NW = 20
LONG_WALK_N = 21
LONG_WALK_NE = 22
ATTACK_WITHOUT_MOVE_SW = 23
ATTACK_WITHOUT_MOVE_S = 24
ATTACK_WITHOUT_MOVE_SE = 25
ATTACK_WITHOUT_MOVE_W = 26
ATTACK_WITHOUT_MOVE_E = 27
ATTACK_WITHOUT_MOVE_NW = 28
ATTACK_WITHOUT_MOVE_N = 29
ATTACK_WITHOUT_MOVE_NE = 30
# Autofight
AUTO_FIGHT = 31
AUTO_FIGHT_WITHOUT_MOVE = 32
# Item types (and common commands)
WIELD_HAND_WEAPON = 33
QUIVER_MISSILE = 34
FIRE_MISSILE = 35
SELECT_MISSILE_AND_FIRE = 36
CYCLE_MISSILE_FORWARD = 37
CYCLE_MISSILE_BACKWARD = 38
WEAR_ARMOUR = 39
TAKE_OFF_ARMOUR = 40
CHOP_CORPSE = 41
EAT = 42
READ = 43
QUAFF = 44
PUT_ON_JEWELLERY = 45
REMOVE_JEWELLERY = 46
EVOKE = 47
SELECT_ITEM_TO_EVOKE = 48
MEMORISE = 49
COUNT_GOLD = 50
# Other gameplay actions
USE_SPECIAL_ABILITY = 51
CAST_SPELL_ABORT_WITHOUT_TARGETS = 52
CAST_SPELL_NO_MATTER_WHAT = 53
LIST_ALL_SPELLS = 54
TELL_ALLIES = 55
REDO_PREVIOUS_COMMAND = 56
# Game Saving and Quitting
SAVE_GAME_AND_EXIT = 57
SAVE_AND_EXIT_WITHOUT_QUERY = 58
ABANDON_CURRENT_CHARACTER_AND_QUIT_GAME = 59
# Player Character Information
DISPLAY_CHARACTER_STATUS = 60
SHOW_SKILL_SCREEN = 61
CHARACTER_OVERVIEW = 62
SHOW_RELIGION_SCREEN = 63
SHOW_ABILITIES_AND_MUTATIONS = 64
SHOW_ITEM_KNOWLEDGE = 65
SHOW_RUNES_COLLECTED = 66
DISPLAY_WORN_ARMOUR = 67
DISPLAY_WORN_JEWELLERY = 68
DISPLAY_EXPERIENCE_INFO = 69
# Dungeon Interaction and Information
OPEN_DOOR = 70
CLOSE_DOOR = 71
TRAVEL_STAIRCASE_DOWN = 72
TRAVEL_STAIRCASE_UP = 73
EXAMINE_CURRENT_TILE_PICKUP_PART_OF_SINGLE_STACK = 74
EXAMINE_SURROUNDINGS_AND_TARGETS = 75
EXAMINE_LEVEL_MAP = 76
LIST_MONSTERS_ITEMS_FEATURES_IN_VIEW = 77
TOGGLE_VIEW_LAYERS = 78
SHOW_DUNGEON_OVERVIEW = 79
TOGGLE_AUTO_PICKUP = 80
SET_TRAVEL_SPEED_TO_CLOSEST_ALLY = 81
# Item Interaction (Inventory)
SHOW_INVENTORY_LIST = 82
INSCRIBE_ITEM = 83
# Item Interaction (floor)
PICKUP_ITEM = 84
SELECT_ITEM_FOR_PICKUP = 85
DROP_ITEM = 86
DROP_LAST_ITEMS_PICKED_UP = 87
# Additional Actions
EXIT_MENU = 88
SHOW_PREVIOUS_GAME_MESSAGES = 89
RESPOND_YES_TO_PROMPT = 90
RESPOND_NO_TO_PROMPT = 91
ENTER_KEY = 92
class Action:
"""
This class represents an action that the agent can take.
"""
command_to_msg = {
Command.MOVE_OR_ATTACK_N: {'msg': 'key', "keycode": -254},
Command.MOVE_OR_ATTACK_S: {'msg': 'key', "keycode": -253},
Command.MOVE_OR_ATTACK_E: {'msg': 'key', "keycode": -251},
Command.MOVE_OR_ATTACK_W: {'msg': 'key', "keycode": -252},
Command.MOVE_OR_ATTACK_NW: {'msg': 'key', "keycode": -249},
Command.MOVE_OR_ATTACK_SW: {'msg': 'key', "keycode": -248},
Command.MOVE_OR_ATTACK_SE: {'msg': 'key', "keycode": -245},
Command.MOVE_OR_ATTACK_NE: {'msg': 'key', "keycode": -246},
Command.REST_AND_LONG_WAIT: {'msg': 'key', 'keycode': ord('5')},
Command.WAIT_1_TURN: {'msg': 'key', 'keycode': ord('.')},
Command.AUTO_EXPLORE: {'msg': 'key', 'keycode': ord('o')},
Command.INTERLEVEL_TRAVEL: {'text': 'G', 'msg': 'input'},
Command.FIND_ITEMS: {'msg': 'key', "keycode": 6},
# Todo - see github issue 9
# Command.SET_WAYPOINT: {...}
Command.LONG_WALK_N: {'msg': 'key', "keycode": -243},
Command.LONG_WALK_S: {'msg': 'key', "keycode": -242},
Command.LONG_WALK_E: {'msg': 'key', "keycode": -240},
Command.LONG_WALK_W: {'msg': 'key', "keycode": -241},
Command.LONG_WALK_NW: {'msg': 'key', "keycode": -238},
Command.LONG_WALK_NE: {'msg': 'key', "keycode": -235},
Command.LONG_WALK_SW: {'msg': 'key', "keycode": -237},
Command.LONG_WALK_SE: {'msg': 'key', "keycode": -234},
Command.ATTACK_WITHOUT_MOVE_N: {'msg': 'key', "keycode": -232},
Command.ATTACK_WITHOUT_MOVE_S: {'msg': 'key', "keycode": -231},
Command.ATTACK_WITHOUT_MOVE_E: {'msg': 'key', "keycode": -229},
Command.ATTACK_WITHOUT_MOVE_W: {'msg': 'key', "keycode": -230},
Command.ATTACK_WITHOUT_MOVE_NW: {'msg': 'key', "keycode": -227},
Command.ATTACK_WITHOUT_MOVE_SW: {'msg': 'key', "keycode": -226},
# Todo - similar issue to github issue 9
# Command.ATTACK_WITHOUT_MOVE_NE: {'msg': 'key', "keycode": },
# Todo - similar issue to github issue 9
# Command.ATTACK_WITHOUT_MOVE_SE: {'msg': 'key', "keycode": },
Command.AUTO_FIGHT: {'msg': 'key', 'keycode': 9},
# Todo - similar issue to github issue 9
# Command.AUTO_FIGHT_WITHOUT_MOVE:
Command.WIELD_HAND_WEAPON: {'text': 'w', 'msg': 'input'},
Command.QUIVER_MISSILE: {'text': 'Q', 'msg': 'input'},
Command.FIRE_MISSILE: {'text': 'f', 'msg': 'input'},
Command.SELECT_MISSILE_AND_FIRE: {'text': 'F', 'msg': 'input'},
Command.CYCLE_MISSILE_FORWARD: {'text': '(', 'msg': 'input'},
Command.CYCLE_MISSILE_BACKWARD: {'text': ')', 'msg': 'input'},
Command.WEAR_ARMOUR: {'text': 'W', 'msg': 'input'},
Command.TAKE_OFF_ARMOUR: {'text': 'T', 'msg': 'input'},
Command.CHOP_CORPSE: {'text': 'c', 'msg': 'input'},
Command.EAT: {'text': 'e', 'msg': 'input'},
Command.QUAFF: {'text': 'q', 'msg': 'input'},
Command.READ: {'text': 'r', 'msg': 'input'},
Command.PUT_ON_JEWELLERY: {'text': 'P', 'msg': 'input'},
Command.REMOVE_JEWELLERY: {'text': 'R', 'msg': 'input'},
Command.EVOKE: {'text': 'v', 'msg': 'input'},
Command.SELECT_ITEM_TO_EVOKE: {'text': 'V', 'msg': 'input'},
Command.MEMORISE: {'text': 'M', 'msg': 'input'},
Command.COUNT_GOLD: {'text': '$', 'msg': 'input'},
Command.USE_SPECIAL_ABILITY: {'text': 'a', 'msg': 'input'},
Command.CAST_SPELL_ABORT_WITHOUT_TARGETS: {'text': 'z', 'msg': 'input'},
Command.CAST_SPELL_NO_MATTER_WHAT: {'text': 'Z', 'msg': 'input'},
Command.LIST_ALL_SPELLS: {'text': 'I', 'msg': 'input'},
Command.TELL_ALLIES: {'text': 'I', 'msg': 'input'},
Command.REDO_PREVIOUS_COMMAND: {'text': '`', 'msg': 'input'},
Command.SAVE_GAME_AND_EXIT: {'text': 'S', 'msg': 'input'},
Command.SAVE_AND_EXIT_WITHOUT_QUERY: {'msg': 'key', "keycode": 19},
Command.ABANDON_CURRENT_CHARACTER_AND_QUIT_GAME: {'msg': 'key', "keycode": 17},
Command.DISPLAY_CHARACTER_STATUS: {'text': '@', 'msg': 'input'},
Command.SHOW_SKILL_SCREEN: {'text': 'm', 'msg': 'input'},
Command.CHARACTER_OVERVIEW: {'text': '%', 'msg': 'input'},
Command.SHOW_RELIGION_SCREEN: {'text': '^', 'msg': 'input'},
Command.SHOW_ABILITIES_AND_MUTATIONS: {'text': 'A', 'msg': 'input'},
Command.SHOW_ITEM_KNOWLEDGE: {'text': '\\', 'msg': 'input'},
Command.SHOW_RUNES_COLLECTED: {'text': '}', 'msg': 'input'},
Command.DISPLAY_WORN_ARMOUR: {'text': '[', 'msg': 'input'},
Command.DISPLAY_WORN_JEWELLERY: {'text': '\"', 'msg': 'input'},
Command.DISPLAY_EXPERIENCE_INFO: {'text': 'E', 'msg': 'input'},
Command.OPEN_DOOR: {'text': 'O', 'msg': 'input'},
Command.CLOSE_DOOR: {'text': 'C', 'msg': 'input'},
Command.TRAVEL_STAIRCASE_UP: {'text': '<', 'msg': 'input'},
Command.TRAVEL_STAIRCASE_DOWN: {'text': '<', 'msg': 'input'},
Command.EXAMINE_CURRENT_TILE_PICKUP_PART_OF_SINGLE_STACK: {'text': ';', 'msg': 'input'},
Command.EXAMINE_SURROUNDINGS_AND_TARGETS: {'text': 'x', 'msg': 'input'},
Command.EXAMINE_LEVEL_MAP: {'text': 'X', 'msg': 'input'},
Command.LIST_MONSTERS_ITEMS_FEATURES_IN_VIEW: {'msg': 'key', "keycode": 24},
Command.TOGGLE_VIEW_LAYERS: {'text': '|', 'msg': 'input'},
Command.SHOW_DUNGEON_OVERVIEW: {'msg': 'key', "keycode": 15},
Command.TOGGLE_AUTO_PICKUP: {'msg': 'key', "keycode": 1},
Command.SET_TRAVEL_SPEED_TO_CLOSEST_ALLY: {'msg': 'key', "keycode": 5},
Command.SHOW_INVENTORY_LIST: {'text': 'i', 'msg': 'input'},
Command.INSCRIBE_ITEM: {'msg': 'input', 'data': [123]},
Command.PICKUP_ITEM: {'text': 'g', 'msg': 'input'},
Command.SELECT_ITEM_FOR_PICKUP: {'text': ',', 'msg': 'input'},
Command.DROP_ITEM: {'text': 'd', 'msg': 'input'},
Command.DROP_LAST_ITEMS_PICKED_UP: {'text': 'D', 'msg': 'input'},
Command.EXIT_MENU: {'msg': 'key', 'keycode': 27},
Command.SHOW_PREVIOUS_GAME_MESSAGES: {'msg': 'key', 'keycode': 16},
Command.RESPOND_YES_TO_PROMPT: {'text': 'Y', 'msg': 'input'},
Command.RESPOND_NO_TO_PROMPT: {'text': 'N', 'msg': 'input'},
Command.ENTER_KEY: {'text': '\r', 'msg': 'input'},
}
@staticmethod
def get_execution_repr(command: Command):
"""
Given a command, return the data that can be sent directly to the game to execute the command.
:return: a message data structure that can be sent directly to the game to execute the command.
"""
#print("Command is {}".format(command))
return Action.command_to_msg[command]
|
6feb56026cd6bbda028011948e3bd468c445fb71
|
[
"Markdown",
"Python"
] | 6 |
Python
|
jcnecio/dcss-ai-wrapper
|
56150f564783685a7e97b0ef72e8044a5b4047eb
|
a5cfed93d66c3047e286a1d210bcdb89ef406c0c
|
refs/heads/master
|
<repo_name>kildevaeld/view.validation<file_sep>/lib/decorators.d.ts
import { ValidatorMap } from './types';
import { BaseView, Constructor, UIMap } from 'view';
import { StringValidator } from './validator';
export declare function validations(v: ValidatorMap | (() => ValidatorMap)): <T extends Constructor<BaseView<E, U>>, E extends Element, U extends UIMap>(target: T) => void;
export declare namespace validations {
function string(key?: string): StringValidator;
}
<file_sep>/dist/view.validation.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('view.html'), require('equaljs'), require('view')) :
typeof define === 'function' && define.amd ? define(['view.html', 'equaljs', 'view'], factory) :
(global.view = global.view || {}, global.view.validation = factory(global.view.html,global.equaljs,global.view));
}(this, (function (view_html_1,equaljs,view_1) { 'use strict';
view_html_1 = view_html_1 && view_html_1.hasOwnProperty('default') ? view_html_1['default'] : view_html_1;
equaljs = equaljs && equaljs.hasOwnProperty('default') ? equaljs['default'] : equaljs;
view_1 = view_1 && view_1.hasOwnProperty('default') ? view_1['default'] : view_1;
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return _get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
var validators = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var AbstractValidator = function AbstractValidator(msg) {
_classCallCheck(this, AbstractValidator);
if (msg) this.message = msg;
};
exports.AbstractValidator = AbstractValidator;
var RequiredValidator =
/*#__PURE__*/
function (_AbstractValidator) {
_inherits(RequiredValidator, _AbstractValidator);
_createClass(RequiredValidator, [{
key: "validate",
value: function validate(value) {
if (value === null || value === void 0) return false;
if (typeof value === 'string' && value == '') return false;
return true;
}
}]);
function RequiredValidator() {
var msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{{label}} mangler";
_classCallCheck(this, RequiredValidator);
return _possibleConstructorReturn(this, (RequiredValidator.__proto__ || Object.getPrototypeOf(RequiredValidator)).call(this, msg));
}
return RequiredValidator;
}(AbstractValidator);
exports.RequiredValidator = RequiredValidator;
var RegexValidator =
/*#__PURE__*/
function (_AbstractValidator2) {
_inherits(RegexValidator, _AbstractValidator2);
function RegexValidator() {
var _this;
var msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{{label}} er invalid";
var regex = arguments[1];
_classCallCheck(this, RegexValidator);
_this = _possibleConstructorReturn(this, (RegexValidator.__proto__ || Object.getPrototypeOf(RegexValidator)).call(this, msg));
_this.regex = regex;
return _this;
}
_createClass(RegexValidator, [{
key: "validate",
value: function validate(value) {
return this.regex.test(String(value));
}
}]);
return RegexValidator;
}(AbstractValidator);
exports.RegexValidator = RegexValidator;
var EmailValidator =
/*#__PURE__*/
function (_RegexValidator) {
_inherits(EmailValidator, _RegexValidator);
function EmailValidator() {
var _this2;
var msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "{{label}} er ikke en valid email";
_classCallCheck(this, EmailValidator);
_this2 = _possibleConstructorReturn(this, (EmailValidator.__proto__ || Object.getPrototypeOf(EmailValidator)).call(this, msg));
_this2.regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return _this2;
}
return EmailValidator;
}(RegexValidator);
exports.EmailValidator = EmailValidator;
var MinLengthValidator =
/*#__PURE__*/
function (_AbstractValidator3) {
_inherits(MinLengthValidator, _AbstractValidator3);
function MinLengthValidator(n, msg) {
var _this3;
_classCallCheck(this, MinLengthValidator);
_this3 = _possibleConstructorReturn(this, (MinLengthValidator.__proto__ || Object.getPrototypeOf(MinLengthValidator)).call(this, msg));
_this3.len = n;
return _this3;
}
_createClass(MinLengthValidator, [{
key: "validate",
value: function validate(value) {
if (typeof value === 'string') {
return value.length >= this.len;
} else if (typeof value === 'number') {
return value >= this.len;
}
return false;
}
}]);
return MinLengthValidator;
}(AbstractValidator);
exports.MinLengthValidator = MinLengthValidator;
var MaxLengthValidator =
/*#__PURE__*/
function (_AbstractValidator4) {
_inherits(MaxLengthValidator, _AbstractValidator4);
function MaxLengthValidator(n, msg) {
var _this4;
_classCallCheck(this, MaxLengthValidator);
_this4 = _possibleConstructorReturn(this, (MaxLengthValidator.__proto__ || Object.getPrototypeOf(MaxLengthValidator)).call(this, msg));
_this4.len = n;
return _this4;
}
_createClass(MaxLengthValidator, [{
key: "validate",
value: function validate(value) {
if (typeof value === 'string') {
return value.length <= this.len;
} else if (typeof value === 'number') {
return value <= this.len;
}
return false;
}
}]);
return MaxLengthValidator;
}(AbstractValidator);
exports.MaxLengthValidator = MaxLengthValidator;
var MatchValidator =
/*#__PURE__*/
function (_AbstractValidator5) {
_inherits(MatchValidator, _AbstractValidator5);
function MatchValidator(selector, msg) {
var _this5;
_classCallCheck(this, MatchValidator);
_this5 = _possibleConstructorReturn(this, (MatchValidator.__proto__ || Object.getPrototypeOf(MatchValidator)).call(this, msg));
_this5.selector = selector;
return _this5;
}
_createClass(MatchValidator, [{
key: "validate",
value: function validate(value) {
var el = document.querySelector(this.selector);
if (!el) {
throw new TypeError("element with selector: \"".concat(this.selector, "\" not found in dom"));
}
var otherValue = view_html_1.getValue(el);
return equaljs.equal(value, otherValue);
}
}]);
return MatchValidator;
}(AbstractValidator);
exports.MatchValidator = MatchValidator;
});
unwrapExports(validators);
var validators_1 = validators.AbstractValidator;
var validators_2 = validators.RequiredValidator;
var validators_3 = validators.RegexValidator;
var validators_4 = validators.EmailValidator;
var validators_5 = validators.MinLengthValidator;
var validators_6 = validators.MaxLengthValidator;
var validators_7 = validators.MatchValidator;
var tim = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
/*!
* Tim (lite)
* github.com/premasagar/tim
*
*/
/**
* This is used by the validator, for interpolating in errors messages
*/
exports.tim = function () {
var start = "{{",
end = "}}",
path = "[a-z0-9_$][\\.a-z0-9_]*",
// e.g. config.person.name
pattern = new RegExp(start + "\\s*(" + path + ")\\s*" + end, "gi"),
undef;
return function (template, data) {
var shouldThrow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
// Merge data into the template string
return template.replace(pattern, function (tag, token) {
var path = token.split("."),
len = path.length,
lookup = data,
i = 0;
for (; i < len; i++) {
lookup = lookup[path[i]]; // Property not found
if (lookup === undef) {
if (shouldThrow) throw new Error("tim: '" + path[i] + "' not found in " + tag);
return '';
} // Return the required value
if (i === len - 1) {
return lookup;
}
}
});
};
}();
});
unwrapExports(tim);
var tim_1 = tim.tim;
var errors = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var ValidationError =
/*#__PURE__*/
function (_Error) {
_inherits(ValidationError, _Error);
function ValidationError(message, validator) {
var _this;
_classCallCheck(this, ValidationError);
_this = _possibleConstructorReturn(this, (ValidationError.__proto__ || Object.getPrototypeOf(ValidationError)).call(this, message));
_this.validator = validator; // TODO: use Object.setPrototypeOf(this, new.target.prototype);
Object.setPrototypeOf(_this, ValidationError.prototype);
return _this;
}
return ValidationError;
}(Error);
exports.ValidationError = ValidationError;
var ValidationErrors =
/*#__PURE__*/
function (_Error2) {
_inherits(ValidationErrors, _Error2);
function ValidationErrors(errors, message) {
var _this2;
_classCallCheck(this, ValidationErrors);
_this2 = _possibleConstructorReturn(this, (ValidationErrors.__proto__ || Object.getPrototypeOf(ValidationErrors)).call(this, message));
_this2.errors = errors; // TODO: use Object.setPrototypeOf(this, new.target.prototype);
Object.setPrototypeOf(_this2, ValidationErrors.prototype);
return _this2;
}
return ValidationErrors;
}(Error);
exports.ValidationErrors = ValidationErrors;
function createError(v, label) {
if (typeof label === 'string') {
label = {
label: label
};
}
var msg = '';
if (v.message) msg = tim.tim(v.message, label);
return new ValidationError(msg, v);
}
exports.createError = createError;
});
unwrapExports(errors);
var errors_1 = errors.ValidationError;
var errors_2 = errors.ValidationErrors;
var errors_3 = errors.createError;
var validator = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var AbstractValidatorCollection =
/*#__PURE__*/
function () {
function AbstractValidatorCollection(key) {
_classCallCheck(this, AbstractValidatorCollection);
this._validators = [];
this._key = key;
}
_createClass(AbstractValidatorCollection, [{
key: "label",
value: function label(_label) {
if (arguments.length == 0) return this._label;
this._label = _label;
return this;
}
}, {
key: "key",
value: function key(_key) {
if (arguments.length == 0) return this._key;
this._key = _key;
return this;
}
}, {
key: "required",
value: function required(msg) {
this._required = new validators.RequiredValidator(msg);
return this;
}
}, {
key: "match",
value: function match(selector, msg) {
return this._addValidator(new validators.MatchValidator(selector, msg));
}
}, {
key: "validate",
value: function validate(value) {
if (this._required) {
if (!this._required.validate(value)) {
var e = errors.createError(this._required, {
label: this._label || '',
key: this._key || ''
});
throw new errors.ValidationErrors([e]);
}
} // Not required, but empty
if (value == null || typeof value === 'string' && value === '') {
return;
}
var errors$$1 = [];
for (var i = 0, ii = this._validators.length; i < ii; i++) {
var _validator = this._validators[i];
if (!_validator.validate(value)) {
errors$$1.push(errors.createError(_validator, {
label: this._label || '',
key: this._key || ''
}));
}
}
if (errors$$1.length) throw new errors.ValidationErrors(errors$$1);
}
}, {
key: "getMessage",
value: function getMessage() {
return "";
}
}, {
key: "_addValidator",
value: function _addValidator(v) {
this._validators.push(v);
return this;
}
}, {
key: "message",
get: function get() {
return this.getMessage();
}
}]);
return AbstractValidatorCollection;
}();
exports.AbstractValidatorCollection = AbstractValidatorCollection;
var StringValidator =
/*#__PURE__*/
function (_AbstractValidatorCol) {
_inherits(StringValidator, _AbstractValidatorCol);
function StringValidator() {
_classCallCheck(this, StringValidator);
return _possibleConstructorReturn(this, (StringValidator.__proto__ || Object.getPrototypeOf(StringValidator)).apply(this, arguments));
}
_createClass(StringValidator, [{
key: "email",
value: function email(msg) {
return this._addValidator(new validators.EmailValidator(msg));
}
}, {
key: "reqexp",
value: function reqexp(req, msg) {
return this._addValidator(new validators.RegexValidator(msg, req));
}
}, {
key: "min",
value: function min(len, msg) {
return this._addValidator(new validators.MinLengthValidator(len, msg));
}
}, {
key: "max",
value: function max(len, msg) {
return this._addValidator(new validators.MaxLengthValidator(len, msg));
}
}]);
return StringValidator;
}(AbstractValidatorCollection);
exports.StringValidator = StringValidator;
});
unwrapExports(validator);
var validator_1 = validator.AbstractValidatorCollection;
var validator_2 = validator.StringValidator;
var decorators = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
function validations(v) {
return function (target) {
target.prototype._validations = v;
};
}
exports.validations = validations;
(function (validations) {
function string(key) {
return new validator.StringValidator(key);
}
validations.string = string;
})(validations = exports.validations || (exports.validations = {}));
});
unwrapExports(decorators);
var decorators_1 = decorators.validations;
var validationView = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
function withValidation(Base) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
event: 'change'
};
function validation_wrap(self, v) {
return function (e) {
var target = e.delegateTarget || e.target;
if (!target) throw new TypeError('no target');
try {
v.validate(view_html_1.getValue(target));
if (typeof this.clearValidationError === 'function') {
this.clearValidationError(target);
}
} catch (e) {
if (typeof this.setValidationError === 'function') {
this.setValidationError(target, e);
}
}
}.bind(self);
}
return (
/*#__PURE__*/
function (_Base) {
_inherits(_class, _Base);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, (_class.__proto__ || Object.getPrototypeOf(_class)).apply(this, arguments));
}
_createClass(_class, [{
key: "render",
value: function render() {
var _this = this;
_get(_class.prototype.__proto__ || Object.getPrototypeOf(_class.prototype), "render", this).call(this);
var v = this._getValidations();
for (var key in v) {
var wrapper = validation_wrap(this, v[key]);
this.delegate(options.event, key, wrapper);
if (options.event !== 'change') this.delegate('change', wrapper); //this.delegate(options.event, key, validation_wrap(this, v[key]));
this.delegate('blur', key, function (e) {
var target = e.delegateTarget,
value = view_html_1.getValue(target);
if (!value) _this.clearValidationError(target);
});
}
return this;
}
}, {
key: "setValidationError",
value: function setValidationError() {}
}, {
key: "clearValidationError",
value: function clearValidationError() {}
}, {
key: "validate",
value: function validate() {
var silent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var v = this._getValidations(),
errors$$1 = [];
for (var key in v) {
var el = this.el.querySelector(key);
try {
v[key].validate(view_html_1.getValue(el));
if (!silent) this.clearValidationError(el);
} catch (e) {
if (!silent) this.setValidationError(el, e);
e.errors.forEach(function (m) {
return errors$$1.push(e);
});
}
}
if (errors$$1.length) {
throw new errors.ValidationErrors(errors$$1);
}
}
}, {
key: "getValue",
value: function getValue() {
var v = this._getValidations(),
out = {};
for (var key in v) {
var el = this.el.querySelector(key),
name = v[key].key() || el.getAttribute('name') || v[key].label() || key;
out[name] = view_html_1.getValue(el);
}
return out;
}
}, {
key: "setValue",
value: function setValue(input) {
var v = this._getValidations();
for (var key in v) {
var el = this.el.querySelector(key),
name = v[key].key() || el.getAttribute('name') || v[key].label() || key;
if (input[name]) {
view_html_1.setValue(el, input[name]);
}
}
}
}, {
key: "clear",
value: function clear() {
var v = this._getValidations();
for (var key in v) {
var el = this.el.querySelector(key);
view_html_1.setValue(el, null);
}
}
}, {
key: "isValid",
value: function isValid() {
try {
this.validate(true);
return true;
} catch (e) {
return false;
}
}
}, {
key: "clearAllErrors",
value: function clearAllErrors() {
var ui = this._ui || this.ui,
v = view_1.normalizeUIKeys(this._validations, ui);
for (var key in v) {
var el = this.el.querySelector(key);
this.clearValidationError(el);
}
return this;
}
}, {
key: "_getValidations",
value: function _getValidations() {
var ui = this._ui || this.ui,
validations = view_1.result(this, '_validations') || this.constructor.validations || {},
v = view_1.normalizeUIKeys(validations, ui);
return v;
}
}]);
return _class;
}(Base)
);
}
exports.withValidation = withValidation;
});
unwrapExports(validationView);
var validationView_1 = validationView.withValidation;
var formView = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true
});
var FormView =
/*#__PURE__*/
function (_validation_view_1$wi) {
_inherits(FormView, _validation_view_1$wi);
function FormView(options) {
_classCallCheck(this, FormView);
return _possibleConstructorReturn(this, (FormView.__proto__ || Object.getPrototypeOf(FormView)).call(this, view_1.extend({
errorMessageClass: 'input-message',
errorClass: 'has-error',
showErrorMessage: true
}, options || {})));
}
_createClass(FormView, [{
key: "setValidationError",
value: function setValidationError(target, errors) {
if (target != document.activeElement) {
// Only show new errors in active element
return;
}
var container = target.parentElement;
if (this.options.showErrorMessage) {
var msg = container.querySelector('.' + this.options.errorMessageClass);
var text = this._getErrorMessage(errors);
if (!msg) {
msg = document.createElement('div');
msg.classList.add(this.options.errorMessageClass);
container.appendChild(msg);
}
msg.innerHTML = text;
msg.classList.remove('hidden');
}
container.classList.add(this.options.errorClass);
view_1.triggerMethodOn(this, 'valid', false);
}
}, {
key: "clearValidationError",
value: function clearValidationError(target) {
var container = target.parentElement;
var msg = container.querySelector('.' + this.options.errorMessageClass);
if (msg) {
msg.innerHTML = '';
msg.classList.add('hidden');
}
container.classList.remove(this.options.errorClass);
view_1.triggerMethodOn(this, 'valid', this.isValid());
}
}, {
key: "_getErrorMessage",
value: function _getErrorMessage(errors) {
return errors.errors.map(function (m) {
return m.message;
}).join('<br/>');
}
}]);
return FormView;
}(validationView.withValidation(view_1.View, {
event: 'keyup'
}));
exports.FormView = FormView;
});
unwrapExports(formView);
var formView_1 = formView.FormView;
var lib = createCommonjsModule(function (module, exports) {
function __export(m) {
for (var p in m) {
if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
}
Object.defineProperty(exports, "__esModule", {
value: true
});
__export(decorators);
__export(validationView);
__export(errors);
__export(formView);
});
var index = unwrapExports(lib);
return index;
})));
<file_sep>/lib/form-view.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const view_1 = require("view");
const validation_view_1 = require("./validation-view");
class FormView extends validation_view_1.withValidation(view_1.View, { event: 'keyup' }) {
constructor(options) {
super(view_1.extend({
errorMessageClass: 'input-message',
errorClass: 'has-error',
showErrorMessage: true
}, options || {}));
}
setValidationError(target, errors) {
if (target != document.activeElement) {
// Only show new errors in active element
return;
}
const container = target.parentElement;
if (this.options.showErrorMessage) {
let msg = container.querySelector('.' + this.options.errorMessageClass);
const text = this._getErrorMessage(errors);
if (!msg) {
msg = document.createElement('div');
msg.classList.add(this.options.errorMessageClass);
container.appendChild(msg);
}
msg.innerHTML = text;
msg.classList.remove('hidden');
}
container.classList.add(this.options.errorClass);
view_1.triggerMethodOn(this, 'valid', false);
}
clearValidationError(target) {
const container = target.parentElement;
let msg = container.querySelector('.' + this.options.errorMessageClass);
if (msg) {
msg.innerHTML = '';
msg.classList.add('hidden');
}
container.classList.remove(this.options.errorClass);
view_1.triggerMethodOn(this, 'valid', this.isValid());
}
_getErrorMessage(errors) {
return errors.errors.map(m => {
return m.message;
}).join('<br/>');
}
}
exports.FormView = FormView;
<file_sep>/src/decorators.ts
import { ValidatorMap } from './types';
import { BaseView, Constructor, UIMap } from 'view';
import { StringValidator } from './validator'
export function validations(v: ValidatorMap | (() => ValidatorMap)) {
return function <T extends Constructor<BaseView<E, U>>, E extends Element, U extends UIMap>(target: T) {
target.prototype._validations = v;
}
}
export namespace validations {
export function string(key?: string) {
return new StringValidator(key);
}
}<file_sep>/lib/types.d.ts
export interface IValidator {
readonly message: string;
validate(value: any): boolean;
}
export interface IValidatorCollection {
validate(value: any): void;
key(): string | undefined;
label(): string | undefined;
}
export declare type ValidatorMap = {
[key: string]: IValidatorCollection;
};
<file_sep>/src/validator.ts
import { IValidator } from './types';
import {
EmailValidator,
MaxLengthValidator,
MinLengthValidator,
RegexValidator,
RequiredValidator,
MatchValidator
} from './validators';
import { createError, ValidationError, ValidationErrors } from './errors';
export abstract class AbstractValidatorCollection<T> {
private _label?: string;
private _key?: string;
private _required?: RequiredValidator;
private _validators: IValidator[] = [];
constructor(key?: string) {
this._key = key;
}
label(label: string): this;
label(): string | undefined;
label(label?: string): any {
if (arguments.length == 0) return this._label;
this._label = label;
return this;
}
key(key: string): this;
key(): string | undefined;
key(key?: string): any {
if (arguments.length == 0) return this._key;
this._key = key;
return this;
}
required(msg?: string) {
this._required = new RequiredValidator(msg);
return this;
}
match(selector: string, msg?: string) {
return this._addValidator(new MatchValidator(selector, msg));
}
get message(): string {
return this.getMessage();
}
validate(value: T | undefined) {
if (this._required) {
if (!this._required.validate(value)) {
let e = createError(this._required, {
label: this._label || '',
key: this._key || ''
});
throw new ValidationErrors([e]);
}
}
// Not required, but empty
if (value == null || (typeof value === 'string' && value === '')) {
return;
}
let errors: ValidationError[] = [];
for (let i = 0, ii = this._validators.length; i < ii; i++) {
const validator = this._validators[i];
if (!validator.validate(value)) {
errors.push(createError(validator, {
label: this._label || '',
key: this._key || ''
}));
}
}
if (errors.length) throw new ValidationErrors(errors);
}
protected getMessage(): string {
return "";
}
protected _addValidator(v: IValidator) {
this._validators.push(v);
return this;
}
}
export class StringValidator extends AbstractValidatorCollection<string> {
email(msg?: string) {
return this._addValidator(new EmailValidator(msg));
}
reqexp(req: RegExp, msg?: string) {
return this._addValidator(new RegexValidator(msg, req));
}
min(len: number, msg?: string) {
return this._addValidator(new MinLengthValidator(len, msg));
}
max(len: number, msg?: string) {
return this._addValidator(new MaxLengthValidator(len, msg));
}
}
<file_sep>/lib/index.d.ts
export * from './decorators';
export * from './types';
export * from './validation-view';
export * from './errors';
export * from './form-view';
<file_sep>/lib/decorators.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const validator_1 = require("./validator");
function validations(v) {
return function (target) {
target.prototype._validations = v;
};
}
exports.validations = validations;
(function (validations) {
function string(key) {
return new validator_1.StringValidator(key);
}
validations.string = string;
})(validations = exports.validations || (exports.validations = {}));
<file_sep>/lib/form-view.d.ts
import { View, BaseViewOptions } from 'view';
import { ValidationErrors } from './errors';
import { IValidationView } from './validation-view';
export interface FormViewOptions extends BaseViewOptions<HTMLElement> {
errorClass?: string;
showErrorMessage?: boolean;
errorMessageClass?: string;
}
declare const FormView_base: (new (...args: any[]) => IValidationView) & typeof View;
export declare class FormView extends FormView_base implements IValidationView {
readonly options: FormViewOptions;
constructor(options?: FormViewOptions);
setValidationError(target: HTMLElement, errors: ValidationErrors): void;
clearValidationError(target: HTMLElement): void;
protected _getErrorMessage(errors: ValidationErrors): string;
}
<file_sep>/src/types.ts
export interface IValidator {
readonly message: string;
validate(value: any): boolean;
}
export interface IValidatorCollection {
validate(value: any): void;
key(): string | undefined;
label(): string | undefined;
}
export type ValidatorMap = { [key: string]: IValidatorCollection }<file_sep>/lib/validator.d.ts
import { IValidator } from './types';
export declare abstract class AbstractValidatorCollection<T> {
private _label?;
private _key?;
private _required?;
private _validators;
constructor(key?: string);
label(label: string): this;
label(): string | undefined;
key(key: string): this;
key(): string | undefined;
required(msg?: string): this;
match(selector: string, msg?: string): this;
readonly message: string;
validate(value: T | undefined): void;
protected getMessage(): string;
protected _addValidator(v: IValidator): this;
}
export declare class StringValidator extends AbstractValidatorCollection<string> {
email(msg?: string): this;
reqexp(req: RegExp, msg?: string): this;
min(len: number, msg?: string): this;
max(len: number, msg?: string): this;
}
<file_sep>/src/form-view.ts
import { View, BaseViewOptions, extend, triggerMethodOn } from 'view';
import { ValidationErrors } from './errors'
import { withValidation, IValidationView } from './validation-view';
export interface FormViewOptions extends BaseViewOptions<HTMLElement> {
errorClass?: string;
showErrorMessage?: boolean;
errorMessageClass?: string;
}
export class FormView extends withValidation(View, { event: 'keyup' }) implements IValidationView {
readonly options: FormViewOptions;
constructor(options?: FormViewOptions) {
super(extend({
errorMessageClass: 'input-message',
errorClass: 'has-error',
showErrorMessage: true
}, options || {}));
}
setValidationError(target: HTMLElement, errors: ValidationErrors) {
if (target != document.activeElement) {
// Only show new errors in active element
return;
}
const container = target.parentElement!
if (this.options.showErrorMessage) {
let msg = container.querySelector('.' + this.options.errorMessageClass!);
const text = this._getErrorMessage(errors);
if (!msg) {
msg = document.createElement('div');
msg.classList.add(this.options.errorMessageClass!);
container.appendChild(msg);
}
msg.innerHTML = text;
msg.classList.remove('hidden');
}
container.classList.add(this.options.errorClass!);
triggerMethodOn(this, 'valid', false);
}
clearValidationError(target: HTMLElement) {
const container = target.parentElement!
let msg = container.querySelector('.' + this.options.errorMessageClass!);
if (msg) {
msg.innerHTML = '';
msg.classList.add('hidden');
}
container.classList.remove(this.options.errorClass!);
triggerMethodOn(this, 'valid', this.isValid());
}
protected _getErrorMessage(errors: ValidationErrors) {
return errors.errors.map(m => {
return m.message;
}).join('<br/>');
}
}<file_sep>/src/errors.ts
import { IValidator } from './types';
import { tim } from './tim';
export class ValidationError extends Error {
message: string;
constructor(message: string, public validator?: IValidator) {
super(message);
// TODO: use Object.setPrototypeOf(this, new.target.prototype);
Object.setPrototypeOf(this, ValidationError.prototype);
}
}
export class ValidationErrors extends Error {
constructor(public errors: ValidationError[], message?: string) {
super(message);
// TODO: use Object.setPrototypeOf(this, new.target.prototype);
Object.setPrototypeOf(this, ValidationErrors.prototype);
}
}
export function createError(v: IValidator | { message: string }, label?: string | { [key: string]: string }) {
if (typeof label === 'string') {
label = { label: label };
}
let msg = '';
if (v.message)
msg = tim(v.message, label);
return new ValidationError(msg, v as any);
}<file_sep>/lib/validation-view.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("./errors");
const view_1 = require("view");
const view_html_1 = require("view.html");
function withValidation(Base, options = { event: 'change' }) {
function validation_wrap(self, v) {
return function (e) {
let target = e.delegateTarget || e.target;
if (!target)
throw new TypeError('no target');
try {
v.validate(view_html_1.getValue(target));
if (typeof this.clearValidationError === 'function') {
this.clearValidationError(target);
}
}
catch (e) {
if (typeof this.setValidationError === 'function') {
this.setValidationError(target, e);
}
}
}.bind(self);
}
return class extends Base {
render() {
super.render();
const v = this._getValidations();
for (let key in v) {
const wrapper = validation_wrap(this, v[key]);
this.delegate(options.event, key, wrapper);
if (options.event !== 'change')
this.delegate('change', wrapper);
//this.delegate(options.event, key, validation_wrap(this, v[key]));
this.delegate('blur', key, (e) => {
let target = e.delegateTarget, value = view_html_1.getValue(target);
if (!value)
this.clearValidationError(target);
});
}
return this;
}
setValidationError(..._) { }
clearValidationError(..._) { }
validate(silent = false) {
const v = this._getValidations(), errors = [];
for (let key in v) {
let el = this.el.querySelector(key);
try {
v[key].validate(view_html_1.getValue(el));
if (!silent)
this.clearValidationError(el);
}
catch (e) {
if (!silent)
this.setValidationError(el, e);
e.errors.forEach(m => errors.push(e));
}
}
if (errors.length) {
throw new errors_1.ValidationErrors(errors);
}
}
getValue() {
const v = this._getValidations(), out = {};
for (let key in v) {
const el = this.el.querySelector(key), name = v[key].key() || el.getAttribute('name') || v[key].label() || key;
out[name] = view_html_1.getValue(el);
}
return out;
}
setValue(input) {
const v = this._getValidations();
for (let key in v) {
const el = this.el.querySelector(key), name = v[key].key() || el.getAttribute('name') || v[key].label() || key;
if (input[name]) {
view_html_1.setValue(el, input[name]);
}
}
}
clear() {
const v = this._getValidations();
for (let key in v) {
const el = this.el.querySelector(key);
view_html_1.setValue(el, null);
}
}
isValid() {
try {
this.validate(true);
return true;
}
catch (e) {
return false;
}
}
clearAllErrors() {
const ui = this._ui || this.ui, v = view_1.normalizeUIKeys(this._validations, ui);
for (let key in v) {
let el = this.el.querySelector(key);
this.clearValidationError(el);
}
return this;
}
_getValidations() {
const ui = this._ui || this.ui, validations = view_1.result(this, '_validations') || this.constructor.validations || {}, v = view_1.normalizeUIKeys(validations, ui);
return v;
}
};
}
exports.withValidation = withValidation;
<file_sep>/src/tim.ts
/*!
* Tim (lite)
* github.com/premasagar/tim
*
*/
/**
* This is used by the validator, for interpolating in errors messages
*/
export const tim = (function () {
"use strict";
var start = "{{",
end = "}}",
path = "[a-z0-9_$][\\.a-z0-9_]*", // e.g. config.person.name
pattern = new RegExp(start + "\\s*(" + path + ")\\s*" + end, "gi"),
undef: undefined;
return function (template: string, data?: any, shouldThrow: boolean = true) {
// Merge data into the template string
return template.replace(pattern, function (tag, token) {
var path = token.split("."),
len = path.length,
lookup = data,
i = 0;
for (; i < len; i++) {
lookup = lookup[path[i]];
// Property not found
if (lookup === undef) {
if (shouldThrow)
throw new Error("tim: '" + path[i] + "' not found in " + tag);
return '';
}
// Return the required value
if (i === len - 1) {
return lookup;
}
}
});
};
}());
<file_sep>/src/validation-view.ts
import { ValidationErrors, ValidationError } from './errors';
import { Constructor, BaseViewConstructor, BaseView, normalizeUIKeys, DelegateEvent, result } from 'view';
import { getValue, setValue } from 'view.html';
import { IValidatorCollection, ValidatorMap } from './types';
export interface IValidationView {
/**
* Validate view. Throws a ValidationErrors on error
* Will all call setValidationError on error, and clearValidationError when no error
*
* @param {boolean} [silent]
* @memberof IValidationView
*/
validate(silent?: boolean): void;
/**
* Check if the view validates to true
*
* @returns {boolean}
* @memberof IValidationView
*/
isValid(): boolean;
/**
* Get the values of the elements defined in the validation hash
*
* @returns {{ [key: string]: any }}
* @memberof IValidationView
*/
getValue(): { [key: string]: any };
/**
* Set the values of the elements defined in the validation hash
*
* @param {{ [key: string]: any }} value
* @memberof IValidationView
*/
setValue(value: { [key: string]: any }): void;
/**
* Clear the value (set to empty) of all the elements defined in the validation hash
*
* @memberof IValidationView
*/
clear(): void;
/**
* This is called when a element is invalid
*
* @param {HTMLElement} target
* @param {ValidationErrors} error
* @memberof IValidationView
*/
setValidationError(target: HTMLElement, error: ValidationErrors): void;
clearValidationError(target: HTMLElement): void;
clearAllErrors(): this;
}
export interface ValidationViewOptions {
event: string;
}
export function withValidation<T extends BaseViewConstructor<BaseView<E>, E>, E extends Element>(Base: T, options: ValidationViewOptions = { event: 'change' }): Constructor<IValidationView> & T {
function validation_wrap<T extends any>(self: T, v: IValidatorCollection) {
return function (this: T, e: DelegateEvent) {
let target = e.delegateTarget || e.target;
if (!target) throw new TypeError('no target');
try {
v.validate(getValue(target as HTMLElement));
if (typeof this.clearValidationError === 'function') {
this.clearValidationError(target);
}
} catch (e) {
if (typeof this.setValidationError === 'function') {
this.setValidationError(target, e);
}
}
}.bind(self);
}
return class extends Base {
private _validations: ValidatorMap | ((this: T) => ValidatorMap);
render() {
super.render()
const v = this._getValidations();
for (let key in v) {
const wrapper = validation_wrap(this, v[key]);
this.delegate(options.event, key, wrapper);
if (options.event !== 'change')
this.delegate('change', wrapper)
//this.delegate(options.event, key, validation_wrap(this, v[key]));
this.delegate('blur', key, (e: DelegateEvent) => {
let target = e.delegateTarget as HTMLElement,
value = getValue(target);
if (!value) this.clearValidationError(target);
});
}
return this;
}
setValidationError(..._: any[]) { }
clearValidationError(..._: any[]) { }
validate(silent: boolean = false): void {
const v = this._getValidations(),
errors = [] as ValidationError[];
for (let key in v) {
let el = this.el!.querySelector(key);
try {
v[key].validate(getValue(el as HTMLElement));
if (!silent)
this.clearValidationError(el!);
} catch (e) {
if (!silent)
this.setValidationError(el!, e);
(e as ValidationErrors).errors.forEach(m => errors.push(e));
}
}
if (errors.length) {
throw new ValidationErrors(errors);
}
}
getValue() {
const v = this._getValidations(),
out: { [key: string]: any } = {};
for (let key in v) {
const el = this.el!.querySelector(key),
name = v[key].key() || el!.getAttribute('name') || v[key].label() || key;
out[name] = getValue(el as HTMLElement);
}
return out;
}
setValue(input: { [key: string]: any }) {
const v = this._getValidations();
for (let key in v) {
const el = this.el!.querySelector(key) as HTMLElement,
name = v[key].key() || el!.getAttribute('name') || v[key].label() || key;
if (input[name]) {
setValue(el!, input[name]);
}
}
}
clear() {
const v = this._getValidations();
for (let key in v) {
const el = this.el!.querySelector(key) as HTMLElement;
setValue(el, null);
}
}
isValid() {
try {
this.validate(true);
return true;
} catch (e) {
return false;
}
}
clearAllErrors() {
const ui = (<any>this)._ui || this.ui,
v: any = normalizeUIKeys(this._validations, ui);
for (let key in v) {
let el = this.el!.querySelector(key);
this.clearValidationError(el!);
}
return this;
}
private _getValidations(): ValidatorMap {
const ui = (<any>this)._ui || this.ui,
validations = result(this, '_validations') || (<any>this.constructor).validations || {},
v: any = normalizeUIKeys(validations, ui);
return v;
}
}
}
<file_sep>/src/validators.ts
import { getValue } from 'view.html';
import { IValidator } from './types';
import { equal } from 'equaljs';
export abstract class AbstractValidator {
message: string;
constructor(msg?: string) {
if (msg) this.message = msg;
}
}
export class RequiredValidator extends AbstractValidator implements IValidator {
validate(value: any): boolean {
if (value === null || value === void 0) return false;
if (typeof value === 'string' && value == '') return false;
return true;
}
constructor(msg: string = "{{label}} mangler") {
super(msg);
}
}
export class RegexValidator extends AbstractValidator implements IValidator {
readonly regex: RegExp;
constructor(msg: string = "{{label}} er invalid", regex?: RegExp) {
super(msg);
(<any>this).regex = regex;
}
validate(value: any): boolean {
return this.regex.test(String(value));
}
}
export class EmailValidator extends RegexValidator {
regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
constructor(msg: string = "{{label}} er ikke en valid email") {
super(msg);
}
}
export class MinLengthValidator extends AbstractValidator implements IValidator {
len: number;
constructor(n: number, msg?: string) {
super(msg);
this.len = n;
}
validate(value: any): boolean {
if (typeof value === 'string') {
return value.length >= this.len;
} else if (typeof value === 'number') {
return value >= this.len;
}
return false;
}
}
export class MaxLengthValidator extends AbstractValidator implements IValidator {
len: number;
constructor(n: number, msg?: string) {
super(msg);
this.len = n;
}
validate(value: any): boolean {
if (typeof value === 'string') {
return value.length <= this.len;
} else if (typeof value === 'number') {
return value <= this.len;
}
return false;
}
}
export class MatchValidator extends AbstractValidator implements IValidator {
constructor(private selector: string, msg?: string) {
super(msg);
}
validate(value: any): boolean {
const el = document.querySelector(this.selector) as HTMLElement;
if (!el) {
throw new TypeError(`element with selector: "${this.selector}" not found in dom`);
}
const otherValue = getValue(el!);
return equal(value, otherValue);
}
}
<file_sep>/lib/validators.d.ts
import { IValidator } from './types';
export declare abstract class AbstractValidator {
message: string;
constructor(msg?: string);
}
export declare class RequiredValidator extends AbstractValidator implements IValidator {
validate(value: any): boolean;
constructor(msg?: string);
}
export declare class RegexValidator extends AbstractValidator implements IValidator {
readonly regex: RegExp;
constructor(msg?: string, regex?: RegExp);
validate(value: any): boolean;
}
export declare class EmailValidator extends RegexValidator {
regex: RegExp;
constructor(msg?: string);
}
export declare class MinLengthValidator extends AbstractValidator implements IValidator {
len: number;
constructor(n: number, msg?: string);
validate(value: any): boolean;
}
export declare class MaxLengthValidator extends AbstractValidator implements IValidator {
len: number;
constructor(n: number, msg?: string);
validate(value: any): boolean;
}
export declare class MatchValidator extends AbstractValidator implements IValidator {
private selector;
constructor(selector: string, msg?: string);
validate(value: any): boolean;
}
<file_sep>/lib/errors.d.ts
import { IValidator } from './types';
export declare class ValidationError extends Error {
validator: IValidator | undefined;
message: string;
constructor(message: string, validator?: IValidator | undefined);
}
export declare class ValidationErrors extends Error {
errors: ValidationError[];
constructor(errors: ValidationError[], message?: string);
}
export declare function createError(v: IValidator | {
message: string;
}, label?: string | {
[key: string]: string;
}): ValidationError;
<file_sep>/lib/validators.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const view_html_1 = require("view.html");
const equaljs_1 = require("equaljs");
class AbstractValidator {
constructor(msg) {
if (msg)
this.message = msg;
}
}
exports.AbstractValidator = AbstractValidator;
class RequiredValidator extends AbstractValidator {
validate(value) {
if (value === null || value === void 0)
return false;
if (typeof value === 'string' && value == '')
return false;
return true;
}
constructor(msg = "{{label}} mangler") {
super(msg);
}
}
exports.RequiredValidator = RequiredValidator;
class RegexValidator extends AbstractValidator {
constructor(msg = "{{label}} er invalid", regex) {
super(msg);
this.regex = regex;
}
validate(value) {
return this.regex.test(String(value));
}
}
exports.RegexValidator = RegexValidator;
class EmailValidator extends RegexValidator {
constructor(msg = "{{label}} er ikke en valid email") {
super(msg);
this.regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
}
}
exports.EmailValidator = EmailValidator;
class MinLengthValidator extends AbstractValidator {
constructor(n, msg) {
super(msg);
this.len = n;
}
validate(value) {
if (typeof value === 'string') {
return value.length >= this.len;
}
else if (typeof value === 'number') {
return value >= this.len;
}
return false;
}
}
exports.MinLengthValidator = MinLengthValidator;
class MaxLengthValidator extends AbstractValidator {
constructor(n, msg) {
super(msg);
this.len = n;
}
validate(value) {
if (typeof value === 'string') {
return value.length <= this.len;
}
else if (typeof value === 'number') {
return value <= this.len;
}
return false;
}
}
exports.MaxLengthValidator = MaxLengthValidator;
class MatchValidator extends AbstractValidator {
constructor(selector, msg) {
super(msg);
this.selector = selector;
}
validate(value) {
const el = document.querySelector(this.selector);
if (!el) {
throw new TypeError(`element with selector: "${this.selector}" not found in dom`);
}
const otherValue = view_html_1.getValue(el);
return equaljs_1.equal(value, otherValue);
}
}
exports.MatchValidator = MatchValidator;
<file_sep>/lib/tim.d.ts
/*!
* Tim (lite)
* github.com/premasagar/tim
*
*/
/**
* This is used by the validator, for interpolating in errors messages
*/
export declare const tim: (template: string, data?: any, shouldThrow?: boolean) => string;
<file_sep>/lib/validation-view.d.ts
import { ValidationErrors } from './errors';
import { Constructor, BaseViewConstructor, BaseView } from 'view';
export interface IValidationView {
/**
* Validate view. Throws a ValidationErrors on error
* Will all call setValidationError on error, and clearValidationError when no error
*
* @param {boolean} [silent]
* @memberof IValidationView
*/
validate(silent?: boolean): void;
/**
* Check if the view validates to true
*
* @returns {boolean}
* @memberof IValidationView
*/
isValid(): boolean;
/**
* Get the values of the elements defined in the validation hash
*
* @returns {{ [key: string]: any }}
* @memberof IValidationView
*/
getValue(): {
[key: string]: any;
};
/**
* Set the values of the elements defined in the validation hash
*
* @param {{ [key: string]: any }} value
* @memberof IValidationView
*/
setValue(value: {
[key: string]: any;
}): void;
/**
* Clear the value (set to empty) of all the elements defined in the validation hash
*
* @memberof IValidationView
*/
clear(): void;
/**
* This is called when a element is invalid
*
* @param {HTMLElement} target
* @param {ValidationErrors} error
* @memberof IValidationView
*/
setValidationError(target: HTMLElement, error: ValidationErrors): void;
clearValidationError(target: HTMLElement): void;
clearAllErrors(): this;
}
export interface ValidationViewOptions {
event: string;
}
export declare function withValidation<T extends BaseViewConstructor<BaseView<E>, E>, E extends Element>(Base: T, options?: ValidationViewOptions): Constructor<IValidationView> & T;
|
e15b27d5f318c8a5ee8ae733ffff61b7255c17bd
|
[
"JavaScript",
"TypeScript"
] | 22 |
TypeScript
|
kildevaeld/view.validation
|
504c3d1729e46de28b45467c5c88d85396b48b28
|
1985f4fca73150fd67ecde703849f1b54a7b9479
|
refs/heads/master
|
<repo_name>KeyserJames/DemoSite<file_sep>/api/api/views.py
from django.shortcuts import render
from rest_framework import generics
from rest_framework.response import Response
from .models import InputModel
from .serializers import InputSerializer
# Create your views here.
class InputTextAll(generics.ListCreateAPIView):
queryset = InputModel.objects.all()
serializer_class = InputSerializer
class InputTextSingle(generics.RetrieveUpdateDestroyAPIView):
queryset = InputModel.objects.all()
serializer_class = InputSerializer<file_sep>/README.md
# Simple DemoSite

Frontend hosted here: https://simple-front-api.herokuapp.com
API hosted here (not browseable): https://demo-site-api-app.herokuapp.com/
Endpoint | Function
------------ | -------------
/api/ | GET, POST
/api/\<key\>/ | GET, PUT, DELETE
<file_sep>/api/api/models.py
from django.db import models
# Create your models here.
class InputModel(models.Model):
inputText = models.TextField()
def __str__(self):
return self.inputText<file_sep>/api/api/urls.py
from django.urls import path
from api import views
urlpatterns = [
path('', views.InputTextAll.as_view()),
path('<int:pk>/', views.InputTextSingle.as_view()),
]<file_sep>/api/api/serializers.py
from rest_framework import serializers
from .models import InputModel
class InputSerializer(serializers.ModelSerializer):
class Meta:
model = InputModel
fields = ('inputText',)
|
e2defa9ba43af0d2a9150f1caa2d73ce3e6a0300
|
[
"Markdown",
"Python"
] | 5 |
Python
|
KeyserJames/DemoSite
|
4e38cb4e2783ac16480d917cb099e00fc5ca044c
|
7dfd4e07bbccfbfeef41cd6c780f3fe471d2957c
|
refs/heads/master
|
<file_sep># Password Strength Calculator
This script return password strength score from 1 to 10 where 10
is most secure one. To score 10 password must be 13 characters long
with upper and lowercase, numbers and special characters.
There is a filter for most common passwords, repetitions,
common family names and dates.
Script is require the blacklist of widely used passwords to check if
given password doesn't have match. You can download one the latest
compilation from here:
https://github.com/danielmiessler/SecLists/tree/master/Passwords
# How to run
script require python3.5 Example of script launch on Linux, Python 3.5:
```#!bash
$ python password_strength.py <blacklist_path> # possibly requires call of python3 executive instead of just python
Password: <<PASSWORD>>
$ python password_strength.py brut_force_dict.list
>>> Password: <PASSWORD>
>>> 1
$ python password_strength.py brut_force_dict.list
>>> Password: <PASSWORD>$
>>> 10
$ python password_strength.py brut_force_dict.list
>>> Password: <PASSWORD>
>>> 5
```
You can not see password while typing it in console cause it's more secure
# Project Goals
The code is written for educational purposes. Training course for web-developers - [DEVMAN.org](https://devman.org)
<file_sep>import re
import sys
from math import log2
import getpass
import requests
def check_slavonic_family_names(password):
name_pattern = re.compile(r'[A-z]+(ov|ich|ko|ev|in|ik|uk|off)')
return re.sub(name_pattern, 'n', password)
def check_phones(password):
return re.sub(r'''(\+\d{1,3})? # international code from 1 to 3 digits
[-]? # posible -
\(? # posible (
(\d{1,3}?)? # domestic code from 1 to 3 digits
\)? # posible )
[-]? # posible -
(\d{1,3}) # 3 digits
[-]? # posible -
(\d{2}) # 2 digits
[-]? # posible -
(\d{2} # 2 digits
)''', 'p', password, flags=re.X)
def check_dates(password):
date_pattern = re.compile(r'''(([\d]{2}) # day - two digitals
(\W|_)? # possible ' ' or _
([A-z]{3}|[\d]{2}) # month - 3 letters or 2 digits
(\W|_)? # possible ' ' or _
(19|20)([\d]{2})) # year
| # or
(([A-z]{3}|[\d]{2}) # month - 3 letters or 2 digits
(\W|_)? # possible ' ' or _
([\d]{2}) # day - two digits
(\W|_)? # possible ' ' or _
(19|20)([\d]{2})) # year
''', re.X)
return re.sub(date_pattern, 'd', password)
def check_repetitions(password):
pattern = re.compile(r"(.+?)\1+")
index = 1
repeated = re.findall(pattern, password)
for repeat in repeated:
split = password.split(repeat)
split.insert(index, repeat)
res = ''
for occurrence in split:
res += occurrence
password = res
return password
def load_blacklist(blacklist_path):
try:
with open(blacklist_path) as blacklist_dict_file:
blacklist = [row.strip() for row in blacklist_dict_file]
return str(blacklist)
except IOError:
return None
def check_blacklist(password, blacklist):
if not password:
return None
if not blacklist:
return password
if password in blacklist:
password = 'b'
return password
def get_password_strength(password, blacklist_path):
if not password:
return None
if not blacklist_path:
pass
else:
password = check_blacklist(password, load_blacklist(blacklist_path))
checks = (
check_dates,
check_slavonic_family_names,
check_phones,
check_repetitions
)
for check in checks:
password = check(password)
all_chars_count = {
'[a-z]': 26,
'[A-Z]': 26,
'\d': 10,
'\W|_': 32
}
variations = 0
for chars_group in all_chars_count.items():
if bool(re.search(chars_group[0], password)):
variations += chars_group[1]
password_entropy = log2(variations) * len(password)
score_tuning = 8
strength = round(password_entropy / score_tuning)
min_strength, max_strength = 1, 10
strength = max(min(max_strength, strength), min_strength)
return strength
if __name__ == '__main__':
password = <PASSWORD>()
try:
blacklist_path = sys.argv[1]
except IndexError:
blacklist_path = None
print(get_password_strength(password, blacklist_path))
|
fc406bd777a5824f6727c7214faf5b3e846abe7b
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
korabkoff/6_password_strength
|
f90bbcef5dba1bed16c434a74b41db7cfa8e5b3c
|
03351f37c9dff34eb079afca2f4f057f71ea678e
|
refs/heads/master
|
<repo_name>Will16/Wingman<file_sep>/Parse/Wingman/BrowseTableViewController.swift
//
// BrowseTableViewController.swift
// Wingman
//
// Created by <NAME> on 3/3/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class BrowseTableViewController: UITableViewController, userLocationProtocol, CLLocationManagerDelegate {
var phoneNumber: String?
var wingmen: [[String:AnyObject]] = []
var arrayOfRegisterInfo = [[String: AnyObject]]()
var arrayOfPostData = [[String: AnyObject]]()
var userLocation: CLLocation?
var tabBarImageView: UIImageView?
var gender: String?
var seekingGender: String?
// var tempGeoPoint = PFGeoPoint(latitude: 33.78604932800356, longitude: -84.37840104103088)
override func viewDidLoad() {
super.viewDidLoad()
GlobalVariableSharedInstance.delegate = self
GlobalVariableSharedInstance.startUpdatingLocation()
self.loadCurrentUserAndThenLoadUsers()
tabBarImageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
tabBarImageView!.clipsToBounds = true
tabBarImageView!.contentMode = .ScaleAspectFill
tabBarImageView!.hidden = true
let image = UIImage(named: "bar")
tabBarImageView!.image = image
navigationItem.titleView = tabBarImageView
// tableView.separatorColor = UIColor.blueColor()
tableView.layoutMargins = UIEdgeInsetsZero
tableView.separatorInset = UIEdgeInsetsZero
let gradientView = GradientView(frame: CGRectMake(view.bounds.origin.x, view.bounds.origin.y, view.bounds.size.width, view.bounds.size.height))
// Set the gradient colors
gradientView.colors = [UIColor.blackColor(), UIColor.darkGrayColor()]
// Optionally set some locations
// gradientView.locations = [0.0, 1.0]
// Optionally change the direction. The default is vertical.
gradientView.direction = .Vertical
//
// gradientView.topBorderColor = UIColor.blueColor()
// gradientView.bottomBorderColor = UIColor.blueColor()
//
//
tableView.backgroundView = gradientView
// self.tableView.hidden = true
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
tabBarImageView!.hidden = true
// self.tableView.hidden = true
self.tableView.backgroundColor = UIColor.blackColor()
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let backButton = UIBarButtonItem()
let backButtonImage = UIImage(named: "backbutton")
backButton.setBackButtonBackgroundImage(backButtonImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
self.navigationController?.navigationItem.backBarButtonItem = backButton
}
override func viewDidAppear(animated: Bool) {
// self.tableView.hidden = false
self.tableView.backgroundColor = UIColor.blackColor()
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let backButton = UIBarButtonItem()
let backButtonImage = UIImage(named: "backbutton")
backButton.setBackButtonBackgroundImage(backButtonImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
self.navigationController?.navigationItem.backBarButtonItem = backButton
tabBarImageView!.hidden = false
springScaleFrom(tabBarImageView!, x: 0, y: -100, scaleX: 0.5, scaleY: 0.5)
// addBlurEffect()
}
func addBlurEffect() {
// Add blur view
let bounds = self.navigationController?.navigationBar.bounds as CGRect!
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView
visualEffectView.frame = bounds
visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
self.navigationController?.navigationBar.addSubview(visualEffectView) // Here you can add visual effects to any UIView control.
// Replace custom view with navigation bar in above code to add effects to custom view.
}
func loadCurrentUserAndThenLoadUsers() {
let query = PFUser.query()
query.whereKey("objectId", equalTo: PFUser.currentUser().objectId)
print("OBJECTID + \(PFUser.currentUser().objectId)")
query.findObjectsInBackgroundWithBlock() {
(objects:[AnyObject]!, error:NSError!)->Void in
if ((error) == nil) {
if let user = objects.last as! PFUser? {
// if we created a postData, the user has a wingmanGender in parse that user is seeking
if let seekingGender = user["wingmanGender"] as! String? {
if let gender = user["gender"] as! String? {
self.gender = gender
self.seekingGender = seekingGender
self.loadUsers(self.seekingGender, ourGender: self.gender)
}
}
else {
self.loadUsers(self.seekingGender, ourGender: self.gender)
}
}
}
}
}
func loadUsers(seekingGender: String?, ourGender: String?) {
// var query = PFQuery(className:"_User")
let query = PFUser.query()
query.whereKeyExists("postData")
query.whereKey("objectId", notEqualTo: PFUser.currentUser().objectId)
// query.whereKey("location", nearGeoPoint: tempGeoPoint, withinMiles: 1000)
if (self.userLocation != nil) {
query.whereKey("location", nearGeoPoint: PFGeoPoint(location: userLocation), withinMiles: 1000)
}
// if we have a seekingGender, then load only users whose gender is our seekingGender, else return all users that are not current user (never go into that loop)
if let seekingGender = seekingGender as String? {
if let ourGender = ourGender as String? {
if seekingGender == "both" {
query.whereKey("wingmanGender", equalTo: ourGender)
}
else {
query.whereKey("gender", equalTo: seekingGender)
query.whereKey("wingmanGender", equalTo: ourGender)
}
}
}
query.findObjectsInBackgroundWithBlock() {
(objects:[AnyObject]!, error:NSError!)->Void in
if ((error) == nil) {
self.arrayOfPostData.removeAll()
self.arrayOfRegisterInfo.removeAll()
for user in objects {
if let registerInfo = user["registerInfo"] as? [String: AnyObject] {
self.arrayOfRegisterInfo.append(registerInfo)
}
if let postData = user["postData"] as? [String: AnyObject] {
self.arrayOfPostData.append(postData)
}
}
}
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.arrayOfRegisterInfo.count
}
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! BrowseTableViewCell
cell.selectionStyle = .None
cell.contentView.backgroundColor = UIColor.clearColor()
cell.backgroundColor = UIColor.clearColor()
var registerInfo = self.arrayOfRegisterInfo[indexPath.row]
if let imageFile = registerInfo["imageFile"] as? PFFile {
imageFile.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) in
if (error == nil) {
let image : UIImage = UIImage(data:imageData)!
//image object implementation
cell.userImage.image = image
}
else {
print(error.description)
}
})
}
if let username = registerInfo["username"] as? String {
cell.usernameLabel.text = username
}
var postData = self.arrayOfPostData[indexPath.row]
if let clubOrBar = postData["clubOrBar"] as? String {
cell.clubOrBarLabel.text = clubOrBar
}
// if let seeking = postData["wingmanGender"] as? String {
//
// cell.seekingLabel.text = "Seeking: \(seeking)"
//
// }
if let startTimeInt = postData["startTime"] as? Int {
if let endTimeInt = postData["endTime"] as? Int {
cell.timeLabel.text = "From: \(startTimeInt) To: \(endTimeInt)"
}
}
if let userLocation = self.userLocation {
if let venueLocation = postData["location"] as? PFGeoPoint {
if let venueLocation = CLLocation(latitude: venueLocation.latitude, longitude: venueLocation.longitude) as CLLocation? {
//
// let tempCLLocation = CLLocation(latitude: self.tempGeoPoint!.latitude, longitude: self.tempGeoPoint!.longitude) as CLLocation?
//convert meters into miles
// let dist1 = venueLocation.distanceFromLocation(tempCLLocation!) * 0.00062137
let dist1 = venueLocation.distanceFromLocation(userLocation) * 0.00062137
//rounding to nearest hundredth
let dist2 = Double(round(100 * dist1) / 100)
cell.distanceLabel.text = "\(dist2) mi from you"
print("THE DISTANCE: \(dist2)", terminator: "")
}
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let cell: BrowseTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as BrowseTableViewCell
//didn't connect segue in storyboard so doing it programmatically here
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("browseDetailVC") as! BrowseDetailViewController
//self for global variables/properties
let registerInfo = self.arrayOfRegisterInfo[indexPath.row]
var postData = self.arrayOfPostData[indexPath.row]
//sending data to BrowseDetailViewController
vc.registerInfo = registerInfo
vc.postData = postData
if let phoneNumber = postData["phonenumber"] as! String? {
// self.phoneNumber = phoneNumber
vc.phoneNumber = phoneNumber
self.navigationController?.pushViewController(vc, animated: true)
}
}
func didReceiveUserLocation(location: CLLocation) {
userLocation = location
self.loadCurrentUserAndThenLoadUsers()
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//
// if segue.identifier == "phoneSegue" {
//
//
//
// let vc = segue.destinationViewController as TextMessageViewController
//
// println(phoneNumber)
// vc.phoneNumber = self.phoneNumber
//
// }
//
// }
}
<file_sep>/Rails/Wingman/FourSquareAPI.swift
//
// FourSquareAPI.swift
// Wingman
//
// Created by <NAME> on 3/10/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
import CoreLocation
let API_URL = "https://api.foursquare.com/v2/"
let CLIENT_ID = "YMDIMRRGBX5CKCZJ2AAUTC55WM0AU1SCDF51BF44BO4R0QKZ"
let CLIENT_SECRET = "<KEY>"
let version = "20150310"
protocol FoursquareAPIProtocol {
func didReceiveVenues(results: [ClubOrBarVenues])
}
class FourSquareAPI: NSObject {
let radiusInMeters = 100000 //foursquare max radius is 100k meters
let categoryId = "4d4b7105d754a06376d81259"
let data = NSMutableData()
var delegate: PickerViewController?
func searchForClubOrBarAtLocation(userLocation: CLLocation) {
print("run method")
let urlPath = "\(API_URL)venues/search?ll=\(userLocation.coordinate.latitude),\(userLocation.coordinate.longitude)&limit=100&categoryId=\(categoryId)&radius=\(radiusInMeters)&client_id=\(CLIENT_ID)&client_secret=\(CLIENT_SECRET)&v=\(version)"
print(urlPath)
let url = NSURL(string: urlPath)
let request = NSURLRequest(URL: url!)
let session: NSURLSession = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("create session")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if((error) != nil) {
print(error!.localizedDescription)
}
else {
var venues = [ClubOrBarVenues]()
if json!.count>0 {
if let response: NSDictionary = json!["response"] as? NSDictionary {
print("\(response)")
let allVenues: [NSDictionary] = response["venues"] as! [NSDictionary]
for venue:NSDictionary in allVenues {
var venueName:String = venue["name"] as! String
var location:NSDictionary = venue["location"] as! NSDictionary
var venueLocation:CLLocation = CLLocation(latitude: location["lat"] as! Double, longitude: location["lng"] as! Double)
venues.append(ClubOrBarVenues(name: venueName, location: venueLocation, distanceFromUser: venueLocation.distanceFromLocation(userLocation)))
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate?.didReceiveVenues(venues)
print(venues)
})
}
}
}
catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
})
task.resume()
}
}<file_sep>/Parse/LocationManager.swift
//
// LocationManager.swift
// ImageUploader
//
// Created by Root on 03/08/14.
//
//
import Foundation
import UIKit
import CoreLocation
protocol userLocationProtocol {
func didReceiveUserLocation(location: CLLocation)
}
let GlobalVariableSharedInstance = LocationManager()
class LocationManager: NSObject, CLLocationManagerDelegate
{
var delegate: userLocationProtocol?
var coreLocationManager = CLLocationManager()
/*
if CLLocationManager.locationServicesEnabled() {
coreLocationManager.startUpdatingLocation()
}
*/
class var SharedLocationManager: LocationManager
{
GlobalVariableSharedInstance.coreLocationManager.requestAlwaysAuthorization()
return GlobalVariableSharedInstance
}
func startUpdatingLocation() {
coreLocationManager.delegate = self
coreLocationManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
coreLocationManager.requestAlwaysAuthorization()
}
coreLocationManager.startUpdatingLocation()
print("start updating location", terminator: "")
}
// func initLocationManager()
// {
// if (CLLocationManager.locationServicesEnabled())
// {
// coreLocationManager.delegate = self
// coreLocationManager.desiredAccuracy = kCLLocationAccuracyBest
// coreLocationManager.startUpdatingLocation()
// coreLocationManager.startMonitoringSignificantLocationChanges()
//// coreLocationManager.st
// }
// else
// {
// let alert:UIAlertView = UIAlertView(title: "Error", message: "Location Services not Enabled. Please enable Location Services in your phone settings.", delegate: nil, cancelButtonTitle: "Ok")
// alert.show()
// }
// }
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
print("LOCATION UPDATED...")
let location = getLatestMeasurementFromLocations(locations)
print("my location: \(location)", terminator: "")
if isLocationMeasurementNotCached(location) && isHorizontalAccuracyValidMeasurement(location) && isLocationMeasurementDesiredAccuracy(location) {
stopUpdatingLocation()
if (locations.count > 0)
{
// the last location is the good one?
let newLocation:CLLocation = locations[0]
// let newLocation = CLLocation(latitude: 33.74900, longitude: -84.38798)
//
delegate?.didReceiveUserLocation(newLocation)
} else {
let newLocation = CLLocation(latitude: 33.74900, longitude: -84.38798)
delegate?.didReceiveUserLocation(newLocation)
}
}
else {
let newLocation = CLLocation(latitude: 33.74900, longitude: -84.38798)
delegate?.didReceiveUserLocation(newLocation)
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if (status == CLAuthorizationStatus.AuthorizedAlways)
{
print("Location manager is authorized...")
}
else if(status == CLAuthorizationStatus.Denied)
{
coreLocationManager.stopUpdatingLocation()
coreLocationManager.stopMonitoringSignificantLocationChanges()
}
}
func stopUpdatingLocation() {
lManager.stopUpdatingLocation()
lManager.delegate = nil
}
func currentLocation() -> CLLocation {
var location:CLLocation? = coreLocationManager.location
if (location==nil) {
print("Location is nil!")
location = CLLocation(latitude: 51.368123, longitude: -0.021973)
}
return location!
}
//if error stop updating location
func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {
if error.code != CLError.LocationUnknown.rawValue {
stopUpdatingLocation()
}
}
func getLatestMeasurementFromLocations(locations:[AnyObject]) -> CLLocation {
return locations[locations.count - 1] as! CLLocation
}
func isLocationMeasurementNotCached(location:CLLocation) -> Bool {
return location.timestamp.timeIntervalSinceNow <= 10.0
}
func isHorizontalAccuracyValidMeasurement(location:CLLocation) -> Bool {
return location.horizontalAccuracy >= 0
}
func isLocationMeasurementDesiredAccuracy(location:CLLocation) -> Bool {
return location.horizontalAccuracy <= coreLocationManager.desiredAccuracy
}
}
<file_sep>/Rails/Wingman/S3.swift
//
// File.swift
// Wingman
//
// Created by <NAME> on 2015-03-26.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
//import AFAmazonS3Manager
let s3URL = "https://s3.amazonaws.com/BUCKET/"
// singleton
private let _S3Model = S3()
// create a directory where we can store the images
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
class S3 {
// class func to return the singleton
class func model() -> S3 { return _S3Model }
// the manager
var s3Manager: AFAmazonS3Manager {
// create a manager with our id and our secret
let manager = AFAmazonS3Manager(accessKeyID: "<KEY>", secret: "<KEY>")
manager.requestSerializer.region = AFAmazonS3USStandardRegion
// the bucket is the name of our app
manager.requestSerializer.bucket = "wingmen"
return manager
}
}
<file_sep>/Rails/Wingman/BrowseDetailViewController.swift
//
// BrowseDetailViewController.swift
// Wingman
//
// Created by <NAME> on 2015-03-06.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import MessageUI
class BrowseDetailViewController: UIViewController, CLLocationManagerDelegate, MFMessageComposeViewControllerDelegate {
var event: [String: AnyObject]?
var venueLocation: PFGeoPoint?
var registerInfo: [String: AnyObject]?
var postData: [String: AnyObject]?
var phoneNumber: String?
var myCustomBackButtonItem: UIBarButtonItem?
var customButton: UIButton?
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var interestsLabel: UILabel!
@IBOutlet weak var seekingLabel: UILabel!
@IBOutlet weak var clubOrBarLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var startTimeLabel: UILabel!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var joinButton: UIButton!
var imageView: UIImageView?
@IBAction func joinButton(sender: AnyObject) {
messageUser()
}
override func viewDidLoad() {
super.viewDidLoad()
print(self.phoneNumber)
fillLabels()
startUpdatingLocation()
customButton = UIButton(type: UIButtonType.Custom) as? UIButton
customButton!.setBackgroundImage(UIImage(named: "backbutton"), forState: UIControlState.Normal)
customButton!.sizeToFit()
customButton!.hidden = true
customButton!.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myCustomBackButtonItem = UIBarButtonItem(customView: customButton!)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
imageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
imageView!.clipsToBounds = true
imageView!.contentMode = .ScaleAspectFill
imageView!.hidden = true
let image = UIImage(named: "bar")
imageView!.image = image
navigationItem.titleView = imageView
// Do any additional setup after loading the view.
self.userImage.hidden = true
self.joinButton.hidden = true
}
override func viewDidAppear(animated:Bool){
// self.navigationController?.navigationItem.backBarButtonItem =
startUpdatingLocation()
customButton!.hidden = false
springScaleFrom(customButton!, x: -100, y: 0, scaleX: 0.5, scaleY: 0.5)
imageView!.hidden = false
springScaleFrom(imageView!, x: 200, y: 0, scaleX: 0.5, scaleY: 0.5)
self.userImage.hidden = false
springScaleFrom(userImage!, x: 0, y: -400, scaleX: 0.5, scaleY: 0.5)
self.joinButton.hidden = false
springScaleFrom(joinButton!, x: 0, y: 200, scaleX: 0.5, scaleY: 0.5)
}
func popToRoot(sender:UIBarButtonItem) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func fillLabels() {
if let event = event {
if let clubOrBar = event["venue"] as? String {
self.clubOrBarLabel.text = clubOrBar
}
if let startTime = event["start_time_string"] as? String {
self.startTimeLabel.text = "From: \(startTime)"
}
if let endTime = event["end_time_string"] as? String {
self.endTimeLabel.text = "To: \(endTime)"
}
if let wingmanGender = event["wingman_gender"] as? String {
self.seekingLabel.text = "Seeking \(wingmanGender) Wingman"
}
//retrieving location from Parse
if let latitudeFloat = event["latitude"] as? Float {
if let longitudeFloat = event["longitude"] as? Float {
let latitude = Double(latitudeFloat)
let longitude = Double(longitudeFloat)
print("LATITUDE IS : \(latitude)")
print("LONGITUDE IS : \(longitude)")
let venueLocation = PFGeoPoint(latitude: latitude, longitude: longitude)
self.venueLocation = venueLocation
}
}
if let interests = event["creator_interests"] as? String {
self.interestsLabel.text = interests
}
if let userInfo = event["user"] as? [String: AnyObject] {
if let username = userInfo["username"] as? String {
self.usernameLabel.text = username
}
if let interests = userInfo["interests"] as? String {
self.interestsLabel.text = interests
}
if let gender = userInfo["gender"] as? String {
self.genderLabel.text = gender
}
// if let urlString = userInfo["image_string"] as? String {
//
// println(urlString)
// let url = NSURL(string: urlString)
// let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
//
//
// }
if let urlString = userInfo["image_string"] as? String {
let urlParts = urlString.componentsSeparatedByString("/")
if let fileName = urlParts.last {
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let filePath = paths[0] + fileName
getImageWithFilePath(filePath, fileName: fileName, completion: { () -> () in
let image = UIImage(contentsOfFile: filePath)
self.userImage.image = image
})
}
}
}
}
}
//sending phone number to TextMessageViewController before going to text messaging client
func getImageWithFilePath(filePath: String, fileName: String, completion: (() -> ())?) {
if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
if let c = completion { c() }
}
do {
// if timestamp of update then delete and redownload ... TODO
try NSFileManager.defaultManager().removeItemAtPath(filePath)
} catch _ {
}
let outputStream = NSOutputStream(toFileAtPath: filePath, append: false)
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * 1)), dispatch_get_main_queue()) { () -> Void in
S3.model().s3Manager.getObjectWithPath(fileName, outputStream: outputStream, progress: { (bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in
// println("\(Int(CGFloat(totalBytesRead) / CGFloat(totalBytesExpectedToRead) * 100.0))% Downloaded")
}, success: { (responseObject) -> Void in
print("image saved")
if let c = completion { c() }
}) { (error) -> Void in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[CLLocation]) {
print("Springtime is here!!!")
let location = getLatestMeasurementFromLocations(locations)
print("my location: \(location)")
if isLocationMeasurementNotCached(location) && isHorizontalAccuracyValidMeasurement(location) && isLocationMeasurementDesiredAccuracy(location) {
stopUpdatingLocation()
if let latitude = self.venueLocation?.latitude as Double? {
if let longitude = self.venueLocation?.longitude as Double? {
if let venueLocation = CLLocation(latitude: latitude, longitude: longitude) as CLLocation? {
//convert meters into miles
let dist1 = venueLocation.distanceFromLocation(location) * 0.00062137
//rounding to nearest hundredth
let dist2 = Double(round(100 * dist1) / 100)
self.distanceLabel.text = "Which is \(dist2) mi from you"
print("THE DISTANCE: \(dist2)")
}
}
}
}
}
//if error stop updating location
func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {
if error.code != CLError.LocationUnknown.rawValue {
stopUpdatingLocation()
}
}
func getLatestMeasurementFromLocations(locations:[AnyObject]) -> CLLocation {
return locations[locations.count - 1] as! CLLocation
}
func isLocationMeasurementNotCached(location:CLLocation) -> Bool {
return location.timestamp.timeIntervalSinceNow <= 5.0
}
func isHorizontalAccuracyValidMeasurement(location:CLLocation) -> Bool {
return location.horizontalAccuracy >= 0
}
func isLocationMeasurementDesiredAccuracy(location:CLLocation) -> Bool {
return location.horizontalAccuracy <= lManager.desiredAccuracy
}
func startUpdatingLocation() {
lManager.delegate = self
lManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
lManager.requestAlwaysAuthorization()
}
lManager.startUpdatingLocation()
print("start updating location")
}
func stopUpdatingLocation() {
lManager.stopUpdatingLocation()
lManager.delegate = nil
}
func messageUser() {
if MFMessageComposeViewController.canSendText() {
let messageController:MFMessageComposeViewController = MFMessageComposeViewController()
if let phoneNumber = self.phoneNumber as String? {
messageController.recipients = ["\(phoneNumber)"]
messageController.messageComposeDelegate = self
self.presentViewController(messageController, animated: true, completion: nil)
}
}
}
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func logout(sender: AnyObject) {
User.currentUser().token = nil
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = storyboard.instantiateViewControllerWithIdentifier("loginNC") as! UINavigationController
//presents LoginViewController without tabbar at bottom
self.presentViewController(nc, animated: true, completion: nil)
}
}
<file_sep>/Parse/Wingman/PostViewController.swift
//
// PostViewController.swift
// Wingman
//
// Created by <NAME> on 3/4/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import CoreLocation
var lastUpdated: NSDate?
class PostViewController: UIViewController, didChooseVenueProtocol {
var postData = [String:AnyObject]()
var clubOrBar: ClubOrBarVenues?
@IBOutlet weak var venueChoiceLabel: UILabel!
@IBOutlet weak var startTime: UITextField!
@IBOutlet weak var endTime: UITextField!
@IBOutlet weak var phoneNumber: UITextField!
@IBOutlet weak var backgroundMaskView: UIView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var chooseBarButton: UIButton!
@IBOutlet weak var postButton: UIButton!
@IBOutlet weak var postImageView: UIView!
@IBOutlet weak var imageView: UIImageView!
var tabBarImageView: UIImageView?
var userLocation: PFGeoPoint?
override func viewDidLoad() {
super.viewDidLoad()
chooseBarButton.titleLabel!.adjustsFontSizeToFitWidth = true
chooseBarButton.titleLabel!.minimumScaleFactor = 0.3
self.tabBarController?.tabBar.hidden = false
// Do any additional setup after loading the view.
// pickerClubBar.dataSource = self
// pickerClubBar.delegate = self
// pickerClubBar.backgroundColor = UIColor.clearColor()
// insertBlurView(backgroundMaskView, UIBlurEffectStyle.Dark)
// add if lastUpdated timeinterval is less than 5 minutes
/* if venues.count > 0 {
} else {
startUpdatingLocation()
}*/
tabBarImageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
tabBarImageView!.clipsToBounds = true
tabBarImageView!.contentMode = .ScaleAspectFill
tabBarImageView!.hidden = true
let image = UIImage(named: "bar")
tabBarImageView!.image = image
navigationItem.titleView = tabBarImageView
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.tabBar.hidden = false
self.postButton.hidden = true
self.chooseBarButton.hidden = true
self.postImageView.hidden = true
self.imageView.hidden = true
}
override func viewDidAppear(animated: Bool) {
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.tabBarController?.tabBar.hidden = false
//"You chose: " label stuff here
//venueChoiceLabel.text = "You chose: \()"
let scale1 = CGAffineTransformMakeScale(0.5, 0.5)
let translate1 = CGAffineTransformMakeTranslation(0, -100)
self.chooseBarButton.transform = CGAffineTransformConcat(scale1, translate1)
tabBarImageView!.hidden = false
springScaleFrom(tabBarImageView!, x: 0, y: -100, scaleX: 0.5, scaleY: 0.5)
spring(1) {
self.chooseBarButton.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.chooseBarButton.transform = CGAffineTransformConcat(scale, translate)
}
// animate the textViews
let scale2 = CGAffineTransformMakeScale(0.5, 0.5)
let translate2 = CGAffineTransformMakeTranslation(0, 100)
self.postButton.transform = CGAffineTransformConcat(scale2, translate2)
self.postImageView.transform = CGAffineTransformConcat(scale2, translate2)
self.imageView.transform = CGAffineTransformConcat(scale2, translate2)
spring(1) {
self.postButton.hidden = false
self.postImageView.hidden = false
self.imageView.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.postButton.transform = CGAffineTransformConcat(scale, translate)
self.postImageView.transform = CGAffineTransformConcat(scale, translate)
self.imageView.transform = CGAffineTransformConcat(scale, translate)
}
}
@IBAction func submitPostButton(sender: AnyObject) {
print("BUTTON WORKS", terminator: "")
if postData["clubOrBar"] != nil && startTime.text != "" && endTime.text != "" && phoneNumber.text != ""
{
print("ALLFIELDSOK", terminator: "")
print(postData["clubOrBar"], terminator: "")
postData["startTime"] = Int(startTime.text!)
postData["endTime"] = Int(endTime.text!)
postData["phonenumber"] = phoneNumber.text
let query = PFQuery(className:"_User")
query.whereKey("objectId", equalTo: PFUser.currentUser().objectId)
query.findObjectsInBackgroundWithBlock() {
(objects:[AnyObject]!, error:NSError!)->Void in
let user = objects.last as! PFUser
print("USER:\(user)", terminator: "")
user["postData"] = self.postData
if self.userLocation != nil {
user["location"] = self.userLocation
}
print("problem", terminator: "")
user.saveInBackground()
self.showAlert()
self.goToBrowseTableVC()
}
}
else {
let alertViewController = UIAlertController(title: "Submission Error", message: "Please complete all fields", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "postToPicker" {
let vc = segue.destinationViewController as! PickerViewController
vc.delegate = self
}
}
func showAlert() {
let alertViewController = UIAlertController(title: "Your post was created!", message: "Now back to browsing", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default) { (_) -> Void in
self.performSegueWithIdentifier("BrowserSegue", sender: self)
}
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
//this takes us to Browser after post button is pushed and info has been successfully sent to parse
func goToBrowseTableVC() {
let tbc = storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
print(tbc, terminator: "")
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
//
// self.navigationController!.pushViewController(self.storyboard!.instantiateViewControllerWithIdentifier("view2") as UIViewController, animated: true)
}
//array of clubs/bars in Atl needs to be pulled from Foursquare API to populate pickerview
// var clubsAndBarsList = venues
//dismiss the keyboard when tapping anywhere on view
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
func didReceiveVenueChoice(venue: ClubOrBarVenues) {
postData["clubOrBar"] = venue.name
let CLLocation = venue.location
let geoPoint = PFGeoPoint(latitude: CLLocation.coordinate.latitude, longitude: CLLocation.coordinate.longitude)
userLocation = geoPoint
postData["location"] = geoPoint
let venueName = venue.name
self.chooseBarButton.setTitle(venueName, forState: UIControlState.Normal)
}
/*
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
if pickerView == pickerClubBar {
return 1
}
return 0
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerClubBar {
return venues.count
}
return 0
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
var venue = venues[row]
var venueName = venue.name
let attributedString = NSAttributedString(string: venue.name, attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])
return attributedString
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row < venues.count {
var clubOrBar = venues[row]
//this creates the club/bar dictionary choice
postData ["clubOrBar"] = clubOrBar.name
var location = clubOrBar.location
let geoPoint = PFGeoPoint(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) as PFGeoPoint
postData["location"] = geoPoint
println("\(row)")
}
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logout(sender: AnyObject) {
PFUser.logOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = storyboard.instantiateViewControllerWithIdentifier("loginNC") as! UINavigationController
//presents LoginViewController without tabbar at bottom
self.presentViewController(nc, animated: true, completion: nil)
}
/*
var once: dispatch_once_t = 0
func locationManager(manager:CLLocationManager!, didUpdateLocations locations:[AnyObject]!) {
let location = getLatestMeasurementFromLocations(locations)
dispatch_once(&once, { () -> Void in
println("my: \(location)")
if self.isLocationMeasurementNotCached(location) && self.isHorizontalAccuracyValidMeasurement(location) {
// if self.isLocationMeasurementDesiredAccuracy(location) {
self.stopUpdatingLocation()
self.findVenues(location)
// } else {
//
// self.once = 0
//
// }
}
})
}
func locationManager(manager:CLLocationManager!, didFailWithError error:NSError!) {
if error.code != CLError.LocationUnknown.rawValue {
stopUpdatingLocation()
}
}
func getLatestMeasurementFromLocations(locations:[AnyObject]) -> CLLocation {
return locations[locations.count - 1] as CLLocation
}
func isLocationMeasurementNotCached(location:CLLocation) -> Bool {
println("cache = \(location.timestamp.timeIntervalSinceNow)")
return location.timestamp.timeIntervalSinceNow <= 5.0
}
func isHorizontalAccuracyValidMeasurement(location:CLLocation) -> Bool {
println("accuracy = \(location.horizontalAccuracy)")
return location.horizontalAccuracy >= 0
}
*/
// func isLocationMeasurementDesiredAccuracy(location:CLLocation) -> Bool {
// println("desired accuracy = \(lManager.desiredAccuracy)")
// return location.horizontalAccuracy <= lManager.desiredAccuracy
// }
//
/* func startUpdatingLocation() {
lManager.delegate = self
lManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
lManager.requestAlwaysAuthorization()
}
lManager.startUpdatingLocation()
println("start updating location")
}
func stopUpdatingLocation() {
lManager.stopUpdatingLocation()
lManager.delegate = nil
}
func findVenues(location:CLLocation) {
api.delegate = self
api.searchForClubOrBarAtLocation(location)
}
func didReceiveVenues(results: [ClubOrBarVenues]) {
venues = sorted(results, { (s1, s2) -> Bool in
return (s1 as ClubOrBarVenues).distanceFromUser > (s2 as ClubOrBarVenues).distanceFromUser
})
println("boom")
lastUpdated = NSDate()
// venues = sort(results, {$0.distanceFromUser < $1.distanceFromUser})
pickerClubBar.reloadAllComponents()
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<file_sep>/Rails/Wingman/User.swift
//
// User.swift
// Wingman
//
// Created by <NAME> on 3/20/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
import UIKit
protocol SignedInProtocol {
func goToApp()
func signInUnsuccesful(error: String)
func update()
}
protocol didPostEventProtocol {
func didReceiveEvent()
func didNotReceiveEvent(error: String?)
}
protocol didGetEventsProtocol {
func didGetAllEvents(events: [[String: AnyObject]])
func didNotGetAllEvents(error: String?)
}
private let _currentUser = User()
// properties like token, email, password. We pass the token to the request class and when api receive after completion resend to the user class
class User {
var registerDelegate: RegisterViewController?
var loginDelegate: LoginViewController?
var postEventDelegate: PostViewController?
var getEventsDelegate: BrowseTableViewController?
var token: String? {
didSet {
// do that so we can get that token value when we open the app
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(token, forKey: "token")
// synchronize = save
defaults.synchronize()
}
}
var userId: Int? {
didSet {
// do that so we can get that token value when we open the app
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(userId, forKey: "userId")
// synchronize = save
defaults.synchronize()
}
}
var email: String?
var phoneNumber: String?
init() {
let defaults = NSUserDefaults.standardUserDefaults()
token = defaults.objectForKey("token") as? String
}
// getter: will return our singleton object
class func currentUser() -> User {
return _currentUser
}
// Change To GET INSTEAD OF POST
func signUp(username: String, email: String, password: String) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users",
"method": "POST",
"body": [
"user": [ "username": username, "email": email, "password": <PASSWORD> ]
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
// println(responseInfo)
if error != nil {
print("Error != nil")
self.registerDelegate?.signInUnsuccesful(error!)
}
else {
print(responseInfo)
if let responseInfo: AnyObject = responseInfo as AnyObject? {
print(responseInfo)
if let dataInfo: AnyObject = responseInfo["user"] {
if let token = dataInfo["authentication_token"] as? String {
self.token = token
}
if let userId = responseInfo["user_id"] as? Int {
self.userId = userId
self.registerDelegate?.update()
}
}
else {
self.registerDelegate?.signInUnsuccesful(responseInfo.description)
}
}
// do something here after request is done
}
})
}
func signIn(username: String, password: String) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/sign_in",
"method": "POST",
"body": [
"user": [ "username": username, "password": <PASSWORD> ]
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
print("Error != nil")
self.loginDelegate?.signInUnsuccesful(error!)
}
else {
print("WHAT")
if let responseInfo: AnyObject = responseInfo as AnyObject? {
print(responseInfo)
if let dataInfo: AnyObject = responseInfo["user"] {
if let token = dataInfo["authentication_token"] as? String {
self.token = token
self.loginDelegate?.goToApp()
/*
if let userId = responseInfo!["user_id"] as? Int {
self.userId = userId
self.loginDelegate?.goToApp()
}
*/
}
}
else {
print("No data Info")
self.loginDelegate?.signInUnsuccesful(responseInfo.description)
}
}
}
// do something here after request is done
})
}
func update(gender: String, interests: String, userId: Int, imageFile: String) {
print("THIS SHOULD BE OUR USERID: \(userId)")
print("THIS SHOULD BE OUR TOKEN: \(self.token)")
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/\(userId)",
"method": "PUT",
"body": [
"user": [ "gender": gender, "interests": interests, "image_string": imageFile]
// "user": [ "gender": gender, "interests": interests, "avatar": userImage]
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
print("Error != nil")
self.loginDelegate?.signInUnsuccesful(error!)
} else {
if let responseInfo: AnyObject = responseInfo as AnyObject? {
print(responseInfo)
if let dataInfo: AnyObject = responseInfo["user"] {
print("Successful")
self.loginDelegate?.goToApp()
} else {
print("Error")
}
}
}
// do something here after request is done
})
}
func postEvent(venueName: String, latitude: Float, longitude: Float, startTime: String, endTime: String, wingmanGender: String) {
let options: [String: AnyObject] = [
"endpoint": "/events",
"method": "POST",
"body": [
"event": ["venue": venueName, "latitude": latitude, "longitude": longitude, "start_time_string": startTime, "end_time_string": endTime, "wingman_gender": wingmanGender]
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
print("Error != nil")
self.postEventDelegate?.didNotReceiveEvent(error)
} else {
if let responseInfo: AnyObject = responseInfo as AnyObject? {
print(responseInfo)
if let dataInfo: AnyObject = responseInfo["event"] {
print("Successful")
self.postEventDelegate?.didReceiveEvent()
} else {
print("Error")
self.postEventDelegate?.didNotReceiveEvent(responseInfo.description)
}
}
// do something here after request is done
}
})
}
func getEvents() {
let options: [String: AnyObject] = [
"endpoint": "/events",
"method": "GET",
"body": [
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
print("Error != nil")
self.getEventsDelegate?.didNotGetAllEvents(error)
// self.delegate2?.signInUnsuccesful(error!)
}
else {
if let responseInfo: AnyObject = responseInfo as AnyObject? {
print(responseInfo)
if let dataInfo: AnyObject = responseInfo["events"] {
if let events = dataInfo as? [[String: AnyObject]] {
self.getEventsDelegate?.didGetAllEvents(events)
}
print("Successful")
}
else {
self.getEventsDelegate?.didNotGetAllEvents(responseInfo.description)
}
}
}
// do something here after request is done
})
}
/*
func sendNewJob(jobDict: Dictionary<String, AnyObject>, authToken: String) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings",
"method": "POST",
"body": [
"auth_token": authToken,
"listing": jobDict
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
self.delegate?.signInUnsuccesful(error!)
} else {
// println("THIS IS THE RESPONSEINFO: \(responseInfo)")
if let dataInfo: AnyObject = responseInfo!["listing"] {
if let token = dataInfo["authentication_token"] as? String {
self.token = token
}
if let delegate = self.delegate2 {
delegate.goToApp()
}
} else {
println("No data Info")
self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
func getUserListings(authToken: String, completion: (listings:[[String:AnyObject]]) -> ()) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings",
"method": "GET",
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
// self.delegate?.signInUnsuccesful(error!)
} else {
if let listings = responseInfo?["listings"] as? [[String:AnyObject]] {
completion(listings: listings)
// if let delegate = self.delegate2 {
// delegate.goToApp()
// }
} else {
println("No data Info")
//self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
func getPreInterviewChecklist(jobDict: Dictionary<String, AnyObject>, listingId: Int) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings/\(listingId)/preinterview",
"method": "GET",
"body": [
"listing": jobDict
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
self.delegate?.signInUnsuccesful(error!)
} else {
println(responseInfo!)
if let dataInfo: AnyObject = responseInfo!["preinterview"] {
if let delegate = self.delegate2 {
delegate.goToApp()
}
} else {
println("No data Info")
self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
func deleteListing(jobDict: Dictionary<String, AnyObject>, listingId: Int) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings/\(listingId)",
"method": "DELETE",
"body": [
"listing": jobDict
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
self.delegate?.signInUnsuccesful(error!)
} else {
println(responseInfo!)
if let dataInfo: AnyObject = responseInfo!["message"] {
if let delegate = self.delegate2 {
delegate.goToApp()
}
} else {
println("No data Info")
self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
func editListing(jobDict: Dictionary<String, AnyObject>, authToken: String, listingId: Int) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings/\(listingId)",
"method": "PATCH",
"body": [
"auth_token": authToken,
"listing": jobDict
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
self.delegate?.signInUnsuccesful(error!)
} else {
// println(responseInfo!)
if let dataInfo: AnyObject = responseInfo!["listing"] {
if let token = dataInfo["authentication_token"] as? String {
self.token = token
}
if let delegate = self.delegate2 {
delegate.goToApp()
}
} else {
println("No data Info")
self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
// DO EDIT AND GET ON
func getOneListing(jobDict: Dictionary<String, AnyObject>, authToken: String) {
// the key names are for us (we chose the name of the keynames, the values are going to be used for url request)
let options: [String:AnyObject] = [
"endpoint": "/users/listings/",
"method": "GET",
"header": [
"auth_token": authToken,
]
]
// responseInfo will be set at the end of the requestwithoptions function: (completion: requestWithoptions), then we will print responseInfo
APIRequest.requestWithOptions(options, andCompletion: { (responseInfo, error) -> () in
if error != nil {
println("Error != nil")
self.delegate?.signInUnsuccesful(error!)
} else {
// println(responseInfo!)
if let dataInfo: AnyObject = responseInfo!["listings"] {
if let delegate = self.delegate2 {
delegate.goToApp()
}
} else {
println("No data Info")
self.delegate2?.signInUnsuccesful(responseInfo!.description)
}
}
// do something here after request is done
})
}
*/
}
<file_sep>/Parse/Wingman/ClubOrBarVenues.swift
//
// ClubOrBarVenues.swift
// Wingman
//
// Created by <NAME> on 3/10/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
import CoreLocation
class ClubOrBarVenues: NSObject {
let name:String!
let location:CLLocation!
let distanceFromUser:CLLocationDistance!
init(name: String, location: CLLocation, distanceFromUser: Double) {
self.name = name
self.location = location
self.distanceFromUser = distanceFromUser
}
}<file_sep>/Rails/Wingman/BrowseTableViewController.swift
//
// BrowseTableViewController.swift
// Wingman
//
// Created by <NAME> on 3/3/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class BrowseTableViewController: UITableViewController, didGetEventsProtocol {
var phoneNumber: String?
var wingmen: [[String:AnyObject]] = []
var arrayOfRegisterInfo = [[String: AnyObject]]()
var arrayOfPostData = [[String: AnyObject]]()
var tabBarImageView: UIImageView?
var arrayOfEvents = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
tabBarImageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
tabBarImageView!.clipsToBounds = true
tabBarImageView!.contentMode = .ScaleAspectFill
tabBarImageView!.hidden = true
let image = UIImage(named: "bar")
tabBarImageView!.image = image
navigationItem.titleView = tabBarImageView
// tableView.separatorColor = UIColor.blueColor()
tableView.layoutMargins = UIEdgeInsetsZero
tableView.separatorInset = UIEdgeInsetsZero
let gradientView = GradientView(frame: CGRectMake(view.bounds.origin.x, view.bounds.origin.y, view.bounds.size.width, view.bounds.size.height))
// Set the gradient colors
gradientView.colors = [UIColor.blackColor(), UIColor.darkGrayColor()]
// Optionally set some locations
// gradientView.locations = [0.0, 1.0]
// Optionally change the direction. The default is vertical.
gradientView.direction = .Vertical
//
// gradientView.topBorderColor = UIColor.blueColor()
// gradientView.bottomBorderColor = UIColor.blueColor()
//
//
tableView.backgroundView = gradientView
User.currentUser().getEventsDelegate = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
User.currentUser().getEvents()
// self.tableView.hidden = true
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
tabBarImageView!.hidden = true
// self.tableView.hidden = true
self.tableView.backgroundColor = UIColor.blackColor()
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let backButton = UIBarButtonItem()
let backButtonImage = UIImage(named: "backbutton")
backButton.setBackButtonBackgroundImage(backButtonImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
self.navigationController?.navigationItem.backBarButtonItem = backButton
}
override func viewDidAppear(animated: Bool) {
// self.tableView.hidden = false
self.tableView.backgroundColor = UIColor.blackColor()
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
var backButton = UIBarButtonItem()
var backButtonImage = UIImage(named: "backbutton")
backButton.setBackButtonBackgroundImage(backButtonImage, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
self.navigationController?.navigationItem.backBarButtonItem = backButton
tabBarImageView!.hidden = false
springScaleFrom(tabBarImageView!, x: 0, y: -100, scaleX: 0.5, scaleY: 0.5)
// addBlurEffect()
self.tableView.reloadData()
}
func addBlurEffect() {
// Add blur view
let bounds = self.navigationController?.navigationBar.bounds as CGRect!
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Dark)) as UIVisualEffectView
visualEffectView.frame = bounds
visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
self.navigationController?.navigationBar.addSubview(visualEffectView) // Here you can add visual effects to any UIView control.
// Replace custom view with navigation bar in above code to add effects to custom view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.arrayOfEvents.count
}
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
cell.separatorInset = UIEdgeInsetsZero
cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
}
// func that takes the filePath (the filePath for the directory where our imageFile is stored) and the fileName (the specific string we created which includes our imageName and a randomNumber)
func getImageWithFilePath(filePath: String, fileName: String, completion: (() -> ())?) {
// NSFileManager is a predefined iOS class
// we check if there is an imageFile in the directory (using the filePath of our directory)
// if there is an imageFile returns true else return false
if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
// if there is an imageFile in the directory then completion = true
// IF THERE IS ALREADY AN IMAGEFILE (WE ALREADY DOWNLOADED IT) IN OUR COMPUTER DIRECTORY WE DON'T NEED TO DOWNLOAD THE IMAGE FROM S3, SO COMPLETION (CODE BELOW DOESN'T GET EXECUTED)
if let c = completion { c() }
}
do {
// IF THERE IS NO IMAGE IN OUR DIRECTORY (WE DIDN'T ALREADY DOWNLOADED IT, SO METHOD DOESN'T END AT COMPLETION ABOVE), THEN DOWNLOAD IMAGEFILE FROM S3 LINK (THAT WE STORED EARLIER IN REGISTERVIEWCONTROLLER)
// AT EVERY STEP OF THE DOWNLOAD OF THE IMAGEFILE, OUTPUT STREAM CHANGES AND THEN WE UPDATE THE IMAGEFILE AT DIRECTORY (BY DELETING THE OLD ONE AND ADDING THE UPDATED ONE)
// remove old imageFile
try NSFileManager.defaultManager().removeItemAtPath(filePath)
} catch _ {
}
// update the file at the filePath directory
// OutputStream is the data we receive from the request (the downloading of the image from the imageFile)
let outputStream = NSOutputStream(toFileAtPath: filePath, append: false)
// getObjectWithPath download the image from the imageFile (the OutputStream) of the directory. It takes the fileName of the directory and the outputStream (OutputStream is the imageFile we downloaded from S3)
S3.model().s3Manager.getObjectWithPath(fileName, outputStream: outputStream, progress: { (bytesRead, totalBytesRead, totalBytesExpectedToRead) -> Void in
// println("\(Int(CGFloat(totalBytesRead) / CGFloat(totalBytesExpectedToRead) * 100.0))% Downloaded")
},
// if the image is succesfully downloaded from the imageFile stored in S3 then completion
success: { (responseObject) -> Void in
print("image saved")
if let c = completion { c() }
}) { (error) -> Void in
// if error do stuff
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! BrowseTableViewCell
cell.selectionStyle = .None
cell.contentView.backgroundColor = UIColor.clearColor()
cell.backgroundColor = UIColor.clearColor()
var event = self.arrayOfEvents[indexPath.row]
if let venue = event["venue"] as? String {
cell.clubOrBarLabel.text = venue
}
// if let seeking = postData["wingmanGender"] as? String {
//
// cell.seekingLabel.text = "Seeking: \(seeking)"
//
// }
if let startTimeInt = event["start_time_string"] as? String {
if let endTimeInt = event["end_time_string"] as? String {
cell.timeLabel.text = "From: \(startTimeInt) To: \(endTimeInt)"
}
}
if let userInfo = event["user"] as! [String: AnyObject]? {
if let username = userInfo["username"] as? String {
cell.usernameLabel.text = username
}
if let gender = userInfo["gender"] as? String {
cell.genderLabel.text = "Gender: \(gender)"
}
// take the amazonS3 URL link that we sent to the Rails API, and that the Rails API sent us back
// THE URL LINK CONTAINS THE FILENAME OF OUR IMAGE AND WE USE THAT FILENAME TO FIND THE DIRECTORY WHERE OUR IMAGEFILE IS STORED
if let urlString = userInfo["image_string"] as? String {
// create all the components separated by / in the URL and store them in an array of string that call urlParts
let urlParts = urlString.componentsSeparatedByString("/")
// take the last part of the URL (our fileName (the specific string that we created for our image (which include our imageName and a random number))
if let fileName = urlParts.last {
// grab the directory where we stored our imageName (the directory has our fileName (the image name with the random number) at the end of it)
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let filePath = paths[0] + fileName
// SEE THE GETIMAGEWITHFILEPATH METHOD IN THIS CLASS
// this function takes our filePath directory and our fileName and gets the image from the imageFile in the directory
getImageWithFilePath(filePath, fileName: fileName, completion: { () -> () in
// take the contentsOfTheImageFile in our directory and create an image with that file
let image = UIImage(contentsOfFile: filePath)
// display the image in the userImageView
cell.userImage.image = image
})
}
}
}
return cell
}
func didGetAllEvents(events: [[String: AnyObject]]) {
for event in events {
self.arrayOfEvents.append(event)
}
self.tableView.reloadData()
}
func didNotGetAllEvents(error: String?) {
let alert:UIAlertView = UIAlertView(title: "Get Events Unsuccessful", message: error, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// let cell: BrowseTableViewCell = tableView.cellForRowAtIndexPath(indexPath) as BrowseTableViewCell
//didn't connect segue in storyboard so doing it programmatically here
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("browseDetailVC") as! BrowseDetailViewController
//self for global variables/properties
//sending data to BrowseDetailViewController
/*
vc.registerInfo = registerInfo
vc.postData = postData
*/
var event = self.arrayOfEvents[indexPath.row]
vc.event = event
if let phoneNumber = event["creator_phone_number"] as? String {
// self.phoneNumber = phoneNumber
vc.phoneNumber = phoneNumber
}
self.navigationController?.pushViewController(vc, animated: true)
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//
// if segue.identifier == "phoneSegue" {
//
//
//
// let vc = segue.destinationViewController as TextMessageViewController
//
// println(phoneNumber)
// vc.phoneNumber = self.phoneNumber
//
// }
//
// }
}
<file_sep>/Parse/Wingman/LoginViewController.swift
//
// ViewController.swift
// Wingman
//
// Created by <NAME> on 3/1/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var logoImageView: UIImageView!
var animator: UIDynamicAnimator!
var attachmentBehavior: UIAttachmentBehavior!
var gravityBehavior: UIGravityBehavior!
var snapBehavior: UISnapBehavior!
var imageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
GlobalVariableSharedInstance.startUpdatingLocation()
animator = UIDynamicAnimator(referenceView: view)
self.logoImageView.layer.cornerRadius = 50
self.logoImageView.clipsToBounds = true
// hides navigation bar on LoginVC
// self.navigationController?.setNavigationBarHidden(true, animated: true)
//sets navigation bar to a clear black color
self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
self.navigationController?.navigationBarHidden = false
//sets navigation bar's "Back" button item to white
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
imageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
imageView!.clipsToBounds = true
imageView!.contentMode = .ScaleAspectFill
imageView!.hidden = true
let image = UIImage(named: "bar")
imageView!.image = image
navigationItem.titleView = imageView
}
override func viewWillAppear(animated: Bool) {
self.logoImageView.hidden = true
self.loginButton.hidden = true
self.signInButton.hidden = true
self.imageView!.hidden = true
}
override func viewDidAppear(animated: Bool) {
self.logoImageView.layer.cornerRadius = 50
self.logoImageView.clipsToBounds = true
self.imageView!.hidden = false
springScaleFrom(self.imageView!, x: 0, y: -100, scaleX: 0.5, scaleY: 0.5)
// animate the logoImageView
let scale1 = CGAffineTransformMakeScale(0.5, 0.5)
let translate1 = CGAffineTransformMakeTranslation(0, 500)
self.logoImageView.transform = CGAffineTransformConcat(scale1, translate1)
animationWithDuration(4) {
self.logoImageView.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.logoImageView.transform = CGAffineTransformConcat(scale, translate)
}
// animate the textViews
let scale2 = CGAffineTransformMakeScale(0.5, 0.5)
let translate2 = CGAffineTransformMakeTranslation(-300, 0)
self.loginButton.transform = CGAffineTransformConcat(scale2, translate2)
spring(1) {
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.loginButton.transform = CGAffineTransformConcat(scale, translate)
self.loginButton.hidden = false
}
let scale3 = CGAffineTransformMakeScale(0.5, 0.5)
let translate3 = CGAffineTransformMakeTranslation(300, 0)
self.signInButton.transform = CGAffineTransformConcat(scale3, translate3)
spring(1) {
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.signInButton.transform = CGAffineTransformConcat(scale, translate)
self.signInButton.hidden = false
}
if PFUser.currentUser() != nil {
let tbc = storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
print(tbc)
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
////
//// self.navigationController?.setNavigationBarHidden(true, animated: true)
//
// self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
}
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var signInButton: UIButton!
@IBAction func loginButton(sender: AnyObject) {
self.usernameField.resignFirstResponder()
self.passwordField.resignFirstResponder()
let fieldValues: [String] = [usernameField.text!, passwordField.text!]
if fieldValues.indexOf("") != nil {
//all fields are not filled in
let alertViewController = UIAlertController(title: "Submission Error", message: "Please complete all fields", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
else {
PFUser.logInWithUsernameInBackground(usernameField.text, password:<PASSWORD>) {
(user: PFUser!, error: NSError!) -> Void in
if (user != nil) {
// need to go to tabBarController
//all fields are filled in
print("All fields are filled in and login complete")
let userQuery = PFUser.query()
userQuery.whereKey("username", equalTo: self.usernameField.text)
userQuery.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if objects.count > 0 {
self.isLoggedIn = true
self.checkIfLoggedIn()
} else {
// self.signUp()
}
})
} else {
if let errorString = error.userInfo["error"] as? NSString
{
let alert:UIAlertView = UIAlertView(title: "Error", message: errorString as String, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
else {
let alert:UIAlertView = UIAlertView(title: "Error", message: "Unable to login" , delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
}
}
}
var isLoggedIn: Bool {
get {
return NSUserDefaults.standardUserDefaults().boolForKey("isLoggedIn")
}
set {
NSUserDefaults.standardUserDefaults().setBool(newValue, forKey: "isLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func checkIfLoggedIn(){
print(isLoggedIn)
if isLoggedIn {
//replace this controller with the tabbarcontroller
let tbc = storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
print(tbc)
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/Parse/Wingman/BrowseDetailViewController.swift
//
// BrowseDetailViewController.swift
// Wingman
//
// Created by <NAME> on 2015-03-06.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import MessageUI
class BrowseDetailViewController: UIViewController, MFMessageComposeViewControllerDelegate, userLocationProtocol, CLLocationManagerDelegate {
var registerInfo: [String: AnyObject]?
var postData: [String: AnyObject]?
var venueLocation: PFGeoPoint?
var phoneNumber: String?
var myCustomBackButtonItem: UIBarButtonItem?
var customButton: UIButton?
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var interestsLabel: UILabel!
@IBOutlet weak var clubOrBarLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var startTimeLabel: UILabel!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var joinButton: UIButton!
var imageView: UIImageView?
// var tempGeoPoint = PFGeoPoint(latitude: 33.78604932800356, longitude: -84.37840104103088)
@IBAction func joinButton(sender: AnyObject) {
messageUser()
}
override func viewDidLoad() {
super.viewDidLoad()
joinButton.titleLabel!.adjustsFontSizeToFitWidth = true
joinButton.titleLabel!.minimumScaleFactor = 0.3
fillLabels()
GlobalVariableSharedInstance.startUpdatingLocation()
GlobalVariableSharedInstance.delegate = self
customButton = UIButton(type: UIButtonType.Custom)
customButton!.setBackgroundImage(UIImage(named: "backbutton"), forState: UIControlState.Normal)
customButton!.sizeToFit()
customButton!.hidden = true
customButton!.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myCustomBackButtonItem = UIBarButtonItem(customView: customButton!)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
imageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
imageView!.clipsToBounds = true
imageView!.contentMode = .ScaleAspectFill
imageView!.hidden = true
let image = UIImage(named: "bar")
imageView!.image = image
navigationItem.titleView = imageView
// Do any additional setup after loading the view.
self.userImage.hidden = true
self.joinButton.hidden = true
userImage.clipsToBounds = true
userImage.layer.cornerRadius = userImage.frame.size.height/2
interestsLabel.layer.cornerRadius = interestsLabel.frame.size.width/18
self.view.layoutSubviews()
print(self.phoneNumber, terminator: "")
customButton!.hidden = false
springScaleFrom(customButton!, x: -100, y: 0, scaleX: 0.5, scaleY: 0.5)
imageView!.hidden = false
springScaleFrom(imageView!, x: 200, y: 0, scaleX: 0.5, scaleY: 0.5)
self.userImage.hidden = false
springScaleFrom(userImage!, x: 0, y: -400, scaleX: 0.5, scaleY: 0.5)
self.joinButton.hidden = false
springScaleFrom(joinButton!, x: 0, y: 200, scaleX: 0.5, scaleY: 0.5)
}
override func viewWillAppear(animated: Bool) {
}
override func viewDidAppear(animated:Bool){
// self.navigationController?.navigationItem.backBarButtonItem =
}
func popToRoot(sender:UIBarButtonItem) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func fillLabels() {
if let registerInfo = registerInfo {
if let username = registerInfo["username"] as? String {
self.usernameLabel.text = username
}
if let interests = registerInfo["interests"] as? String {
self.interestsLabel.text = interests
}
if let gender = registerInfo["gender"] as? String {
self.genderLabel.text = gender
}
if let imageFile = registerInfo["imageFile"] as? PFFile {
//taking PPFile and turning it into data and then into UIImage
imageFile.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) in
if (error == nil) {
let image : UIImage = UIImage(data:imageData)!
//image object implementation
self.userImage.image = image
}
})
}
}
if let postData = postData {
if let clubOrBar = postData["clubOrBar"] as? String {
self.clubOrBarLabel.text = clubOrBar
}
if let startTime = postData["startTime"] as? Int {
self.startTimeLabel.text = "From: \(startTime)"
}
if let endTime = postData["endTime"] as? Int {
self.endTimeLabel.text = "To: \(endTime)"
}
// if let wingmanGender = postData["wingmanGender"] as? String {
//
// self.seekingLabel.text = "Seeking \(wingmanGender) Wingman"
//
// }
//
//retrieving location from Parse
if let venueLocation = postData["location"] as? PFGeoPoint {
self.venueLocation = venueLocation
}
}
}
//sending phone number to TextMessageViewController before going to text messaging client
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didReceiveUserLocation(location: CLLocation) {
if let latitude = self.venueLocation?.latitude as Double? {
if let longitude = self.venueLocation?.longitude as Double? {
if let venueLocation = CLLocation(latitude: latitude, longitude: longitude) as CLLocation? {
// let tempCLLocation = CLLocation(latitude: self.tempGeoPoint!.latitude, longitude: self.tempGeoPoint!.longitude) as CLLocation?
//convert meters into miles
let dist1 = venueLocation.distanceFromLocation(location) * 0.00062137
// let dist1 = venueLocation.distanceFromLocation(tempCLLocation!) * 0.00062137
//rounding to nearest hundredth
let dist2 = Double(round(100 * dist1) / 100)
self.distanceLabel.text = "Which is \(dist2) mi from you"
print("THE DISTANCE: \(dist2)", terminator: "")
}
}
}
}
func messageUser() {
if MFMessageComposeViewController.canSendText() {
let messageController:MFMessageComposeViewController = MFMessageComposeViewController()
if let phoneNumber = self.phoneNumber as String? {
messageController.recipients = ["\(phoneNumber)"]
messageController.messageComposeDelegate = self
self.presentViewController(messageController, animated: true, completion: nil)
}
}
}
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func logout(sender: AnyObject) {
PFUser.logOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = storyboard.instantiateViewControllerWithIdentifier("loginNC") as! UINavigationController
//presents LoginViewController without tabbar at bottom
self.presentViewController(nc, animated: true, completion: nil)
}
}
<file_sep>/Parse/Wingman/RegisterViewController.swift
//
// RegisterViewController.swift
// Wingman
//
// Created by <NAME> on 3/2/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
@IBDesignable
class RegisterViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate
{
let segments = ["male", "female"]
var user = PFUser()
var registerInfo = [String:AnyObject]()
var myCustomBackButtonItem: UIBarButtonItem?
var customButton: UIButton?
var imageView: UIImageView?
var gender = "Male"
var seekingGender = "Female"
override func viewDidLoad() {
super.viewDidLoad()
GlobalVariableSharedInstance.startUpdatingLocation()
//
// pickProfilePicButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlState.Highlighted)
//
self.registerInfo["gender"] = "male"
self.interestField.layer.cornerRadius = 5
self.navigationController?.setNavigationBarHidden(false, animated: true)
customButton = UIButton(type: UIButtonType.Custom)
customButton!.setBackgroundImage(UIImage(named: "backbutton"), forState: UIControlState.Normal)
customButton!.sizeToFit()
customButton!.hidden = true
customButton!.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myCustomBackButtonItem = UIBarButtonItem(customView: customButton!)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
imageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
imageView!.clipsToBounds = true
imageView!.contentMode = .ScaleAspectFill
imageView!.hidden = true
let image = UIImage(named: "bar")
imageView!.image = image
navigationItem.titleView = imageView
}
// viewWillAppear:
override func viewWillAppear(animated: Bool) {
self.imageView!.hidden = true
self.createUsernameField.hidden = true
self.createPasswordField.hidden = true
self.logoImageView.hidden = true
}
override func viewDidAppear(animated: Bool) {
customButton!.hidden = false
self.imageView!.hidden = false
springScaleFrom(customButton!, x: -100, y: 0, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(imageView!, x: 200, y: 0, scaleX: 0.5, scaleY: 0.5)
self.logoImageView.layer.cornerRadius = self.logoImageView.frame.size.width/2
self.logoImageView.clipsToBounds = true
// animate the logoImageView
let scale1 = CGAffineTransformMakeScale(0.5, 0.5)
let translate1 = CGAffineTransformMakeTranslation(0, -100)
self.createUsernameField.transform = CGAffineTransformConcat(scale1, translate1)
spring(1) {
self.createUsernameField.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.createUsernameField.transform = CGAffineTransformConcat(scale, translate)
}
// animate the textViews
let scale2 = CGAffineTransformMakeScale(0.5, 0.5)
let translate2 = CGAffineTransformMakeTranslation(0, -100)
let scale3 = CGAffineTransformMakeScale(0.5, 0.5)
let translate3 = CGAffineTransformMakeTranslation(0, -100)
self.createPasswordField.transform = CGAffineTransformConcat(scale3, translate3)
spring(1) {
self.createPasswordField.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.createPasswordField.transform = CGAffineTransformConcat(scale, translate)
}
let scale4 = CGAffineTransformMakeScale(0.5, 0.5)
let translate4 = CGAffineTransformMakeTranslation(0, 200)
self.logoImageView.transform = CGAffineTransformConcat(scale4, translate4)
spring(1) {
self.logoImageView.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.logoImageView.transform = CGAffineTransformConcat(scale, translate)
}
if pickProfilePicButton.highlighted == true {
pickProfilePicButton.backgroundColor = UIColor.blueColor()
}
if pickProfilePicButton.highlighted == false{
pickProfilePicButton.backgroundColor = UIColor.clearColor()
}
if PFUser.currentUser() != nil {
let tbc = storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
print(tbc)
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
// self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
//
// self.navigationController?.navigationBar.tintColor = UIColor.clearColor()
//
// self.navigationController?.navigationBar.barTintColor = UIColor.clearColor()
//
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
func buttonClicked(sender:UIButton)
{
if sender.highlighted {
sender.backgroundColor = UIColor.blueColor()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//this is the button to initiate choosing a profile pic
@IBAction func pickImage(sender: AnyObject) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
self.dismissViewControllerAnimated(true, completion: nil)
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//profileImage = scaleImage(profileImage, newSize: CGSizeMake(600, 600))
logoImageView.image = image
let resizedImage = self.resizeImage(image, toSize: CGSizeMake(100, 100))
// tranforming it to a PFFile
// image to data
let imageData = UIImagePNGRepresentation(resizedImage)
// data to pffile
let imageFile = PFFile(name: "image.png", data: imageData)
registerInfo["imageFile"] = imageFile
picker.dismissViewControllerAnimated(true, completion: nil)
}
func resizeImage(original : UIImage, toSize size:CGSize) -> UIImage
{
var imageSize:CGSize = CGSizeZero
if (original.size.width < original.size.height)
{
imageSize.height = size.width * original.size.height / original.size.width
imageSize.width = size.width
}
else
{
imageSize.height = size.height
imageSize.width = size.height * original.size.width / original.size.height
}
UIGraphicsBeginImageContext(imageSize)
// draw the new image with the imageSize.width and height (based on the UIImageView size)
original.drawInRect(CGRectMake(0,0,imageSize.width,imageSize.height))
// put the drawing in a UIImage
let resizedImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return resizedImage
}
// func resizeImage(orignalImage: UIImage, withSize: CGSize) {
//
// var scale : Float = if(originalImage.size.height > originalImage.size.width) { size.width / originalImage.size.width } else { size.height / originalImage.size.height}
/*
-(UIImage *)resizeImage:(UIImage *) originalImage withSize: (CGSize)size {
float scale = (originalImage.size.height > originalImage.size.width) ? size.width / originalImage.size.width : size.height / originalImage.size.height;
CGSize ratioSize = CGSizeMake(originalImage.size.width * scale, originalImage.size.height * scale);
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[originalImage drawInRect:CGRectMake(0, 0, ratioSize.width, ratioSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
*/
@IBOutlet weak var createUsernameField: UITextField!
@IBOutlet weak var createPasswordField: UITextField!
@IBOutlet weak var pickProfilePicButton: UIButton!
@IBOutlet weak var logoImageView: UIImageView!
@IBAction func seekingGenderSC(sender: AnyObject) {
let selectedSegment = sender.selectedSegmentIndex
if selectedSegment == 0 {
registerInfo["wingmanGender"] = "male"
}
if selectedSegment == 1 {
registerInfo["wingmanGender"] = "female"
}
if selectedSegment == 2 {
registerInfo["wingmanGender"] = "both"
}
}
@IBAction func genderSC(sender: UISegmentedControl) {
let selectedSegment = sender.selectedSegmentIndex
if selectedSegment == 0 {
registerInfo["gender"] = "male"
print("isOff")
}
if selectedSegment == 1 {
registerInfo["gender"] = "female"
print("isOn")
}
// var segmentedControl: UISegmentedControl!
// let selectedSegmentIndex = sender.selectedSegmentIndex
//
// let selectedSegmentText = sender.titleForSegmentAtIndex(selectedSegmentIndex)
//
// let segments = ["Male", "Female"]
//
// segmentedControl = UISegmentedControl(items: segments)
//
// segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: .ValueChanged)
//
//
//
//
//
// println("Segment \(selectedSegmentIndex) with text of" + " \(selectedSegmentText) is selected")
}
@IBOutlet @IBInspectable weak var interestField: UITextView!
func popToRoot(sender:UIBarButtonItem) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
@IBAction func signUp(sender: AnyObject) {
print("SIGNUP BUTTON WORKS")
let fieldValues = [createUsernameField.text!, createPasswordField.text!, interestField.text!] //interestField.text
if (fieldValues).indexOf("") != nil || self.registerInfo["imageFile"] == nil {
print("TEXTFIELDS NOT COMPLETE")
//all fields are not filled in
let alertViewController = UIAlertController(title: "Submission Error", message: "Please complete all fields", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
else {
user.username = createUsernameField.text
user.password = <PASSWORD>
print("TEXTFIELDS COMPLETE")
registerInfo["username"] = self.createUsernameField.text
registerInfo["interests"] = self.interestField.text
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
self.saveInfoToParse()
/*
println(user)
self.createUsernameField.text = ""
self.createPasswordField.text = ""
self.enterEmailField.text = ""
//self.interestField.text = ""
// self.genderSC(sender: UISegmentedControl(items: segments)) = ""
*/
}
else
{
if let errorString = error.userInfo["error"] as? NSString
{
let alert:UIAlertView = UIAlertView(title: "Error", message: errorString as String, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
else {
let alert:UIAlertView = UIAlertView(title: "Error", message: "Unable to create account" , delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
}
}
}
func saveInfoToParse() {
let query = PFQuery(className:"_User")
query.whereKey("objectId", equalTo: PFUser.currentUser().objectId)
query.findObjectsInBackgroundWithBlock() {
(objects:[AnyObject]!, error:NSError!)->Void in
if ((error) == nil) {
let user:PFUser = objects.last as! PFUser
//this creates the registerInfo column in Parse
user["registerInfo"] = self.registerInfo
if let gender = self.registerInfo["gender"] as? String {
user["gender"] = gender
self.gender = gender
}
if let wingmanGender = self.registerInfo["wingmanGender"] as? String {
user["wingmanGender"] = wingmanGender
self.seekingGender = wingmanGender
}
// user["postData"] = ["name": "JOHN", "AGE": "12"]
user.saveInBackground()
let tbc = self.storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
let navigationVC = tbc?.viewControllers![0] as! UINavigationController
let tableViewVC = navigationVC.viewControllers[0] as! BrowseTableViewController
tableViewVC.gender = self.gender
tableViewVC.seekingGender = self.seekingGender
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
}
}
}
<file_sep>/Rails/Wingman/BrowseTableViewCell.swift
//
// BrowseTableViewCell.swift
// Wingman
//
// Created by <NAME> on 2015-03-05.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
class BrowseTableViewCell: UITableViewCell {
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
// @IBOutlet weak var seekingLabel: UILabel!
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var clubOrBarLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
springScaleFrom(genderLabel, x: 200, y: 200, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(usernameLabel, x: 200, y: 200, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(clubOrBarLabel, x: 200, y: 200, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(timeLabel, x: 200, y: 200, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(userImage, x: -100, y: 200, scaleX: 0.5, scaleY: 0.5)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>/Parse/PickerViewController.swift
//
// PickerViewController.swift
// Wingman
//
// Created by <NAME> on 3/19/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import CoreLocation
let api = FourSquareAPI()
let lManager = CLLocationManager()
var venues = [ClubOrBarVenues]()
protocol didChooseVenueProtocol {
func didReceiveVenueChoice(venue: ClubOrBarVenues)
}
class PickerViewController: UIViewController, UINavigationControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, CLLocationManagerDelegate, FoursquareAPIProtocol {
var postData = [String:AnyObject]()
var clubOrBar: ClubOrBarVenues?
var delegate: PostViewController?
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var backButton: UIButton!
@IBAction func backButton(sender: AnyObject) {
self.presentingViewController?.tabBarController?.tabBar.hidden = false
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var pickerClubBar: UIPickerView!
@IBAction func doneButton(sender: AnyObject) {
if let _ = self.clubOrBar
{
showAlert()
self.presentingViewController?.tabBarController?.tabBar.hidden = false
self.dismissViewControllerAnimated(true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.hidden = true
backButton.alpha = 0
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.tabBarController?.tabBar.hidden = true
pickerClubBar.dataSource = self
pickerClubBar.delegate = self
pickerClubBar.backgroundColor = UIColor.clearColor()
if venues.count > 0 {
} else {
startUpdatingLocation()
}
}
override func viewDidAppear(animated: Bool) {
let scale1 = CGAffineTransformMakeScale(0.5, 0.5)
let translate1 = CGAffineTransformMakeTranslation(0, 200)
self.imageView.transform = CGAffineTransformConcat(scale1, translate1)
spring(1) {
self.imageView.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.imageView.transform = CGAffineTransformConcat(scale, translate)
}
backButton.alpha = 1
springScaleFrom(backButton!, x: -100, y: 0, scaleX: 0.5, scaleY: 0.5)
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.tabBarController?.tabBar.hidden = true
}
override func viewWillAppear(animated: Bool) {
self.presentingViewController?.tabBarController?.tabBar.hidden = true
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
if pickerView == pickerClubBar {
return 1
}
return 0
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == pickerClubBar {
return venues.count
}
return 0
}
//changes the color of the items in the pickerview rows to white
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let venue = venues[row]
let attributedString = NSAttributedString(string: venue.name, attributes: [NSForegroundColorAttributeName : UIColor.whiteColor()])
return attributedString
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row < venues.count {
let clubOrBar = venues[row]
self.clubOrBar = clubOrBar
//saves the club/bar in postData column in Parse
postData ["clubOrBar"] = clubOrBar.name
let location = clubOrBar.location
let geoPoint = PFGeoPoint(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) as PFGeoPoint
//saves location of club/bar in postData column in Parse
postData["location"] = geoPoint
print("\(row)", terminator: "")
self.delegate?.didReceiveVenueChoice(clubOrBar)
}
}
func showAlert() {
let alertViewController = UIAlertController(title: "Saved", message: "Back to finding your Wingman", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default) { (_) -> Void in
}
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
//run the API call once to avoid maxing out rate limit
var once: dispatch_once_t = 0
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[CLLocation]) {
let location = getLatestMeasurementFromLocations(locations)
dispatch_once(&once, { () -> Void in
print("my: \(location)", terminator: "")
if self.isLocationMeasurementNotCached(location) && self.isHorizontalAccuracyValidMeasurement(location) {
// if self.isLocationMeasurementDesiredAccuracy(location) {
self.stopUpdatingLocation()
self.findVenues(location)
// } else {
//
// self.once = 0
//
// }
}
})
}
func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {
if error.code != CLError.LocationUnknown.rawValue {
stopUpdatingLocation()
}
}
func getLatestMeasurementFromLocations(locations:[AnyObject]) -> CLLocation {
return locations[locations.count - 1] as! CLLocation
}
func isLocationMeasurementNotCached(location:CLLocation) -> Bool {
print("cache = \(location.timestamp.timeIntervalSinceNow)", terminator: "")
return location.timestamp.timeIntervalSinceNow <= 5.0
}
func isHorizontalAccuracyValidMeasurement(location:CLLocation) -> Bool {
print("accuracy = \(location.horizontalAccuracy)", terminator: "")
return location.horizontalAccuracy >= 0
}
// func isLocationMeasurementDesiredAccuracy(location:CLLocation) -> Bool {
// println("desired accuracy = \(lManager.desiredAccuracy)")
// return location.horizontalAccuracy <= lManager.desiredAccuracy
// }
//
func startUpdatingLocation() {
lManager.delegate = self
lManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined {
lManager.requestAlwaysAuthorization()
}
lManager.startUpdatingLocation()
print("start updating location", terminator: "")
}
func stopUpdatingLocation() {
lManager.stopUpdatingLocation()
lManager.delegate = nil
}
func findVenues(location:CLLocation) {
api.delegate = self;
api.searchForClubOrBarAtLocation(location)
}
func didReceiveVenues(results: [ClubOrBarVenues]) {
venues = results.sort({ (s1, s2) -> Bool in
return (s1 as ClubOrBarVenues).distanceFromUser > (s2 as ClubOrBarVenues).distanceFromUser
})
print("boom", terminator: "")
lastUpdated = NSDate()
// venues = sort(results, {$0.distanceFromUser < $1.distanceFromUser})
pickerClubBar.reloadAllComponents()
}
@IBAction func logout(sender: AnyObject) {
PFUser.logOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nc = storyboard.instantiateViewControllerWithIdentifier("loginNC") as! UINavigationController
//presents LoginViewController without tabbar at bottom
self.presentViewController(nc, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// sending the club/bar choice over to PostVC
}
<file_sep>/Parse/Wingman/TextMessageViewController.swift
//
// TextMessageViewController.swift
// Wingman
//
// Created by <NAME> on 3/14/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
import MessageUI
class TextMessageViewController: UIViewController, MFMessageComposeViewControllerDelegate {
var phoneNumber: String?
@IBAction func messageUser(sender: AnyObject) {
if MFMessageComposeViewController.canSendText() {
let messageController:MFMessageComposeViewController = MFMessageComposeViewController()
if let phoneNumber = self.phoneNumber as String? {
messageController.recipients = ["\(phoneNumber)"]
messageController.messageComposeDelegate = self
self.presentViewController(messageController, animated: true, completion: nil)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>/Rails/Wingman/APIRequest.swift
//
// APIRequest.swift
// Wingman
//
// Created by <NAME> on 3/20/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import Foundation
// amazon s3 buckets save images, cached images
let RAILS_URL = "https://cryptic-mesa-8497.herokuapp.com"
var email: String?
class APIRequest {
// (responseInfo: [String:AnyObject]) -> ()
// that class func gets called in the user class
//from options, take the body string, change it in json and the nchange the json to data
// USEFULNESS OF BLOCKS VS CREATING A FUNCTION AT THE END: WITH BLOCK, CAN DO SOMETHING SPECIFIC AT THEN END EVERYTIME WE CALL A FUNCTION
class func requestWithOptions(options: [String: AnyObject], andCompletion completion: (responseInfo: [String:AnyObject]?, error: String?) -> ()) {
// wrapping it in a parenthesis otherwise the + sign doesn't see the as String
// the url + users
var url = NSURL(string: RAILS_URL + (options["endpoint"] as! String))
var request = NSMutableURLRequest(URL: url!)
// method is post
request.HTTPMethod = options["method"] as! String
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
//let boundary = self.generateBoundaryString()
//request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if let token = User.currentUser().token {
request.setValue(token, forHTTPHeaderField: "authentication-token")
}
switch request.HTTPMethod {
case "GET" :
print("GET", terminator: "")
default :
let bodyInfo = options["body"] as! [String: AnyObject]
let requestData = try? NSJSONSerialization.dataWithJSONObject(bodyInfo, options: NSJSONWritingOptions())
let jsonString = NSString(data: requestData!, encoding: NSUTF8StringEncoding)
let postLength = "\(jsonString!.length)"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
let postData = jsonString?.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
request.HTTPBody = postData
}
// mainQueue is not the main thread (just a queue)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error == nil {
// do something with data
// mutable containers so we can change something with it
let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)) as? [String:AnyObject]
// WE CALL THE COMPLETION BLOCK
completion(responseInfo: json, error: nil)
}
else {
var errorString = error!.description
//completion(responseInfo: nil, error: errorString)
print(errorString)
}
}
}
}
<file_sep>/Rails/Wingman/RegisterViewController.swift
//
// RegisterViewController.swift
// Wingman
//
// Created by <NAME> on 3/2/15.
// Copyright (c) 2015 <NAME>. All rights reserved.
//
import UIKit
@IBDesignable
class RegisterViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, SignedInProtocol
{
let segments = ["male", "female"]
var registerInfo = [String:AnyObject]()
var myCustomBackButtonItem: UIBarButtonItem?
var customButton: UIButton?
var imageView: UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
//
// pickProfilePicButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlState.Highlighted)
//
User.currentUser().registerDelegate = self
self.registerInfo["gender"] = "male"
self.interestField.layer.cornerRadius = 5
self.navigationController?.setNavigationBarHidden(false, animated: true)
customButton = UIButton(type: UIButtonType.Custom)
customButton!.setBackgroundImage(UIImage(named: "backbutton"), forState: UIControlState.Normal)
customButton!.sizeToFit()
customButton!.hidden = true
customButton!.addTarget(self, action: "popToRoot:", forControlEvents: UIControlEvents.TouchUpInside)
myCustomBackButtonItem = UIBarButtonItem(customView: customButton!)
self.navigationItem.leftBarButtonItem = myCustomBackButtonItem
imageView = UIImageView(frame: CGRect(x: -80, y: 0, width: 300, height: 40))
imageView!.clipsToBounds = true
imageView!.contentMode = .ScaleAspectFill
imageView!.hidden = true
let image = UIImage(named: "bar")
imageView!.image = image
navigationItem.titleView = imageView
}
override func viewWillAppear(animated: Bool) {
self.imageView!.hidden = true
self.createUsernameField.hidden = true
self.createPasswordField.hidden = true
self.enterEmailField.hidden = true
self.pickedImage.hidden = true
}
override func viewDidAppear(animated: Bool) {
customButton!.hidden = false
self.imageView!.hidden = false
springScaleFrom(customButton!, x: -100, y: 0, scaleX: 0.5, scaleY: 0.5)
springScaleFrom(imageView!, x: 200, y: 0, scaleX: 0.5, scaleY: 0.5)
self.logoImageView.layer.cornerRadius = 50
self.logoImageView.clipsToBounds = true
// animate the logoImageView
let scale1 = CGAffineTransformMakeScale(0.5, 0.5)
let translate1 = CGAffineTransformMakeTranslation(0, -100)
self.createUsernameField.transform = CGAffineTransformConcat(scale1, translate1)
spring(1) {
self.createUsernameField.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.createUsernameField.transform = CGAffineTransformConcat(scale, translate)
}
// animate the textViews
let scale2 = CGAffineTransformMakeScale(0.5, 0.5)
let translate2 = CGAffineTransformMakeTranslation(0, -100)
self.enterEmailField.transform = CGAffineTransformConcat(scale2, translate2)
spring(1) {
self.enterEmailField.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.enterEmailField.transform = CGAffineTransformConcat(scale, translate)
}
var scale3 = CGAffineTransformMakeScale(0.5, 0.5)
var translate3 = CGAffineTransformMakeTranslation(0, -100)
self.createPasswordField.transform = CGAffineTransformConcat(scale3, translate3)
spring(1) {
self.createPasswordField.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.createPasswordField.transform = CGAffineTransformConcat(scale, translate)
}
let scale4 = CGAffineTransformMakeScale(0.5, 0.5)
var translate4 = CGAffineTransformMakeTranslation(0, 200)
self.pickedImage.transform = CGAffineTransformConcat(scale4, translate4)
spring(1) {
self.pickedImage.hidden = false
let scale = CGAffineTransformMakeScale(1, 1)
let translate = CGAffineTransformMakeTranslation(0, 0)
self.pickedImage.transform = CGAffineTransformConcat(scale, translate)
}
if pickProfilePicButton.highlighted == true {
pickProfilePicButton.backgroundColor = UIColor.blueColor()
}
if pickProfilePicButton.highlighted == false{
pickProfilePicButton.backgroundColor = UIColor.clearColor()
}
if let _ = User.currentUser().token {
let tbc = storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
print(tbc)
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
// self.navigationController?.navigationBar.backgroundColor = UIColor.clearColor()
//
// self.navigationController?.navigationBar.tintColor = UIColor.clearColor()
//
// self.navigationController?.navigationBar.barTintColor = UIColor.clearColor()
//
self.navigationController?.navigationBar.barStyle = UIBarStyle.BlackTranslucent
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
func buttonClicked(sender:UIButton)
{
if sender.highlighted {
sender.backgroundColor = UIColor.blueColor()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//this is the button to initiate choosing a profile pic
@IBAction func pickImage(sender: AnyObject) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
@IBOutlet weak var pickedImage: UIImageView!
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
self.dismissViewControllerAnimated(true, completion: nil)
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
//profileImage = scaleImage(profileImage, newSize: CGSizeMake(600, 600))
pickedImage.image = image
var resizedImage = self.resizeImage(image, toSize: CGSizeMake(100, 100))
// create a random number
let randomNumber = arc4random_uniform(UINT32_MAX)
// create a specific string for the amazonS3 URL of our image. That string consists of our image image name with a random number.
var photoFileName = "\(randomNumber)_avatar.png"
// create a directory for storing the image and add the image name to that directory
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var filePath = paths[0] + photoFileName
// create a PNG version of our image and store it in our directory
UIImagePNGRepresentation(resizedImage)!.writeToFile(filePath, atomically: true)
// take our singleton and call the postObject pre-defined method (pre-defined in the AFAmazonS3Manager class)
// this method posts the filePath (of our directory with the image in it to the amazonS3. If successful, amazonS3 will store our image and we will have an amazonS3 link with our image in it.
S3.model().s3Manager.postObjectWithFile(filePath, destinationPath: "", parameters: nil, progress: { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) -> Void in
print("\(Int(CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) * 100))% Uploaded")
}, success: { (responseObject) -> Void in
// if successful, we have an amazon S3 link with our image in it. The url ends with our photoFileName (the specific string we created above with a random number at the end of it). We then store the imageUrl to our registerInfo dictionary that we're going to send to Rails. We only send that Url to Rails and not the image itself.
print(responseObject)
// store the imageUrl to our registerInfo dictionary that we're going to send to Rails
self.registerInfo["image_string"] = "https://wingmen.s3.amazonaws.com/\(photoFileName)"
}) { (error) -> Void in
// if error do stuff
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func resizeImage(original : UIImage, toSize size:CGSize) -> UIImage
{
var imageSize:CGSize = CGSizeZero
if (original.size.width < original.size.height)
{
imageSize.height = size.width * original.size.height / original.size.width
imageSize.width = size.width
}
else
{
imageSize.height = size.height
imageSize.width = size.height * original.size.width / original.size.height
}
UIGraphicsBeginImageContext(imageSize)
// draw the new image with the imageSize.width and height (based on the UIImageView size)
original.drawInRect(CGRectMake(0,0,imageSize.width,imageSize.height))
// put the drawing in a UIImage
let resizedImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return resizedImage
}
// func resizeImage(orignalImage: UIImage, withSize: CGSize) {
//
// var scale : Float = if(originalImage.size.height > originalImage.size.width) { size.width / originalImage.size.width } else { size.height / originalImage.size.height}
/*
-(UIImage *)resizeImage:(UIImage *) originalImage withSize: (CGSize)size {
float scale = (originalImage.size.height > originalImage.size.width) ? size.width / originalImage.size.width : size.height / originalImage.size.height;
CGSize ratioSize = CGSizeMake(originalImage.size.width * scale, originalImage.size.height * scale);
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[originalImage drawInRect:CGRectMake(0, 0, ratioSize.width, ratioSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
*/
@IBOutlet weak var createUsernameField: UITextField!
@IBOutlet weak var enterEmailField: UITextField!
@IBOutlet weak var createPasswordField: UITextField!
@IBOutlet weak var pickProfilePicButton: UIButton!
@IBOutlet weak var logoImageView: UIImageView!
@IBAction func genderSC(sender: UISegmentedControl) {
let selectedSegment = sender.selectedSegmentIndex
if selectedSegment == 0 {
registerInfo["gender"] = "male"
print("isOff")
}
if selectedSegment == 1 {
registerInfo["gender"] = "female"
print("isOn")
}
// var segmentedControl: UISegmentedControl!
// let selectedSegmentIndex = sender.selectedSegmentIndex
//
// let selectedSegmentText = sender.titleForSegmentAtIndex(selectedSegmentIndex)
//
// let segments = ["Male", "Female"]
//
// segmentedControl = UISegmentedControl(items: segments)
//
// segmentedControl.addTarget(self, action: "segmentedControlValueChanged:", forControlEvents: .ValueChanged)
//
//
//
//
//
// println("Segment \(selectedSegmentIndex) with text of" + " \(selectedSegmentText) is selected")
}
@IBOutlet @IBInspectable weak var interestField: UITextView!
func popToRoot(sender:UIBarButtonItem) {
self.navigationController?.popToRootViewControllerAnimated(true)
}
func goToApp() {
let tbc = self.storyboard?.instantiateViewControllerWithIdentifier("TabBarController") as? UITabBarController
tbc?.tabBar.tintColor = UIColor.whiteColor()
tbc?.tabBar.barStyle = UIBarStyle.Black
print(tbc)
UIApplication.sharedApplication().keyWindow?.rootViewController = tbc
}
func signInUnsuccesful(error: String) {
let alert:UIAlertView = UIAlertView(title: "Error", message: error, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
func update() {
let gender = registerInfo["gender"] as! String
let imageUrl = registerInfo["image_string"] as! String
if let userId = User.currentUser().userId {
User.currentUser().update(gender, interests: self.interestField.text, userId: userId, imageFile:
imageUrl)
}
}
@IBAction func signUp(sender: AnyObject) {
//how to take results from func genderSC and put it here?
// user["gender"] = String(genderSC(UISegmentedControl(items: segments)))
//how to save a pic in Parse?
//user["profile pic"] =
//user["interests"] = interestField[] or .text
// other fields can be set just like with PFObject
//user["phone"] = "415-392-0202"
let fieldValues: [String] = [createUsernameField.text!, createPasswordField.text!, enterEmailField.text!, interestField.text!] //interestField.text
if fieldValues.indexOf("") != nil || self.registerInfo["image_string"] == nil {
//all fields are not filled in
let alertViewController = UIAlertController(title: "Submission Error", message: "Please complete all fields", preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertViewController.addAction(defaultAction)
presentViewController(alertViewController, animated: true, completion: nil)
}
else {
registerInfo["username"] = self.createUsernameField.text
registerInfo["interests"] = self.interestField.text
User.currentUser().signUp(createUsernameField.text!, email: enterEmailField.text!, password: create<PASSWORD>.text!)
}
}
}
|
7b62eea25717cee11ec28a11fed6be3b0ef10962
|
[
"Swift"
] | 17 |
Swift
|
Will16/Wingman
|
44504e88ca263db46299549b77d72f6a39705bfe
|
41b768647df281dc0e9f618b92542ac4f8f5234d
|
refs/heads/master
|
<repo_name>sinamoeini/xtal<file_sep>/src/command_sine_arc.h
#ifdef Command_Style
CommandStyle(Command_sine_arc,sine_arc)
#else
#ifndef __xtal__command_sine_arc__
#define __xtal__command_sine_arc__
#include <stdio.h>
#include "init.h"
class Command_sine_arc: protected InitPtrs
{
private:
type0 elliptic_e(type0);
type0 elliptic_e(type0,type0);
type0 solve(type0);
inline void mid_map(type0,type0,type0
,type0,type0,type0&,type0&);
protected:
public:
Command_sine_arc(Xtal*,int,char**);
~Command_sine_arc();
};
#endif
#endif
<file_sep>/src/memory.h
#ifndef __xtal__memory__
#define __xtal__memory__
#include <iostream>
#include <exception>
#include <stdio.h>
#include "init.h"
#define GROW(A,oldsize,newsize) memory->groww(A,oldsize,newsize,#A,__LINE__,__FILE__,__FUNCTION__)
#define CREATE1D(A,d0) memory->fcreate(A,d0,#A,__LINE__,__FILE__,__FUNCTION__)
#define CREATE2D(A,d0,d1) memory->fcreate(A,d0,d1,#A,__LINE__,__FILE__,__FUNCTION__)
using namespace std;
class Memory {
private:
protected:
public:
Memory(){}
~Memory(){}
// allocation for 1d arrays
template <typename TYPE>
TYPE* fcreate(TYPE*& array,int d0,const char* name,int line_no,const char* file,const char* function)
{
if(d0==0)
{
array=NULL;
return NULL;
}
//array = NULL;
try
{
array = new TYPE [d0];
}
catch(bad_alloc&)
{
printf("memory allocation "
"failure in file %s, function %s, line: %d for variable: %s",file,function,line_no,name);
exit(EXIT_FAILURE);
}
return array;
}
template <typename TYPE>
TYPE** fcreate(TYPE**& array,int d0,int d1,const char* name,int line_no,const char* file,const char* function)
{
fcreate(array,d0,name,line_no,file,function);
for(int i=0;i<d0;i++)
fcreate(array[i],d1,name,line_no,file,function);
return array;
}
template <typename TYPE>
TYPE* groww(TYPE*& array,int oldsize,int newsize,const char* name,int line_no,const char* file,const char* function)
{
if (oldsize==0)
{
return fcreate(array,newsize,name,line_no,file,function);
}
else if (oldsize==newsize)
{
return array;
}
else
{
TYPE* newarray=array;
try
{
int size1=newsize;
int size2=oldsize;
int size=MIN(size1,size2);
newarray = new TYPE[newsize];
memcpy(newarray,array,size*sizeof(TYPE));
delete [] array;
array=newarray;
}
catch (bad_alloc&)
{
printf("reallocation "
"failure in file %s, function %s, line: %d for variable: %s",file,function,line_no,name);
exit(EXIT_FAILURE);
}
return array;
}
}
template <typename TYPE>
TYPE* resizee(TYPE*& array,int oldsize,int newsize,const char* name,int line_no,const char* file,const char* function)
{
if (oldsize==0)
{
return fcreate(array,newsize,name,line_no,file,function);
}
else if (oldsize==newsize)
{
return array;
}
else
{
TYPE* newarray=array;
try
{
newarray = new TYPE[newsize];
memcpy(newarray,array,newsize*sizeof(TYPE));
delete [] array;
array=newarray;
}
catch (bad_alloc&)
{
printf("reallocation "
"failure in file %s, function %s, line: %d for variable: %s",file,function,line_no,name);
exit(EXIT_FAILURE);
}
return array;
}
}
};
#endif /* defined(__xtal__memory__) */
<file_sep>/src/command_move.cpp
#include "command_move.h"
#include "memory.h"
#include "error.h"
#include "box2cfg.h"
#include "box_collection.h"
#include "region_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_move::Command_move(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=6 && narg!=7)
{
error->warning("move command needs 5 arguments\n"
"SYNTAX: move x box dx dy dz\n"
"or\n"
"SYNTAX: move s box ds_x ds_y ds_z\n"
"or\n"
"SYNTAX: move region x box dx dy dz\n"
"or\n"
"SYNTAX: move region s box ds_x ds_y ds_z\n");
return;
}
int iarg=1;
Region* region=NULL;
if(narg==7)
{
int iregion=region_collection->find(arg[1]);
if(iregion<0)
{
error->warning("region %s not found",arg[1]);
return;
}
region=region_collection->regions[iregion];
iarg++;
}
int mode;
if(strcmp(arg[iarg],"s")==0)
mode=0;
else if(strcmp(arg[iarg],"x")==0)
mode=1;
else
{
error->warning("displacement mode %s is invalid (s or x)",arg[iarg]);
return;
}
iarg++;
int ibox=box_collection->find(arg[iarg]);
if(ibox<0)
{
error->warning("box %s not found",arg[iarg]);
return;
}
iarg++;
type0* dx;
type0* ds;
CREATE1D(dx,3);
CREATE1D(ds,3);
dx[0]=atof(arg[iarg++]);
dx[1]=atof(arg[iarg++]);
dx[2]=atof(arg[iarg++]);
ds[0]=ds[1]=ds[2]=0.0;
Box* box=box_collection->boxes[ibox];
if(mode==1)
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
ds[i]+=box->B[j][i]*dx[j];
}
else
for(int i=0;i<3;i++)
ds[i]=dx[i];
for(int i=0;i<3;i++)
{
while (ds[i]<0.0)
ds[i]++;
while (ds[i]>=1.0)
ds[i]--;
}
if(region==NULL)
{
for(int i=0;i<box->natms;i++)
{
for(int j=0;j<3;j++)
{
box->s[3*i+j]+=ds[j];
if( box->s[3*i+j]>=1.0)
box->s[3*i+j]--;
}
}
}
else
{
type0* s=box->s;
for(int i=0;i<box->natms;i++)
{
if(region->belong(box->H,&s[3*i]))
{
for(int j=0;j<3;j++)
{
box->s[3*i+j]+=ds[j];
if( box->s[3*i+j]>=1.0)
box->s[3*i+j]--;
}
}
}
}
delete [] dx;
delete [] ds;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_move::~Command_move()
{
}
<file_sep>/src/region_collection.h
#ifndef __xtal__region_collection__
#define __xtal__region_collection__
#include "init.h"
#include "region.h"
#include <stdio.h>
class RegionCollection:protected InitPtrs
{
private:
void del(int);
protected:
public:
RegionCollection(Xtal*);
~RegionCollection();
//symbol based functions
int find(char*);
void del(char*);
int add_cmd(int,char**);
Region** regions;
int no_regions;
};
#endif /* defined(__xtal__region_collection__) */
<file_sep>/src/box.cpp
#include "box.h"
#include <math.h>
#include "memory.h"
#include "xmath.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Box::Box(Xtal* xtal):InitPtrs(xtal)
{
natms=nghosts=no_types=dof_xst=0;
CREATE2D(H,3,3);
CREATE2D(B,3,3);
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Box::Box(Xtal* xtal,char* name):InitPtrs(xtal),
atom_names(NULL),
mass(NULL),
type_count(NULL),
s(NULL),
type(NULL),
dof(NULL)
{
natms=nghosts=no_types=dof_xst=0;
CREATE2D(H,3,3);
CREATE2D(B,3,3);
int lngth=static_cast<int>(strlen(name))+1;
CREATE1D(box_name,lngth);
memcpy(box_name,name,lngth*sizeof(char));
}
/*--------------------------------------------
int dof_xst;
char* box_name;
int no_types;
char** atom_names;
type0* mass;
int* type_count;
type0** H;
type0** B;
int natms;
type0* s;
int* type;
char* dof;
--------------------------------------------*/
Box::Box(Box& other):InitPtrs(other.xtal)
{
natms=nghosts=no_types=dof_xst=0;
CREATE2D(H,3,3);
CREATE2D(B,3,3);
box_name=NULL;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
B[i][j]=other.B[i][j];
H[i][j]=other.H[i][j];
}
natms=other.natms;
nghosts=other.nghosts;
no_types=other.no_types;
dof_xst=other.dof_xst;
CREATE1D(mass,no_types);
CREATE1D(type_count,no_types);
CREATE1D(atom_names,no_types);
for(int i=0;i<no_types;i++)
{
int len=static_cast<int>(strlen(other.atom_names[i]))+1;
CREATE1D(atom_names[i],len);
memcpy(atom_names[i],other.atom_names[i],len*sizeof(char));
}
CREATE1D(type,natms);
CREATE1D(s,3*natms);
if(dof_xst)
CREATE1D(dof,natms*3);
memcpy(type,other.type,natms*sizeof(int));
memcpy(s,other.s,3*natms*sizeof(type0));
if(dof_xst)
memcpy(dof,other.dof,3*natms*sizeof(char));
}
/*--------------------------------------------
change the name of the box
--------------------------------------------*/
void Box::chng_name(char* name)
{
delete [] box_name;
int lngth=static_cast<int>(strlen(name))+1;
CREATE1D(box_name,lngth);
memcpy(box_name,name,lngth*sizeof(char));
}
/*--------------------------------------------
constructor
--------------------------------------------*/
void Box::join(Box* box0,Box* box1,int dim)
{
if(no_types)
{
for(int i=0;i<no_types;i++)
{
delete [] atom_names[i];
}
delete [] atom_names;
delete [] mass;
delete [] type_count;
}
if(natms)
{
delete [] s;
delete [] type;
if(dof_xst)
delete [] dof;
}
natms=no_types=dof_xst=0;
//allocate s and type
natms=box0->natms+box1->natms;
CREATE1D(s,natms*3);
CREATE1D(type,natms);
dof_xst=box0->dof_xst;
if(dof_xst)
CREATE1D(dof,natms*3);
// add the tyoes
for(int i=0;i<box0->no_types;i++)
{
add_type(box0->mass[i],box0->atom_names[i]);
type_count[i]=box0->type_count[i];
}
int* type_ref;
CREATE1D(type_ref,box1->no_types);
for(int i=0;i<box1->no_types;i++)
{
type_ref[i]=add_type(box1->mass[i],box1->atom_names[i]);
type_count[type_ref[i]]+=box1->type_count[i];
}
for(int iatom=0;iatom<box0->natms;iatom++)
type[iatom]=box0->type[iatom];
if(dof_xst)
for(int iatom=0;iatom<3*box0->natms;iatom++)
dof[iatom]=box0->dof[iatom];
for(int iatom=0;iatom<box1->natms;iatom++)
type[box0->natms+iatom]=type_ref[box1->type[iatom]];
if(dof_xst)
for(int iatom=0;iatom<3*box1->natms;iatom++)
dof[3*box0->natms+iatom]=box1->dof[iatom];
delete [] type_ref;
// we are done with type
// pre-req to figure out new s
type0 r0,r1,rtot;
type0** B0=box0->B;
r0=1.0/sqrt(B0[0][dim]*B0[0][dim]+B0[1][dim]*B0[1][dim]+B0[2][dim]*B0[2][dim]);
B0=box1->B;
r1=1.0/sqrt(B0[0][dim]*B0[0][dim]+B0[1][dim]*B0[1][dim]+B0[2][dim]*B0[2][dim]);
rtot=r0+r1;
r0/=rtot;
r1/=rtot;
type0 smin_0=1.0,smin_1=1.0,smax_0=0.0,smax_1=0.0,del_s;
for(int i=0;i<box0->natms;i++)
{
smin_0=MIN(smin_0,box0->s[3*i+dim]);
smax_0=MAX(smax_0,box0->s[3*i+dim]);
}
smin_0*=r0;
smax_0*=r0;
for(int i=0;i<box1->natms;i++)
{
smin_1=MIN(smin_1,box1->s[3*i+dim]);
smax_1=MAX(smax_1,box1->s[3*i+dim]);
}
smin_1*=r1;
smin_1+=r0;
smax_1*=r1;
smax_1+=r0;
del_s=0.5*((1.0+smin_0-smax_1)-(smin_1-smax_0));
// taking care of s
int icomp=0;
for(int i=0;i<box0->natms;i++)
{
for(int j=0;j<3;j++)
s[icomp+j]=box0->s[3*i+j];
s[icomp+dim]*=r0;
icomp+=3;
}
for(int i=0;i<box1->natms;i++)
{
for(int j=0;j<3;j++)
s[icomp+j]=box1->s[3*i+j];
s[icomp+dim]*=r1;
s[icomp+dim]+=r0+del_s;
icomp+=3;
}
// taking care of H and B
for(int i=0;i<3;i++)
{
if(i!=dim)
{
for(int j=0;j<3;j++)
H[i][j]=0.5*(box0->H[i][j]+box1->H[i][j]);
}
else
{
for(int j=0;j<3;j++)
H[i][j]=box0->H[i][j]+box1->H[i][j];
}
}
M3INV_TRI_LOWER(H,B);
}
/*--------------------------------------------
constructor
--------------------------------------------*/
void Box::join(Box* box0,Box* box1)
{
if(no_types)
{
for(int i=0;i<no_types;i++)
{
delete [] atom_names[i];
}
delete [] atom_names;
delete [] mass;
delete [] type_count;
}
if(natms)
{
delete [] s;
delete [] type;
if(dof_xst)
delete [] dof;
}
natms=no_types=dof_xst=0;
//allocate s and type
natms=box0->natms+box1->natms;
CREATE1D(s,natms*3);
CREATE1D(type,natms);
dof_xst=box0->dof_xst;
if(dof_xst)
CREATE1D(dof,natms*3);
// add the types
for(int i=0;i<box0->no_types;i++)
{
add_type(box0->mass[i],box0->atom_names[i]);
type_count[i]=box0->type_count[i];
}
int* type_ref;
CREATE1D(type_ref,box1->no_types);
for(int i=0;i<box1->no_types;i++)
{
type_ref[i]=add_type(box1->mass[i],box1->atom_names[i]);
type_count[type_ref[i]]+=box1->type_count[i];
}
for(int iatom=0;iatom<box0->natms;iatom++)
type[iatom]=box0->type[iatom];
if(dof_xst)
for(int iatom=0;iatom<3*box0->natms;iatom++)
dof[iatom]=box0->dof[iatom];
for(int iatom=0;iatom<box1->natms;iatom++)
type[box0->natms+iatom]=type_ref[box1->type[iatom]];
if(dof_xst)
for(int iatom=0;iatom<3*box1->natms;iatom++)
dof[3*box0->natms+iatom]=box1->dof[iatom];
delete [] type_ref;
// we are done with type
type0 ** A;
CREATE2D(A,3,3);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
A[i][j]=0.0;
for(int k=0;k<3;k++)
A[i][j]+=box0->B[k][i]*box1->H[j][k];
}
// taking care of s
int icomp=0;
for(int i=0;i<box0->natms;i++)
{
for(int j=0;j<3;j++)
s[icomp+j]=box0->s[3*i+j];
icomp+=3;
}
for(int i=0;i<box1->natms;i++)
{
for(int j=0;j<3;j++)
{
s[icomp+j]=0.0;
for(int k=0;k<3;k++)
s[icomp+j]+=A[j][k]*box1->s[3*i+k];
}
icomp+=3;
}
for(int i=0;i<3;i++)
delete [] A[i];
delete [] A;
// taking care of H and B
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
H[i][j]=box0->H[i][j];
B[i][j]=box0->B[i][j];
}
}
/*--------------------------------------------
desstructor
--------------------------------------------*/
Box::~Box()
{
delete [] box_name;
if(no_types)
{
for(int i=0;i<no_types;i++)
{
delete [] atom_names[i];
}
delete [] atom_names;
delete [] mass;
}
for(int i=0;i<3;i++)
{
delete [] H[i];
delete [] B[i];
}
delete [] H;
delete [] B;
if(natms)
{
delete [] s;
delete [] type;
if(dof_xst)
delete [] dof;
}
}
/*--------------------------------------------
find a type
--------------------------------------------*/
int Box::find_type(char* name)
{
int type=-1;
for (int i=0;i<no_types;i++)
if(!strcmp(name,atom_names[i]))
{
type=i;
return type;
}
return type;
}
/*--------------------------------------------
add a type
--------------------------------------------*/
int Box::add_type(type0 m,char* name)
{
int type=-1;
for (int i=0;i<no_types;i++)
if(!strcmp(name,atom_names[i]))
type=i;
if (type!=-1)
return (type);
GROW(type_count,no_types,no_types+1);
GROW(atom_names,no_types,no_types+1);
GROW(mass,no_types,no_types+1);
type_count[no_types]=0;
int lngth= static_cast<int>(strlen(name))+1;
CREATE1D(atom_names[no_types],lngth);
memcpy(atom_names[no_types],name,lngth*sizeof(char));
mass[no_types]=m;
no_types++;
return (no_types-1);
}
/*--------------------------------------------
add an array of atoms
--------------------------------------------*/
void Box::add_atoms(int no,int* type_buff,type0* s_buff)
{
GROW(s,natms*3,(natms+no)*3);
GROW(type,natms,natms+no);
for(int i=0;i<no*3;i++)
{
while(s_buff[i]<0.0)
s_buff[i]++;
while(s_buff[i]>=1.0)
s_buff[i]--;
s[natms*3+i]=s_buff[i];
}
for(int i=0;i<no;i++)
{
type[natms+i]=type_buff[i];
type_count[type_buff[i]]++;
}
natms+=no;
}
/*--------------------------------------------
add an array of atoms
--------------------------------------------*/
void Box::add_atoms(int no,int* type_buff
,type0* s_buff,char* dof_buff)
{
GROW(s,natms*3,(natms+no)*3);
GROW(type,natms,natms+no);
if(dof_xst)
GROW(dof,natms*3,(natms+no)*3);
for(int i=0;i<no*3;i++)
{
while(s_buff[i]<0.0)
s_buff[i]++;
while(s_buff[i]>=1.0)
s_buff[i]--;
s[natms*3+i]=s_buff[i];
}
for(int i=0;i<no;i++)
{
type[natms+i]=type_buff[i];
type_count[type_buff[i]]++;
}
if(dof_xst)
for(int i=0;i<no*3;i++)
dof[natms*3+i]=dof_buff[i];
natms+=no;
}
/*--------------------------------------------
del a list of atoms
--------------------------------------------*/
void Box::del_atoms(int no,int* lst)
{
int tmp_natms=natms;
for(int i=no-1;i>-1;i--)
{
type_count[type[lst[i]]]--;
memcpy(&s[3*lst[i]],&s[3*(natms-1)],3*sizeof(type0));
if(dof_xst)
memcpy(&dof[3*lst[i]],&dof[3*(natms-1)],3*sizeof(char));
memcpy(&type[lst[i]],&type[natms-1],sizeof(int));
natms--;
}
type0* s_tmp;
int* type_tmp;
char* dof_tmp=NULL;
CREATE1D(s_tmp,3*natms);
CREATE1D(type_tmp,natms);
if(dof_xst)
{
CREATE1D(dof_tmp,3*natms);
memcpy(dof_tmp,dof,3*natms*sizeof(char));
}
memcpy(s_tmp,s,3*natms*sizeof(type0));
memcpy(type_tmp,type,natms*sizeof(int));
if(tmp_natms)
{
delete [] s;
delete [] type;
if(dof_xst)
delete [] dof;
}
s=s_tmp;
type=type_tmp;
if(dof_xst)
dof=dof_tmp;
for(int itype=no_types-1;itype>-1;itype--)
if(type_count[itype]==0)
del_type(itype);
}
/*--------------------------------------------
del a all of atoms
--------------------------------------------*/
void Box::del_atoms()
{
if(no_types)
{
for(int i=0;i<no_types;i++)
{
delete [] atom_names[i];
}
delete [] atom_names;
delete [] mass;
}
if(natms)
{
delete [] s;
delete [] type;
if(dof_xst)
delete [] dof;
}
natms=no_types=0;
}
/*--------------------------------------------
change the name of box
--------------------------------------------*/
void Box::change_name(char* name)
{
delete [] box_name;
int lngth=static_cast<int>(strlen(name))+1;
CREATE1D(box_name,lngth);
memcpy(box_name,name,lngth*sizeof(char));
}
/*--------------------------------------------
change the name of box
--------------------------------------------*/
void Box::add_name(char* name)
{
int lngth=static_cast<int>(strlen(name))+1;
CREATE1D(box_name,lngth);
memcpy(box_name,name,lngth*sizeof(char));
}
/*--------------------------------------------
multiple box by three numbers
--------------------------------------------*/
void Box::mul(int* n)
{
type0* nn;
type0* r;
int* ii;
CREATE1D(nn,3);
CREATE1D(r,3);
CREATE1D(ii,3);
for(int i=0;i<3;i++)
nn[i]=static_cast<type0>(n[i]);
for(int i=0;i<3;i++)
r[i]=1.0/nn[i];
int tmp_natms=n[0]*n[1]*n[2]*natms;
type0* tmp_s;
int* tmp_type;
char* tmp_dof=NULL;
CREATE1D(tmp_s,tmp_natms*3);
CREATE1D(tmp_type,tmp_natms);
if(dof_xst)
CREATE1D(tmp_dof,tmp_natms*3);
int icomp=0;
int tmp_icomp=0;
int tmp_iatm=0;
for(ii[0]=0;ii[0]<n[0];ii[0]++)
for(ii[1]=0;ii[1]<n[1];ii[1]++)
for(ii[2]=0;ii[2]<n[2];ii[2]++)
{
icomp=0;
for(int iatm=0;iatm<natms;iatm++)
{
for(int i=0;i<3;i++)
{
tmp_s[tmp_icomp+i]=s[icomp+i]*r[i]+ii[i]*r[i];
if(dof_xst)
tmp_dof[tmp_icomp+i]=dof[icomp+i];
}
tmp_type[tmp_iatm]=type[iatm];
icomp+=3;
tmp_iatm++;
tmp_icomp+=3;
}
}
if(natms)
{
delete [] type;
delete [] s;
if(dof_xst)
delete [] dof;
}
s=tmp_s;
type=tmp_type;
if(dof_xst)
dof=tmp_dof;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
H[i][j]*=nn[i];
M3INV_TRI_LOWER(H,B);
delete [] ii;
delete [] r;
delete [] nn;
natms=tmp_natms;
for(int i=0;i<no_types;i++)
type_count[i]*=n[0]*n[1]*n[2];
}
/*--------------------------------------------
add vaccuum at the top of the box
--------------------------------------------*/
void Box::add_vac(int dim,int t_b,type0 thickness)
{
type0 old_thickness=
1.0/sqrt(B[0][dim]*B[0][dim]+B[1][dim]*B[1][dim]+B[2][dim]*B[2][dim]);
type0 ratio=old_thickness/(old_thickness+thickness);
int icomp=0;
if(t_b==1)
{
for(int iatm=0;iatm<natms;iatm++)
{
s[icomp+dim]*=ratio;
icomp+=3;
}
}
else
{
for(int iatm=0;iatm<natms;iatm++)
{
s[icomp+dim]*=ratio;
s[icomp+dim]+=1.0-ratio;
icomp+=3;
}
}
ratio=(old_thickness+thickness)/old_thickness;
for(int i=0;i<3;i++)
H[dim][i]*=ratio;
M3INV_TRI_LOWER(H,B);
}
/*--------------------------------------------
add vaccuum at the top of the box
--------------------------------------------*/
void Box::ucell_chang(type0** u)
{
type0 det_u,tmp0;
int chk,icomp,natms_new;
int* lo_bound;
int* hi_bound;
type0* s_tmp;
type0* b;
type0* sq;
//type0* d;
type0** n;
type0** H_new;
type0** H_x;
type0* s_new=NULL;
int* type_new=NULL;
char* dof_new=NULL;
CREATE1D(lo_bound,3);
CREATE1D(hi_bound,3);
CREATE1D(s_tmp,3);
CREATE1D(b,3);
CREATE1D(sq,3);
CREATE2D(H_x,3,3);
CREATE2D(H_new,3,3);
CREATE2D(n,3,3);
M3NORMAL(u,n);
det_u=M3DET(u);
// find the lo_bound and hi_bound
for(int i=0;i<3;i++)
{
lo_bound[i]=hi_bound[i]=0.0;
for(int j=0;j<3;j++)
{
lo_bound[i]=MIN(lo_bound[i],static_cast<int>(u[j][i]));
hi_bound[i]=MAX(hi_bound[i],static_cast<int>(u[j][i]));
}
tmp0=0.0;
for(int j=0;j<3;j++)
tmp0+=u[j][i];
lo_bound[i]=MIN(lo_bound[i],static_cast<int>(tmp0));
hi_bound[i]=MAX(hi_bound[i],static_cast<int>(tmp0));
for(int j=0;j<3;j++)
{
lo_bound[i]=MIN(lo_bound[i],static_cast<int>(tmp0-u[j][i]));
hi_bound[i]=MAX(hi_bound[i],static_cast<int>(tmp0-u[j][i]));
}
}
icomp=0;
natms_new=0;
for(int iatm=0;iatm<natms;iatm++)
{
for(int i0=lo_bound[0];i0<hi_bound[0];i0++)
{
for(int i1=lo_bound[1];i1<hi_bound[1];i1++)
{
for(int i2=lo_bound[2];i2<hi_bound[2];i2++)
{
s_tmp[0]=s[icomp]+static_cast<type0>(i0);
s_tmp[1]=s[icomp+1]+static_cast<type0>(i1);
s_tmp[2]=s[icomp+2]+static_cast<type0>(i2);
M3mV3(n,s_tmp,b);
for(int i=0;i<3;i++)
b[i]/=det_u;
chk=1;
for(int i=0;i<3;i++)
if(b[i]<0.0 || b[i]>=1.0)
chk=0;
if(chk)
{
GROW(type_new,natms_new,natms_new+1);
GROW(s_new,3*natms_new,3*natms_new+3);
type_new[natms_new]=type[iatm];
s_new[natms_new*3]=b[0];
s_new[natms_new*3+1]=b[1];
s_new[natms_new*3+2]=b[2];
if(dof_xst)
{
GROW(dof_new,3*natms_new,3*natms_new+3);
dof_new[natms_new*3]=dof[icomp];
dof_new[natms_new*3+1]=dof[icomp+1];
dof_new[natms_new*3+2]=dof[icomp+2];
}
natms_new++;
}
}
}
}
icomp+=3;
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
H_x[i][j]=0.0;
for(int k=0;k<3;k++)
H_x[i][j]+=u[i][k]*H[k][j];
}
}
XMath* xmath=new XMath(xtal);
xmath->square2lo_tri(H_x,H_new);
delete xmath;
for(int i=0;i<3;i++)
{
delete [] H[i];
delete [] H_x[i];
delete [] n[i];
}
delete [] H;
delete [] H_x;
delete [] n;
delete [] b;
delete [] s_tmp;
delete [] sq;
delete [] lo_bound;
delete [] hi_bound;
if(natms)
{
delete [] type;
delete [] s;
if(dof_xst)
delete [] dof;
}
H=H_new;
s=s_new;
type=type_new;
natms=natms_new;
if(dof_xst)
dof_new=dof;
M3INV_TRI_LOWER(H,B);
for(int i=0;i<no_types;i++)
type_count[i]=0;
for(int i=0;i<natms;i++)
type_count[type[i]]++;
}
/*--------------------------------------------
add vaccuum at the top of the box
--------------------------------------------*/
void Box::id_correction()
{
// first test to see if there is a mess
// if there is then do the sort
int chk=1;
int iatm=0;
int lo_cnt=0;
int hi_cnt;
int itype=0;
while (chk && itype<no_types)
{
hi_cnt=lo_cnt+type_count[itype];
while(iatm<hi_cnt && chk)
{
if(type[iatm]!=itype)
chk=0;
iatm++;
}
lo_cnt+=type_count[itype];
itype++;
}
if(chk)
return;
int* new_type;
type0* new_s;
char* new_dof=NULL;
CREATE1D(new_type,natms);
CREATE1D(new_s,natms*3);
if(dof_xst)
CREATE1D(new_dof,natms*3);
int icurs=0;
for(int itype=0;itype<no_types;itype++)
{
for(int iatm=0;iatm<natms;iatm++)
{
if(type[iatm]==itype)
{
new_type[icurs]=iatm;
memcpy(&new_s[icurs*3],&s[iatm*3],3*sizeof(type0));
if(dof_xst)
memcpy(&new_dof[icurs*3],&dof[iatm*3],3*sizeof(char));
new_type[icurs]=itype;
icurs++;
}
}
}
if(natms)
{
delete [] type;
delete [] s;
if(dof_xst)
delete [] dof;
}
type=new_type;
s=new_s;
if(dof_xst)
dof=new_dof;
}
/*--------------------------------------------
add vaccuum at the top of the box
--------------------------------------------*/
void Box::del_type(int itype)
{
char** new_atom_names;
type0* new_mass;
int* new_type_count;
CREATE1D(new_atom_names,no_types-1);
CREATE1D(new_mass,no_types-1);
CREATE1D(new_type_count,no_types-1);
for(int i=0;i<itype;i++)
{
new_atom_names[i]=atom_names[i];
new_mass[i]=mass[i];
new_type_count[i]=type_count[i];
}
delete [] atom_names[itype];
for(int i=itype+1;i<no_types;i++)
{
new_atom_names[i-1]=atom_names[i];
new_mass[i-1]=mass[i];
new_type_count[i-1]=type_count[i];
}
if(no_types)
{
delete [] atom_names;
delete [] type_count;
delete [] mass;
}
atom_names=new_atom_names;
mass=new_mass;
type_count=new_type_count;
for(int i=0;i<natms;i++)
if(type[i]>itype)
type[i]--;
no_types--;
}
/*--------------------------------------------
add vaccuum at the top of the box
--------------------------------------------*/
void Box::rm_frac(int dim,type0 s_lo,type0 s_hi)
{
type0 ds=s_hi-s_lo;
int list_sz=0;
int* list=NULL;
for(int i=dim;i<natms*3;i+=3)
{
if(s[i]<s_lo)
{
s[i]/=1.0-ds;
}
else if(s[i]>=s_hi)
{
s[i]-=ds;
s[i]/=1.0-ds;
}
else
{
GROW(list,list_sz,list_sz+1);
list[list_sz++]=i/3;
}
}
if(list_sz)
{
del_atoms(list_sz,list);
delete [] list;
list_sz=0;
}
for(int i=0;i<3;i++)
H[dim][i]*=1.0-ds;
M3INV_TRI_LOWER(H,B);
}
/*--------------------------------------------
add image at a specific direction
--------------------------------------------*/
void Box::add_image(int idir,type0 s_cut)
{
int s_size=(nghosts+natms)*3;
int type_size=nghosts+natms;
Arr<type0> _s_(s,s_size,3*type_size/10);
Arr<int> _type_(type,type_size,type_size/10);
type0 s_tmp[3];
int type_tmp;
for(int i=0;i<natms;i++)
{
type_tmp=type[i];
s_tmp[0]=s[3*i];
s_tmp[1]=s[3*i+1];
s_tmp[2]=s[3*i+2];
s_tmp[idir]++;
while(s_tmp[idir]<s_cut+1.0)
{
_s_(s_tmp);
_type_(type_tmp);
s_tmp[idir]++;
}
s_tmp[0]=s[3*i];
s_tmp[1]=s[3*i+1];
s_tmp[2]=s[3*i+2];
s_tmp[idir]--;
while(s_tmp[idir]>=-s_cut)
{
_s_(s_tmp);
_type_(type_tmp);
s_tmp[idir]--;
}
}
nghosts=type_size-natms;
}
/*--------------------------------------------
add image at a specific direction
--------------------------------------------*/
void Box::add_ghost(bool (&dirs)[3],type0 (&s_cut)[3] )
{
for(int idim=0;idim<3;idim++)
{
if(!dirs[idim]) continue;
add_image(idim,s_cut[idim]);
}
}
/*--------------------------------------------
add image at a specific direction
--------------------------------------------*/
void Box::del_ghost()
{
if(nghosts==0)
return;
type0* s_=new type0[3*natms];
int* type_=new int[natms];
memcpy(s_,s,3*natms*sizeof(type0));
memcpy(type_,type,natms*sizeof(int));
nghosts=0;
}
<file_sep>/src/command_add_region.cpp
#include "command_add_region.h"
#include "region_collection.h"
#include "error.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_add_region::Command_add_region(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg<3)
{
error->warning("add_region needs at least 3 arguments\n"
"SYNTAX: it varies dependent on the style of region");
return;
}
int iregion=region_collection->find(arg[2]);
if(iregion!=-1)
region_collection->del(arg[2]);
region_collection->add_cmd(narg-1,&arg[1]);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_add_region::~Command_add_region()
{
}
<file_sep>/src/gr.h
#ifndef __xtal__gr__
#define __xtal__gr__
#include <stdio.h>
#include "init.h"
#include "box.h"
class Gr:protected InitPtrs
{
private:
Box*& box;
type0& cutoff;
type0& k_cutoff;
type0 s_cutoff[3];
bool (&dims)[3];
int nbins[3];
int bin_vec[3];
int* bin_list;
int* next_bin;
void get_s_cutoff();
void setup_bins();
void deallocate_bins();
void allocate_gr();
void finalize_gr();
type0 dr,dk;
type0 dr_inv;
void find_bin(type0*,int(&)[3]);
int find_bin(type0*);
int* neigh_bins;
int nneigh_bins;
type0 dist(int&,int&);
int& no_bins;
type0***& gr;
type0***& sr;
void prepare_2d();
void prepare_1d(int);
int ndims;
public:
Gr(Xtal*,type0***&,type0***&,Box*&,bool(&)[3],type0&,type0&,int&);
~Gr();
};
#endif
<file_sep>/src/box2vasp.cpp
#include "box2vasp.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Box2VASP::Box2VASP(Xtal* xtal,char* box,char* name):InitPtrs(xtal)
{
FILE* poscar;
poscar=fopen(name,"w");
int ibox=box_collection->find(box);
int dof_xst=box_collection->boxes[ibox]->dof_xst;
int no_types=box_collection->boxes[ibox]->no_types;
char** atom_names=box_collection->boxes[ibox]->atom_names;
int* type_count=box_collection->boxes[ibox]->type_count;
type0** H=box_collection->boxes[ibox]->H;
int natms=box_collection->boxes[ibox]->natms;
type0* s=box_collection->boxes[ibox]->s;
int* type=box_collection->boxes[ibox]->type;
char* dof=box_collection->boxes[ibox]->dof;
fprintf(poscar,"%s\n",box);
fprintf(poscar,"%23.16lf\n",1.0);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
fprintf(poscar,"%23.16lf",H[i][j]);
fprintf(poscar,"\n");
}
for(int i=0;i<no_types;i++)
fprintf(poscar,"%6s",atom_names[i]);
fprintf(poscar,"\n");
for(int i=0;i<no_types;i++)
fprintf(poscar,"%6d",type_count[i]);
fprintf(poscar,"\n");
if(dof_xst)
fprintf(poscar,"Selective dynamics\n");
fprintf(poscar,"Direct\n");
for(int itype=0;itype<no_types;itype++)
{
for(int iatm=0;iatm<natms;iatm++)
{
if(type[iatm]==itype)
{
for(int i=0;i<3;i++)
fprintf(poscar,"%20.16lf",s[iatm*3+i]);
if(dof_xst)
for(int i=0;i<3;i++)
{
if(dof[3*iatm+i]=='0')
fprintf(poscar," T");
else
fprintf(poscar," F");
}
fprintf(poscar,"\n");
}
}
}
fclose(poscar);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Box2VASP::~Box2VASP()
{
}<file_sep>/src/box2lammps.cpp
#include <math.h>
#include "box2lammps.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Box2LAMMPS::Box2LAMMPS(Xtal* xtal,char* box,char* name):InitPtrs(xtal)
{
lammpsfile=fopen(name,"w");
int ibox=box_collection->find(box);
int no_types=box_collection->boxes[ibox]->no_types;
char** atom_names=box_collection->boxes[ibox]->atom_names;
type0* mass=box_collection->boxes[ibox]->mass;
type0** H=box_collection->boxes[ibox]->H;
int natms=box_collection->boxes[ibox]->natms;
type0* s=box_collection->boxes[ibox]->s;
int* type=box_collection->boxes[ibox]->type;
fprintf(lammpsfile,"#");
for(int i=0;i<no_types;i++)
fprintf(lammpsfile," %s(%lf)",atom_names[i],mass[i]);
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"%d atoms\n",natms);
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"%d atom types\n",no_types);
bool triclinic=false;
if(H[1][0]!=0.0)
triclinic=true;
if(H[2][0]!=0.0)
triclinic=true;
if(H[2][1]!=0.0)
triclinic=true;
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"%lf %lf xlo xhi\n",0.0,H[0][0]);
fprintf(lammpsfile,"%lf %lf ylo yhi\n",0.0,H[1][1]);
fprintf(lammpsfile,"%lf %lf zlo zhi\n",0.0,H[2][2]);
if(triclinic) fprintf(lammpsfile,"%lf %lf %lf xy xz yz\n",H[1][0],H[2][0],H[2][1]);
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"Masses\n");
fprintf(lammpsfile,"\n");
for(int i=0;i<no_types;i++)
fprintf(lammpsfile,"%d %lf\n",i+1,mass[i]);
type0 tmp;
fprintf(lammpsfile,"\n");
fprintf(lammpsfile,"Atoms\n");
fprintf(lammpsfile,"\n");
for(int i=0;i<natms;i++)
{
fprintf(lammpsfile,"%d %d",i+1,type[i]+1);
for(int j=0;j<3;j++)
{
tmp=0.0;
for(int k=0;k<3;k++)
tmp+=H[k][j]*s[3*i+k];
fprintf(lammpsfile," %lf",tmp);
}
fprintf(lammpsfile,"\n");
}
fclose(lammpsfile);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Box2LAMMPS::~Box2LAMMPS()
{
}
<file_sep>/src/command_list_id.cpp
#include <string>
#include <stdlib.h>
#include <math.h>
#include "command_list_id.h"
#include "box_collection.h"
#include "region_collection.h"
#include "error.h"
#include "memory.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_list_id::Command_list_id(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=4 && narg!=5)
{
error->warning("list_id command needs 3 or 4 arguments\n"
"SYNTAX: list_id box region id_file\n"
"or\n"
"SYNTAX: list_id box region type id_file");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
int iregion=region_collection->find(arg[2]);
if(iregion<0)
{
error->warning("region %s not found",arg[2]);
return;
}
box_collection->boxes[ibox]->id_correction();
int natms=box_collection->boxes[ibox]->natms;
type0** H=box_collection->boxes[ibox]->H;
type0* s=box_collection->boxes[ibox]->s;
int* id_lst;
CREATE1D(id_lst,natms);
int icomp=0;
int no=0;
if(narg==4)
{
for(int i=0;i<natms;i++)
{
if(region_collection->regions[iregion]->belong(H,&s[icomp]))
id_lst[no++]=i;
icomp+=3;
}
}
else
{
int itype=box_collection->boxes[ibox]->find_type(arg[3]);
int* type=box_collection->boxes[ibox]->type;
for(int i=0;i<natms;i++)
{
if(type[i]==itype && region_collection->regions[iregion]->belong(H,&s[icomp]))
id_lst[no++]=i;
icomp+=3;
}
}
FILE* idfile;
idfile=fopen(arg[narg-1],"w");
for(int i=0;i<no;i++)
fprintf(idfile,"%d\n",id_lst[i]);
fclose(idfile);
if(natms)
delete [] id_lst;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_list_id::~Command_list_id()
{
}
<file_sep>/src/command_box2vasp.cpp
#include "command_box2vasp.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "box2vasp.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_box2vasp::Command_box2vasp(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("box2vasp command needs 2 arguments\n"
"SYNTAX: box2vasp box file");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("%s box not found",arg[1]);
return;
}
/*
if(!box_collection->boxes[ibox]->dof_xst)
{
error->warning("box %s does not have dof set",arg[1]);
return;
}
*/
class Box2VASP* box2vasp=new Box2VASP(xtal,arg[1],arg[2]);
delete box2vasp;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_box2vasp::~Command_box2vasp()
{
}
<file_sep>/src/command_mismatch.cpp
#include <math.h>
#include "command_mismatch.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_mismatch::Command_mismatch(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=6)
{
error->warning("mismatch command needs 5 arguments\n"
"SYNTAX: mismatch box_0 box_1 N_x N_y N_z");
return;
}
int ibox0=box_collection->find(arg[1]);
if(ibox0<0)
{
error->warning("box %s not found",arg[1]);
return;
}
int ibox1=box_collection->find(arg[2]);
if(ibox1<0)
{
error->warning("box %s not found",arg[2]);
return;
}
int* n0;
CREATE1D(n0,3);
for(int i=0;i<3;i++)
n0[i]=atoi(arg[3+i]);
for(int i=0;i<3;i++)
{
if(n0[i]<=0)
{
error->warning("for mismatch n[%d] should be greater than 0",i);
delete [] n0;
return;
}
}
int* n1;
CREATE1D(n1,3);
type0* eps_0;
type0* eps_1;
CREATE1D(eps_0,3);
CREATE1D(eps_1,3);
type0** H0=box_collection->boxes[ibox0]->H;
type0** H1=box_collection->boxes[ibox1]->H;
type0 tmp,tmp0,tmp1;
for(int i=0;i<3;i++)
{
tmp0=tmp1=0.0;
for(int j=0;j<3;j++)
{
tmp0+=H0[i][j]*H0[i][j];
tmp1+=H1[i][j]*H1[i][j];
}
n1[i]=static_cast<int>(sqrt(tmp0/tmp1)*static_cast<type0>(n0[i])+0.5);
tmp=0.0;
for(int j=0;j<3;j++)
{
tmp+=(static_cast<type0>(n0[i])*H0[i][j]+static_cast<type0>(n1[i])*H1[i][j])
*(static_cast<type0>(n0[i])*H0[i][j]+static_cast<type0>(n1[i])*H1[i][j])*0.25;
}
tmp=sqrt(tmp);
eps_0[i]=tmp/(sqrt(tmp0)*static_cast<type0>(n0[i]))-1.0;
eps_1[i]=tmp/(sqrt(tmp1)*static_cast<type0>(n1[i]))-1.0;
}
int natms0=box_collection->boxes[ibox0]->natms*n0[0]*n0[1]*n0[2];
int natms1=box_collection->boxes[ibox1]->natms*n1[0]*n1[1]*n1[2];
printf("\n");
printf("%s: %d atoms\n",arg[1],natms0);
for(int i=0;i<2;i++)
printf("%d\u00D7",n0[i]);
printf("%d\n",n0[2]);
printf("epsilon: ");
for(int i=0;i<2;i++)
printf("%lf ",eps_0[i]);
printf("%lf\n",eps_0[2]);
printf("\n");
printf("%s: %d atoms\n",arg[2],natms1);
for(int i=0;i<2;i++)
printf("%d\u00D7",n1[i]);
printf("%d\n",n1[2]);
printf("epsilon: ");
for(int i=0;i<2;i++)
printf("%lf ",eps_1[i]);
printf("%lf\n",eps_1[2]);
printf("\n");
delete [] eps_0;
delete [] eps_1;
delete [] n1;
delete [] n0;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_mismatch::~Command_mismatch()
{
}
<file_sep>/src/command_cfg2box.h
#ifdef Command_Style
CommandStyle(Command_cfg2box,cfg2box)
#else
#ifndef __xtal__command_cfg2box__
#define __xtal__command_cfg2box__
#include "init.h"
#include <stdio.h>
class Command_cfg2box: protected InitPtrs
{
private:
protected:
public:
Command_cfg2box(Xtal*,int,char**);
~Command_cfg2box();
};
#endif
#endif
<file_sep>/src/command_arc.h
#ifdef Command_Style
CommandStyle(Command_arc,arc)
#else
#ifndef __xtal__command_arc__
#define __xtal__command_arc__
#include <stdio.h>
#include "init.h"
class Command_arc: protected InitPtrs
{
private:
inline void mid_map(type0,type0,type0
,type0,type0,type0&,type0&);
type0 r1(type0,type0);
type0 r2(type0,type0);
type0 n1(type0,type0);
type0 n2(type0,type0);
type0 l,w;
protected:
public:
Command_arc(Xtal*,int,char**);
~Command_arc();
};
#endif
#endif
<file_sep>/src/command_vasp2box.cpp
#include "command_vasp2box.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "vasp2box.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_vasp2box::Command_vasp2box(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("cfg2box command needs 2 arguments\n"
"SYNTAX: cfg2box box file.cfg");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox>=0)
{
box_collection->del(arg[1]);
}
box_collection->add(arg[1]);
xtal->error_flag=0;
class VASP2Box* vasp2box=new VASP2Box(xtal,arg[1],arg[2]);
delete vasp2box;
if(xtal->error_flag==-1)
{
box_collection->del(arg[1]);
xtal->error_flag=0;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_vasp2box::~Command_vasp2box()
{
}
<file_sep>/src/cfg2box.h
#ifndef __xtal__cfg2box__
#define __xtal__cfg2box__
#include <stdio.h>
#include "init.h"
class CFG2Box :protected InitPtrs
{
private:
FILE* cfgfile;
char* file_name;
type0** H0;
type0** eta;
type0** eta_sq;
type0** trns;
type0** H_x;
type0** Ht;
type0* sq;
type0* b;
type0* s_buff;
int* type_buff;
char* line;
type0 basic_length;
int entry_count;
int ext_cfg;
int header_cmplt;
int vel_chk;
int atom_cmplt;
int last_type;
int curr_id;
void read_header();
void set_box();
void M3sqroot(type0**,type0**);
void read_atom();
void alloc();
void dealloc();
int tmp_natms;
int ibox;
protected:
public:
CFG2Box(Xtal*,char*,char*);
~CFG2Box();
//char* box;
};
#endif
<file_sep>/src/region_block.cpp
#include "region_block.h"
#include "memory.h"
#include "error.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Region_block::Region_block(Xtal* xtal
,int narg,char** arg):Region(xtal)
{
type0 tmp0,tmp1;
alloc=0;
if(narg!=5)
{
error->warning("region block needs 4 arguments\n"
"SYNTAX: block name (lo_x,hi_x) (lo_y,hi_y) (lo_z,hi_z)");
xtal->error_flag=-1;
return;
}
int lngth=static_cast<int>(strlen(arg[1]))+1;
CREATE1D(region_name,lngth);
CREATE1D(bond,6);
CREATE1D(bond_st,6);
alloc=1;
memcpy(region_name,arg[1],lngth);
for(int i=0;i<6;i++)
bond_st[i]=1;
for(int i=0;i<3;i++)
{
if(strcmp(arg[2+i],"(none,none)")==0)
{
bond_st[2*i]=bond_st[2*i+1]=0;
}
else
{
if(sscanf(arg[2+i],"(%lf,%lf)",&tmp0,&tmp1)==2)
{
bond[2*i]=tmp0;
bond[2*i+1]=tmp1;
if(tmp0<0.0 || tmp0>1.0)
{
error->warning("block boundary should between 0.0 & 1.0");
xtal->error_flag=-1;
return;
}
if(tmp1<0.0 || tmp1>1.0)
{
error->warning("block boundary should between 0.0 & 1.0");
xtal->error_flag=-1;
return;
}
if(tmp0>=tmp1)
{
error->warning("higher block boundary should be greater than lower one");
xtal->error_flag=-1;
return;
}
}
else
{
if(sscanf(arg[2+i],"(none,%lf)",&tmp1)==1)
{
bond_st[2*i]=0;
bond[2*i+1]=tmp1;
if(tmp1<0.0 || tmp1>1.0)
{
error->warning("block boundary should between 0.0 & 1.0");
xtal->error_flag=-1;
return;
}
}
else if(sscanf(arg[2+i],"(%lf,none)",&tmp0)==1)
{
bond_st[2*i+1]=0;
bond[2*i]=tmp0;
if(tmp0<0.0 || tmp0>1.0)
{
error->warning("block boundary should between 0.0 & 1.0");
xtal->error_flag=-1;
return;
}
}
else
{
error->warning("block boundary for dimension %d "
"should be of the format: (lo,hi)",i);
xtal->error_flag=-1;
return;
}
}
}
}
for(int i=0;i<3;i++)
{
if(bond_st[2*i] && bond_st[2*i+1])
{
if(bond[2*i]>bond[2*i+1])
{
error->warning("lower bound of dimension "
"%d should be less than higher bound\n",i);
xtal->error_flag=-1;
return;
}
}
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Region_block::~Region_block()
{
if(alloc)
{
delete [] bond;
delete [] bond_st;
delete [] region_name;
}
}
/*--------------------------------------------
belong
--------------------------------------------*/
inline int Region_block::belong(type0** H,type0* s)
{
if(bond_st[0])
if (s[0]<bond[0])
return 0;
if(bond_st[1])
if (bond[1]<=s[0])
return 0;
if(bond_st[2])
if (s[1]<bond[2])
return 0;
if(bond_st[3])
if (bond[3]<=s[1])
return 0;
if(bond_st[4])
if (s[2]<bond[4])
return 0;
if(bond_st[5])
if (bond[5]<=s[2])
return 0;
return 1;
}<file_sep>/src/box2cfg.h
#ifndef __xtal__box2cfg__
#define __xtal__box2cfg__
#include <stdio.h>
#include "init.h"
class Box2CFG :protected InitPtrs
{
private:
FILE* cfgfile;
protected:
public:
Box2CFG(Xtal*,char*,char*);
~Box2CFG();
};
#endif /* defined(__xtal__box2cfg__) */
<file_sep>/src/command_strain.h
#ifdef Command_Style
CommandStyle(Command_strain,strain)
#else
#ifndef __xtal__command_strain__
#define __xtal__command_strain__
#include <stdio.h>
#include <stdio.h>
#include "init.h"
class Command_strain: protected InitPtrs
{
private:
protected:
public:
Command_strain(Xtal*,int,char**);
~Command_strain();
};
#endif
#endif
<file_sep>/src/command_del_atoms.h
#ifdef Command_Style
CommandStyle(Command_del_atoms,del_atoms)
#else
#ifndef __xtal__command_del_atoms__
#define __xtal__command_del_atoms__
#include <stdio.h>
#include "init.h"
class Command_del_atoms: protected InitPtrs
{
private:
int include;
int seed;
type0 rand_gen();
protected:
public:
Command_del_atoms(Xtal*,int,char**);
~Command_del_atoms();
};
#endif
#endif
<file_sep>/src/region.cpp
#include "region.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Region::Region(Xtal* xtal):InitPtrs(xtal)
{
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Region::~Region()
{
}<file_sep>/src/command_add_vac.cpp
#include "command_add_vac.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_add_vac::Command_add_vac(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
int t_b;
if(narg!=4)
{
error->warning("add_vac command needs 3 arguments\n"
"SYNTAX: add_vac box dim vaccuum_thickness");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
type0 depth;
int dim;
if(strcmp(arg[2],"x")==0)
{
dim=0;
t_b=1;
}
else if(strcmp(arg[2],"y")==0)
{
dim=1;
t_b=1;
}
else if(strcmp(arg[2],"z")==0)
{
dim=2;
t_b=1;
}
else if(strcmp(arg[2],"-x")==0)
{
dim=0;
t_b=-1;
}
else if(strcmp(arg[2],"-y")==0)
{
dim=1;
t_b=-1;
}
else if(strcmp(arg[2],"-z")==0)
{
dim=2;
t_b=-1;
}
else
{
error->warning("invalid dimension: %s",arg[2]);
return;
}
depth=atof(arg[3]);
if(depth<=0.0)
{
error->warning("thickness of vaccuum cannot be less than 0.0");
return;
}
box_collection->boxes[ibox]->add_vac(dim,t_b,depth);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_add_vac::~Command_add_vac()
{
}
<file_sep>/src/command_ls_box.cpp
#include "command_ls_box.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_ls_box::Command_ls_box(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
printf("\n");
for(int i=0;i<box_collection->no_boxes;i++)
printf("%s\n",box_collection->boxes[i]->box_name);
printf("\n");
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_ls_box::~Command_ls_box()
{
}
<file_sep>/src/command_strain.cpp
#include "command_strain.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_strain::Command_strain(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
int ibox;
type0 det;
if(narg!=8)
{
error->warning("rotate command needs at least 7 arguments\n"
"SYNTAX: strain box e[0][0] e[1][1] e[2][2] e[2][1] e[2][0] e[1][0]\n");
return;
}
ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
type0** F;
CREATE2D(F,3,3);
type0** G;
CREATE2D(G,3,3);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
G[i][j]=0.0;
if(i==j)
F[i][j]=1.0;
else
F[i][j]=0.0;
}
F[0][0]+=atof(arg[2]);
F[1][1]+=atof(arg[3]);
F[2][2]+=atof(arg[4]);
F[2][1]+=atof(arg[5]);
F[2][0]+=atof(arg[6]);
F[1][0]+=atof(arg[7]);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
G[i][j]+=F[i][k]*box_collection->boxes[ibox]->H[j][k];
det=M3DET(G);
if(det<=0.0)
{
error->warning("determinant after transformation should be greater than zero");
for(int i=0;i<3;i++)
{
delete [] F[i];
delete [] G[i];
}
delete [] F;
delete [] G;
return;
}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
box_collection->boxes[ibox]->H[i][j]=G[i][j];
for(int i=0;i<3;i++)
{
delete [] F[i];
delete [] G[i];
}
delete [] F;
delete [] G;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_strain::~Command_strain()
{
}<file_sep>/src/command_random_gas.h
#ifdef Command_Style
CommandStyle(Command_random_gas,random_gas)
#else
#ifndef __xtal__command_random_gas__
#define __xtal__command_random_gas__
#include "init.h"
#include <stdio.h>
class Command_random_gas: protected InitPtrs
{
private:
int seed;
type0 bond;
void rand_gen(type0**&,type0*,type0*);
type0 rand_gen();
protected:
public:
Command_random_gas(Xtal*,int,char**);
~Command_random_gas();
};
#endif
#endif
<file_sep>/src/command_random_gas.cpp
#include "command_random_gas.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "gr.h"
#include <math.h>
#define RNG_M 2147483647
#define RNG_MI 1.0/2147483647
#define RNG_A 16807
#define RNG_Q 127773
#define RNG_R 2836
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_random_gas::Command_random_gas(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
Box* box=box_collection->boxes[box_collection->find(arg[1])];
int itype=box->add_type(atof(arg[3]),arg[2]);
bond=atof(arg[4]);
int N=atoi(arg[5]);
seed=atoi(arg[6]);
int natms=box->natms;
type0* s;//=box->s;
int* type;
//GROW(s,3*natms,3*(2*N+natms));
//GROW(type,natms,2*N+natms);
int new_natms=natms+2*N;
type=new int[natms+2*N];
s=new type0[(natms+2*N)*3];
memcpy(type,box->type,natms*sizeof(int));
memcpy(s,box->s,3*natms*sizeof(type0));
delete [] box->s;
delete [] box->type;
box->s=s;
box->type=type;
box->natms=new_natms;
int j=natms;
for(int i=0;i<N;i++)
{
rand_gen(box->B,s+3*j,s+3*(j+1));
type[j]=itype;
type[j+1]=itype;
j+=2;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_random_gas::~Command_random_gas()
{
}
/*--------------------------------------------
uniform number generator between 0.0 and 1.0
--------------------------------------------*/
type0 Command_random_gas::rand_gen()
{
int first,second,rnd;
first = seed/RNG_Q;
second = seed%RNG_Q;
rnd = RNG_A*second-RNG_R*first;
if (rnd > 0)
seed=rnd;
else
seed=rnd+RNG_M;
return seed*RNG_MI;
}
/*--------------------------------------------
uniform number generator between 0.0 and 1.0
--------------------------------------------*/
void Command_random_gas::rand_gen(type0**& B,type0* s0,type0* s1)
{
for(int i=0;i<3;i++)
s0[i]=rand_gen();
type0 phi=M_PI*rand_gen();
type0 theta=2.0*M_PI*rand_gen();
s1[0]=cos(theta)*sin(phi)*bond;
s1[1]=sin(theta)*sin(phi)*bond;
s1[2]=cos(phi)*bond;
s1[0]=B[0][0]*s1[0]+B[1][0]*s1[1]+B[2][0]*s1[2];
s1[1]=B[1][1]*s1[1]+B[2][1]*s1[2];
s1[2]*=B[2][2];
for(int i=0;i<3;i++)
{
s1[i]=s0[i]+s1[i];
while(s1[i]<0.0)
s1[i]++;
while(s1[i]>=1.0)
s1[i]--;
}
}
<file_sep>/src/region_sphere.h
#ifdef Region_Style
RegionStyle(Region_sphere,sphere)
#else
#ifndef __xtal__region_sphere__
#define __xtal__region_sphere__
#include <stdio.h>
#include "region.h"
class Region_sphere :public Region
{
private:
type0* x;
type0 r;
type0 rsq;
type0 x0,x1,x2;
int alloc;
protected:
public:
Region_sphere(Xtal*,int,char**);
~Region_sphere();
int belong(type0**,type0*);
};
#endif
#endif
<file_sep>/src/command_rm_thickness.h
#ifdef Command_Style
CommandStyle(Command_rm_thickness,rm_thickness)
#else
#ifndef __xtal__command_rm_thickness__
#define __xtal__command_rm_thickness__
#include "init.h"
#include <stdio.h>
class Command_rm_thickness: protected InitPtrs
{
private:
protected:
public:
Command_rm_thickness(Xtal*,int,char**);
~Command_rm_thickness();
};
#endif
#endif
<file_sep>/src/command_styles.h
#include "command_add_region.h"
#include "command_add_vac.h"
#include "command_arc.h"
#include "command_box2cfg.h"
#include "command_box2lammps.h"
#include "command_box2vasp.h"
#include "command_box_prop.h"
#include "command_cfg2box.h"
#include "command_cp.h"
#include "command_del_atoms.h"
#include "command_dislocation.h"
#include "command_fix_id.h"
#include "command_gr.h"
#include "command_help.h"
#include "command_join.h"
#include "command_list_id.h"
#include "command_ls_box.h"
#include "command_ls_region.h"
#include "command_mismatch.h"
#include "command_move.h"
#include "command_mul.h"
#include "command_random_gas.h"
#include "command_rm_thickness.h"
#include "command_rotate.h"
#include "command_sine_arc.h"
#include "command_strain.h"
#include "command_ucell_change.h"
#include "command_vasp2box.h"
#include "command_wrinkle.h"
<file_sep>/src/cfg2box.cpp
#include <math.h>
#include "cfg2box.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
CFG2Box::CFG2Box(Xtal* xtal,char* box,char* name):InitPtrs(xtal)
{
ibox=box_collection->find(box);
basic_length=1.0;
xtal->error_flag=0;
tmp_natms=0;
file_name=name;
cfgfile=fopen(file_name,"r");
if(cfgfile==NULL)
{
error->warning("%s file not found",file_name);
xtal->error_flag=-1;
return;
}
alloc();
CREATE1D(line,MAX_CHAR);
M3ZERO(H0);
M3ZERO(eta);
M3ZERO(trns);
trns[0][0]=trns[1][1]=trns[2][2]=1.0;
H0[0][0]=H0[1][1]=H0[2][2]=1.0;
fpos_t pos;
header_cmplt=0;
while (!header_cmplt)
{
fgetpos(cfgfile,&pos);
fgets(line,MAX_CHAR,cfgfile);
read_header();
if(xtal->error_flag==-1)
{
dealloc();
delete [] line;
fclose(cfgfile);
return;
}
}
//fsetpos(cfgfile,&pos);
set_box();
dealloc();
if(xtal->error_flag==-1)
{
delete [] line;
fclose(cfgfile);
return;
}
CREATE1D(s_buff,3*tmp_natms);
CREATE1D(type_buff,tmp_natms);
atom_cmplt=0;
if(tmp_natms==0)
atom_cmplt=1;
curr_id=0;
while (!atom_cmplt)
{
read_atom();
if(xtal->error_flag==-1)
{
delete [] s_buff;
delete [] type_buff;
delete [] line;
fclose(cfgfile);
return;
}
if(curr_id==tmp_natms)
atom_cmplt=1;
}
if(curr_id<tmp_natms)
{
xtal->error_flag=-1;
delete [] s_buff;
delete [] type_buff;
delete [] line;
fclose(cfgfile);
return;
}
box_collection->boxes[ibox]->add_atoms(tmp_natms,type_buff,s_buff);
delete [] s_buff;
delete [] type_buff;
delete [] line;
fclose(cfgfile);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
CFG2Box::~CFG2Box()
{
}
/*--------------------------------------------
allocate the matrices and vectors
--------------------------------------------*/
void CFG2Box::alloc()
{
CREATE2D(H_x,3,3);
CREATE2D(Ht,3,3);
CREATE1D(sq,3);
CREATE1D(b,3);
CREATE2D(H0,3,3);
CREATE2D(eta,3,3);
CREATE2D(eta_sq,3,3);
CREATE2D(trns,3,3);
}
/*--------------------------------------------
deallocate the matrices and vectors
--------------------------------------------*/
void CFG2Box::dealloc()
{
for(int i=0;i<3;i++)
{
delete [] Ht[i];
delete [] H_x[i];
delete [] eta_sq[i];
delete [] eta[i];
delete [] H0[i];
delete [] trns[i];
}
delete [] H_x;
delete [] Ht;
delete [] eta_sq;
delete [] eta;
delete [] H0;
delete [] trns;
delete [] b;
delete [] sq;
}
/*--------------------------------------------
read the header of the file
--------------------------------------------*/
void CFG2Box::read_header()
{
char* command;
int narg = xtal->hash_remover(line,command);
if(narg==0)
return;
type0 tmp;
int icmp,jcmp,tmpno;
char* strtmp1;
char* strtmp2;
CREATE1D(strtmp1,MAX_CHAR);
CREATE1D(strtmp2,MAX_CHAR);
if(strcmp(command,".NO_VELOCITY.")==0)
{
vel_chk=0;
ext_cfg=1;
entry_count-=3;
}
else if(sscanf(command,"Transform(%d,%d) = %lf",&icmp,&jcmp,&tmp)==3)
{
icmp--;
jcmp--;
if (icmp>2 || icmp<0)
{
error->warning("wrong component in %s file for Transform(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
if(jcmp>2 || jcmp<0)
{
error->warning("wrong component in %s file for Transform(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
trns[icmp][jcmp]=tmp;
}
else if(sscanf(command,"eta(%d,%d) = %lf",&icmp,&jcmp,&tmp)==3)
{
icmp--;
jcmp--;
if (icmp>2 || icmp<0)
{
error->warning("wrong component in %s file for eta(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
if(jcmp>2 || jcmp<0)
{
error->warning("wrong component in %s file for eta(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
eta[icmp][jcmp]=tmp;
}
else if(sscanf(command,"entry_count = %d",&tmpno)==1)
{
entry_count=tmpno;
ext_cfg=1;
header_cmplt=1;
int mincomp=3+(3*vel_chk);
if (entry_count < mincomp)
{
error->warning("entry_count in %s should at least be equal to %d",file_name,mincomp);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
}
else if(sscanf(command,"H0(%d,%d) = %lf A",&icmp,&jcmp,&tmp)==3)
{
icmp--;
jcmp--;
if (icmp>2 || icmp<0)
{
error->warning("wrong component in %s file for H(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
if(jcmp>2 || jcmp<0)
{
error->warning("wrong component in %s file for H(%d,%d)",file_name,icmp+1,jcmp+1);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
H0[icmp][jcmp]=tmp;
}
else if(sscanf(command,"R = %lf %s",&tmp,strtmp1)==2)
{
}
else if(sscanf(command,"Number of particles = %d",&tmpno)==1)
{
tmp_natms=tmpno;
if(tmp_natms<0)
{
error->warning("Number of particles in %s file should be greater than or equal to 0",file_name);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
}
else if(sscanf(command,"auxiliary[%d] = %s %s",&icmp,strtmp1,strtmp2)==3)
{
int mincomp=3+(3*vel_chk);
if(icmp+mincomp+1>entry_count)
{
error->warning("wrong component in %s file for auxiliary[%d], %d+%d+1 > entry_count",file_name,icmp,mincomp,icmp);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
}
else if(sscanf(command,"A = %lf Angstrom (basic length-scale)",&tmp)==1)
{
if(tmp<=0.0)
{
error->warning("A in %s file should be greater than 0.0",file_name);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
basic_length=tmp;
}
else
{
if (narg==8&&ext_cfg==0)
header_cmplt=1;
else if (narg==1&&ext_cfg)
header_cmplt=1;
else
{
error->warning("invalid line in %s file: %s",file_name,command);
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
xtal->error_flag=-1;
return;
}
}
if(narg)
delete [] command;
delete [] strtmp2;
delete [] strtmp1;
return;
}
/*--------------------------------------------
calculates H from H0, Transform, and eta;
** make sure H is zeroed before;
for now we disregard eta;
remeber to fix it later;
--------------------------------------------*/
void CFG2Box::set_box()
{
type0 babs;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
{
H_x[i][j]=0.0;
for (int k=0;k<3;k++)
H_x[i][j]+=H0[i][k]*trns[k][j];
}
int chk=1;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(eta[i][j]!=0.0)
chk=0;
if(chk==0)
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
eta[i][j]*=2.0;
for(int i=0;i<3;i++)
eta[i][i]++;
M3sqroot(eta,eta_sq);
if(xtal->error_flag==-1)
return;
M3EQV(H_x,H0);
M3ZERO(H_x);
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
for (int k=0;k<3;k++)
H_x[i][j]+=H0[i][k]*eta_sq[k][j];
}
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
{
H_x[i][j]*=basic_length;
box_collection->boxes[ibox]->H[i][j]=H_x[i][j];
}
if (M3DET(H_x)==0.0)
{
error->warning("determinant of H in %s file is 0.0",file_name);
xtal->error_flag=-1;
return;
}
type0 det;
for (int i=0;i<3;i++)
{
sq[i]=0.0;
for (int j=0;j<3;j++)
{
sq[i]+=H_x[i][j]*H_x[i][j];
Ht[i][j]=0.0;
}
}
Ht[0][0]=sqrt(sq[0]);
for (int i=0;i<3;i++)
Ht[1][0]+=H_x[0][i]*H_x[1][i];
Ht[1][0]/=Ht[0][0];
Ht[1][1]=sqrt(sq[1]-Ht[1][0]*Ht[1][0]);
for (int i=0;i<3;i++)
Ht[2][0]+=H_x[0][i]*H_x[2][i];
Ht[2][0]/=Ht[0][0];
b[0]=H_x[0][1]*H_x[1][2]-H_x[0][2]*H_x[1][1];
b[1]=H_x[0][2]*H_x[1][0]-H_x[0][0]*H_x[1][2];
b[2]=H_x[0][0]*H_x[1][1]-H_x[0][1]*H_x[1][0];
babs=sqrt(b[0]*b[0]+b[1]*b[1]+b[2]*b[2]);
b[0]/=babs;
b[1]/=babs;
b[2]/=babs;
for (int i=0;i<3;i++)
Ht[2][2]+=H_x[2][i]*b[i];
Ht[2][1]=sqrt(sq[2]-Ht[2][2]*Ht[2][2]-Ht[2][0]*Ht[2][0]);
M3EQV(Ht,box_collection->boxes[ibox]->H);
M3EQV(Ht,H_x);
M3INV(box_collection->boxes[ibox]->H,box_collection->boxes[ibox]->B,det);
}
/*--------------------------------------------
calculates square root of 3x3 matrix
ref: <NAME>
An Algorithm to Compute The Square Root of
a 3x3 Positive Definite Matrix
Computers Math. Applic. Vol. 18, No. 5,
pp. 459-466, 1989
--------------------------------------------*/
void CFG2Box::M3sqroot(type0** A,type0** Asq)
{
type0 IA=0;
for(int i=0;i<3;i++)
IA+=A[i][i];
type0 IIA=0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
IIA-=A[i][j]*A[j][i];
IIA+=IA*IA;
IIA*=0.5;
type0 IIIA=M3DET(A);
type0 k=IA*IA-3*IIA;
if(k<0.0)
{
error->warning("eta in %s should be positive definite",file_name);
xtal->error_flag=-1;
return;
}
if(k<TOLERANCE)
{
if(IA<=0.0)
{
error->warning("eta in %s should be positive definite",file_name);
xtal->error_flag=-1;
return;
}
M3ZERO(Asq);
for(int i=0;i<3;i++)
Asq[i][i]=sqrt(IA/3.0);
return;
}
type0 l=IA*(IA*IA -4.5*IIA)+13.5*IIIA;
type0 temp=l/(k*sqrt(k));
if(temp>1.0||temp<-1.0)
{
error->warning("eta in %s should be positive definite",file_name);
xtal->error_flag=-1;
return;
}
type0 phi=acos(temp);
type0 lambda=sqrt((1.0/3.0)*(IA+2*sqrt(k)*cos(phi/3.0)));
type0 IIIAsq=sqrt(IIIA);
type0 y=-lambda*lambda+IA+2*IIIAsq/lambda;
if(y<0.0)
{
error->warning("eta in %s should be positive definite",file_name);
xtal->error_flag=-1;
return;
}
type0 IAsq=lambda+sqrt(y);
type0 IIAsq=0.5*(IAsq*IAsq-IA);
type0 coef0=IAsq*IIAsq-IIIAsq;
if(coef0==0)
{
error->warning("eta in %s should be positive definite",file_name);
xtal->error_flag=-1;
return;
}
coef0=1.0/coef0;
M3ZERO(Asq);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
Asq[i][j]-=coef0*A[i][k]*A[k][j];
type0 coef1=coef0*(IAsq*IAsq-IIAsq);
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
Asq[i][j]+=coef1*A[i][j];
type0 coef2=coef0*IAsq*IIIAsq;
for(int i=0;i<3;i++)
Asq[i][i]+=coef2;
}
/*--------------------------------------------
reads the atom section of the cfg file
--------------------------------------------*/
void CFG2Box::read_atom()
{
fgets(line,MAX_CHAR,cfgfile);
char** arg;
type0 mass;
int narg=xtal->parse_line(line,arg);
if(feof(cfgfile))
atom_cmplt=1;
if(atom_cmplt)
{
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
return;
}
if (narg!=8 && ext_cfg==0)
{
error->warning("invalid line in %s file: %s",file_name,line);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
if (ext_cfg && !(narg==1 || narg==entry_count))
{
error->warning("invalid line in %s file: %s",file_name,line);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
if(ext_cfg)
{
if(narg==1)
{
mass=static_cast<type0>(atof(arg[0]));
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
fgets(line,MAX_CHAR,cfgfile);
narg=xtal->parse_line(line,arg);
if(narg!=1)
{
error->warning("invalid line in %s file: %s",file_name,line);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
if(mass<=0.0)
{
error->warning("mass of %s %s file (%lf) should be greater than 0.0",arg[0],file_name,line,mass);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
last_type=box_collection->boxes[ibox]->add_type(mass,arg[0]);
}
else if(narg==entry_count)
{
type_buff[curr_id]=last_type;
s_buff[3*curr_id]=atof(arg[0]);
s_buff[3*curr_id+1]=atof(arg[1]);
s_buff[3*curr_id+2]=atof(arg[2]);
curr_id++;
}
else
{
error->warning("invalid line in %s file: %s",file_name,line);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
}
else
{
if(narg==8)
{
mass=static_cast<type0>(atof(arg[0]));
last_type=box_collection->boxes[ibox]->add_type(mass,arg[1]);
if(mass<=0.0)
{
error->warning("mass of %s %s file (%lf) should be greater than 0.0",arg[1],file_name,line,mass);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
type_buff[curr_id]=last_type;
s_buff[3*curr_id]=atof(arg[2]);
s_buff[3*curr_id+1]=atof(arg[3]);
s_buff[3*curr_id+2]=atof(arg[4]);
curr_id++;
}
else
{
error->warning("invalid line in %s file: %s",file_name,line);
if(narg)
{
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
}
xtal->error_flag=-1;
return;
}
}
for(int i=0;i<narg;i++)
delete [] arg[i];
if(narg)
delete [] arg;
}
<file_sep>/src/command_help.h
#ifdef Command_Style
CommandStyle(Command_help,help)
#else
#ifndef __xtal__command_help__
#define __xtal__command_help__
#include "init.h"
#include <stdio.h>
class Command_help: protected InitPtrs
{
private:
protected:
public:
Command_help(Xtal*,int,char**);
~Command_help();
};
#endif
#endif
<file_sep>/src/command_gr.cpp
#include "command_gr.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "gr.h"
#include <math.h>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_gr::Command_gr(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=8)
{
error->warning("gr command needs 7 arguments\n"
"SYNTAX: gr box dims cutoff k_cutoff nbins file_name file_name");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
bool dims[3];
dims[0]=dims[1]=dims[2]=false;
for(int i=0;i<strlen(arg[2]);i++)
{
if(arg[2][i]=='x')
{
dims[0]=true;
continue;
}
if(arg[2][i]=='y')
{
dims[1]=true;
continue;
}
if(arg[2][i]=='z')
{
dims[2]=true;
continue;
}
error->warning("invalid dimension: %c",arg[2][i]);
return;
}
type0 cutoff=atof(arg[3]);
if(cutoff<=0.0)
{
error->warning("cutoff cannot be less than or equal to 0.0");
return;
}
type0 k_cutoff=atof(arg[4])*2.0*M_PI;
if(k_cutoff<=0.0)
{
error->warning("k_cutoff cannot be less than or equal to 0.0");
return;
}
int no_bins=atoi(arg[5]);
if(no_bins<=0)
{
error->warning("number of bins cannot be less than or equal to 0");
return;
}
FILE* fp0=fopen(arg[6],"w");
FILE* fp1=fopen(arg[7],"w");
Box* box=box_collection->boxes[ibox];
type0*** gr=NULL;
type0*** sr=NULL;
Gr gr_(xtal,gr,sr,box,dims,cutoff,k_cutoff,no_bins);
int no_types=box->no_types;
type0 dr=cutoff/static_cast<type0>(no_bins);
type0 dk=k_cutoff/static_cast<type0>(no_bins);
type0 r=0.5*dr,k=0.0;
fprintf(fp0,"r");
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<ityp+1;jtyp++)
fprintf(fp0," %s-%s",box->atom_names[ityp],box->atom_names[jtyp]);
fprintf(fp0,"\n");
for(int i=0;i<no_bins;i++,r+=dr)
{
fprintf(fp0,"%lf",r);
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<ityp+1;jtyp++)
fprintf(fp0," %lf",gr[ityp][jtyp][i]);
fprintf(fp0,"\n");
}
fclose(fp0);
fprintf(fp1,"k");
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<ityp+1;jtyp++)
fprintf(fp1," %s-%s",box->atom_names[ityp],box->atom_names[jtyp]);
fprintf(fp1,"\n");
for(int i=0;i<no_bins;i++,k+=dk)
{
fprintf(fp1,"%lf",k/(2.0*M_PI));
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<ityp+1;jtyp++)
fprintf(fp1," %lf",sr[ityp][jtyp][i]);
fprintf(fp1,"\n");
}
fclose(fp1);
delete [] **gr;
delete [] *gr;
delete [] gr;
delete [] **sr;
delete [] *sr;
delete [] sr;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_gr::~Command_gr()
{
}
<file_sep>/src/error.cpp
#include <stdlib.h>
#include <stdio.h>
#include <cstdarg>
#include <cstdlib>
#include <string.h>
#include "error.h"
/*--------------------------------------------
constructor of the error handler:
--------------------------------------------*/
Error::Error(Xtal* xtal) : InitPtrs(xtal)
{
}
/*--------------------------------------------
destructor of the error handler:
--------------------------------------------*/
Error::~Error()
{
}
/*--------------------------------------------
output the error line and abort the code
--------------------------------------------*/
void Error::abort(const char* msg,...)
{
char err_msg[MAX_CHAR];
va_list args;
va_start (args, msg);
vsprintf (err_msg,msg, args);
printf("ABORTED! %s \n",err_msg);
va_end (args);
exit(EXIT_FAILURE);
}
/*--------------------------------------------
output the error line and abort the code
--------------------------------------------*/
void Error::abort(int line,char* file
,const char* msg,...)
{
char err_msg[MAX_CHAR];
va_list args;
va_start (args, msg);
vsprintf (err_msg,msg, args);
printf("ABORTED! %s \n"
,err_msg);
va_end (args);
char* pch=NULL;
pch=strchr(file,'/');
int start=0;
while (pch!=NULL)
{
start=static_cast<int>(pch-file);
pch=strchr(pch+1,'/');
}
start++;
int fin=static_cast<int>(strlen(file));
printf("For more details see ");
for(int i=start;i<fin;i++)
printf("%c",file[i]);
printf(":%d\n",line);
exit(EXIT_FAILURE);
}
/*--------------------------------------------
output the warning msg
--------------------------------------------*/
void Error::warning(const char *msg,...)
{
char war_msg[MAX_CHAR];
va_list args;
va_start (args, msg);
vsprintf (war_msg,msg, args);
printf("%s \n"
,war_msg);
va_end (args);
}
<file_sep>/src/command_box_prop.cpp
#include "command_box_prop.h"
#include "box_collection.h"
#include "error.h"
#include "memory.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_box_prop::Command_box_prop(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg==1)
{
error->warning("box_prop command needs atleast 1 argument\n"
"SYNTAX: box_prop box0 box1 ...");
return;
}
int no_boxes=narg-1;
int* box_list;
CREATE1D(box_list,no_boxes);
for(int i=0;i<no_boxes;i++)
{
box_list[i]=box_collection->find(arg[i+1]);
if(box_list[i]<0)
{
if(no_boxes)
delete [] box_list;
error->warning("box %s not found",arg[i+1]);
return;
}
}
int no_types;
int ibox;
for(int i=0;i<no_boxes;i++)
{
ibox=box_list[i];
printf("%s:\n",box_collection->boxes[ibox]->box_name);
printf("%d atoms:",box_collection->boxes[ibox]->natms);
no_types=box_collection->boxes[ibox]->no_types;
for(int j=0;j<no_types-1;j++)
printf(" %d %s,",box_collection->boxes[ibox]->type_count[j]
,box_collection->boxes[ibox]->atom_names[j]);
printf(" %d %s\n",box_collection->boxes[ibox]->type_count[no_types-1]
,box_collection->boxes[ibox]->atom_names[no_types-1]);
printf(" |%lf %lf %lf|\n"
,box_collection->boxes[ibox]->H[0][0]
,box_collection->boxes[ibox]->H[0][1]
,box_collection->boxes[ibox]->H[0][2]);
printf("H=|%lf %lf %lf|\n"
,box_collection->boxes[ibox]->H[1][0]
,box_collection->boxes[ibox]->H[1][1]
,box_collection->boxes[ibox]->H[1][2]);
printf(" |%lf %lf %lf|\n"
,box_collection->boxes[ibox]->H[2][0]
,box_collection->boxes[ibox]->H[2][1]
,box_collection->boxes[ibox]->H[2][2]);
printf("\n");
}
if(no_boxes)
delete [] box_list;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_box_prop::~Command_box_prop()
{
}<file_sep>/src/box2cfg.cpp
#include <math.h>
#include "box2cfg.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Box2CFG::Box2CFG(Xtal* xtal,char* box,char* name):InitPtrs(xtal)
{
cfgfile=fopen(name,"w");
int ibox=box_collection->find(box);
int no_types=box_collection->boxes[ibox]->no_types;
char** atom_names=box_collection->boxes[ibox]->atom_names;
type0* mass=box_collection->boxes[ibox]->mass;
type0** H=box_collection->boxes[ibox]->H;
int natms=box_collection->boxes[ibox]->natms;
type0* s=box_collection->boxes[ibox]->s;
int* type=box_collection->boxes[ibox]->type;
fprintf(cfgfile,"Number of particles = %d\n",natms);
fprintf(cfgfile,"A = 1 Angstrom (basic length-scale)\n");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
fprintf(cfgfile,"H0(%d,%d) = %20.16lf A\n",i+1,j+1,H[i][j]);
fprintf(cfgfile,".NO_VELOCITY.\n");
fprintf(cfgfile,"entry_count = %d\n",3);
int icomp;
for(int itype=0;itype<no_types;itype++)
{
fprintf(cfgfile,"%lf \n%s \n",mass[itype],atom_names[itype]);
icomp=0;
for(int iatm=0;iatm<natms;iatm++)
{
if(type[iatm]==itype)
fprintf(cfgfile,"%18.16lf %18.16lf %18.16lf\n",s[icomp],s[icomp+1],s[icomp+2]);
icomp+=3;
}
}
fclose(cfgfile);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Box2CFG::~Box2CFG()
{
}
<file_sep>/src/xtal.h
#ifndef __xtal__xtal__
#define __xtal__xtal__
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>
typedef double type0;
char* command_generator(const char*,int);
char** completion(const char*,int,int);
class Xtal
{
private:
void gen_cmd_ls();
protected:
public:
class Memory* memory;
class Error* error;
class BoxCollection* box_collection;
class RegionCollection* region_collection;
Xtal(int,char**);
~Xtal();
FILE* output_file;
FILE* input_file;
int parse_line(char*,char**&);
int hash_remover(char*,char*&);
void concatenate(int,char**,char*&);
void read_file();
void read_line();
void command(char*);
int error_flag;
void add_vals();
int no_cmds;
int no_vals;
char** cmds_lst;
};
#endif
<file_sep>/src/region_block.h
#ifdef Region_Style
RegionStyle(Region_block,block)
#else
#ifndef __xtal__region_block__
#define __xtal__region_block__
#include <stdio.h>
#include "region.h"
class Region_block :public Region
{
private:
type0* bond;
int* bond_st;
type0 x,y,z;
int alloc;
protected:
public:
Region_block(Xtal*,int,char**);
~Region_block();
int belong(type0**,type0*);
};
#endif
#endif
<file_sep>/src/command_mul.h
#ifdef Command_Style
CommandStyle(Command_mul,mul)
#else
#ifndef __xtal__command_mul__
#define __xtal__command_mul__
#include "init.h"
#include <stdio.h>
class Command_mul: protected InitPtrs
{
private:
protected:
public:
Command_mul(Xtal*,int,char**);
~Command_mul();
};
#endif
#endif
<file_sep>/src/box_collection.h
#ifndef __xtal__box_collection__
#define __xtal__box_collection__
#include <stdio.h>
#include "init.h"
#include "box.h"
class BoxCollection:protected InitPtrs
{
private:
protected:
public:
BoxCollection(Xtal*);
~BoxCollection();
//symbol based functions
int find(char*);
int add(char*);
int cp(char*,char*);
void del(char*);
int add_unsafe();
void del(int);
Box** boxes;
int no_boxes;
};
#endif
<file_sep>/src/region_ellipsoid.cpp
#include "region_ellipsoid.h"
#include "memory.h"
#include "error.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Region_ellipsoid::Region_ellipsoid(Xtal* xtal
,int narg,char** arg):Region(xtal)
{
type0 tmp0,tmp1,tmp2;
alloc=0;
if(narg!=4)
{
error->warning("region ellipsoid needs 3 arguments\n"
"SYNTAX: ellipsoid name (c0,c1,c2) (a0,a1,a2)");
xtal->error_flag=-1;
return;
}
int lngth=static_cast<int>(strlen(arg[1]))+1;
CREATE1D(region_name,lngth);
CREATE1D(x,3);
CREATE1D(asq_inv,3);
alloc=1;
memcpy(region_name,arg[1],lngth);
if(sscanf(arg[2],"(%lf,%lf,%lf)",&tmp0,&tmp1,&tmp2)==3)
{
x[0]=tmp0;
x[1]=tmp1;
x[2]=tmp2;
}
else
{
error->warning("c should be of the format: (c0,c1,c2)");
xtal->error_flag=-1;
return;
}
tmp0=tmp1=tmp2=1.0;
if(sscanf(arg[3],"(%lf,%lf,%lf)",&tmp0,&tmp1,&tmp2)==3)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=1.0/(asq_inv[0]*asq_inv[0]);
asq_inv[1]=1.0/(asq_inv[1]*asq_inv[1]);
asq_inv[2]=1.0/(asq_inv[2]*asq_inv[2]);
}
else if(sscanf(arg[3],"(inf,%lf,%lf)",&tmp1,&tmp2)==2)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=0.0;
asq_inv[1]=1.0/(asq_inv[1]*asq_inv[1]);
asq_inv[2]=1.0/(asq_inv[2]*asq_inv[2]);
}
else if(sscanf(arg[3],"(%lf,inf,%lf)",&tmp0,&tmp2)==2)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=1.0/(asq_inv[0]*asq_inv[0]);
asq_inv[1]=0.0;
asq_inv[2]=1.0/(asq_inv[2]*asq_inv[2]);
}
else if(sscanf(arg[3],"(%lf,%lf,inf)",&tmp0,&tmp1)==2)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=1.0/(asq_inv[0]*asq_inv[0]);
asq_inv[1]=1.0/(asq_inv[1]*asq_inv[1]);
asq_inv[2]=0.0;
}
else if(sscanf(arg[3],"(%lf,inf,inf)",&tmp0)==1)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=1.0/(asq_inv[0]*asq_inv[0]);
asq_inv[1]=0.0;
asq_inv[2]=0.0;
}
else if(sscanf(arg[3],"(inf,%lf,inf)",&tmp1)==1)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=0.0;
asq_inv[1]=1.0/(asq_inv[1]*asq_inv[1]);
asq_inv[2]=0.0;
}
else if(sscanf(arg[3],"(inf,inf,%lf)",&tmp2)==1)
{
asq_inv[0]=tmp0;
asq_inv[1]=tmp1;
asq_inv[2]=tmp2;
for(int i=0;i<3;i++)
if(asq_inv[i]<=0.0)
{
error->warning("a[%d] should be greater than 0.0",i);
xtal->error_flag=-1;
return;
}
asq_inv[0]=0.0;
asq_inv[1]=0.0;
asq_inv[2]=1.0/(asq_inv[2]*asq_inv[2]);
}
else
{
error->warning("a should be of the format: (a0,a1,a2)");
xtal->error_flag=-1;
return;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Region_ellipsoid::~Region_ellipsoid()
{
if(alloc)
{
delete [] region_name;
delete [] x;
delete [] asq_inv;
}
}
/*--------------------------------------------
belong
--------------------------------------------*/
inline int Region_ellipsoid::belong(type0** H,type0* s)
{
x0=H[0][0]*s[0]+H[1][0]*s[1]+H[2][0]*s[2]-x[0];
x1=H[1][1]*s[1]+H[2][1]*s[2]-x[1];
x2=H[2][2]*s[2]-x[2];
if(x0*x0*asq_inv[0]+x1*x1*asq_inv[1]+x2*x2*asq_inv[2]<1.0)
return 1;
else
return 0;
}
<file_sep>/src/command_fix_id.cpp
#include "command_fix_id.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_fix_id::Command_fix_id(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
int ibox,nfatms;
ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
CREATE1D(idof,3);
idof[0]=idof[1]=idof[2]='0';
if(strcmp(arg[2],"x")==0)
{
idof[0]='1';
}
else if(strcmp(arg[2],"y")==0)
{
idof[1]='1';
}
else if(strcmp(arg[2],"z")==0)
{
idof[2]='1';
}
else if(strcmp(arg[2],"xy")==0)
{
idof[0]=idof[1]='1';
}
else if(strcmp(arg[2],"yx")==0)
{
idof[0]=idof[1]='1';
}
else if(strcmp(arg[2],"yz")==0)
{
idof[2]=idof[1]='1';
}
else if(strcmp(arg[2],"zy")==0)
{
idof[2]=idof[1]='1';
}
else if(strcmp(arg[2],"zx")==0)
{
idof[2]=idof[0]='1';
}
else if(strcmp(arg[2],"xz")==0)
{
idof[2]=idof[0]='1';
}
else if(strcmp(arg[2],"xyz")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else if(strcmp(arg[2],"xzy")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else if(strcmp(arg[2],"yzx")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else if(strcmp(arg[2],"yxz")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else if(strcmp(arg[2],"zxy")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else if(strcmp(arg[2],"zyx")==0)
{
idof[0]=idof[1]=idof[2]='1';
}
else
{
error->warning("unknown dof %s\n",arg[2]);
delete [] idof;
return;
}
CREATE1D(id_list,narg-3);
for(int i=3;i<narg;i++)
id_list[i-3]=atoi(arg[i]);
nfatms=narg-3;
Box* box=box_collection->boxes[ibox];
for(int i=0;i<nfatms;i++)
{
if(id_list[i]<0 || id_list[i]>box->natms)
{
error->warning("atom id must be between 0 and %d\n",box->natms);
delete [] id_list;
delete [] idof;
return;
}
}
box->id_correction();
if(box->dof_xst==0)
{
CREATE1D(box->dof,3*box->natms);
for(int i=0;i<3*box->natms;i++)
box->dof[i]='0';
box->dof_xst=1;
}
for(int i=0;i<nfatms;i++)
memcpy(&box->dof[3*id_list[i]],idof,3*sizeof(char));
delete [] id_list;
delete [] idof;
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_fix_id::~Command_fix_id()
{
}
<file_sep>/src/command_dislocation.h
#ifdef Command_Style
CommandStyle(Command_dislocation,dislocation)
#else
#ifndef __xtal__command_dislocation__
#define __xtal__command_dislocation__
#include "init.h"
#include <stdio.h>
class Command_dislocation: protected InitPtrs
{
private:
type0 nu,b_edge,b_screw,y_scale,x_scale,ux_scale,uy_scale,uz_scale;
void disp(type0,type0,type0&,type0&);
void disp(type0,type0,type0&);
void disp(type0,type0,type0&,type0&,type0&);
int n[3];
int n_edge,n_screw;
void correct_s(type0&);
protected:
public:
Command_dislocation(Xtal*,int,char**);
~Command_dislocation();
};
#endif
#endif
<file_sep>/src/box.h
#ifndef __xtal__box__
#define __xtal__box__
#include <stdio.h>
#include "init.h"
class Box:protected InitPtrs
{
private:
void add_image(int,type0);
protected:
public:
int dof_xst;
char* box_name;
int no_types;
char** atom_names;
type0* mass;
int* type_count;
type0** H;
type0** B;
int natms;
int nghosts;
type0* s;
int* type;
char* dof;
Box(Xtal*);
Box(Xtal*,char*);
Box(Box&);
void chng_name(char*);
void join(Box*,Box*,int);
void join(Box*,Box*);
~Box();
int add_type(type0,char*);
int find_type(char*);
void add_atoms(int,int*,type0*);
void add_atoms(int,int*,type0*,char*);
void del_atoms(int,int*);
void del_atoms();
void change_name(char*);
void add_name(char*);
void mul(int*);
void add_vac(int,int,type0);
void rm_frac(int,type0,type0);
void ucell_chang(type0**);
void id_correction();
void del_type(int);
void add_ghost(bool(&)[3],type0(&)[3]);
void del_ghost();
};
template<typename T>
class Arr
{
private:
T*& arr;
int& sz;
int length;
int grth;
void sz_chk(int& n)
{
if(sz+n<length)
return;
int length_=sz+n+grth;
T* arr_=new T[length_];
memcpy(arr_,arr,sz*sizeof(T));
delete [] arr;
arr=arr_;
length=length_;
}
protected:
public:
Arr(T*& arr_,int& sz_,int grow):
arr(arr_),
sz(sz_)
{
length=sz;
grth=grow;
if(sz==0) arr=NULL;
}
~Arr()
{
if(sz==length)
return;
T* arr_=new T[sz];
memcpy(arr_,arr,sz*sizeof(T));
delete [] arr;
arr=arr_;
}
void operator()(T*& _arr ,int _arr_sz)
{
sz_chk(_arr_sz);
memcpy(arr+sz,_arr,_arr_sz*sizeof(T));
sz+=_arr_sz;
}
void operator()(T& elem)
{
int i=1;
sz_chk(i);
arr[sz]=elem;
sz++;
}
template<int N>
void operator()(T (&v) [N])
{
T* v_=v;
operator()(v_,N);
}
};
#endif
<file_sep>/src/command_fix_id.h
#ifdef Command_Style
CommandStyle(Command_fix_id,fix_id)
#else
#ifndef __xtal__command_fix_id__
#define __xtal__command_fix_id__
#include "init.h"
#include <stdio.h>
class Command_fix_id: protected InitPtrs
{
private:
char* idof;
int* id_list;
protected:
public:
Command_fix_id(Xtal*,int,char**);
~Command_fix_id();
};
#endif
#endif
<file_sep>/src/command_mismatch.h
#ifdef Command_Style
CommandStyle(Command_mismatch,mismatch)
#else
#ifndef __xtal__command_mismatch__
#define __xtal__command_mismatch__
#include "init.h"
#include <stdio.h>
class Command_mismatch: protected InitPtrs
{
private:
protected:
public:
Command_mismatch(Xtal*,int,char**);
~Command_mismatch();
};
#endif
#endif
<file_sep>/src/command_cp.cpp
#include "command_cp.h"
#include "memory.h"
#include "error.h"
#include "box2cfg.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_cp::Command_cp(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("cp command needs 2 arguments\n"
"SYNTAX: cp src_box des_box");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
int jbox=box_collection->find(arg[2]);
if(jbox>=0)
{
if(jbox!=ibox)
box_collection->del(jbox);
else
return;
}
box_collection->cp(arg[1],arg[2]);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_cp::~Command_cp()
{
}
<file_sep>/src/command_box2vasp.h
#ifdef Command_Style
CommandStyle(Command_box2vasp,box2vasp)
#else
#ifndef __xtal__command_box2vasp__
#define __xtal__command_box2vasp__
#include "init.h"
#include <stdio.h>
class Command_box2vasp: protected InitPtrs
{
private:
protected:
public:
Command_box2vasp(Xtal*,int,char**);
~Command_box2vasp();
};
#endif
#endif
<file_sep>/src/command_move.h
#ifdef Command_Style
CommandStyle(Command_move,move)
#else
#ifndef __xtal__command_move__
#define __xtal__command_move__
#include "init.h"
#include <stdio.h>
class Command_move: protected InitPtrs
{
private:
protected:
public:
Command_move(Xtal*,int,char**);
~Command_move();
};
#endif
#endif<file_sep>/src/xmath.h
#ifndef __xtal__xmath__
#define __xtal__xmath__
#include <stdio.h>
#include "init.h"
class XMath: protected InitPtrs
{
private:
protected:
public:
XMath(Xtal*);
~XMath();
void square2lo_tri(type0**,type0**);
type0 solve_sinx_ov_x(type0);
type0 bracket(type0((type0)),type0,type0);
};
#endif
<file_sep>/src/box2vasp.h
#ifndef __xtal__box2vasp__
#define __xtal__box2vasp__
#include <stdio.h>
#include "init.h"
class Box2VASP :protected InitPtrs
{
private:
protected:
public:
Box2VASP(Xtal*,char*,char*);
~Box2VASP();
};
#endif
<file_sep>/src/command_add_region.h
#ifdef Command_Style
CommandStyle(Command_add_region,add_region)
#else
#ifndef __xtal__command_add_region__
#define __xtal__command_add_region__
#include "init.h"
#include <stdio.h>
class Command_add_region: protected InitPtrs
{
private:
protected:
public:
Command_add_region(Xtal*,int,char**);
~Command_add_region();
};
#endif
#endif<file_sep>/src/command_rotate.h
#ifdef Command_Style
CommandStyle(Command_rotate,rotate)
#else
#ifndef __xtal__command_rotate__
#define __xtal__command_rotate__
#include "init.h"
#include <stdio.h>
class Command_rotate: protected InitPtrs
{
private:
protected:
public:
Command_rotate(Xtal*,int,char**);
~Command_rotate();
};
#endif
#endif
<file_sep>/src/command_wrinkle.cpp
#include "memory.h"
#include "xmath.h"
#include "command_wrinkle.h"
#include <cmath>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_wrinkle::Command_wrinkle(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
N=20;
l=10.0;
int icomp;
type0 ii;
type0 max_h,f_norm;
//type0 ii,rsin_theta_2,rcos_theta_2;
no=static_cast<type0>(N);
CREATE1D(x,2*(N+4));
CREATE1D(x0,2*(N+4));
CREATE1D(xx0,2*(N+4));
CREATE1D(f,2*(N+4));
CREATE1D(f0,2*(N+4));
CREATE1D(h,2*(N+4));
w=1.0*l;
//m=0.000000285*l*l;
m=1.65e-8*l*l;
m=0.0*l*l;
max_iter=100000;
tol=1.0e-14;
slope=0.4;
norm=1.0e-1*l/no;
type0 eform,erelax=0.0;
for(int j=0;j<17;j++)
{
icomp=0;
for(int i=0;i<N+4;i++)
{
ii=static_cast<type0>(i);
x[icomp]=r1((ii-1.5)/no,1.0-w/l);
x[icomp+1]=r2((ii-1.5)/no,1.0-w/l);
icomp+=2;
}
solve();
max_h=0.0;
for(int i=0;i<N+4;i++)
{
max_h=MAX(max_h,x[i*2+1]);
}
f_norm=0.0;
for(int i=0;i<2*(N+4);i++)
f_norm+=f[i]*f[i];
if(j==0)
{
eform=0.0;
erelax=energy();
}
else
{
eform=(erelax-energy())/(erelax*(no));
}
//printf("%lf %lf %lf %e \n",w/l,max_h/l,energy(),f_norm);
printf("%lf %lf\n",1-w/l,max_h/w);
//printf("%lf %12.10lf %e \n",1.0-w/l,eform,f_norm);
w-=0.005*l;
}
/*
for(int i=0;i<(N+4);i++)
{
printf("f[%d]: %e %e\n",i,x[2*i],x[2*i+1]);
}
*/
delete [] h;
delete [] f0;
delete [] f;
delete [] xx0;
delete [] x0;
delete [] x;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_wrinkle::~Command_wrinkle()
{
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_wrinkle::force()
{
type0 en;
type0 del_inv=no/l;
type0 rsq,dx,dy;
type0 r0,r1;
int icomp;
en=l;
for(int i=1;i<N+3;i++)
{
icomp=i*2;
if(i!=1 && i!=N+2)
{
r0=sqrt((x[icomp]-x[icomp-4])*(x[icomp]-x[icomp-4])
+(x[icomp+1]-x[icomp-3])*(x[icomp+1]-x[icomp-3]));
r1=sqrt((x[icomp]-x[icomp+4])*(x[icomp]-x[icomp+4])
+(x[icomp+1]-x[icomp+5])*(x[icomp+1]-x[icomp+5]));
f[icomp]=
0.5*del_inv*(x[icomp+4]+x[icomp-4]-2.0*x[icomp])
+2.0*m*del_inv*del_inv*del_inv*
(4.0*x[icomp+2]+4.0*x[icomp-2]-x[icomp+4]-x[icomp-4]-6.0*x[icomp])
+(x[icomp]-x[icomp-4])/r0
+(x[icomp]-x[icomp+4])/r1;
f[icomp+1]=
0.5*del_inv*(x[icomp+5]+x[icomp-3]-2.0*x[icomp+1])
+2.0*m*del_inv*del_inv*del_inv*
(4.0*x[icomp+3]+4.0*x[icomp-1]-x[icomp+5]-x[icomp-3]-6.0*x[icomp+1])
+(x[icomp+1]-x[icomp-3])/r0
+(x[icomp+1]-x[icomp+5])/r1;
}
rsq=(x[icomp+2]-x[icomp-2])*(x[icomp+2]-x[icomp-2])
+(x[icomp+3]-x[icomp-1])*(x[icomp+3]-x[icomp-1]);
dx=x[icomp+2]+x[icomp-2]-2.0*x[icomp];
dy=x[icomp+3]+x[icomp-1]-2.0*x[icomp+1];
en+=0.25*del_inv*rsq-sqrt(rsq)
+m*del_inv*del_inv*del_inv*(dx*dx+dy*dy);
}
f[0]=f[1]=f[2]=f[3]=
f[2*(N+2)]=f[2*(N+2)+1]=f[2*(N+3)]=f[2*(N+3)+1]=0.0;
return en;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_wrinkle::energy()
{
type0 en=l;
type0 del_inv=no/l;
type0 rsq,dx,dy;
int icomp;
for(int i=1;i<N+3;i++)
{
icomp=i*2;
rsq=(x[icomp+2]-x[icomp-2])*(x[icomp+2]-x[icomp-2])
+(x[icomp+3]-x[icomp-1])*(x[icomp+3]-x[icomp-1]);
dx=x[icomp+2]+x[icomp-2]-2.0*x[icomp];
dy=x[icomp+3]+x[icomp-1]-2.0*x[icomp+1];
en+=0.25*del_inv*rsq-sqrt(rsq)
+m*del_inv*del_inv*del_inv*(dx*dx+dy*dy);
}
return en;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
void Command_wrinkle::solve()
{
int iter;
type0 f0_f0,f_h,f_f0,f_f,r,h_norm;
type0 en,d_en,curr_en;
type0 alpha,max_alpha;
int dof=2*(N+4),chk;
en=force();
f0_f0=0.0;
for(int i=0;i<dof;i++)
f0_f0+=f[i]*f[i];
f_f=f_h=f0_f0;
memcpy(h,f,dof*sizeof(type0));
iter=0;
d_en=tol*3.0;
chk=0;
while (iter<max_iter && f_f>tol && chk==0)
{
memcpy(x0,x,dof*sizeof(type0));
memcpy(f0,f,dof*sizeof(type0));
h_norm=0.0;
for(int i=0;i<dof;i++)
h_norm+=h[i]*h[i];
h_norm=sqrt(h_norm);
max_alpha=norm/h_norm;
for(int i=2;i<N+2;i++)
{
if(h[2*i+1]<0.0)
{
max_alpha=MIN(-x[2*i+1]/h[2*i+1],max_alpha);
}
}
max_alpha*=0.99;
curr_en=en;
chk=1;
alpha=max_alpha;
//printf("energy :%lf alpha %lf\n",en,alpha);
while(alpha>0.0 && chk)
{
for(int i=0;i<dof;i++)
x[i]=x0[i]+alpha*h[i];
en=energy();
//printf("kkk energy :%lf\n",en);
if(en<curr_en-slope*f_h*alpha)
chk=0;
alpha*=0.5;
}
if(chk==0)
{
en=force();
f_f0=0.0;
for(int i=0;i<dof;i++)
f_f0+=f[i]*f0[i];
f_f=0.0;
for(int i=0;i<dof;i++)
f_f+=f[i]*f[i];
r=(f_f-f_f0)/f0_f0;
f0_f0=f_f;
f_h=0.0;
for(int i=0;i<dof;i++)
{
h[i]*=r;
h[i]+=f[i];
f_h+=f[i]*h[i];
}
if(f_h<0.0)
{
memcpy(h,f,dof*sizeof(type0));
f_h=f_f;
}
d_en=fabs(en-curr_en);
}
else
{
memcpy(x,x0,dof*sizeof(type0));
/*
memcpy(h,f,dof*sizeof(type0));
f_f=0.0;
for(int i=0;i<dof;i++)
f_f+=f[i]*f[i];
f_h=f_f;
chk=0;
*/
//norm*=1.2;
//chk=0;
}
iter++;
}
//cout << iter <<endl;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
void Command_wrinkle::md()
{
int dof,iter,chk;
type0 f_f,en,d_en,f_norm,max_alpha
,curr_en,alpha;
dof=2*(N+4);
en=force();
f_f=0.0;
for(int i=0;i<dof;i++)
f_f+=f[i]*f[i];
f_norm=sqrt(f_f);
iter=0;
d_en=tol*3.0;
chk=0;
while (iter<max_iter && f_f>tol && chk==0)
{
memcpy(x0,x,dof*sizeof(type0));
max_alpha=norm/f_norm;
for(int i=2;i<N+2;i++)
{
if(f[2*i+1]<0.0)
{
max_alpha=MIN(-x[2*i+1]/f[2*i+1],max_alpha);
}
}
max_alpha*=0.99;
curr_en=en;
chk=1;
alpha=max_alpha;
while(alpha>0.0 && chk)
{
for(int i=0;i<dof;i++)
x[i]=x0[i]+alpha*f[i];
en=energy();
//printf("kkk energy :%lf\n",en);
if(en<curr_en-slope*f_f*alpha)
chk=0;
alpha*=0.5;
}
if(chk==0)
{
en=force();
d_en=fabs(en-curr_en);
}
else
{
memcpy(x,x0,dof*sizeof(type0));
//norm*=1.2;
//chk=0;
}
f_norm=0.0;
for(int i=0;i<dof;i++)
f_norm+=f[i]*f[i];
f_norm=sqrt(f_norm);
iter++;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_wrinkle::r1(type0 x,type0 r)
{
if(0.0<x && x<=0.25)
return l*x*(1.0-4.0*r*x);
else if(0.25<x && x<=0.5)
return 0.5*w-r1(0.5-x,r);
else if(0.5<x && x<=0.75)
return 0.5*w+r1(x-0.5,r);
else if(0.75<x && x<=1.0)
return w-r1(1.0-x,r);
else if(1.0<x)
return w+(x-1.0)*l;
else
return x*l;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_wrinkle::r2(type0 x,type0 r)
{
if(r==0.0)
return 0.0;
else
{
if(0.0<x && x<=0.25)
return (4.0*(8.0*x*r-1.0)*sqrt(x*r*(1.0-4.0*r*x))+asin(8.0*r*x-1.0)+0.5*M_PI)*l/(16.0*r);
else if(0.25<x && x<=0.5)
return 2.0*r2(0.25,r)-r2(0.5-x,r);
else if(0.5<x && x<=0.75)
return 2.0*r2(0.25,r)-r2(x-0.5,r);
else if(0.75<x && x<=1.0)
return r2(1.0-x,r);
else
return 0.0;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
void Command_wrinkle::test()
{
type0 ii,en,den,alpha,en_0;
alpha=1.0e-17;
m=0.0001;
w=0.80;
int icomp=0;
for(int i=0;i<N+4;i++)
{
ii=static_cast<type0>(i);
x[icomp]=r1((ii-1.5)/no,1.0-w/l);
x[icomp+1]=r2((ii-1.5)/no,1.0-w/l);
icomp+=2;
}
en=force();
den=0.0;
for(int j=0;j<2*(N+4);j++)
den+=f[j]*f[j]*alpha;
for(int j=0;j<2*(N+4);j++)
x[j]+=f[j]*alpha;
en_0=force();
printf("energy %e %e\n",(en_0-en)/alpha,-den/alpha);
}
<file_sep>/src/command_box2lammps.h
#ifdef Command_Style
CommandStyle(Command_box2lammps,box2lammps)
#else
#ifndef __xtal__command_box2lammps__
#define __xtal__command_box2lammps__
#include "init.h"
#include <stdio.h>
class Command_box2lammps: protected InitPtrs
{
private:
protected:
public:
Command_box2lammps(Xtal*,int,char**);
~Command_box2lammps();
};
#endif
#endif
<file_sep>/src/command_gr.h
#ifdef Command_Style
CommandStyle(Command_gr,gr)
#else
#ifndef __xtal__command_gr__
#define __xtal__command_gr__
#include "init.h"
#include <stdio.h>
class Command_gr: protected InitPtrs
{
private:
protected:
public:
Command_gr(Xtal*,int,char**);
~Command_gr();
};
#endif
#endif
<file_sep>/src/command_vasp2box.h
#ifdef Command_Style
CommandStyle(Command_vasp2box,vasp2box)
#else
#ifndef __xtal__command_vasp2box__
#define __xtal__command_vasp2box__
#include "init.h"
#include <stdio.h>
class Command_vasp2box: protected InitPtrs
{
private:
protected:
public:
Command_vasp2box(Xtal*,int,char**);
~Command_vasp2box();
};
#endif
#endif
<file_sep>/src/command_cp.h
#ifdef Command_Style
CommandStyle(Command_cp,cp)
#else
#ifndef __xtal__command_cp__
#define __xtal__command_cp__
#include "init.h"
#include <stdio.h>
class Command_cp: protected InitPtrs
{
private:
protected:
public:
Command_cp(Xtal*,int,char**);
~Command_cp();
};
#endif
#endif
<file_sep>/src/box_collection.cpp
#include <math.h>
#include "box_collection.h"
#include "memory.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
BoxCollection::BoxCollection(Xtal* xtal):InitPtrs(xtal)
{
no_boxes=0;
}
/*--------------------------------------------
desstructor
--------------------------------------------*/
BoxCollection::~BoxCollection()
{
for(int ibox=0;ibox<no_boxes;ibox++)
{
delete boxes[ibox];
}
if(no_boxes)
delete [] boxes;
no_boxes=0;
}
/*--------------------------------------------
add a box
--------------------------------------------*/
int BoxCollection::add(char* name)
{
Box** new_boxs;
CREATE1D(new_boxs,no_boxes+1);
for(int i=0;i<no_boxes;i++)
new_boxs[i]=boxes[i];
new_boxs[no_boxes]=new Box(xtal,name);
if(no_boxes)
delete [] boxes;
boxes=new_boxs;
no_boxes++;
return no_boxes-1;
}
/*--------------------------------------------
add a box
--------------------------------------------*/
int BoxCollection::cp(char* src_name,char* des_name)
{
Box** new_boxs;
CREATE1D(new_boxs,no_boxes+1);
for(int i=0;i<no_boxes;i++)
new_boxs[i]=boxes[i];
int ibox=find(src_name);
new_boxs[no_boxes]=new Box(*boxes[ibox]);
new_boxs[no_boxes]->chng_name(des_name);
if(no_boxes)
delete [] boxes;
boxes=new_boxs;
no_boxes++;
return no_boxes-1;
}
/*--------------------------------------------
add a box without a name
name should be added later!!!!!
--------------------------------------------*/
int BoxCollection::add_unsafe()
{
Box** new_boxs;
CREATE1D(new_boxs,no_boxes+1);
for(int i=0;i<no_boxes;i++)
new_boxs[i]=boxes[i];
new_boxs[no_boxes]=new Box(xtal);
if(no_boxes)
delete [] boxes;
boxes=new_boxs;
no_boxes++;
return no_boxes-1;
}
/*--------------------------------------------
add a box
--------------------------------------------*/
int BoxCollection::find(char* name)
{
for(int i=0;i<no_boxes;i++)
{
if(strcmp(name,boxes[i]->box_name)==0)
return i;
}
return -1;
}
/*--------------------------------------------
add a box
--------------------------------------------*/
void BoxCollection::del(int ibox)
{
delete boxes[ibox];
Box** new_boxs;
CREATE1D(new_boxs,no_boxes-1);
for(int i=0;i<ibox;i++)
new_boxs[i]=boxes[i];
for(int i=ibox+1;i<no_boxes;i++)
new_boxs[i-1]=boxes[i];
delete [] boxes;
boxes=new_boxs;
no_boxes--;
}
/*--------------------------------------------
add a box
--------------------------------------------*/
void BoxCollection::del(char* name)
{
int ibox=find(name);
del(ibox);
}
/*--------------------------------------------
multiply a box
--------------------------------------------*/
/*
void BoxCollection::mul(char* box,int* n)
{
boxes[find(box)]->mul(n);
}
void BoxCollection::add_vac(char* box,int dim
,type0 thickness)
{
boxes[find(box)]->add_vac(dim,thickness);
}
int BoxCollection::add_type(char* box,type0 m
,char* name)
{
return boxes[find(box)]->add_type(m,name);
}
void BoxCollection::add_atoms(char* box,int no
,int* type_buff,type0* s_buff)
{
boxes[find(box)]->add_atoms(no,type_buff,s_buff);
}
int BoxCollection::ret_no_types(char* box)
{
return boxes[find(box)]->no_types;
}
char** BoxCollection::ret_atom_names(char* box)
{
return boxes[find(box)]->atom_names;
}
type0* BoxCollection::ret_mass(char* box)
{
return boxes[find(box)]->mass;
}
type0** BoxCollection::ret_H(char* box)
{
return boxes[find(box)]->H;
}
type0** BoxCollection::ret_B(char* box)
{
return boxes[find(box)]->B;
}
int BoxCollection::ret_natms(char* box)
{
return boxes[find(box)]->natms;
}
type0* BoxCollection::ret_s(char* box)
{
return boxes[find(box)]->s;
}
int* BoxCollection::ret_type(char* box)
{
return boxes[find(box)]->type;
}
*/<file_sep>/src/command_dislocation.cpp
#include "command_dislocation.h"
#include "memory.h"
#include "error.h"
#include "box2cfg.h"
#include "box_collection.h"
#include <cmath>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_dislocation::Command_dislocation(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=7)
{
error->warning("dislocation command needs 6 arguments\n"
"SYNTAX: dislocation box periodic_dim dislocation_line_dim (n_edge,n_screw) (nx,ny) poisson");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
Box* box=box_collection->boxes[ibox];
type0** H=box->H;
if(H[1][0]!=0.0 || H[2][0]!=0.0 || H[2][1]!=0.0)
{
error->warning("box %s must be orthogonal",arg[1]);
return;
}
int disloc_dim;
int per_dim;
int other_dim=-1;
if(strcmp(arg[2],"x")==0)
{
per_dim=0;
b_edge=H[0][0];
}
else if(strcmp(arg[2],"y")==0)
{
per_dim=1;
b_edge=H[1][1];
}
else if(strcmp(arg[2],"z")==0)
{
per_dim=2;
b_edge=H[2][2];
}
else
{
error->warning("invalid screw dislocation direction: %s",arg[2]);
return;
}
if(strcmp(arg[3],"x")==0)
{
disloc_dim=0;
b_screw=H[0][0];
}
else if(strcmp(arg[3],"y")==0)
{
disloc_dim=1;
b_screw=H[1][1];
}
else if(strcmp(arg[3],"z")==0)
{
disloc_dim=2;
b_screw=H[2][2];
}
else
{
error->warning("invalid edge dislocation direction: %s",arg[3]);
return;
}
if(disloc_dim==per_dim)
{
error->warning("periodic dimension and dislocation line orientation must be prependicular top each other: %s",arg[3]);
return;
}
for(int i=0;i<3;i++)
if(i!=disloc_dim && i!=per_dim)
other_dim=i;
if(sscanf(arg[4],"(%d,%d)",&n_edge,&n_screw)==2)
{
if(n_edge<0 || n_screw<0)
{
error->warning("dislocation unit cell size should be greater than or equal to 0");
return;
}
}
else
{
error->warning("edge and screw dislocation unit cell size "
"should be of the format: (n_edge,n_screw)");
return;
}
int m[2];
if(sscanf(arg[5],"(%d,%d)",&m[0],&m[1])==2)
{
if(m[0]<=0 || m[1]<=0 )
{
error->warning("unit cell size should be greater than 0");
return;
}
if(m[0]<=n_edge || m[1]<=n_screw)
{
error->warning("unit cell size should be greater than dislocation");
return;
}
}
else
{
error->warning("unit cell size "
"should be of the format: (n_x,n_y)");
return;
}
nu=atof(arg[6]);
if(nu<=0.0 || nu>0.5)
{
error->warning("poisson ratio must be betweeen 0.0 and 0.5");
return;
}
n[per_dim]=m[0];
n[disloc_dim]=1;
n[other_dim]=m[1];
box->mul(n);
H=box->H;
x_scale=M_PI;
y_scale=M_PI*H[other_dim][other_dim]/H[per_dim][per_dim];
H[per_dim][per_dim]-=0.5*static_cast<type0>(n_edge)*b_edge;
ux_scale=static_cast<type0>(n_edge)*b_edge/H[per_dim][per_dim];
uy_scale=static_cast<type0>(n_edge)*b_edge/H[other_dim][other_dim];
uz_scale=static_cast<type0>(n_screw)*b_screw/H[disloc_dim][disloc_dim];
type0 s_x_lo=0.5*(1.0-static_cast<type0>(n_edge)/static_cast<type0>(n[0]));
type0 s_x_hi=0.5*(1.0+static_cast<type0>(n_edge)/static_cast<type0>(n[0]));
type0 sh_x=static_cast<type0>(n[0])/(static_cast<type0>(n[0])-0.5*static_cast<type0>(n_edge));
/*
s_x<0.5*(1+n_edge/n[0])
s_x<=0.5*(1-n_edge/n[0])
s_y>=0.5;
*/
type0* s=box->s;
int natms=box->natms;
if(ux_scale==0)
{
/*
box->add_vac(0,1,100.0);
box->add_vac(0,-1,100.0);
uz_scale=static_cast<type0>(n_screw)*b_screw/H[disloc_dim][disloc_dim];
*/
type0 dsz;
for(int i=0;i<natms;i++,s+=3)
{
disp(s[per_dim],s[other_dim],dsz);
s[disloc_dim]+=dsz;
correct_s(s[disloc_dim]);
}
}
else if(uz_scale==0)
{
int* del_list;
CREATE1D(del_list,natms);
int sz=0;
type0 dsx,dsy;
for(int i=0;i<natms;i++,s+=3)
{
if(s[per_dim]>=s_x_lo && s[per_dim]<s_x_hi && s[other_dim]>=0.5)
del_list[sz++]=i;
else
{
disp(s[per_dim],s[other_dim],dsx,dsy);
s[per_dim]*=sh_x;
s[per_dim]+=dsx;
s[other_dim]+=dsy;
correct_s(s[per_dim]);
correct_s(s[other_dim]);
}
}
box->del_atoms(sz,del_list);
delete [] del_list;
}
else
{
int* del_list;
CREATE1D(del_list,natms);
int sz=0;
type0 dsx,dsy,dsz;
for(int i=0;i<natms;i++,s+=3)
{
if(s[per_dim]>=s_x_lo && s[per_dim]<s_x_hi && s[other_dim]>=0.5)
del_list[sz++]=i;
else
{
disp(s[per_dim],s[other_dim],dsx,dsy,dsz);
s[per_dim]*=sh_x;
s[per_dim]+=dsx;
s[other_dim]+=dsy;
s[disloc_dim]+=dsz;
correct_s(s[disloc_dim]);
correct_s(s[per_dim]);
correct_s(s[other_dim]);
}
}
box->del_atoms(sz,del_list);
delete [] del_list;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_dislocation::~Command_dislocation()
{
}
/*--------------------------------------------
displacement for edge dislocation
--------------------------------------------*/
void Command_dislocation::correct_s(type0& s)
{
while(s<0.0)
s++;
while(s>=1.0)
s--;
}
/*--------------------------------------------
displacement for edge dislocation
--------------------------------------------*/
void Command_dislocation::disp(type0 x,type0 y,type0& ux,type0& uy)
{
x-=0.5;
x*=x_scale;
y-=0.5;
y*=y_scale;
if(x==0.0 && y==0.0)
{
ux=-0.25;
uy=0.0;
ux*=ux_scale;
uy*=uy_scale;
return;
}
type0 sinx,cosx,sinhy,coshy;
sinx=sin(x);
cosx=cos(x);
sinhy=sinh(y);
coshy=cosh(y);
type0 tmp=coshy*coshy-cosx*cosx;
ux=atan(sinx*coshy/(cosx*sinhy))-y*sinx*cosx/(tmp*2.0*(1.0-nu));
ux/=2.0*M_PI;
uy=(0.5-nu)*log(tmp)-y*sinhy*coshy/tmp;
uy/=4.0*M_PI*(1.0-nu);
if(y>=0.0)
{
if(x>0.0)
ux-=0.5;
else if(x<0.0)
ux+=0.5;
}
ux-=0.25;
ux*=ux_scale;
uy*=uy_scale;
}
/*--------------------------------------------
displacement for screw dislocation
--------------------------------------------*/
void Command_dislocation::disp(type0 x,type0 y,type0& uz)
{
x-=0.5;
x*=x_scale;
y-=0.5;
y*=y_scale;
if(x==0 && y==0)
{
uz=0.0;
return;
}
uz=atan(tan(x)/tanh(y))/(2.0*M_PI);
if(y>=0.0)
{
if(x>0.0)
uz-=0.5;
else
uz+=0.5;
}
uz*=uz_scale;
}
/*--------------------------------------------
displacement for mixed dislocation
--------------------------------------------*/
void Command_dislocation::disp(type0 x,type0 y,type0& ux,type0& uy,type0& uz)
{
x-=0.5;
x*=x_scale;
y-=0.5;
y*=y_scale;
if(x==0 && y==0)
{
ux=-0.25;
uy=0.0;
uz=0.0;
return;
}
type0 sinx,cosx,sinhy,coshy;
sinx=sin(x);
cosx=cos(x);
sinhy=sinh(y);
coshy=cosh(y);
type0 tmp0=coshy*coshy-cosx*cosx;
type0 tmp1=atan(sinx*coshy/(cosx*sinhy));
ux=(tmp1-y*sinx*cosx/(tmp0*2.0*(1.0-nu)))/(2.0*M_PI);
uy=((0.5-nu)*log(tmp0)-y*sinhy*coshy/tmp0)/(4.0*M_PI*(1.0-nu));
uz=tmp1/(2.0*M_PI);
if(y>=0.0)
{
if(x>0.0)
{
ux-=0.5;
uz-=0.5;
}
else if(x<0.0)
{
ux+=0.5;
uz+=0.5;
}
}
ux-=0.25;
ux*=ux_scale;
uy*=uy_scale;
uz*=uz_scale;
}
<file_sep>/src/init.h
#define MIN(A,B) ((A) < (B) ? (A) : (B))
#define MAX(A,B) ((A) > (B) ? (A) : (B))
#define MAX_CHAR 1024
#define TOLERANCE 1.0e-10
#define V3ZERO(V) (V[0]=0, V[1]=0, V[2]=0)
#define M3DET(A) A[0][0]*A[1][1]*A[2][2]\
+A[1][0]*A[2][1]*A[0][2]\
+A[2][0]*A[0][1]*A[1][2]\
-A[0][2]*A[1][1]*A[2][0]\
-A[1][2]*A[2][1]*A[0][0]\
-A[2][2]*A[0][1]*A[1][0]
#define M3ZERO(A) ( A[0][0]=0, A[0][1]=0, A[0][2]=0, A[1][0]=0, \
A[1][1]=0, A[1][2]=0, A[2][0]=0, A[2][1]=0, A[2][2]=0 )
#define M3INV(A,B,determinant) ( \
B[0][0] = A[1][1]*A[2][2]-A[1][2]*A[2][1], \
B[1][1] = A[2][2]*A[0][0]-A[2][0]*A[0][2], \
B[2][2] = A[0][0]*A[1][1]-A[0][1]*A[1][0], \
B[1][0] = A[1][2]*A[2][0]-A[1][0]*A[2][2], \
B[2][1] = A[2][0]*A[0][1]-A[2][1]*A[0][0], \
B[0][2] = A[0][1]*A[1][2]-A[0][2]*A[1][1], \
B[2][0] = A[1][0]*A[2][1]-A[2][0]*A[1][1], \
B[0][1] = A[2][1]*A[0][2]-A[0][1]*A[2][2], \
B[1][2] = A[0][2]*A[1][0]-A[1][2]*A[0][0], \
(determinant) = A[0][0]*B[0][0] + A[0][1]*B[1][0] + A[0][2]*B[2][0], \
B[0][0] /= (determinant),B[1][1] /= (determinant),B[2][2] /= (determinant), \
B[1][0] /= (determinant),B[2][1] /= (determinant),B[0][2] /= (determinant), \
B[2][0] /= (determinant),B[0][1] /= (determinant),B[1][2] /= (determinant) )
#define M3COFAC(A,B) ( \
B[0][0] = A[1][1]*A[2][2]-A[1][2]*A[2][1], \
B[1][1] = A[2][2]*A[0][0]-A[2][0]*A[0][2], \
B[2][2] = A[0][0]*A[1][1]-A[0][1]*A[1][0], \
B[1][0] = A[1][2]*A[2][0]-A[1][0]*A[2][2], \
B[2][1] = A[2][0]*A[0][1]-A[2][1]*A[0][0], \
B[0][2] = A[0][1]*A[1][2]-A[0][2]*A[1][1], \
B[2][0] = A[1][0]*A[2][1]-A[2][0]*A[1][1], \
B[0][1] = A[2][1]*A[0][2]-A[0][1]*A[2][2], \
B[1][2] = A[0][2]*A[1][0]-A[1][2]*A[0][0])
#define M3NORMAL(A,B) ( \
B[0][0] = A[1][1]*A[2][2]-A[1][2]*A[2][1], \
B[0][1] = A[1][2]*A[2][0]-A[1][0]*A[2][2], \
B[0][2] = A[1][0]*A[2][1]-A[2][0]*A[1][1], \
B[1][0] = A[2][1]*A[0][2]-A[0][1]*A[2][2], \
B[1][1] = A[2][2]*A[0][0]-A[2][0]*A[0][2], \
B[1][2] = A[2][0]*A[0][1]-A[2][1]*A[0][0], \
B[2][0] = A[0][1]*A[1][2]-A[0][2]*A[1][1], \
B[2][1] = A[0][2]*A[1][0]-A[1][2]*A[0][0], \
B[2][2] = A[0][0]*A[1][1]-A[0][1]*A[1][0])
#define THICKNESS(B,d) (\
d[0]=1.0/sqrt(B[0][0]*B[0][0]+B[1][0]*B[1][0]+B[2][0]*B[2][0]),\
d[1]=1.0/sqrt(B[0][1]*B[0][1]+B[1][1]*B[1][1]+B[2][1]*B[2][1]),\
d[2]=1.0/sqrt(B[0][2]*B[0][2]+B[1][2]*B[1][2]+B[2][2]*B[2][2]))
#define M3EQV(A,B) ( B[0][0] = A[0][0], B[0][1] = A[0][1], \
B[0][2] = A[0][2], B[1][0] = A[1][0], B[1][1] = A[1][1], \
B[1][2] = A[1][2], B[2][0] = A[2][0], B[2][1] = A[2][1], \
B[2][2] = A[2][2] )
#define M3IDENTITY(A) ( A[0][0]=1, A[0][1]=0, A[0][2]=0, \
A[1][0]=0, A[1][1]=1, A[1][2]=0, A[2][0]=0, A[2][1]=0, A[2][2]=1 )
#define M3MUL_TRI_LOWER(A,B,C) (C[0][0]=A[0][0]*B[0][0],C[0][1]=0,C[0][2]=0,\
C[1][0]=A[1][0]*B[0][0]+A[1][1]*B[1][0],C[1][1]=A[1][1]*B[1][1],C[1][2]=0,\
C[2][0]=A[2][0]*B[0][0]+A[2][1]*B[1][0]+A[2][2]*B[2][0],\
C[2][1]=A[2][1]*B[1][1]+A[2][2]*B[2][1],C[2][2]=A[2][2]*B[2][2])
#define M3INV_TRI_LOWER(A,B) (B[0][0]=1.0/A[0][0],B[0][1]=0,B[0][2]=0,\
B[1][0]=-A[1][0]/(A[0][0]*A[1][1]),B[1][1]=1.0/A[1][1],B[1][2]=0,\
B[2][0]=(A[1][0]*A[2][1]-A[1][1]*A[2][0])/(A[0][0]*A[1][1]*A[2][2]),\
B[2][1]=-A[2][1]/(A[1][1]*A[2][2]),B[2][2]=1.0/A[2][2])
#define M3mV3(A,b,c) ( \
(c)[0] = A[0][0]*(b)[0] + A[0][1]*(b)[1] + A[0][2]*(b)[2], \
(c)[1] = A[1][0]*(b)[0] + A[1][1]*(b)[1] + A[1][2]*(b)[2], \
(c)[2] = A[2][0]*(b)[0] + A[2][1]*(b)[1] + A[2][2]*(b)[2] )
#define COMP(ityp,jtyp) ((ityp) < (jtyp) ? ((jtyp+1)*jtyp/2+ityp) : ((ityp+1)*ityp/2+jtyp))
#define LOC __LINE__,__FILE__
#ifndef xtal_init_h
#define xtal_init_h
#include "xtal.h"
class InitPtrs{
private:
public:
InitPtrs(Xtal* ptr):
xtal(ptr),
memory(ptr->memory),
error(ptr->error),
box_collection(ptr->box_collection),
region_collection(ptr->region_collection)
{}
virtual ~InitPtrs(){}
protected:
Xtal* xtal;
Memory*& memory;
Error*& error;
BoxCollection*& box_collection;
RegionCollection*& region_collection;
};
#endif
<file_sep>/src/command_join.cpp
#include "command_join.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_join::Command_join(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=5 && narg!=4)
{
error->warning("join command needs 3 or 4 arguments\n"
"SYNTAX: join box box_0 box_1 dim\n"
"SYNTAX: join box box_0 box_1\n");
return;
}
int ibox0=box_collection->find(arg[2]);
int ibox1=box_collection->find(arg[3]);
if(ibox0<0)
{
error->warning("%s box not found",arg[2]);
return;
}
if(ibox1<0)
{
error->warning("%s box not found",arg[3]);
return;
}
int dim=-1;
if(narg==5)
{
if(strcmp(arg[4],"x")==0)
{
dim=0;
}
else if(strcmp(arg[4],"y")==0)
{
dim=1;
}
else if(strcmp(arg[4],"z")==0)
{
dim=2;
}
else
{
error->warning("invalid dimension: %s",arg[4]);
return;
}
}
Box* box0=box_collection->boxes[ibox0];
Box* box1=box_collection->boxes[ibox1];
int ibox;
if(strcmp(arg[1],arg[2])==0 && strcmp(arg[1],arg[3])!=0)
{
ibox=box_collection->add_unsafe();
if(narg==5)
box_collection->boxes[ibox]->join(box0,box1,dim);
else
box_collection->boxes[ibox]->join(box0,box1);
box_collection->boxes[ibox]->add_name(arg[2]);
box_collection->del(ibox0);
}
else if(strcmp(arg[1],arg[2])!=0 && strcmp(arg[1],arg[3])==0)
{
ibox=box_collection->add_unsafe();
box_collection->boxes[ibox]->join(box0,box1,dim);
if(narg==5)
box_collection->boxes[ibox]->join(box0,box1,dim);
else
box_collection->boxes[ibox]->join(box0,box1);
box_collection->boxes[ibox]->add_name(arg[3]);
box_collection->del(ibox1);
}
else if(strcmp(arg[1],arg[2])==0 && strcmp(arg[1],arg[3])==0)
{
ibox=box_collection->add_unsafe();
box_collection->boxes[ibox]->join(box0,box1,dim);
if(narg==5)
box_collection->boxes[ibox]->join(box0,box1,dim);
else
box_collection->boxes[ibox]->join(box0,box1);
box_collection->boxes[ibox]->add_name(arg[2]);
box_collection->del(ibox0);
}
else
{
ibox=box_collection->find(arg[1]);
int box_exist=1;
if(ibox<0)
{
box_exist=0;
ibox=box_collection->add_unsafe();
}
if(narg==5)
box_collection->boxes[ibox]->join(box0,box1,dim);
else
box_collection->boxes[ibox]->join(box0,box1);
if(box_exist==0)
box_collection->boxes[ibox]->add_name(arg[1]);
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_join::~Command_join()
{
}
<file_sep>/src/command_rotate.cpp
#include <math.h>
#include "command_rotate.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
#include "region_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_rotate::Command_rotate(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
int region_xst,iregion,ibox,iarg,natms,icomp;
type0 n_lngth,theta,cos_theta,sin_theta,tmp0,tmp1,tmp2;
type0* n;
type0* c;
type0* c_s;
type0* s_new;
type0* s;
type0** Q_0;
type0** Q;
type0** H;
type0** B;
if(narg!=5 && narg!=6)
{
error->warning("rotate command needs at least 4 arguments\n"
"SYNTAX: rotate box (c0,c1,c2) (n0,n1,n2) theta\n"
"or\n"
"SYNTAX: rotate box region (c0,c1,c2) (n0,n1,n2) theta\n");
return;
}
ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
if(narg==6)
{
region_xst=1;
iregion=region_collection->find(arg[2]);
if(iregion<0)
{
error->warning("region %s not found",arg[2]);
return;
}
iarg=3;
}
else
{
iregion=-1;
region_xst=0;
iarg=2;
}
CREATE1D(c,3);
CREATE1D(n,3);
if(sscanf(arg[iarg],"(%lf,%lf,%lf)",&tmp0,&tmp1,&tmp2)==3)
{
c[0]=tmp0;
c[1]=tmp1;
c[2]=tmp2;
}
else
{
error->warning("c should be of the format: (c0,c1,c2)");
delete [] c;
delete [] n;
return;
}
iarg++;
if(sscanf(arg[iarg],"(%lf,%lf,%lf)",&tmp0,&tmp1,&tmp2)==3)
{
n[0]=tmp0;
n[1]=tmp1;
n[2]=tmp2;
}
else
{
error->warning("n should be of the format: (n0,n1,n2)");
delete [] c;
delete [] n;
return;
}
iarg++;
theta=atof(arg[iarg]);
theta*=M_PI/180.0;
cos_theta=cos(theta);
sin_theta=sin(theta);
/* normalize n */
n_lngth=sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
if(n_lngth==0.0)
{
error->warning("n size cannot be 0.0");
delete [] c;
delete [] n;
return;
}
n[0]/=n_lngth;
n[1]/=n_lngth;
n[2]/=n_lngth;
/* calculate Q_0 */
CREATE2D(Q_0,3,3);
Q_0[0][0]=Q_0[1][1]=Q_0[2][2]=cos_theta;
Q_0[2][1]=n[0]*sin_theta;
Q_0[1][2]=-n[0]*sin_theta;
Q_0[0][2]=n[1]*sin_theta;
Q_0[2][0]=-n[1]*sin_theta;
Q_0[1][0]=n[2]*sin_theta;
Q_0[0][1]=-n[2]*sin_theta;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
Q_0[i][j]+=n[i]*n[j]*(1.0-cos_theta);
/* allocate Q */
CREATE2D(Q,3,3);
/* calculate Q */
H=box_collection->boxes[ibox]->H;
B=box_collection->boxes[ibox]->B;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
Q[i][j]=0.0;
for(int k=0;k<3;k++)
for(int l=0;l<3;l++)
Q[i][j]+=B[k][i]*H[j][l]*Q_0[k][l];
}
/* claculate c_s */
CREATE1D(c_s,3);
for(int i=0;i<3;i++)
{
c_s[i]=0.0;
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
{
c_s[i]-=B[j][i]*Q_0[j][k]*c[k];
if(j==k)
c_s[i]+=B[j][i]*c[k];
}
}
/* remove unneccassry pointers: Q_0, c & n */
for(int i=0;i<3;i++)
delete [] Q_0[i];
delete [] Q_0;
delete [] c;
delete [] n;
/* allocate s_new */
CREATE1D(s_new,3);
/* get s & natms*/
s=box_collection->boxes[ibox]->s;
natms=box_collection->boxes[ibox]->natms;
/* perform rotation*/
icomp=0;
if(region_xst)
{
Region* region=region_collection->regions[iregion];
for(int iatm=0;iatm<natms;iatm++)
{
if(region->belong(H,&s[icomp]))
{
M3mV3(Q,&s[icomp],s_new);
s[icomp]=s_new[0]+c_s[0];
s[icomp+1]=s_new[1]+c_s[1];
s[icomp+2]=s_new[2]+c_s[2];
}
icomp+=3;
}
}
else
{
for(int iatm=0;iatm<natms;iatm++)
{
M3mV3(Q,&s[icomp],s_new);
s[icomp]=s_new[0]+c_s[0];
s[icomp+1]=s_new[1]+c_s[1];
s[icomp+2]=s_new[2]+c_s[2];
icomp+=3;
}
}
for(int i=0;i<3*natms;i++)
{
while(s[i]<0.0)
s[i]++;
while(s[i]>=1.0)
s[i]--;
}
for(int i=0;i<3;i++)
delete [] Q[i];
delete [] Q;
delete [] c_s;
delete [] s_new;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_rotate::~Command_rotate()
{
}
<file_sep>/src/command_ls_region.h
#ifdef Command_Style
CommandStyle(Command_ls_region,ls_region)
#else
#ifndef __xtal__command_ls_region__
#define __xtal__command_ls_region__
#include "init.h"
#include <stdio.h>
class Command_ls_region: protected InitPtrs
{
private:
protected:
public:
Command_ls_region(Xtal*,int,char**);
~Command_ls_region();
};
#endif
#endif
<file_sep>/src/gr.cpp
#include "gr.h"
#include <math.h>
#include "memory.h"
#include "xmath.h"
#include "region_block.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Gr::Gr(Xtal* xtal,type0***& gr_,type0***& sr_,Box*& box_,bool(&dims_)[3],type0& cutoff_,type0& k_cutoff_,int& no_bins_):InitPtrs(xtal),
box(box_),
cutoff(cutoff_),
k_cutoff(k_cutoff_),
dims(dims_),
no_bins(no_bins_),
gr(gr_),
sr(sr_)
{
ndims=0;
for(int i=0;i<3;i++) if(dims[i]) ndims++;
if(ndims==1)
{
gr=NULL;
allocate_gr();
for(int i=0;i<3;i++) if(dims[i]) prepare_1d(i);
return;
}
dr=cutoff/static_cast<type0>(no_bins);
dk=k_cutoff/static_cast<type0>(no_bins);
dr_inv=1.0/dr;
next_bin=NULL;
bin_list=NULL;
get_s_cutoff();
box->add_ghost(dims,s_cutoff);
setup_bins();
gr=NULL;
allocate_gr();
int natms=box->natms;
int igr;
type0* s=box->s;
type0 cut_sq=cutoff*cutoff;
type0 delta;
for(int i=0;i<natms;i++)
{
int ibin=find_bin(s+3*i);
for(int in=0;in<nneigh_bins;in++)
{
int j=bin_list[ibin+neigh_bins[in]];
while(j!=-1)
{
if(j<=i)
{
j=next_bin[j];
continue;
}
delta=dist(i,j);
if(delta>=cut_sq)
{
j=next_bin[j];
continue;
}
igr=static_cast<int>(sqrt(delta)*dr_inv);
gr[box->type[i]][box->type[j]][igr]++;
if(j<natms)
gr[box->type[i]][box->type[j]][igr]++;
j=next_bin[j];
}
}
}
finalize_gr();
deallocate_bins();
box->del_ghost();
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Gr::~Gr()
{
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::finalize_gr()
{
type0 vol=box->H[0][0]*box->H[1][1]*box->H[2][2];
type0 area_frac=1.0;
type0 hm[3];
int no_dims=0;
for(int i=0;i<3;i++)
{
if(dims[i])
{
no_dims++;
area_frac*=dr;
continue;
}
type0 tmp=0.0;
for(int j=i;j<3;j++)
tmp+=box->B[j][i]*box->B[j][i];
vol*=sqrt(tmp);
}
if(no_dims==3)
{
area_frac*=4.0*M_PI/3.0;
hm[0]=area_frac;
hm[1]=3.0*area_frac;
hm[2]=3.0*area_frac;
}
if(no_dims==2)
{
area_frac*=M_PI;
hm[0]=area_frac;
hm[1]=2.0*area_frac;
hm[2]=0.0;
}
if(no_dims==1)
{
area_frac*=M_PI;
hm[0]=area_frac;
hm[1]=0.0;
hm[2]=0.0;
}
int no_types=box->no_types;
type0 density=1.0/vol;
type0 dfrac;
type0 ii;
type0 tmp,r,k;
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<no_types;jtyp++)
{
dfrac=static_cast<type0>(box->type_count[ityp])*static_cast<type0>(box->type_count[jtyp])*density;
//dfrac=static_cast<type0>(box->type_count[ityp]);
for(int i=0;i<no_bins;i++)
{
ii=static_cast<type0>(i);
gr[ityp][jtyp][i]/=dfrac*(hm[0]+hm[1]*ii+hm[2]*ii*ii);
}
}
if(ndims==2)
{
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<no_types;jtyp++)
{
r=dr*0.5;
for(int i=0;i<no_bins;i++,r+=dr)
{
tmp=gr[ityp][jtyp][i]*r*dr;
k=0.5*dk;
for(int j=0;j<no_bins;j++,k+=dk)
sr[ityp][jtyp][j]+=tmp*j0(k*r);
}
}
}
else
{
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<no_types;jtyp++)
{
r=dr*0.5;
for(int i=0;i<no_bins;i++,r+=dr)
{
tmp=gr[ityp][jtyp][i]*r*dr;
k=0.5*dk;
for(int j=0;j<no_bins;j++,k+=dk)
sr[ityp][jtyp][j]+=tmp*sin(k*r)/k;
}
}
}
}
/*--------------------------------------------
--------------------------------------------*/
inline type0 Gr::dist(int& iatm,int& jatm)
{
type0 tmp0,rsq=0.0;
for(int i=0;i<3;i++)
{
if(!dims[i]) continue;
for(int j=i;j<3;j++)
{
tmp0=(box->s[3*iatm+j]-box->s[3*jatm+j])*box->H[j][i];
rsq+=tmp0*tmp0;
}
}
return rsq;
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::find_bin(type0* s_,int (&nn)[3])
{
for(int i=0;i<3;i++)
if(dims[i])
nn[i]=static_cast<int>((s_[i]+s_cutoff[i])/s_cutoff[i]);
}
/*--------------------------------------------
--------------------------------------------*/
int Gr::find_bin(type0* s_)
{
int n=0;
for(int i=0;i<3;i++)
if(dims[i])
n+=bin_vec[i]*static_cast<int>((s_[i]+s_cutoff[i])/s_cutoff[i]);
return n;
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::get_s_cutoff()
{
type0** B=box->B;
type0 tmp;
for(int idim=0;idim<3;idim++)
{
tmp=0.0;
for(int jdim=idim;jdim<3;jdim++)
tmp+=B[jdim][idim]*B[jdim][idim];
s_cutoff[idim]=sqrt(tmp)*cutoff;
}
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::setup_bins()
{
for(int i=0;i<3;i++)
{
if(dims[i])
nbins[i]=static_cast<int>((2.0*s_cutoff[i]+1.0)/s_cutoff[i])+1;
else
nbins[i]=1;
}
bin_vec[0]=1;
bin_vec[1]=nbins[0];
bin_vec[2]=nbins[0]*nbins[1];
bin_list=new int[nbins[0]*nbins[1]*nbins[2]];
for(int i=0;i<nbins[0]*nbins[1]*nbins[2];i++)
bin_list[i]=-1;
nneigh_bins=1;
for(int i=0;i<3;i++)
if(dims[i])
nneigh_bins*=3;
neigh_bins=new int[nneigh_bins];
int lo_lim[3];
int hi_lim[3];
for(int i=0;i<3;i++)
{
if(dims[i])
{
lo_lim[i]=-1;
hi_lim[i]=2;
}
else
{
lo_lim[i]=0;
hi_lim[i]=1;
}
}
int ibin=0;
for(int i0=lo_lim[0];i0<hi_lim[0];i0++)
for(int i1=lo_lim[1];i1<hi_lim[1];i1++)
for(int i2=lo_lim[2];i2<hi_lim[2];i2++)
neigh_bins[ibin++]=i0*bin_vec[0]+i1*bin_vec[1]+i2*bin_vec[2];
//bin the atoms and create the link list
int t_natms=box->natms+box->nghosts;
next_bin=new int[t_natms];
type0* s=box->s;
for(int i=t_natms-1;i>-1;i--)
{
ibin=find_bin(s+3*i);
next_bin[i]=bin_list[ibin];
bin_list[ibin]=i;
}
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::deallocate_bins()
{
delete [] bin_list;
delete [] next_bin;
delete [] neigh_bins;
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::allocate_gr()
{
int no_types=box->no_types;
gr=new type0**[no_types];
*gr=new type0*[no_types*no_types];
type0* tmp_gr=new type0[no_types*(no_types+1)*no_bins/2];
for(int i=1;i<no_types;i++)
gr[i]=gr[i-1]+no_types;
for(int i=0;i<no_types;i++)
for(int j=0;j<i+1;j++)
{
gr[i][j]=tmp_gr;
gr[j][i]=tmp_gr;
tmp_gr+=no_bins;
}
for(int i=0;i<no_types*(no_types+1)*no_bins/2;i++)
gr[0][0][i]=0.0;
sr=new type0**[no_types];
*sr=new type0*[no_types*no_types];
type0* tmp_sr=new type0[no_types*(no_types+1)*no_bins/2];
for(int i=1;i<no_types;i++)
sr[i]=sr[i-1]+no_types;
for(int i=0;i<no_types;i++)
for(int j=0;j<i+1;j++)
{
sr[i][j]=tmp_sr;
sr[j][i]=tmp_sr;
tmp_sr+=no_bins;
}
type0 k;
if(ndims==1)
{
for(int i=0;i<no_types*(no_types+1)*no_bins/2;i++)
sr[0][0][i]=0.0;
}
else if(ndims==2)
{
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<no_types;jtyp++)
{
k=0.5*dk;
for(int i=0;i<no_bins;i++,k+=dk)
sr[ityp][jtyp][i]=-cutoff*j1(cutoff*k)/k;
}
}
else
{
for(int ityp=0;ityp<no_types;ityp++)
for(int jtyp=0;jtyp<no_types;jtyp++)
{
k=0.5*dk;
for(int i=0;i<no_bins;i++,k+=dk)
sr[ityp][jtyp][i]=(k*cutoff*cos(k*cutoff)-sin(k*cutoff))/(k*k*k);
}
}
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::prepare_2d()
{
int dim0=0,dim1=0;
int xtra_dim=0;
if(!dims[0])
{
xtra_dim=0;
dim0=1;
dim1=2;
}
if(!dims[1])
{
xtra_dim=1;
dim0=2;
dim1=0;
}
if(!dims[2])
{
xtra_dim=2;
dim0=0;
dim1=1;
}
Box* tmp_box=new Box(*box);
for(int i=0;i<xtra_dim;i++)
tmp_box->H[xtra_dim][i]=0.0;
type0 det;
M3INV(tmp_box->H,tmp_box->B,det);
int natms=tmp_box->natms;
type0* old_s=box->s;
type0* s=tmp_box->s;
type0 x[3];
type0** old_H=box->H;
type0** B=tmp_box->B;
x[0]=x[1]=x[2]=0.0;
for(int i=0;i<natms;i++)
{
x[dim0]=x[dim1]=0.0;
for(int j=dim0;j<3;j++)
x[dim0]+=old_H[j][dim0]*old_s[3*i+j];
for(int j=dim0;j<3;j++)
x[dim0]+=old_H[j][dim0]*old_s[3*i+j];
for(int j=0;j<3;j++)
s[3*i+j]=0.0;
for(int j=0;j<3;j++)
for(int k=j;k<3;k++)
s[3*i+j]=B[k][j]*x[k];
}
}
/*--------------------------------------------
--------------------------------------------*/
void Gr::prepare_1d(int idim)
{
type0 l,length=box->H[idim][idim];
cutoff=length;
dr=cutoff/static_cast<type0>(no_bins);
dk=k_cutoff/static_cast<type0>(no_bins);
dr_inv=1.0/dr;
type0* s=box->s;
type0** H=box->H;
int* type=box->type;
int natms=box->natms;
int no_types=box->no_types;
int ibin;
type0** bin_count=new type0*[no_types];
*bin_count=new type0[no_types*no_bins];
for(int i=1;i<no_types;i++)
bin_count[i]=bin_count[i-1]+no_types;
for(int i=0;i<no_types*no_bins;i++)
bin_count[0][i]=0.0;
for(int i=0;i<natms;i++)
{
l=0.0;
for(int j=idim;j<3;j++)
l+=s[3*i+j]*H[j][idim];
while(l>=length)
l-=length;
while(l<0.0)
l+=length;
ibin=static_cast<int>(l*dr_inv);
bin_count[type[i]][ibin]++;
}
type0 rat;
for(int it=0;it<no_types;it++)
for(int jt=it;jt<no_types;jt++)
for(int i=0;i<no_bins;i++)
{
gr[it][jt][0]+=2.0*bin_count[jt][i]*bin_count[it][i];
for(int j=i+1;j<no_bins;j++)
{
rat=bin_count[jt][j]*bin_count[it][i];
gr[it][jt][j-i]+=rat;
gr[it][jt][i-j+no_bins]+=rat;
}
}
type0 fac;
for(int it=0;it<no_types;it++)
for(int jt=it;jt<no_types;jt++)
{
fac=(length/dr)/static_cast<type0>(box->type_count[it]*box->type_count[jt]);
for(int i=0;i<no_bins;i++)
gr[it][jt][i]*=fac;
}
type0 k,r,tmp;
for(int it=0;it<no_types;it++)
for(int jt=it;jt<no_types;jt++)
{
k=0.0;
for(int i=0;i<no_bins;i++,k+=dk)
{
r=0.0;
tmp=0.0;
for(int j=0;j<no_bins;j++,r+=dr)
{
tmp+=gr[it][jt][j]*cos(r*k);
}
sr[it][jt][i]=tmp;
}
}
delete [] *bin_count;
delete [] bin_count;
}
<file_sep>/src/region_sphere.cpp
#include "region_sphere.h"
#include "memory.h"
#include "error.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Region_sphere::Region_sphere(Xtal* xtal
,int narg,char** arg):Region(xtal)
{
type0 tmp0,tmp1,tmp2;
alloc=0;
if(narg!=4)
{
error->warning("region sphere needs 3 arguments\n"
"SYNTAX: sphere name (c0,c1,c2) radius");
xtal->error_flag=-1;
return;
}
if(atof(arg[3])<0.0)
{
error->warning("redius of sphere cannot "
"be less than 0.0");
xtal->error_flag=-1;
return;
}
int lngth=static_cast<int>(strlen(arg[1]))+1;
CREATE1D(region_name,lngth);
CREATE1D(x,3);
alloc=1;
memcpy(region_name,arg[1],lngth);
if(sscanf(arg[2],"(%lf,%lf,%lf)",&tmp0,&tmp1,&tmp2)==3)
{
x[0]=tmp0;
x[1]=tmp1;
x[2]=tmp2;
}
else
{
error->warning("c should be of the format: (c0,c1,c2)");
xtal->error_flag=-1;
return;
}
r=atof(arg[3]);
rsq=r*r;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Region_sphere::~Region_sphere()
{
if(alloc)
{
delete [] region_name;
delete [] x;
}
}
/*--------------------------------------------
belong
--------------------------------------------*/
inline int Region_sphere::belong(type0** H,type0* s)
{
x0=H[0][0]*s[0]+H[1][0]*s[1]+H[2][0]*s[2]-x[0];
x1=H[1][1]*s[1]+H[2][1]*s[2]-x[1];
x2=H[2][2]*s[2]-x[2];
if(x0*x0+x1*x1+x2*x2<rsq)
return 1;
else
return 0;
}
<file_sep>/src/command_rm_thickness.cpp
#include "command_rm_thickness.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_rm_thickness::Command_rm_thickness(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=5)
{
error->warning("rm_thickness command needs 4 arguments\n"
"SYNTAX: rm_thickness box dim s_lo s_hi");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
int dim;
if(strcmp(arg[2],"x")==0)
{
dim=0;
}
else if(strcmp(arg[2],"y")==0)
{
dim=1;
}
else if(strcmp(arg[2],"z")==0)
{
dim=2;
}
else
{
error->warning("invalid dimension: %s",arg[2]);
return;
}
type0 s_lo,s_hi;
s_lo=atof(arg[3]);
s_hi=atof(arg[4]);
if(s_lo<0.0 || s_lo>1.0)
{
error->warning("s_lo must be between 0.0 & 1.0");
return;
}
if(s_hi<0.0 || s_hi>1.0)
{
error->warning("s_hi must be between 0.0 & 1.0");
return;
}
if(s_lo>=s_hi)
{
error->warning("s_hi must be greater than s_lo");
return;
}
box_collection->boxes[ibox]->rm_frac(dim,s_lo,s_hi);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_rm_thickness::~Command_rm_thickness()
{
}
<file_sep>/src/command_add_vac.h
#ifdef Command_Style
CommandStyle(Command_add_vac,add_vac)
#else
#ifndef __xtal__command_add_vac__
#define __xtal__command_add_vac__
#include "init.h"
#include <stdio.h>
class Command_add_vac: protected InitPtrs
{
private:
protected:
public:
Command_add_vac(Xtal*,int,char**);
~Command_add_vac();
};
#endif
#endif
<file_sep>/src/xtal.cpp
#include "xtal.h"
#include "memory.h"
#include "error.h"
#include "box_collection.h"
#include "region_collection.h"
#include "command_styles.h"
char** cmd;
/*--------------------------------------------
constructor of the main executer
--------------------------------------------*/
Xtal::Xtal(int narg,char** args)
{
no_cmds=no_vals=0;
memory=new Memory;
error=new Error(this);
box_collection=new BoxCollection(this);
region_collection=new RegionCollection(this);
input_file=NULL;
input_file=stdin;
int iarg=1;
while(iarg<narg)
{
if(strcmp(args[iarg],"-i")==0)
{
iarg++;
if(iarg==narg)
error->abort("no input file");
input_file=fopen(args[iarg],"r");
iarg++;
}
else if(strcmp(args[iarg],"-o")==0)
{
iarg++;
if(iarg==narg)
error->abort("no output file");
output_file=fopen(args[iarg],"w");
iarg++;
}
else
error->abort("unknown postfix: %s",args[iarg]);
}
if(narg!=1)
{
if(input_file==NULL)
error->abort("input file not found");
read_file();
if(input_file!=stdin)
fclose(input_file);
}
else
{
read_history(".xtal_history");
gen_cmd_ls();
read_line();
for(int i=0;i<no_cmds+no_vals+1;i++)
delete [] cmd[i];
delete [] cmd;
write_history(".xtal_history");
}
}
/*--------------------------------------------
destructor of the main executer
--------------------------------------------*/
Xtal::~Xtal()
{
delete region_collection;
delete box_collection;
delete error;
delete memory;
}
/*--------------------------------------------
parse a command line:
chops up a 1d array line into 2d array of
char, also returns the number of arguments
if the line starts with # it returns 0
for example:
line=
" this is a test, #here is comment";
will be converted to:
arg[0]="this";
arg[1]="is";
arg[2]="a";
arg[3]="test,";
narg=4;
--------------------------------------------*/
int Xtal::parse_line(char* line,char**& arg)
{
arg = NULL;
int narg = 0;
int cursor = 0;
int length= static_cast<int>(strlen(line));
int ll[length];
while (cursor < length
&& line[cursor]!='#'){
if (isspace(line[cursor]))
cursor++;
else
{
if (narg==0 && line[cursor]=='#')
return 0;
int i = 0;
while(!isspace(line[cursor])
&& cursor < length)
{
cursor++;
i++;
}
ll[narg]=i+1;
narg++;
}
}
if (narg==0) return 0;
CREATE1D(arg,narg);
for(int i=0;i<narg;i++)
CREATE1D(arg[i],ll[i]);
narg = 0;
cursor = 0;
while (cursor<length&&line[cursor]!='#')
{
if ( isspace(line[cursor]))
cursor++;
else
{
int i=0;
while(!isspace(line[cursor])
&& cursor < strlen(line))
arg[narg][i++]=line[cursor++];
arg[narg][i] = '\0';
narg++;
}
}
return narg;
}
/*--------------------------------------------
hash sign remover:
it removes the statement after hash sign,
replaces the withe spaces with space;
for example:
line=
" this is a test, #here is comment";
will be converted to:
newline=
"this is a test,";
narg=4;
--------------------------------------------*/
int Xtal::hash_remover(char* line,char*& newline)
{
newline = NULL;
CREATE1D(newline,MAX_CHAR);
int narg = 0;
int cursor = 0;
int icursor = 0;
while (cursor < strlen(line)&& line[cursor]!='#')
{
if (isspace(line[cursor]))
cursor++;
else
{ if (narg!=0)
newline[icursor++]=' ';
while(!isspace(line[cursor])
&& cursor < strlen(line))
newline[icursor++]=line[cursor++];
narg++;
}
}
newline[icursor]='\0';
return narg;
}
/*--------------------------------------------
hash sign remover:
it removes the statement after hash sign,
replaces the withe spaces with space;
for example:
line=
" this is a test, #here is comment";
will be converted to:
newline=
"this is a test,";
narg=4;
--------------------------------------------*/
void Xtal::concatenate(int narg,char** args
,char*& line)
{
int lngth=0;
int pos=0;
for(int i=0;i<narg;i++)
lngth+=static_cast<int>(strlen(args[i]));
lngth+=narg;
CREATE1D(line,lngth);
for(int i=0;i<narg;i++)
{
lngth=static_cast<int>(strlen(args[i]));
for(int j=0;j<lngth;j++)
{
line[pos]=args[i][j];
pos++;
}
if(i!=narg-1)
{
line[pos]=' ';
pos++;
}
else
{
line[pos]='\0';
pos++;
}
}
}
/*--------------------------------------------
test field
--------------------------------------------*/
void Xtal::read_line()
{
/*
rl_readline_name=(char*)"xtal-0.0$ ";
rl_attempted_completion_function=completion;
*/
#ifdef __APPLE__
rl_completion_entry_function=(Function*)command_generator;
#elif __linux__
rl_completion_entry_function=command_generator;
#endif
FILE* tmp_input;
tmp_input=fopen(".input","w");
char* line,shell_prompt[100];
snprintf(shell_prompt,sizeof(shell_prompt),"xtal-0.0$ ");
while(1)
{
line=readline(shell_prompt);
rl_bind_key('\t',rl_complete);
if(strcmp(line,"exit")==0)
{
fclose(input_file);
return;
}
command(line);
fprintf(tmp_input,"%s\n",line);
add_vals();
add_history(line);
free(line);
}
/*
FILE* tmp_input;
tmp_input=fopen(".intput","w");
char* line, shell_prompt[100];
snprintf(shell_prompt, sizeof(shell_prompt), "xtal$ ");
rl_completion_entry_function=(Function*)command_generator;
while(1)
{
line=readline(shell_prompt);
rl_bind_key('\t',rl_complete);
if(strcmp(line,"exit")==0)
{
fclose(input_file);
return;
}
command(line);
fprintf(tmp_input,"%s\n",line);
add_vals();
add_history(line);
free(line);
}
*/
}
/*--------------------------------------------
test field
--------------------------------------------*/
void Xtal::read_file()
{
int input_file_chk=1;
char* line;
int lngth;
int size=MAX_CHAR;
int line_complt,pos;
int max_line_char;
char* srch;
max_line_char=size;
CREATE1D(line,size);
while (input_file_chk)
{
pos=0;
line_complt=0;
while (line_complt==0)
{
fgets(&line[pos],size-pos,input_file);
lngth=static_cast<int>(strlen(line));
while(line[lngth-1]!='\n')
{
pos=lngth;
GROW(line,size,pos+max_line_char);
size=pos+max_line_char;
fgets(&line[pos],size-pos,input_file);
lngth=static_cast<int>(strlen(line));
}
srch=NULL;
srch=strchr(line,'\\');
if(srch==NULL)
{
line_complt=1;
}
else
{
pos=static_cast<int>(srch-line);
GROW(line,size,pos+max_line_char);
size=pos+max_line_char;
}
}
if(feof(input_file))
{
input_file_chk=0;
continue;
}
command(line);
}
delete [] line;
}
/*--------------------------------------------
analysing the commands
--------------------------------------------*/
void Xtal::command(char* command)
{
char** args;
int narg;
narg=parse_line(command,args);
if(narg==0)
return;
#define Command_Style
#define CommandStyle(class_name,style_name) \
else if(strcmp(args[0],#style_name)==0){ \
class class_name* command = \
new class_name(this,narg,args); \
delete command;}
if(0){}
#include "command_styles.h"
else
error->warning("unknown command: %s",args[0]);
#undef Command_Style
#undef CommandStyle
}
/*--------------------------------------------
generate list of commands for auto-complete
--------------------------------------------*/
void Xtal::gen_cmd_ls()
{
if(0) return;
no_cmds=0;
#define Command_Style
#define CommandStyle(class_name,style_name) no_cmds++;
#include "command_styles.h"
#undef CommandStyle
#undef Command_Style
CREATE1D(cmd,no_cmds+1);
int i=0;
int size;
#define Command_Style
#define CommandStyle(class_name,style_name) \
size=static_cast<int>(strlen(#style_name))+1; \
CREATE1D(cmd[i],size); \
memcpy(cmd[i],#style_name, \
size*sizeof(char)); i++;
#include "command_styles.h"
#undef Command_Style
#undef CommandStyle
CREATE1D(cmd[no_cmds],2);
size=static_cast<int>(strlen("\r"))+1;
memcpy(cmd[no_cmds],"\r",sizeof(char)*size);
cmds_lst=cmd;
no_vals=0;
}
/*--------------------------------------------
generate list of commands for auto-complete
--------------------------------------------*/
void Xtal::add_vals()
{
char** cmd_tmp;
int no_boxes=box_collection->no_boxes;
int no_regions=region_collection->no_regions;
int icurs=0;
int size=no_cmds+no_boxes+no_regions+1;
CREATE1D(cmd_tmp,size);
for(int i=0;i<no_cmds;i++)
{
size=static_cast<int>(strlen(cmd[i]))+1;
CREATE1D(cmd_tmp[icurs],size);
memcpy(cmd_tmp[icurs],cmd[i],size*sizeof(char));
icurs++;
}
for(int i=0;i<no_boxes;i++)
{
size=static_cast<int>(strlen(box_collection->boxes[i]->box_name))+1;
CREATE1D(cmd_tmp[icurs],size);
memcpy(cmd_tmp[icurs],box_collection->boxes[i]->box_name,size*sizeof(char));
icurs++;
}
for(int i=0;i<no_regions;i++)
{
size=static_cast<int>(strlen(region_collection->regions[i]->region_name))+1;
CREATE1D(cmd_tmp[icurs],size);
memcpy(cmd_tmp[icurs],region_collection->regions[i]->region_name,size*sizeof(char));
icurs++;
}
CREATE1D(cmd_tmp[icurs],2);
size=static_cast<int>(strlen("\r"))+1;
memcpy(cmd_tmp[icurs],"\r",sizeof(char)*size);
for(int i=0;i<no_vals+no_cmds+1;i++)
delete [] cmd[i];
delete [] cmd;
no_vals=no_boxes+no_regions;
cmd=cmd_tmp;
cmds_lst=cmd;
}
/*----------------------------------------------------------------------------------------
readline crap
----------------------------------------------------------------------------------------*/
char** completion(const char* text,int start,int end)
{
char **matches;
matches=(char** )NULL;
if (start==0)
matches=rl_completion_matches(text,command_generator);
return (matches);
}
/*--------------------------------------------
--------------------------------------------*/
char* command_generator(const char* text,int state)
{
static int icmd,len;
char* name;
if (!state)
{
icmd=0;
len=static_cast<int>(strlen(text));
}
while ((name=cmd[icmd]) && strncmp(cmd[icmd],"\r",1)!=0)
{
icmd++;
if (strncmp(name,text,len)==0)
{
char* r;
r=(char* )malloc((static_cast<int>(strlen(name))+1));
memcpy(r,name,(static_cast<int>(strlen(name))+1)*sizeof(char));
return r;
}
}
return ((char *)NULL);
}
/*----------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------*/
<file_sep>/src/main.cpp
#include <iostream>
#include "xtal.h"
using namespace std;
int main(int narg, char** arg)
{
Xtal* xtal=new Xtal(narg,arg);
delete xtal;
return EXIT_SUCCESS;
}
<file_sep>/src/command_ls_region.cpp
#include "command_ls_region.h"
#include "error.h"
#include "region_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_ls_region::Command_ls_region(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
printf("\n");
for(int i=0;i<region_collection->no_regions;i++)
printf("%s\n",region_collection->regions[i]->region_name);
printf("\n");
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_ls_region::~Command_ls_region()
{
}
<file_sep>/src/command_list_id.h
#ifdef Command_Style
CommandStyle(Command_list_id,list_id)
#else
#ifndef __xtal__command_list_id__
#define __xtal__command_list_id__
#include <stdio.h>
#include "init.h"
class Command_list_id: protected InitPtrs
{
private:
protected:
public:
Command_list_id(Xtal*,int,char**);
~Command_list_id();
};
#endif
#endif
<file_sep>/src/vasp2box.h
#ifndef __xtal__vasp2box__
#define __xtal__vasp2box__
#include <stdio.h>
#include "init.h"
class VASP2Box :protected InitPtrs
{
private:
type0** H0;
type0** B0;
char* line;
char* file_name;
type0 basic_length;
int read_line(FILE*);
void alloc();
void dealloc();
type0 find_mass(char*);
int natms_tmp;
type0* s_tmp;
int* type_tmp;
char* dof_tmp;
int dof_exist;
protected:
public:
VASP2Box(Xtal*,char*,char*);
~VASP2Box();
};
#endif
<file_sep>/src/command_ucell_change.cpp
#include "command_ucell_change.h"
#include "box_collection.h"
#include "memory.h"
#include "error.h"
#include <math.h>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_ucell_change::Command_ucell_change(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=5)
{
error->warning("ucell_change command needs 4 arguments\n"
"SYNTAX: ucell_change box [H00,H01,H02] [H10,H11,H12] [H20,H21,H22]");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
type0** u;
CREATE2D(u,3,3);
int tmp0,tmp1,tmp2;
for(int i=0;i<3;i++)
{
if(sscanf(arg[2+i],"[%d,%d,%d]",&tmp0,&tmp1,&tmp2)==3)
{
u[i][0]=static_cast<type0>(tmp0);
u[i][1]=static_cast<type0>(tmp1);
u[i][2]=static_cast<type0>(tmp2);
}
else
{
error->warning("H_%d should be of the format: [H_%d0,H_%d1,H_%d2]",i,i,i,i);
for(int i=0;i<3;i++)
delete [] u[i];
delete [] u;
return;
}
}
//suppose that u is set
type0 det_u=M3DET(u);
if(det_u<=0)
{
error->warning("determinat of new H is negative");
for(int i=0;i<3;i++)
delete [] u[i];
delete [] u;
return;
}
box_collection->boxes[ibox]->ucell_chang(u);
for(int i=0;i<3;i++)
delete [] u[i];
delete [] u;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_ucell_change::~Command_ucell_change()
{
}
<file_sep>/src/box2lammps.h
#ifndef __xtal__box2lammps__
#define __xtal__box2lammps__
#include <stdio.h>
#include "init.h"
class Box2LAMMPS :protected InitPtrs
{
private:
FILE* lammpsfile;
protected:
public:
Box2LAMMPS(Xtal*,char*,char*);
~Box2LAMMPS();
};
#endif
<file_sep>/src/command_arc.cpp
#include "command_arc.h"
#include "xmath.h"
#include "region_collection.h"
#include "box_collection.h"
#include "memory.h"
#include "error.h"
#include <cmath>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_arc::Command_arc(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=9 )
{
error->warning("add_region needs 6 arguments\n"
"SYNTAX: arc box prim_dim normal_dim lo hi delta");
return;
}
int p,n,ibox;
//width of the arc
type0 h,w_ov_l,h_max;
//number of the unit cells along the arc
int no,no_pad;
type0 c_s;
type0 tmp0;
ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
if(strcmp(arg[2],"x")==0)
{
p=0;
}
else if(strcmp(arg[2],"y")==0)
{
p=1;
}
else if(strcmp(arg[2],"z")==0)
{
p=2;
}
else
{
error->warning("invalid dimension for primary axes: %s",arg[2]);
return;
}
if(strcmp(arg[3],"x")==0)
{
n=0;
}
else if(strcmp(arg[3],"y")==0)
{
n=1;
}
else if(strcmp(arg[3],"z")==0)
{
n=2;
}
else
{
error->warning("invalid dimension for normal axes: %s",arg[3]);
return;
}
if(n==p)
{
error->warning("normal axes and primary axes cannot be the same");
return;
}
no=atoi(arg[4]);
if(no<1)
{
error->warning("number of unit cell should be greater than 1");
return;
}
no_pad=atoi(arg[5]);
if(no_pad<0)
{
error->warning("number of pad unit cells should be greater than 0");
return;
}
w_ov_l=atof(arg[6]);
h_max=atof(arg[7]);
c_s=atof(arg[8]);
if(c_s<0.0 || c_s>=1.0)
{
error->warning("c_s should be between 0.0 & 1.0");
return;
}
/*
if(w_ov_l/(1.0+eps) <=0.0 || w_ov_l/(1.0+eps)>=1.0)
{
error->warning("w/l must be between 2/pi & 1.0 (%lf)",w_ov_l/(1.0+eps));
return;
}
*/
Box* box=box_collection->boxes[ibox];
int natms=box->natms;
int no_types=box->no_types;
type0* s=box->s;
char* dof=box->dof;
int* type=box->type;
type0** H=box->H;
type0** B=box->B;
type0 H_p_norm,B_n_norm,B_n_norm_inv;
H_p_norm=sqrt(H[p][0]*H[p][0]+H[p][1]*H[p][1]+H[p][2]*H[p][2]);
B_n_norm=sqrt(B[0][n]*B[0][n]+B[1][n]*B[1][n]+B[2][n]*B[2][n]);
B_n_norm_inv=1.0/B_n_norm;
l=static_cast<type0>(no)*H_p_norm;
w=l*w_ov_l;
h=2.0*r2(0.25,1.0-w_ov_l);
if(h+B_n_norm_inv>h_max)
{
error->warning("h_max must be greater than %lf",h+B_n_norm_inv);
return;
}
type0 r_p,r_n;
type0 t,delta_n,delta_p,traj_p,traj_n;
type0 e_p;
type0* e_n;
CREATE1D(e_n,3);
r_p=H_p_norm/(w+2.0*H_p_norm*static_cast<type0>(no_pad));
r_n=1.0/(h_max*B_n_norm);
for(int i=0;i<3;i++)
{
e_n[i]=0.0;
for(int j=0;j<3;j++)
e_n[i]+=B[j][i]*B[j][n];
}
tmp0=1.0/sqrt(e_n[n]);
for(int i=0;i<3;i++)
e_n[i]*=tmp0;
e_n[n]*=r_n;
e_n[p]*=r_p;
for(int i=0;i<3;i++)
{
B[i][n]*=r_n;
B[i][p]*=r_p;
}
int iiatm;
int natms_new=(no+2*no_pad)*natms;
type0* s_new;
int* type_new;
char* dof_new=NULL;
CREATE1D(s_new,3*natms_new);
CREATE1D(type_new,natms_new);
if(box->dof_xst)
CREATE1D(dof_new,3*natms_new);
e_p=1.0/(w+2.0*H_p_norm*static_cast<type0>(no_pad));
iiatm=0;
for(int icell=0;icell<no_pad;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]*=r_n;
s_new[3*iiatm+p]*=r_p;
s_new[3*iiatm+p]+=e_p*static_cast<type0>(icell)*H_p_norm;
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
delta_p=static_cast<type0>(no_pad)*H_p_norm;
for(int icell=0;icell<no;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
t=(s[3*iatm+p]+static_cast<type0>(icell))/static_cast<type0>(no);
delta_n=(s[3*iatm+n]-c_s)*B_n_norm_inv;
mid_map(t,h,l,delta_n,delta_p,traj_p,traj_n);
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]=0.0;
s_new[3*iiatm+p]=0.0;
traj_n+=c_s*B_n_norm_inv;
for(int i=0;i<3;i++)
s_new[3*iiatm+i]+=traj_n*e_n[i];
s_new[3*iiatm+p]+=traj_p*e_p;
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
for(int icell=0;icell<no_pad;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]*=r_n;
s_new[3*iiatm+p]*=r_p;
s_new[3*iiatm+p]+=e_p*(static_cast<type0>(icell+no_pad)*H_p_norm+w);
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
delete [] e_n;
for(int i=0;i<3;i++)
{
H[n][i]/=r_n;
H[p][i]/=r_p;
}
if(natms)
{
delete [] s;
delete [] type;
if(box->dof_xst)
delete [] dof;
}
box->natms=natms_new;
box->s=s_new;
box->type=type_new;
if(box->dof_xst)
box->dof=dof_new;
for(int i=0;i<no_types;i++)
box->type_count[i]*=(no+2*no_pad);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_arc::~Command_arc()
{
}
/*--------------------------------------------
elliptic
--------------------------------------------*/
inline void Command_arc::mid_map(type0 t,type0 h,type0 l
,type0 delta_n,type0 delta_p,type0& traj_p,type0& traj_n)
{
traj_p=r1(t,1.0-w/l)+delta_n*n1(t,1.0-w/l)+delta_p;
traj_n=r2(t,1.0-w/l)+delta_n*n2(t,1.0-w/l);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_arc::r1(type0 x,type0 r)
{
if(r==0.0)
return x*l;
else
{
if(0.0<x && x<=0.25)
return l*x*(1.0-4.0*r*x);
else if(0.25<x && x<=0.5)
return 0.5*w-r1(0.5-x,r);
else if(0.5<x && x<=0.75)
return 0.5*w+r1(x-0.5,r);
else if(0.75<x && x<=1.0)
return w-r1(1.0-x,r);
else if(1.0<x)
return w+(x-1.0)*l;
else
return x*l;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_arc::r2(type0 x,type0 r)
{
if(r==0.0)
return 0.0;
else
{
if(0.0<x && x<=0.25)
return (4.0*(8.0*x*r-1.0)*sqrt(x*r*(1.0-4.0*r*x))
+asin(8.0*r*x-1.0)+0.5*M_PI)*l/(16.0*r);
else if(0.25<x && x<=0.5)
return 2.0*r2(0.25,r)-r2(0.5-x,r);
else if(0.5<x && x<=0.75)
return 2.0*r2(0.25,r)-r2(x-0.5,r);
else if(0.75<x && x<=1.0)
return r2(1.0-x,r);
else
return 0.0;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_arc::n1(type0 x,type0 r)
{
if(0.0<x && x<=0.25)
return -4.0*sqrt(r*x*(1.0-4.0*r*x));
else if(0.25<x && x<=0.5)
return n1(0.5-x,r);
else if(0.5<x && x<=0.75)
return -n1(x-0.5,r);
else if(0.75<x && x<=1.0)
return -n1(1.0-x,r);
else if(1.0<x)
return 0.0;
else
return 0.0;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
type0 Command_arc::n2(type0 x,type0 r)
{
if(r==0.0)
return 1.0;
else
{
if(0.0<x && x<=0.25)
return 1.0-8.0*r*x;
else if(0.25<x && x<=0.5)
return n2(0.5-x,r);
else if(0.5<x && x<=0.75)
return n2(x-0.5,r);
else if(0.75<x && x<=1.0)
return n2(1.0-x,r);
else
return 1.0;
}
}
<file_sep>/src/command_ls_box.h
#ifdef Command_Style
CommandStyle(Command_ls_box,ls_box)
#else
#ifndef __xtal__command_ls_box__
#define __xtal__command_ls_box__
#include "init.h"
#include <stdio.h>
class Command_ls_box: protected InitPtrs
{
private:
protected:
public:
Command_ls_box(Xtal*,int,char**);
~Command_ls_box();
};
#endif
#endif
<file_sep>/src/command_join.h
#ifdef Command_Style
CommandStyle(Command_join,join)
#else
#ifndef __xtal__command_join__
#define __xtal__command_join__
#include "init.h"
#include <stdio.h>
class Command_join: protected InitPtrs
{
private:
protected:
public:
Command_join(Xtal*,int,char**);
~Command_join();
};
#endif
#endif
<file_sep>/src/command_box2cfg.h
#ifdef Command_Style
CommandStyle(Command_box2cfg,box2cfg)
#else
#ifndef __xtal__command_box2cfg__
#define __xtal__command_box2cfg__
#include "init.h"
#include <stdio.h>
class Command_box2cfg: protected InitPtrs
{
private:
protected:
public:
Command_box2cfg(Xtal*,int,char**);
~Command_box2cfg();
};
#endif
#endif
<file_sep>/src/command_del_atoms.cpp
#include "command_del_atoms.h"
#include "box_collection.h"
#include "region_collection.h"
#include "error.h"
#include "memory.h"
#define RNG_M 2147483647
#define RNG_MI 1.0/2147483647
#define RNG_A 16807
#define RNG_Q 127773
#define RNG_R 2836
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_del_atoms::Command_del_atoms(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
/*
del_atoms <box> keywords
keywords:
region <include>/<exclude> <region>
random <type> <seed>
file <id_file>
all
*/
if(narg<3)
{
error->warning("del_atoms command needs at least 4 arguments\n"
"SYNTAX: del_atoms region include/exclude box region0 region1 ...\n"
"or\n"
"SYNTAX: del_atoms random box type fraction seed\n"
"or\n"
"SYNTAX: del_atoms id box file0 file1 ...\n"
"or\n"
"SYNTAX: del_atoms all box\n");
return;
}
if(strcmp(arg[1],"region")==0)
{
if(narg<5)
{
error->warning("del_atoms command needs at least 4 arguments\n"
"SYNTAX: del_atoms region include/exclude box region0 region1 ...\n");
return;
}
if(strcmp(arg[2],"include")==0)
include=1;
else if(strcmp(arg[2],"exclude")==0)
include=0;
else
error->warning("uknown keyword "
"for del_atoms region: %s",arg[2]);
int ibox=box_collection->find(arg[3]);
if(ibox<0)
{
error->warning("box %s not found",arg[3]);
return;
}
int no_regions=narg-4;
int* iregions;
CREATE1D(iregions,no_regions);
for(int iregion=0;iregion<no_regions;iregion++)
{
iregions[iregion]=region_collection->find(arg[4+iregion]);
if(iregions[iregion]<0)
{
error->warning("region %s not found",arg[4+iregion]);
delete [] iregions;
return;
}
}
Box* box=box_collection->boxes[ibox];
int natms=box->natms;
type0* s=box->s;
type0** H=box->H;
Region* region;
int* id_lst;
CREATE1D(id_lst,natms);
int icomp=0;
int no=0;
int chk;
int iregion;
for(int i=0;i<natms;i++)
{
chk=1;
iregion=0;
while(chk==1 && iregion<no_regions)
{
region=region_collection->regions[iregions[iregion]];
if(region->belong(H,&s[icomp])!=include)
chk=0;
iregion++;
}
if(chk)
id_lst[no++]=i;
icomp+=3;
}
box_collection->boxes[ibox]->del_atoms(no,id_lst);
if(natms)
delete [] id_lst;
if(no_regions)
delete [] iregions;
}
else if(strcmp(arg[1],"random")==0)
{
if(narg!=6)
{
error->warning("del_atoms command needs at least 4 arguments\n"
"SYNTAX: del_atoms random box type fraction seed\n");
return;
}
int ibox=box_collection->find(arg[2]);
if(ibox<0)
{
error->warning("box %s not found",arg[2]);
return;
}
Box* box=box_collection->boxes[ibox];
int itype=box->find_type(arg[3]);
if(itype<0)
{
error->warning("type %s not found"
" in box %s",arg[2],arg[3]);
return;
}
type0 frac=atof(arg[4]);
type0 frac_ach;
if(frac>1.0 || frac<=0.0)
{
error->warning("fraction should be between 0.0 and 1.0");
return;
}
seed=atoi(arg[5]);
if(seed<0)
{
error->warning("seed should be larger than 0");
return;
}
//warm up rand_gen
for(int i=0;i<20;i++)
rand_gen();
int natms=box->natms;
int* type=box->type;
int* id_lst;
CREATE1D(id_lst,natms);
int no=0;
for(int i=0;i<natms;i++)
{
if(type[i]==itype)
{
if(rand_gen()<frac)
{
id_lst[no++]=i;
}
}
}
frac_ach=static_cast<type0>(no)
/static_cast<type0>(box->type_count[itype]);
box->del_atoms(no,id_lst);
if(natms)
delete [] id_lst;
printf("\nfraction desired: %lf fraction achieved: %lf\n\n",frac,frac_ach);
}
else if(strcmp(arg[1],"id")==0)
{
if(narg<4)
{
error->warning("del_atoms command needs at least 3 arguments\n"
"SYNTAX: del_atoms id box file0 file1 ...\n");
return;
}
int ibox=box_collection->find(arg[2]);
if(ibox<0)
{
error->warning("box %s not found",arg[2]);
return;
}
Box* box=box_collection->boxes[ibox];
int natms=box->natms;
int no_files=narg-3;
int id_list_size=0;
int tmp;
int size;
int* id_list=NULL;
FILE* fp;
char* line;
CREATE1D(line,MAX_CHAR);
for(int ifile=0;ifile<no_files;ifile++)
{
fp=fopen(arg[3+ifile],"r");
if(fp==NULL)
{
error->warning("%s file not found",arg[3+ifile]);
if(id_list_size)
delete [] id_list;
if(MAX_CHAR)
delete [] line;
return;
}
fgets(line,MAX_CHAR,fp);
sscanf(line,"%d",&size);
GROW(id_list,id_list_size,id_list_size+size);
for(int i=0;i<size;i++)
{
if(feof(fp))
{
error->warning("%s file ended immaturely",arg[3+ifile]);
if(id_list_size)
delete [] id_list;
if(MAX_CHAR)
delete [] line;
return;
}
fgets(line,MAX_CHAR,fp);
sscanf(line,"%d",&tmp);
id_list[id_list_size+i]=tmp;
if(tmp<0 || natms<=tmp)
{
error->warning("atom id should be between %d & %d");
if(id_list_size)
delete [] id_list;
if(MAX_CHAR)
delete [] line;
return;
}
}
fclose(fp);
id_list_size+=size;
}
//delete line
if(MAX_CHAR)
delete [] line;
//sort
for(int i=0;i<id_list_size;i++)
for(int j=i+1;j<id_list_size;j++)
{
if(id_list[i]>id_list[j])
{
tmp=id_list[i];
id_list[i]=id_list[j];
id_list[j]=tmp;
}
}
//find the same atoms
int same_cnt=0;
for(int i=1;i<id_list_size;i++)
if(id_list[i]==id_list[i-1])
same_cnt++;
//remove the same atoms
int* del_atms;
int del_atms_no=id_list_size-same_cnt;
if(same_cnt)
{
CREATE1D(del_atms,del_atms_no);
if (del_atms_no)
del_atms[0]=id_list[0];
int cur=1;
for(int i=1;i<id_list_size;i++)
if(id_list[i]!=id_list[i-1])
del_atms[cur++]=id_list[i];
}
else
del_atms=id_list;
box->del_atoms(del_atms_no,del_atms);
if(id_list_size)
delete [] id_list;
}
else if(strcmp(arg[1],"all")==0)
{
if(narg!=3)
{
error->warning("del_atoms command needs 2 arguments\n"
"SYNTAX: del_atoms all box\n");
return;
}
int ibox=box_collection->find(arg[2]);
if(ibox<0)
{
error->warning("box %s not found",arg[2]);
return;
}
box_collection->boxes[ibox]->del_atoms();
}
else
{
error->warning("uknown keyword "
"for del_atoms: %s",arg[1]);
return;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_del_atoms::~Command_del_atoms()
{
}
/*--------------------------------------------
uniform number generator between 0.0 and 1.0
--------------------------------------------*/
type0 Command_del_atoms::rand_gen()
{
int first,second,rnd;
first = seed/RNG_Q;
second = seed%RNG_Q;
rnd = RNG_A*second-RNG_R*first;
if (rnd > 0)
seed=rnd;
else
seed=rnd+RNG_M;
return seed*RNG_MI;
}<file_sep>/src/command_box_prop.h
#ifdef Command_Style
CommandStyle(Command_box_prop,box_prop)
#else
#ifndef __xtal__command_box_prop__
#define __xtal__command_box_prop__
#include "init.h"
#include <stdio.h>
class Command_box_prop: protected InitPtrs
{
private:
protected:
public:
Command_box_prop(Xtal*,int,char**);
~Command_box_prop();
};
#endif
#endif
<file_sep>/src/command_box2cfg.cpp
#include "command_box2cfg.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "box2cfg.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_box2cfg::Command_box2cfg(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("box2cfg command needs 2 arguments\n"
"SYNTAX: box2cfg box file.cfg");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("%s box not found",arg[1]);
return;
}
//box_collection->add(arg[1]);
class Box2CFG* box2cfg=new Box2CFG(xtal,arg[1],arg[2]);
delete box2cfg;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_box2cfg::~Command_box2cfg()
{
}
<file_sep>/src/region_ellipsoid.h
#ifdef Region_Style
RegionStyle(Region_ellipsoid,ellipsoid)
#else
#ifndef __xtal__region_ellipsoid__
#define __xtal__region_ellipsoid__
#include <stdio.h>
#include "region.h"
class Region_ellipsoid :public Region
{
private:
type0* x;
type0* asq_inv;
type0 x0,x1,x2;
int alloc;
protected:
public:
Region_ellipsoid(Xtal*,int,char**);
~Region_ellipsoid();
int belong(type0**,type0*);
};
#endif
#endif
<file_sep>/src/command_box2lammps.cpp
#include "command_box2lammps.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "box2lammps.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_box2lammps::Command_box2lammps(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("box2lammps command needs 2 arguments\n"
"SYNTAX: box2lammps box file");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("%s box not found",arg[1]);
return;
}
class Box2LAMMPS* box2lammps=new Box2LAMMPS(xtal,arg[1],arg[2]);
delete box2lammps;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_box2lammps::~Command_box2lammps()
{
}
<file_sep>/src/vasp2box.cpp
#include "box_collection.h"
#include "error.h"
#include "memory.h"
#include "xmath.h"
#include "vasp2box.h"
#include <cmath>
/*--------------------------------------------
constructor
--------------------------------------------*/
VASP2Box::VASP2Box(Xtal* xtal,char* box_name,char* name):InitPtrs(xtal)
{
FILE* poscar;
type0 s0,s1,s2;
char dof0,dof1,dof2;
char** arg;
Box* box;
int narg;
type0 mass,det;
int ibox;
int iatm,s_x=1;
natms_tmp=0;
file_name=name;
ibox=box_collection->find(box_name);
basic_length=1.0;
poscar=fopen(file_name,"r");
if(poscar==NULL)
{
error->warning("%s file not found",file_name);
xtal->error_flag=-1;
return;
}
alloc();
for(int i=0;i<2;i++)
if(read_line(poscar))
return;
if(sscanf(line,"%lf",&basic_length)!=1)
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
for (int i=0;i<3;i++)
{
if(read_line(poscar))
return;
if(sscanf(line,"%lf %lf %lf",&H0[i][0],&H0[i][1],&H0[i][2])!=3)
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
}
det=M3DET(H0);
if(det<=0.0)
{
error->warning("determinant of H is should be greater than 0.0");
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
if(basic_length<0.0)
basic_length=pow(-basic_length/det,1.0/3.0);
for (int i=0;i<3;i++)
for (int j=0;j<3;j++)
H0[i][j]*=basic_length;
M3INV(H0,B0,det);
box=box_collection->boxes[ibox];
if(read_line(poscar))
return;
narg=xtal->parse_line(line,arg);
for(int iarg=0;iarg<narg;iarg++)
{
mass=find_mass(arg[iarg]);
if(mass==-1.0)
{
error->warning("element %s in file %s was not found in the periodic table",arg[iarg],file_name);
for(int i=0;i<narg;i++)
delete [] arg[i];
delete [] arg;
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
box->add_type(mass,arg[iarg]);
}
for(int i=0;i<narg;i++)
delete [] arg[i];
if(narg)
delete [] arg;
if(read_line(poscar))
return;
narg=xtal->parse_line(line,arg);
if(box->no_types!=narg)
{
error->warning("the count of all the types are not provided in file %s: %s",file_name,line);
for(int i=0;i<narg;i++)
delete [] arg[i];
if(narg)
delete [] arg;
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
for(int i=0;i<narg;i++)
box->type_count[i]=atoi(arg[i]);
for(int i=0;i<narg;i++)
delete [] arg[i];
if(narg)
delete [] arg;
dof_exist=0;
if(read_line(poscar))
return;
if(strcmp(line,"Selective dynamics\n")==0)
{
dof_exist=1;
if(read_line(poscar))
return;
}
if(strcmp(line,"Direct\n")==0)
s_x=1;
else if(strcmp(line,"Cartesian\n")==0)
s_x=0;
else
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
for(int i=0;i<box->no_types;i++)
natms_tmp+=box->type_count[i];
CREATE1D(s_tmp,3*natms_tmp);
CREATE1D(type_tmp,natms_tmp);
if(dof_exist)
CREATE1D(dof_tmp,3*natms_tmp);
box->dof_xst=dof_exist;
iatm=0;
for(int itype=0;itype<box->no_types;itype++)
for(int iiatm=0;iiatm<box->type_count[itype];iiatm++)
{
if(read_line(poscar))
return;
if(dof_exist)
{
if(sscanf(line,"%lf %lf %lf %c %c %c",&s0,&s1,&s2,&dof0,&dof1,&dof2)!=6)
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
dof_tmp[iatm*3]=dof0;
dof_tmp[iatm*3+1]=dof1;
dof_tmp[iatm*3+2]=dof2;
}
else
{
if(sscanf(line,"%lf %lf %lf",&s0,&s1,&s2)!=3)
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
}
type_tmp[iatm]=itype;
if(s_x)
{
s_tmp[iatm*3]=s0;
s_tmp[iatm*3+1]=s1;
s_tmp[iatm*3+2]=s2;
}
else
{
s_tmp[iatm*3]=s0*B0[0][0]+s1*B0[1][0]+s2*B0[2][0];
s_tmp[iatm*3+1]=s0*B0[0][1]+s1*B0[1][1]+s2*B0[2][1];
s_tmp[iatm*3+2]=s0*B0[0][2]+s1*B0[1][2]+s2*B0[2][2];
}
iatm++;
}
if(dof_exist)
{
for(int iiatm=0;iiatm<3*natms_tmp;iiatm++)
{
if(dof_tmp[iiatm]=='T')
dof_tmp[iiatm]='0';
else if(dof_tmp[iiatm]=='F')
dof_tmp[iiatm]='1';
else
{
error->warning("wrong format in file %s: %s",file_name,line);
dealloc();
fclose(poscar);
xtal->error_flag=-1;
return;
}
}
}
for(int itype=0;itype<box->no_types;itype++)
box->type_count[itype]=0;
if(dof_exist)
box_collection->boxes[ibox]->add_atoms(natms_tmp,type_tmp,s_tmp,dof_tmp);
else
box_collection->boxes[ibox]->add_atoms(natms_tmp,type_tmp,s_tmp);
XMath* xmath=new XMath(xtal);
xmath->square2lo_tri(H0,box->H);
M3INV_TRI_LOWER(box->H,box->B);
delete xmath;
dealloc();
fclose(poscar);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
VASP2Box::~VASP2Box()
{
}
/*--------------------------------------------
read line
--------------------------------------------*/
int VASP2Box::read_line(FILE* fp)
{
if(feof(fp))
{
error->warning("%s file ended immaturely",file_name);
dealloc();
fclose(fp);
xtal->error_flag=-1;
return 1;
}
fgets(line,MAX_CHAR,fp);
return 0;
}
/*--------------------------------------------
alloc
--------------------------------------------*/
void VASP2Box::alloc()
{
CREATE1D(line,MAX_CHAR);
CREATE2D(H0,3,3);
CREATE2D(B0,3,3);
}
/*--------------------------------------------
dealloc
--------------------------------------------*/
void VASP2Box::dealloc()
{
delete [] line;
for(int i=0;i<3;i++)
{
delete [] H0[i];
delete [] B0[i];
}
delete [] H0;
delete [] B0;
if (natms_tmp)
{
delete [] s_tmp;
delete [] type_tmp;
if(dof_exist)
delete [] dof_tmp;
}
}
/*--------------------------------------------
find mass
--------------------------------------------*/
type0 VASP2Box::find_mass(char* atm_name)
{
if(strcmp(atm_name,"H")==0)
return 1.007900;
else if(strcmp(atm_name,"He")==0)
return 4.002600;
else if(strcmp(atm_name,"Li")==0)
return 6.941000;
else if(strcmp(atm_name,"Be")==0)
return 9.012200;
else if(strcmp(atm_name,"B")==0)
return 10.811000;
else if(strcmp(atm_name,"C")==0)
return 12.010700;
else if(strcmp(atm_name,"N")==0)
return 14.006700;
else if(strcmp(atm_name,"O")==0)
return 15.999400;
else if(strcmp(atm_name,"F")==0)
return 18.998400;
else if(strcmp(atm_name,"Ne")==0)
return 20.179700;
else if(strcmp(atm_name,"Na")==0)
return 22.989700;
else if(strcmp(atm_name,"Mg")==0)
return 24.305000;
else if(strcmp(atm_name,"Al")==0)
return 26.981500;
else if(strcmp(atm_name,"Si")==0)
return 28.085500;
else if(strcmp(atm_name,"P")==0)
return 30.973800;
else if(strcmp(atm_name,"S")==0)
return 32.065000;
else if(strcmp(atm_name,"Cl")==0)
return 35.453000;
else if(strcmp(atm_name,"Ar")==0)
return 39.948000;
else if(strcmp(atm_name,"K")==0)
return 39.098300;
else if(strcmp(atm_name,"Ca")==0)
return 40.078000;
else if(strcmp(atm_name,"Sc")==0)
return 44.955900;
else if(strcmp(atm_name,"Ti")==0)
return 47.867000;
else if(strcmp(atm_name,"V")==0)
return 50.941500;
else if(strcmp(atm_name,"Cr")==0)
return 51.996100;
else if(strcmp(atm_name,"Mn")==0)
return 54.938000;
else if(strcmp(atm_name,"Fe")==0)
return 55.845000;
else if(strcmp(atm_name,"Co")==0)
return 58.933200;
else if(strcmp(atm_name,"Ni")==0)
return 58.693400;
else if(strcmp(atm_name,"Cu")==0)
return 63.546000;
else if(strcmp(atm_name,"Zn")==0)
return 65.390000;
else if(strcmp(atm_name,"Ga")==0)
return 69.723000;
else if(strcmp(atm_name,"Ge")==0)
return 72.640000;
else if(strcmp(atm_name,"As")==0)
return 74.921600;
else if(strcmp(atm_name,"Se")==0)
return 78.960000;
else if(strcmp(atm_name,"Br")==0)
return 79.904000;
else if(strcmp(atm_name,"Kr")==0)
return 83.800000;
else if(strcmp(atm_name,"Rb")==0)
return 85.467800;
else if(strcmp(atm_name,"Sr")==0)
return 87.620000;
else if(strcmp(atm_name,"Y")==0)
return 88.905900;
else if(strcmp(atm_name,"Zr")==0)
return 91.224000;
else if(strcmp(atm_name,"Nb")==0)
return 92.906400;
else if(strcmp(atm_name,"Mo")==0)
return 95.940000;
else if(strcmp(atm_name,"Tc")==0)
return 98.000000;
else if(strcmp(atm_name,"Ru")==0)
return 101.070000;
else if(strcmp(atm_name,"Rh")==0)
return 102.905500;
else if(strcmp(atm_name,"Pd")==0)
return 106.420000;
else if(strcmp(atm_name,"Ag")==0)
return 107.868200;
else if(strcmp(atm_name,"Cd")==0)
return 112.411000;
else if(strcmp(atm_name,"In")==0)
return 114.818000;
else if(strcmp(atm_name,"Sn")==0)
return 118.710000;
else if(strcmp(atm_name,"Sb")==0)
return 121.760000;
else if(strcmp(atm_name,"Te")==0)
return 127.600000;
else if(strcmp(atm_name,"I")==0)
return 126.904500;
else if(strcmp(atm_name,"Xe")==0)
return 131.293000;
else if(strcmp(atm_name,"Cs")==0)
return 132.905500;
else if(strcmp(atm_name,"Ba")==0)
return 137.327000;
else if(strcmp(atm_name,"La")==0)
return 138.905500;
else if(strcmp(atm_name,"Ce")==0)
return 140.116000;
else if(strcmp(atm_name,"Pr")==0)
return 140.907700;
else if(strcmp(atm_name,"Nd")==0)
return 144.240000;
else if(strcmp(atm_name,"Pm")==0)
return 145.000000;
else if(strcmp(atm_name,"Sm")==0)
return 150.360000;
else if(strcmp(atm_name,"Eu")==0)
return 151.964000;
else if(strcmp(atm_name,"Gd")==0)
return 157.250000;
else if(strcmp(atm_name,"Tb")==0)
return 158.925300;
else if(strcmp(atm_name,"Dy")==0)
return 162.500000;
else if(strcmp(atm_name,"Ho")==0)
return 164.930300;
else if(strcmp(atm_name,"Er")==0)
return 167.259000;
else if(strcmp(atm_name,"Tm")==0)
return 168.934200;
else if(strcmp(atm_name,"Yb")==0)
return 173.040000;
else if(strcmp(atm_name,"Lu")==0)
return 174.967000;
else if(strcmp(atm_name,"Hf")==0)
return 178.490000;
else if(strcmp(atm_name,"Ta")==0)
return 180.947900;
else if(strcmp(atm_name,"W")==0)
return 183.840000;
else if(strcmp(atm_name,"Re")==0)
return 186.207000;
else if(strcmp(atm_name,"Os")==0)
return 190.230000;
else if(strcmp(atm_name,"Ir")==0)
return 192.217000;
else if(strcmp(atm_name,"Pt")==0)
return 195.078000;
else if(strcmp(atm_name,"Au")==0)
return 196.966500;
else if(strcmp(atm_name,"Hg")==0)
return 200.590000;
else if(strcmp(atm_name,"Tl")==0)
return 204.383300;
else if(strcmp(atm_name,"Pb")==0)
return 207.200000;
else if(strcmp(atm_name,"Bi")==0)
return 208.980400;
else if(strcmp(atm_name,"Po")==0)
return 209.000000;
else if(strcmp(atm_name,"At")==0)
return 210.000000;
else if(strcmp(atm_name,"Rn")==0)
return 222.000000;
else if(strcmp(atm_name,"Fr")==0)
return 223.000000;
else if(strcmp(atm_name,"Ra")==0)
return 226.000000;
else if(strcmp(atm_name,"Ac")==0)
return 227.000000;
else if(strcmp(atm_name,"Th")==0)
return 232.038100;
else if(strcmp(atm_name,"Pa")==0)
return 231.035900;
else if(strcmp(atm_name,"U")==0)
return 238.028900;
else if(strcmp(atm_name,"Np")==0)
return 237.000000;
else if(strcmp(atm_name,"Pu")==0)
return 244.000000;
else if(strcmp(atm_name,"Am")==0)
return 243.000000;
else if(strcmp(atm_name,"Cm")==0)
return 247.000000;
else if(strcmp(atm_name,"Bk")==0)
return 247.000000;
else if(strcmp(atm_name,"Cf")==0)
return 251.000000;
else if(strcmp(atm_name,"Es")==0)
return 252.000000;
else if(strcmp(atm_name,"Fm")==0)
return 257.000000;
else if(strcmp(atm_name,"Md")==0)
return 258.000000;
else if(strcmp(atm_name,"No")==0)
return 259.000000;
else if(strcmp(atm_name,"Lr")==0)
return 262.000000;
else if(strcmp(atm_name,"Rf")==0)
return 261.000000;
else if(strcmp(atm_name,"Db")==0)
return 262.000000;
else if(strcmp(atm_name,"Sg")==0)
return 266.000000;
else if(strcmp(atm_name,"Bh")==0)
return 264.000000;
else if(strcmp(atm_name,"Hs")==0)
return 277.000000;
else if(strcmp(atm_name,"Mt")==0)
return 268.000000;
else
return -1.0;
}
<file_sep>/src/xmath.cpp
#include "xmath.h"
#include "memory.h"
#include <cmath>
#define SOLVE_TOL 1.0e-10
/*--------------------------------------------
constructor
--------------------------------------------*/
XMath::XMath(Xtal* xtal): InitPtrs(xtal)
{
}
/*--------------------------------------------
destructor
--------------------------------------------*/
XMath::~XMath()
{
}
/*--------------------------------------------
autogrid the domain
--------------------------------------------*/
void XMath::square2lo_tri(type0** H_old
,type0** H_new)
{
type0** Q;
CREATE2D(Q,3,3);
type0 H0H0;
type0 H0H1;
H0H0=H0H1=0.0;
for(int i=0;i<3;i++)
{
H0H0+=H_old[0][i]*H_old[0][i];
H0H1+=H_old[0][i]*H_old[1][i];
}
Q[0][0]=H_old[0][0];
Q[0][1]=H_old[0][1];
Q[0][2]=H_old[0][2];
Q[1][0]=H0H0*H_old[1][0]-H0H1*H_old[0][0];
Q[1][1]=H0H0*H_old[1][1]-H0H1*H_old[0][1];
Q[1][2]=H0H0*H_old[1][2]-H0H1*H_old[0][2];
Q[2][0]=H_old[0][1]*H_old[1][2]-H_old[0][2]*H_old[1][1];
Q[2][1]=H_old[0][2]*H_old[1][0]-H_old[0][0]*H_old[1][2];
Q[2][2]=H_old[0][0]*H_old[1][1]-H_old[0][1]*H_old[1][0];
for(int i=0;i<3;i++)
{
H0H0=0.0;
for(int j=0;j<3;j++)
H0H0+=Q[i][j]*Q[i][j];
H0H1=sqrt(H0H0);
for(int j=0;j<3;j++)
Q[i][j]/=H0H1;
}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
H_new[i][j]=0.0;
for(int i=0;i<3;i++)
for(int j=0;j<i+1;j++)
{
for(int k=0;k<3;k++)
H_new[i][j]+=H_old[i][k]*Q[j][k];
}
for(int i=0;i<3;i++)
delete [] Q[i];
delete [] Q;
}
/*--------------------------------------------
solve sin(x)/x=y
make sure 0<y<1
--------------------------------------------*/
type0 XMath::solve_sinx_ov_x(type0 y)
{
type0 err,a,b,c;
b=M_PI;
a=0.0;
c=0.5*(a+b);
err=sin(c)/c-y;
while (fabs(err)>SOLVE_TOL)
{
if(err>0.0)
a=c;
else
b=c;
c=0.5*(a+b);
err=sin(c)/c-y;
if(isnan(err))
err=-y;
}
return c;
}
/*--------------------------------------------
use bracket to solve
f(a) should be greater than 0.0
f(b) should be less than 0.0
--------------------------------------------*/
type0 XMath::bracket(type0(f(type0)),type0 a,type0 b)
{
type0 c,fc;
c=0.5*(a+b);
fc=(*f)(c);
while (fabs(a-b)<SOLVE_TOL)
{
if(fc>0.0)
a=c;
if(fc<0.0)
b=c;
c=0.5*(a+b);
fc=(*f)(c);
}
return c;
}
<file_sep>/src/region_collection.cpp
#include "region_collection.h"
#include "region_styles.h"
#include "memory.h"
#include "error.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
RegionCollection::RegionCollection(Xtal* xtal):InitPtrs(xtal)
{
no_regions=0;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
RegionCollection::~RegionCollection()
{
for(int i=0;i<no_regions;i++)
delete regions[i];
if(no_regions)
delete [] regions;
no_regions=0;
}
/*--------------------------------------------
add a region
--------------------------------------------*/
int RegionCollection::add_cmd(int narg,char** arg)
{
class Region** new_regions;
CREATE1D(new_regions,no_regions+1);
for(int i=0;i<no_regions;i++)
new_regions[i]=regions[i];
CREATE1D(regions,no_regions+1);
#define Region_Style
#define RegionStyle(class_name,style_name) \
else if(strcmp(arg[0],#style_name)==0){ \
new_regions[no_regions]=new class_name(xtal,narg,arg);}
if(0){}
#include "region_styles.h"
else
{
error->warning("unknown region: %s",arg[1]);
return -1;
}
#undef Region_Style
#undef RegionStyle
if(xtal->error_flag==-1)
{
xtal->error_flag=0;
delete new_regions[no_regions];
delete [] new_regions;
return -1;
}
if(no_regions)
delete [] regions;
regions=new_regions;
no_regions++;
return no_regions-1;
}
/*--------------------------------------------
find a region by name
--------------------------------------------*/
int RegionCollection::find(char* name)
{
for(int i=0;i<no_regions;i++)
{
if(strcmp(name,regions[i]->region_name)==0)
return i;
}
return -1;
}
/*--------------------------------------------
remove a region by number
--------------------------------------------*/
void RegionCollection::del(int iregion)
{
delete regions[iregion];
Region** new_regions;
CREATE1D(new_regions,no_regions-1);
for(int i=0;i<iregion;i++)
new_regions[i]=regions[i];
for(int i=iregion+1;i<no_regions;i++)
new_regions[i-1]=regions[i];
delete [] regions;
regions=new_regions;
no_regions--;
}
/*--------------------------------------------
remove a region by number
--------------------------------------------*/
void RegionCollection::del(char* name)
{
del(find(name));
}
<file_sep>/src/command_wrinkle.h
#ifdef Command_Style
CommandStyle(Command_wrinkle,wrinkle)
#else
#ifndef __xtal__command_wrinkle__
#define __xtal__command_wrinkle__
#include <stdio.h>
#include "init.h"
class Command_wrinkle: protected InitPtrs
{
private:
int N;
type0 m,no,l,w,r,theta;
type0 energy();
type0 force();
void solve();
void md();
type0* x;
type0* x0;
type0* xx0;
type0* f;
type0* f0;
type0* h;
type0 r1(type0,type0);
type0 r2(type0,type0);
void test();
int max_iter;
type0 norm,slope,tol;
protected:
public:
Command_wrinkle(Xtal*,int,char**);
~Command_wrinkle();
};
#endif
#endif
<file_sep>/src/command_help.cpp
#include "command_help.h"
#include "error.h"
#include "xtal.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_help::Command_help(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
char** cmds=xtal->cmds_lst;
int no_cmds=xtal->no_cmds;
printf("\n");
for(int i=0;i<no_cmds;i++)
printf(" -%s\n",cmds[i]);
printf("\n");
}
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_help::~Command_help()
{
}<file_sep>/src/command_mul.cpp
#include "command_mul.h"
#include "memory.h"
#include "error.h"
#include "box2cfg.h"
#include "box_collection.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_mul::Command_mul(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=5)
{
error->warning("mul command needs 4 arguments\n"
"SYNTAX: mul box N_x N_y N_z");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[1]);
return;
}
int* n;
CREATE1D(n,3);
n[0]=atoi(arg[2]);
n[1]=atoi(arg[3]);
n[2]=atoi(arg[4]);
for(int i=0;i<3;i++)
{
if(n[0]<=0)
{
error->warning("mul argumets should be larger than 0");
delete [] n;
return;
}
}
box_collection->boxes[ibox]->mul(n);
delete [] n;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_mul::~Command_mul()
{
}
<file_sep>/src/command_ucell_change.h
#ifdef Command_Style
CommandStyle(Command_ucell_change,ucell_change)
#else
#ifndef __xtal__command_ucell_change__
#define __xtal__command_ucell_change__
#include <stdio.h>
#include "init.h"
class Command_ucell_change: protected InitPtrs
{
private:
protected:
public:
Command_ucell_change(Xtal*,int,char**);
~Command_ucell_change();
};
#endif
#endif
<file_sep>/src/region.h
#ifndef __xtal__region__
#define __xtal__region__
#include <stdio.h>
#include "init.h"
class Region :protected InitPtrs
{
private:
protected:
public:
Region(Xtal*);
virtual ~Region();
virtual inline int belong(type0**,type0*)=0;
char* region_name;
};
#endif /* defined(__xtal__region__) */
<file_sep>/src/command_cfg2box.cpp
#include "command_cfg2box.h"
#include "error.h"
#include "memory.h"
#include "box_collection.h"
#include "cfg2box.h"
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_cfg2box::Command_cfg2box(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=3)
{
error->warning("cfg2box command needs 2 arguments\n"
"SYNTAX: cfg2box box file.cfg");
return;
}
int ibox=box_collection->find(arg[1]);
if(ibox>=0)
{
box_collection->del(arg[1]);
}
box_collection->add(arg[1]);
class CFG2Box* cfg2box=new CFG2Box(xtal,arg[1],arg[2]);
delete cfg2box;
if(xtal->error_flag==-1)
{
box_collection->del(arg[1]);
xtal->error_flag=0;
}
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_cfg2box::~Command_cfg2box()
{
}
<file_sep>/src/command_sine_arc.cpp
#include "command_sine_arc.h"
#include "xmath.h"
#include "region_collection.h"
#include "box_collection.h"
#include "memory.h"
#include "error.h"
#include <cmath>
/*--------------------------------------------
constructor
--------------------------------------------*/
Command_sine_arc::Command_sine_arc(Xtal* xtal,
int narg,char** arg):InitPtrs(xtal)
{
if(narg!=9 && narg!=10)
{
error->warning("add_region needs 6 arguments\n"
"SYNTAX: arc box prim_dim normal_dim lo hi delta");
return;
}
int p,n,ibox;
//width of the arc
type0 h,w_ov_l,l,w,h_max,eps;
//number of the unit cells along the arc
int no,no_pad;
type0 c_s;
type0 tmp0;
ibox=box_collection->find(arg[1]);
if(ibox<0)
{
error->warning("box %s not found",arg[3]);
return;
}
if(strcmp(arg[2],"x")==0)
{
p=0;
}
else if(strcmp(arg[2],"y")==0)
{
p=1;
}
else if(strcmp(arg[2],"z")==0)
{
p=2;
}
else
{
error->warning("invalid dimension for primary axes: %s",arg[2]);
return;
}
if(strcmp(arg[3],"x")==0)
{
n=0;
}
else if(strcmp(arg[3],"y")==0)
{
n=1;
}
else if(strcmp(arg[3],"z")==0)
{
n=2;
}
else
{
error->warning("invalid dimension for normal axes: %s",arg[3]);
return;
}
if(n==p)
{
error->warning("normal axes and primary axes cannot be the same");
return;
}
no=atoi(arg[4]);
if(no<1)
{
error->warning("number of unit cell should be greater than 1");
return;
}
no_pad=atoi(arg[5]);
if(no_pad<0)
{
error->warning("number of pad unit cells should be greater than 0");
return;
}
w_ov_l=atof(arg[6]);
h_max=atof(arg[7]);
c_s=atof(arg[8]);
if(c_s<0.0 || c_s>=1.0)
{
error->warning("c_s should be between 0.0 & 1.0");
return;
}
if(narg==10)
eps=atof(arg[9]);
else
eps=0.0;
if(eps<-1.0 || eps>1.0)
{
error->warning("epsilon must be between 0.0 & 1.0");
return;
}
if(w_ov_l/(1.0+eps) <=2.0/M_PI || w_ov_l/(1.0+eps)>=1.0)
{
error->warning("w/l must be between 2/pi & 1.0 (%lf)",w_ov_l/(1.0+eps));
return;
}
Box* box=box_collection->boxes[ibox];
int natms=box->natms;
int no_types=box->no_types;
type0* s=box->s;
char* dof=box->dof;
int* type=box->type;
type0** H=box->H;
type0** B=box->B;
type0 H_p_norm,B_n_norm,B_n_norm_inv;
H_p_norm=sqrt(H[p][0]*H[p][0]+H[p][1]*H[p][1]+H[p][2]*H[p][2]);
B_n_norm=sqrt(B[0][n]*B[0][n]+B[1][n]*B[1][n]+B[2][n]*B[2][n]);
B_n_norm_inv=1.0/B_n_norm;
l=static_cast<type0>(no)*H_p_norm;
w=l*w_ov_l;
h=l*(1.0+eps)*solve(w_ov_l/(1.0+eps));
if(h+B_n_norm_inv>h_max)
{
error->warning("h_max must be greater than %lf",h+B_n_norm_inv);
return;
}
type0 r_p,r_n;
type0 t,delta_n,delta_p,traj_p,traj_n;
type0 e_p;
type0* e_n;
CREATE1D(e_n,3);
r_p=H_p_norm/(w+2.0*H_p_norm*static_cast<type0>(no_pad));
r_n=1.0/(h_max*B_n_norm);
for(int i=0;i<3;i++)
{
e_n[i]=0.0;
for(int j=0;j<3;j++)
e_n[i]+=B[j][i]*B[j][n];
}
tmp0=1.0/sqrt(e_n[n]);
for(int i=0;i<3;i++)
e_n[i]*=tmp0;
e_n[n]*=r_n;
e_n[p]*=r_p;
for(int i=0;i<3;i++)
{
B[i][n]*=r_n;
B[i][p]*=r_p;
}
int iiatm;
int natms_new=(no+2*no_pad)*natms;
type0* s_new;
int* type_new;
char* dof_new=NULL;
CREATE1D(s_new,3*natms_new);
CREATE1D(type_new,natms_new);
if(box->dof_xst)
CREATE1D(dof_new,3*natms_new);
e_p=1.0/(w+2.0*H_p_norm*static_cast<type0>(no_pad));
iiatm=0;
for(int icell=0;icell<no_pad;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]*=r_n;
s_new[3*iiatm+p]*=r_p;
s_new[3*iiatm+p]+=e_p*static_cast<type0>(icell)*H_p_norm;
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
delta_p=static_cast<type0>(no_pad)*H_p_norm;
for(int icell=0;icell<no;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
t=(s[3*iatm+p]+static_cast<type0>(icell))/static_cast<type0>(no);
delta_n=(s[3*iatm+n]-c_s)*B_n_norm_inv;
mid_map(t,h,l*(1.0+eps),delta_n,delta_p,traj_p,traj_n);
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]=0.0;
s_new[3*iiatm+p]=0.0;
traj_n+=c_s*B_n_norm_inv;
for(int i=0;i<3;i++)
s_new[3*iiatm+i]+=traj_n*e_n[i];
s_new[3*iiatm+p]+=traj_p*e_p;
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
for(int icell=0;icell<no_pad;icell++)
{
for(int iatm=0;iatm<natms;iatm++)
{
type_new[iiatm]=type[iatm];
for(int i=0;i<3;i++)
s_new[3*iiatm+i]=s[3*iatm+i];
s_new[3*iiatm+n]*=r_n;
s_new[3*iiatm+p]*=r_p;
s_new[3*iiatm+p]+=e_p*(static_cast<type0>(icell+no_pad)*H_p_norm+w);
if(box->dof_xst)
for(int i=0;i<3;i++)
dof_new[3*iiatm+i]=dof[3*iatm+i];
iiatm++;
}
}
delete [] e_n;
for(int i=0;i<3;i++)
{
H[n][i]/=r_n;
H[p][i]/=r_p;
}
if(natms)
{
delete [] s;
delete [] type;
if(box->dof_xst)
delete [] dof;
}
box->natms=natms_new;
box->s=s_new;
box->type=type_new;
if(box->dof_xst)
box->dof=dof_new;
for(int i=0;i<no_types;i++)
box->type_count[i]*=(no+2*no_pad);
}
/*--------------------------------------------
destructor
--------------------------------------------*/
Command_sine_arc::~Command_sine_arc()
{
}
/*--------------------------------------------
2*EllipticE(pi^2*x^2)/pi
30 points for Legendre-Gauss Quadrature
--------------------------------------------*/
type0 Command_sine_arc::elliptic_e(type0 x)
{
type0 r=x*x;
type0 ans=0.0;
ans+=0.102852652894*sqrt(1.0-r*0.255829309967);
ans+=0.101762389748*sqrt(1.0-r*2.13212136323);
ans+=0.0995934205868*sqrt(1.0-r*5.07855567722);
ans+=0.0963687371746*sqrt(1.0-r*7.90283101647);
ans+=0.0921225222378*sqrt(1.0-r*9.59884371249);
ans+=0.0868997872011*sqrt(1.0-r*9.73952238574);
ans+=0.0807558952294*sqrt(1.0-r*8.52093017855);
ans+=0.0737559747377*sqrt(1.0-r*6.52298510176);
ans+=0.0659742298822*sqrt(1.0-r*4.38473571984);
ans+=0.0574931562176*sqrt(1.0-r*2.56925061702);
ans+=0.0484026728306*sqrt(1.0-r*1.28360607207);
ans+=0.0387991925696*sqrt(1.0-r*0.521093860614);
ans+=0.0287847078833*sqrt(1.0-r*0.154867331082);
ans+=0.0184664683111*sqrt(1.0-r*0.0259591547181);
ans+=0.00796819249617*sqrt(1.0-r*0.000940010860158);
return ans;
}
/*--------------------------------------------
EllipticE(2pi*y,pi^2*x^2)/pi
30 points for Legendre-Gauss Quadrature
--------------------------------------------*/
type0 Command_sine_arc::elliptic_e(type0 x,type0 y)
{
type0 tmp;
type0 r=x*x*9.86960440109;
type0 ans=0.0;
tmp=sin(y*2.97988909115);
ans+=0.102852652894*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*3.30329621603);
ans+=0.102852652894*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*2.65819606339);
ans+=0.101762389748*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*3.62498924379);
ans+=0.101762389748*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*2.34162715701);
ans+=0.0995934205868*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*3.94155815017);
ans+=0.0995934205868*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*2.03353807898);
ans+=0.0963687371746*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*4.2496472282);
ans+=0.0963687371746*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*1.7371946473);
ans+=0.0921225222378*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*4.54599065988);
ans+=0.0921225222378*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*1.45573817205);
ans+=0.0868997872011*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*4.82744713513);
ans+=0.0868997872011*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*1.19215215575);
ans+=0.0807558952294*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*5.09103315143);
ans+=0.0807558952294*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.949230665843);
ans+=0.0737559747377*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*5.33395464134);
ans+=0.0737559747377*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.729548713297);
ans+=0.0659742298822*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*5.55363659388);
ans+=0.0659742298822*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.535434948818);
ans+=0.0574931562176*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*5.74775035836);
ans+=0.0574931562176*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.368946957997);
ans+=0.0484026728306*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*5.91423834918);
ans+=0.0484026728306*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.231849388831);
ans+=0.0387991925696*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*6.05133591835);
ans+=0.0387991925696*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.12559501532);
ans+=0.0287847078833*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*6.15759029186);
ans+=0.0287847078833*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.0513081039237);
ans+=0.0184664683111*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*6.23187720326);
ans+=0.0184664683111*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*0.00975940760934);
ans+=0.00796819249617*sqrt(1.0-r*tmp*tmp);
tmp=sin(y*6.27342589957);
ans+=0.00796819249617*sqrt(1.0-r*tmp*tmp);
return 0.5*y*ans;
}
/*--------------------------------------------
elliptic
--------------------------------------------*/
type0 Command_sine_arc::solve(type0 x)
{
type0 a=0.0;
type0 b=1.0/M_PI;
type0 c=0.5*(a+b);
type0 fc=elliptic_e(c);
while (abs(fc-x)>1.0e-9)
{
if(fc>x)
a=c;
else
b=c;
c=0.5*(a+b);
fc=elliptic_e(c);
}
return c;
}
/*--------------------------------------------
elliptic
--------------------------------------------*/
inline void Command_sine_arc::mid_map(type0 t,type0 h,type0 l
,type0 delta_n,type0 delta_p,type0& traj_p,type0& traj_n)
{
type0 tmp0=h*M_PI*sin(2.0*M_PI*t)/l;
traj_p=l*elliptic_e(h/l,t)-tmp0*delta_n+delta_p;
traj_n=0.5*h*(1.0-cos(2.0*M_PI*t))+delta_n*sqrt(1.0-tmp0*tmp0);
}
<file_sep>/src/error.h
#ifndef __xtal__error__
#define __xtal__error__
#include <stdio.h>
#include "init.h"
class Error : protected InitPtrs {
private:
protected:
public:
Error(Xtal *);
~Error();
void abort(const char*,...);
void abort(int,char*,const char*,...);
void warning(const char*,...);
};
#endif
|
c4c7d6b36de28565e3fcf51827df64de3f71ee57
|
[
"C",
"C++"
] | 94 |
C++
|
sinamoeini/xtal
|
7e03b54bc7b665706e33d6385d0228d1004923e9
|
8cb8c0e9d6fe47da0a9af002cb74aabd673bd231
|
refs/heads/master
|
<repo_name>kornellapacz/online-world-backend<file_sep>/src/Entity/Answer.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\AnswerRepository")
*/
class Answer
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $answer;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Survey")
*/
private $survey;
/**
* Get the value of answer
*/
public function getAnswer()
{
return $this->answer;
}
/**
* Set the value of answer
*
* @return self
*/
public function setAnswer($answer)
{
$this->answer = $answer;
return $this;
}
/**
* Get the value of survey
*/
public function getSurvey(): Survey
{
return $this->survey;
}
/**
* Set the value of survey
*
* @return self
*/
public function setSurvey(Survey $survey)
{
$this->survey = $survey;
return $this;
}
}
<file_sep>/src/Controller/SurveyController.php
<?php
namespace App\Controller;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Entity\Survey;
use App\Entity\Answer;
use App\Repository\SurveyRepository;
use App\Repository\AnswerRepository;
use Doctrine\ORM\EntityManagerInterface;
class SurveyController extends Controller
{
/**
* @Route("/survey/{name}", name="survey")
*/
public function getResults($name, SurveyRepository $surveyRepository, AnswerRepository $answerRepository)
{
$survey = $surveyRepository->findOneBy([
'name' => $name
]);
$answers = $answerRepository->findBy(
['survey' => $survey]
);
$result = [];
foreach ($answers as $value) {
$result[] = $value->getAnswer();
}
return $this->json([
'answers' => $result,
]);
}
/**
* @Route("/survey/{name}/{number}", name="add_answer")
*/
public function setAnswer($name, $number, EntityManagerInterface $em, SurveyRepository $surveyRepository) {
$survey = $surveyRepository->findOneBy([
'name' => $name
]);
$answer = new Answer();
$answer->setAnswer($number);
$answer->setSurvey($survey);
$em->persist($answer);
$em->flush();
return $this->json([
'ok' => true
]);
}
}
|
5c466f1d7a622a6c2552144d00f3fc3c0a5778b9
|
[
"PHP"
] | 2 |
PHP
|
kornellapacz/online-world-backend
|
d75d9e7f78941033ec0f869910b9f2181ae5d162
|
02d5264f2dc1c19f86159e146379d6a07f1a2791
|
refs/heads/master
|
<repo_name>YangW0223/Blog<file_sep>/index.js
/**
* Created by yang on 17/2/13.
*/
window.onload =function () {
//var c = $('#ddd').find('.qwerty').css('color','red');
$("#a b b"");
var aa = $(".member");
aa.hover(function () {
$("ul").show();
$("#imgs").attr("src","images/arrow2.png");
},function () {
$("ul").hide();
$("#imgs").attr("src","images/arrow.png");
});
//็นๅป็ปๅฝๆก็ๅ
ณ้ญๆ้ฎ,ๅ
ณ้ญ็ปๅฝๆก
$(".close").click(function () {
var login = $("#login");
if(login.css("display")=="block"){
$("#login").css("display","none");
$("#lock").unLock();//ๅ
ณ้ญ้ฎ็ฝฉๅฑ
}
});
//็นๅป็ปๅฝๆ้ฎๅผนๆก
$(".login").click(function () {
var login = $("#login");
if(login.css("display")=="none"){
$("#login").css("display","block");
login.setElesposition();
/*
ๅฝ็นๅป็ปๅฝๆ้ฎ,ไธบๆต่งๅจๆทปๅ resizeไบไปถ,ๅฝๆต่งๅจๆนๅๅคงๅฐ,็ปๅฝ็ชๅฃๅง็ปๅฑ
ไธญ
*/
(function () {
login.resize(function () {
//login.setElesposition();//่ฎพ็ฝฎๆฏๆฌกresize,็ปๅฝๆก้ฝๅฑ
ไธญ
if(login.css("display")==="block"){
$("#lock").lock();
}
login.setWinPosition();
});
})();
$("#lock").lock();//ๆๅผ้ฎ็ฝฉๅฑ
login.drag([$('h2').getElement(0)]);//็ปๅฝๅผนๅบๆกๆๆฝ
}
});
};
<file_sep>/base_drag.js
/**
* Created by yang on 17/2/21.
*/
$().extend('drag',function (tags) {
for (var i = 0, eles = this.elements, len = eles.length; i < len; i++) {
EventUtils.addEvent(eles[i], 'mousedown', function (e) {
var _this = this;
var difWidth = e.clientX - _this.offsetLeft;
var difHeight = e.clientY - _this.offsetTop;
var flag = false;
if(tags.length){
for(var i in tags){
if(tags[i]==e.target){
flag=true;
break;
}
}
}
if(flag){
EventUtils.addEvent(document, 'mousemove', move);
EventUtils.addEvent(document,'mouseup',up);
}
function up() {
EventUtils.removeEvent(document, 'mousemove', move);
}
function move(e) {
//var evn = EventUtils.getEvent(e);
var left = e.clientX - difWidth,
top = e.clientY - difHeight,
clientSize = $().getClientSize();
if (left < 0) {
left = 0;
} else if (left > clientSize[0] - _this.offsetWidth) {
left = clientSize[0] - _this.offsetWidth;
}
if (top < 0) {
top = 0;
} else if (top > clientSize[1] - _this.offsetHeight) {
top = clientSize[1] - _this.offsetHeight;
}
_this.style.left = left + 'px';
_this.style.top = top + 'px';
}
});
}
});<file_sep>/Event.js
/**
* Created by yang on 17/2/7.
*/
/*
่ทจๆต่งๅจไบไปถๅค็ๅทฅๅ
ท
*/
var EventUtils = {
//่ทจๆต่งๅจๆทปๅ ไบไปถ
addEvent : function (ele, type, fn) {
if (ele.addEventListener) {
ele.addEventListener(type, fn, false);
} else {
//ไธบeleๆทปๅ ไบไปถๅฏน่ฑก
if (!ele.events) ele.events = {};
//ไธบeleๆทปๅ ไบไปถๅค็ๅฝๆฐๆฐ็ป
if (!ele.events[type]) {
ele.events[type] = [];
//ele.events[type][0] = fn;
} else {
if (EventUtils.addEvent.equal(ele.events[type], fn)) {
return false;
}
}
//ๅฐไบไปถๅค็ๅฝๆฐๆทปๅ ๅฐๅ
็ด ็ๆฐ็ปไธญ
ele.events[type][EventUtils.addEvent.ID++] = fn;
//้กบๅบๆง่กไบไปถๅฝๆฐ
ele["on" + type] = EventUtils.addEvent.exec;
}
},
removeEvent: function (ele, type, fn) {
if (ele.removeEventListener) {
ele.removeEventListener(type, fn, false);
} else {
for (var i in ele.events[type]) {
if (ele.events[type][i] === fn) {
delete ele.events[type][i];
}
}
}
},
preventD : function (evn) {
evn.preventDefault ? evn.preventDefault() : evn.returnValue = false;
},
getTarget : function (evn) {
return evn ? evn.target : window.event.srcElement;
},
getEvent : function (e) {
return e || window.event;
},
//่ทจๆต่งๅจๅๅพๅญ็ฌฆ็ผ็
getCharCode: function (evn) {
var event = EventUtils.getTarget(evn);
if (typeof event.keyCode === "number") {
return event.keyCode;
} else {
return event.charCode;
}
}
};
/*
cookieๅค็ๅทฅๅ
ท
*/
var CookieUtils = {
//่ฎพ็ฝฎcookie
setCookie : function (name, value, expires, path, domain, secure) {
var cookie = '';
if (name && value) {
cookie += encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
else {
throw new Error("nameๅvalueไธ่ฝไธบ็ฉบ");
}
if (expires instanceof Date) {
cookie += ';expires=' + expires;
}
if (path) {
cookie += ';path=' + path;
}
if (domain) {
cookie += ';domain=' + domain;
}
if (secure) {
cookie += ';secure';
}
document.cookie = cookie;
},
//่ทๅพcookie
getCookie : function (name) {
if (name) {
var cookieName = encodeURIComponent(name) + '=',
cookieStart = document.cookie.indexOf(cookieName),
cookieEnd,
cookieValue = '';
if (cookieStart > -1) {
cookieEnd = document.cookie.indexOf(";", cookieStart);
if (cookieEnd === -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
} else {
throw new TypeError("็ฑปๅ้่ฏฏ");
}
},
//่ฎพ็ฝฎcookie็ๆถ้ด
setCookieDate: function (day) {
if (typeof day === "number" && day > 0) {
var date = new Date();
date.setDate(date.getDate() + day);
return date;
} else {
throw new TypeError("ๆถ้ดไธๅๆณ");
}
},
//ๅ ้คcookie
deleteCookie : function (name) {
this.setCookie(name, "0", new Date(0));
}
};
/*
่ทจๆต่งๅจๅค็xml
*/
var XMLUtils = {
DOMParse : function (xmlString) {
var xmlDom;
if (DOMParser && xmlString) {
var domParse = new DOMParser();
xmlDom = domParse.parseFromString(xmlString);
return xmlDom;
} else if (ActiveXObject) {
var versions = ["MSXML.DOMDocument.6", "MSXML.DOMDocument.3", "MSXML.DOMDocument"];
for (var i = 0, len = versions.length; i < len; i++) {
try {
xmlDom = new ActiveXObject(versions[i]);
if (xmlDom) {
return xmlDom;
//break;
}
} catch (e) {
}
}
}
},
XMLSerializer: function () {
}
};
/*
่ทจๆต่งๅจ ๅค็xpath
*/
var XpathUtils = {
//่ทๅพๅไธ่็น
selectSingleNode: function (xmlDom, nodeXpath) {
var node = null;
if (typeof xmlDom.evaluate !== "undefined") {
var xpath,
partten = /\[(\d+)\]/,
value;
var flag = nodeXpath.match(partten);
if (flag) {
value = parseInt(RegExp.$1) + 1;
nodeXpath = nodeXpath.replace('[0]', '[' + value + ']');
}
xpath = xmlDom.evaluate(nodeXpath, xmlDom, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
if (xpath != null) {
node = xpath.singleNodeValue;
}
} else if (typeof xmlDom.selectSingleNode) {
var result = xmlDom.selectSingleNode(nodeXpath);
if (result !== null) {
return node = result;
} else {
throw new Error("้่ฏฏ");
}
}
return node;
},
//่ทๅพ่็น้ๅ
selectNodes : function (xmlDom, nodeXpath) {
var nodes = [];
if (typeof xmlDom.evaluate !== "undefined") {
var xpath,
partten = /\[(\d+)\]/,
value;
var flag = nodeXpath.match(partten);
if (flag) {
value = parseInt(RegExp.$1) + 1;
nodeXpath = nodeXpath.replace('[0]', '[' + value + ']');
}
xpath = xmlDom.evaluate(nodeXpath, xmlDom, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
if (xpath != null) {
var re = xpath.iterateNext();
while (re) {
nodes.push(re);
re = xpath.iterateNext();
}
}
} else if (typeof xmlDom.selectSingleNode) {
var result = xmlDom.selectNodes(nodeXpath);
if (result !== null) {
return nodes = result;
} else {
throw new Error("้่ฏฏ");
}
}
return nodes;
}
};
EventUtils.addEvent.ID = 1;
EventUtils.addEvent.exec = function () {
var event = window.event;
if (this.events[event.type].length > 0) {
for (var i in this.events[event.type]) {
this.events[event.type][i].call(this, event);
}
}
};
//ๅคๆญไบไปถๅค็ๅฝๆฐๆฏๅฆๅทฒ็ปๅญๅจ
EventUtils.addEvent.equal = function (funcs, fn) {
for (var i in funcs) {
if (funcs[i] === fn) {
return true;
}
}
};
//ๅฐieไธญ็ไบไปถๅน้
ไธบw3c็ๆ ผๅผ
EventUtils.addEvent.fixEvent = function (event) {
event.preventDefault = function () {
this.returnValue = false;
};
event.stopPropagation = function () {
this.cancelBubble = true;
};
return event;
};
|
3d336beb721be5e133703f0742e6822c40d04c0f
|
[
"JavaScript"
] | 3 |
JavaScript
|
YangW0223/Blog
|
88cb9cf07bf78c665fd13f78cc75967b9c0274b5
|
8f96b63c28c14d24cd71f03dbc2db6f34a3d0ee9
|
refs/heads/main
|
<repo_name>mustafaturan/compass<file_sep>/README.md
# ๐งญ Compass
[](https://godoc.org/github.com/mustafaturan/compass)
[](https://travis-ci.com/mustafaturan/compass)
[](https://coveralls.io/github/mustafaturan/compass?branch=main)
[](https://goreportcard.com/report/github.com/mustafaturan/compass)
[](https://github.com/mustafaturan/compass/blob/main/LICENSE)
Compass is a HTTP server router with middleware support.
## Installation
Via go packages:
```go get github.com/mustafaturan/compass```
## Version
Compass is using semantic versioning rules for versioning.
## Usage
### Configure
Init router with options
```go
import (
"net/http"
"github.com/mustafaturan/compass"
)
...
router := compass.New(
// register allowed schemes, if not specified default allows all
compass.WithSchemes("http", "https"),
// register allowed hostnames, if not specified default allows all
compass.WithHostnames("localhost", "yourdomain.com"),
// register not found handler
compass.WithHandler(404, http.NotFoundHandler()),
// register internal server error handler
compass.WithHandler(500, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if err := recover(); err != nil {
http.Error(rw,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
}
})),
// NOTE: Only allowed to register directly for 404 and 500 status code
// handlers to enable a way to handle most common error cases easily
// register interceptors(middlewares)
compass.WithInterceptors(interceptor1, interceptor2, interceptor3),
)
```
### Routes
```go
// pass options to New function as in the configure section
// there are currently 3 options available
// scheme registry: compass.WithSchemes("http", "https"), default: "*"
// hostname registry: compass.WithHostnames("localhost"), default: "*"
// interceptor registry: compass.WithInterceptor(interceptor1), no default
router := compass.New()
// <Method>: Get, Head, Post, Put, Patch, Delete, Connect, Options, Trace
// <path>: routing path with params
// <http.Handler>: any implementation of net/http.Handler
router.<Method>(<path>, <http.Handler>)
```
**Path examples:**
```
"/posts" -> params: nil
"/posts/:id" -> params: id
"/posts/:id/comments" -> params: id
"/posts/:id/comments/:commentID/likes" -> params: id, commentID
"/posts/:id/reviews" -> params: id
"/posts/:id/reviews/:reviewID" -> params: id, reviewID
```
### Serving
```go
// init router with desired options
router := compass.New()
// register routes with any http handler
router.Get("/tests/:id", func(rw http.ResponseWriter, req *http.Request) {
params := compass.Params(req.Context())
response := fmt.Sprintf("tests endpoint called with %s", params["id"])
rw.Write([]byte())
})
// init an HTTP server as usual and pass the router instance as handler
srv := &http.Server{
Handler: router, // compass.Router
Addr: "127.0.0.1:8000",
// Set server options as usual
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
// start serving
log.Fatal(srv.ListenAndServe())
```
### Accessing Routing Params
Compass writes routing params to request's context, to access params, `Params`
function can be used:
```go
// returns map[string]string
params := compass.Params(ctx)
```
### Interceptors
Interceptors are basically middlewares. The interceptors are compatible with
popular muxer `gorilla/mux` library middlewares which implements also the same
`Middleware(handler http.Handler) http.Handler` function. So, `gorilla/mux`
middlewares can directly be used as `Interceptor`.
**Creating a new interceptor:**
Option 1) Implement the `interceptor.Interceptor` interface:
```go
import (
"github.com/mustafaturan/compass/interceptor"
...
)
...
type myinterceptor struct {}
func (i *myinterceptor) Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("X-Middleware", "compass")
h.ServeHTTP(rw, req)
})
}
// init router with interceptor/middleware
i := &myinterceptor{}
router := compass.New(router.WithInterceptors(i))
```
Option 2) Use home-ready implementation of Interceptor function
`interceptor.Func`
```go
import (
"github.com/mustafaturan/compass/interceptor"
...
)
...
myMiddleware := interceptor.Func(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("X-Middleware", "compass")
h.ServeHTTP(rw, req)
})
})
// init router with interceptor/middleware
router := compass.New(router.WithInterceptors(myMiddleware))
```
## Contributing
All contributors should follow [Contributing Guidelines](CONTRIBUTING.md) before
creating pull requests.
## Credits
[<NAME>](https://github.com/mustafaturan)
## Disclaimer
This is just a hobby project that is used in some fun projects. There is no
warranty even on the bug fixes but please file if you find any. Please use at
your own risk.
## License
Apache License 2.0
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<file_sep>/interceptor/interceptor.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
package interceptor
import (
"net/http"
)
// Interceptor interface is anything which implements a interceptor.Func
type Interceptor interface {
Middleware(handler http.Handler) http.Handler
}
// Func is a function which receives an http.Handler and returns another
// http.Handler. Typically, the returned handler is a closure which does
// something with the http.ResponseWriter and http.Request passed to it, and
// then calls the handler passed as parameter to the Func.
type Func func(http.Handler) http.Handler
// Middleware allows Func to implement interceptor interface
func (fn Func) Middleware(handler http.Handler) http.Handler {
return fn(handler)
}
<file_sep>/compass_test.go
package compass
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
chandler "github.com/mustafaturan/compass/handler"
)
func TestNew(t *testing.T) {
notfoundHandler := fakeHandler{}
tests := []struct {
options []Option
expectedSchemes map[string]struct{}
expectedHostnames map[string]struct{}
expectedNotfound http.Handler
expectedInternalservererror http.Handler
err error
}{
{
options: []Option{
WithSchemes("http", "https"),
WithHostnames("*"),
WithHandler(404, notfoundHandler),
},
expectedSchemes: map[string]struct{}{"http": {}, "https": {}},
expectedHostnames: map[string]struct{}{"*": {}},
expectedNotfound: notfoundHandler,
expectedInternalservererror: chandler.InternalServerError{},
},
{
options: []Option{
WithSchemes("http", "https"),
WithHostnames("*"),
WithHandler(401, fakeHandler{}),
},
expectedSchemes: map[string]struct{}{"http": {}, "https": {}},
expectedHostnames: map[string]struct{}{"*": {}},
err: errors.New("can't set a default handler for status code 401"),
},
}
for _, test := range tests {
ri, err := New(test.options...)
if test.err != nil {
t.Run("err match", func(t *testing.T) {
if test.err.Error() != err.Error() {
t.Fatalf("errors does not match: '%s'", err.Error())
}
})
continue
}
r := ri.(*router)
t.Run("has correct schemes registered", func(t *testing.T) {
if !reflect.DeepEqual(test.expectedSchemes, r.schemes) {
t.Fatalf("config schemes don't match")
}
})
t.Run("has correct hostnames registered", func(t *testing.T) {
if !reflect.DeepEqual(test.expectedHostnames, r.hostnames) {
t.Fatalf("config hostnames don't match")
}
})
t.Run("has correct not found http handler", func(t *testing.T) {
if !reflect.DeepEqual(test.expectedNotfound, r.notfound) {
t.Fatalf("not found handler does not match")
}
})
t.Run("has correct internal server error http handler", func(t *testing.T) {
if !reflect.DeepEqual(test.expectedInternalservererror, r.internalservererror) {
t.Fatalf("internal server error handler does not match")
}
})
}
}
func TestWithSchemes(t *testing.T) {
tests := []struct {
schemes []string
expected map[string]struct{}
}{
{[]string{"file", "ftp"}, map[string]struct{}{"file": {}, "ftp": {}}},
}
r := &router{schemes: map[string]struct{}{}}
for _, test := range tests {
err := WithSchemes(test.schemes...)(r)
if err != nil {
t.Fatalf("registration of schemes with %+v should not return error", test.schemes)
}
if !reflect.DeepEqual(test.expected, r.schemes) {
t.Fatalf("registration of schemes hasn't set the schemes correctly %+v", test.schemes)
}
}
}
func TestHostnames(t *testing.T) {
tests := []struct {
hostnames []string
expected map[string]struct{}
}{
{[]string{"example.com", "test.com"}, map[string]struct{}{"example.com": {}, "test.com": {}}},
}
r := &router{hostnames: map[string]struct{}{}}
for _, test := range tests {
err := WithHostnames(test.hostnames...)(r)
if err != nil {
t.Fatalf("registration with %+v should not return error", test.hostnames)
}
if !reflect.DeepEqual(test.expected, r.hostnames) {
t.Fatalf("registration of hostnames hasn't set the hostnames correctly %+v", test.hostnames)
}
}
}
func TestWithHandler(t *testing.T) {
tests := []struct {
statusCode int
handlerFunc http.Handler
err string
}{
{404, nil, "handler can't be nil"},
{404, http.NotFoundHandler(), ""},
{500, chandler.InternalServerError{}, ""},
}
r := &router{}
for _, test := range tests {
err := WithHandler(test.statusCode, test.handlerFunc)(r)
if err != nil && err.Error() != test.err {
t.Fatalf("registration with %+v must return err with correct message", test.handlerFunc)
}
if err == nil && test.err != "" {
t.Fatalf("registration with %+v must return err", test.handlerFunc)
}
}
}
func TestWithInterceptors(t *testing.T) {
r := &router{}
first, second := &fakeInterceptor{"first"}, &fakeInterceptor{"second"}
_ = WithInterceptors(first, second)(r)
t.Run("adds interceptors in correct order", func(t *testing.T) {
if r.interceptors[0] != first || r.interceptors[1] != second {
t.Fatalf("interceptors registered in incorrect order")
}
})
t.Run("has correct number of interceptors", func(t *testing.T) {
if len(r.interceptors) != 2 {
t.Fatalf("must register exactly 2 interceptors")
}
})
}
func TestParams(t *testing.T) {
expected := map[string]string{"test": "val"}
ctx := context.Background()
ctx = context.WithValue(ctx, CtxParams, expected)
val := Params(ctx)
if !reflect.DeepEqual(expected, val) {
t.Fatalf("vals couldn't be extracted")
}
}
func TestServeHTTP(t *testing.T) {
tests := []struct {
handler http.Handler
path string
reqURL string
schemes []string
hostnames []string
statusCode int
params map[string]string
}{
{
handler: fakeHandler{"ok"},
path: "/",
reqURL: "https://example.com/",
schemes: []string{"https", "http"},
hostnames: []string{"example.com"},
statusCode: 200,
params: make(map[string]string),
},
{ // hostname, scheme, path registered
handler: fakeHandler{"ok"},
path: "/posts",
reqURL: "https://example.com/posts",
schemes: []string{"https", "http"},
hostnames: []string{"example.com"},
statusCode: 200,
params: make(map[string]string),
},
{ // hostname, scheme, path registered
handler: fakeHandler{"ok"},
path: "/posts",
reqURL: "https://example.com/posts",
schemes: []string{"https", "http"},
hostnames: []string{"www.example.com", "example.com"},
statusCode: 200,
params: make(map[string]string),
},
{ // hostname, scheme, path registered with interceptor
handler: fakeHandler{"ok"},
path: "/posts",
reqURL: "https://example.com/posts",
schemes: []string{"https", "http"},
hostnames: []string{"www.example.com", "example.com"},
statusCode: 200,
params: make(map[string]string),
},
{ // hostname, scheme, path registered with interceptor with params
handler: fakeHandler{"ok"},
path: "/posts/:id",
reqURL: "https://example.com/posts/1",
schemes: []string{"https", "http"},
hostnames: []string{"www.example.com", "example.com"},
statusCode: 200,
params: map[string]string{"id": "1"},
},
{ // match-all hostname, match-all scheme
handler: fakeHandler{"ok"},
path: "/posts/:id",
reqURL: "https://example.com/posts/1",
schemes: []string{"*"},
hostnames: []string{"*"},
statusCode: 200,
params: map[string]string{"id": "1"},
},
{ // hostname not registered
handler: fakeHandler{"na"},
path: "/posts",
reqURL: "https://example.com/posts",
schemes: []string{"https", "http"},
hostnames: []string{"www.example.com"},
statusCode: 404,
params: make(map[string]string),
},
{ // scheme not registered
handler: fakeHandler{"na"},
path: "/posts",
reqURL: "https://example.com/posts",
schemes: []string{"http"},
hostnames: []string{"example.com"},
statusCode: 404,
params: make(map[string]string),
},
{ // path not registered
handler: fakeHandler{"na"},
path: "/posts",
reqURL: "https://example.com/posts/1",
schemes: []string{"https"},
hostnames: []string{"example.com"},
statusCode: 404,
params: make(map[string]string),
},
}
for _, test := range tests {
req := httptest.NewRequest("GET", test.reqURL, nil)
rw := httptest.NewRecorder()
mockInterceptorFirst := &fakeInterceptor{"first"}
mockInterceptorSecond := &fakeInterceptor{"second"}
r, _ := New(
WithSchemes(test.schemes...),
WithHostnames(test.hostnames...),
WithInterceptors(mockInterceptorFirst, mockInterceptorSecond),
)
_ = r.Get(test.path, test.handler)
r.ServeHTTP(rw, req)
t.Run("applies interceptors in correct order", func(t *testing.T) {
if mockInterceptorFirst.name != "called" {
t.Fatalf("interceptor must be executed on the serve")
}
if mockInterceptorSecond.name != "called" {
t.Fatalf("interceptor must be executed on the serve")
}
})
resp := rw.Result()
t.Run("has correct status code", func(t *testing.T) {
if resp.StatusCode != test.statusCode {
t.Fatalf(
"want status code %d, but got %d",
test.statusCode,
resp.StatusCode,
)
}
})
}
}
func TestMethodRegistrations(t *testing.T) {
r, _ := New()
getPath, getHandler := "/test-get-path", fakeHandler{"ok"}
headPath, headHandler := "/test-head-path", fakeHandler{"ok"}
postPath, postHandler := "/test-post-path", fakeHandler{"ok"}
putPath, putHandler := "/test-put-path", fakeHandler{"ok"}
patchPath, patchHandler := "/test-patch-path", fakeHandler{"ok"}
deletePath, deleteHandler := "/test-delete-path", fakeHandler{"ok"}
connectPath, connectHandler := "/test-connect-path", fakeHandler{"ok"}
optionsPath, optionsHandler := "/test-options-path", fakeHandler{"ok"}
tracePath, traceHandler := "/test-trace-path", fakeHandler{"ok"}
tests := []struct {
method string
path string
handler http.Handler
}{
{http.MethodGet, getPath, getHandler},
{http.MethodHead, headPath, headHandler},
{http.MethodPost, postPath, postHandler},
{http.MethodPut, putPath, putHandler},
{http.MethodPatch, patchPath, patchHandler},
{http.MethodDelete, deletePath, deleteHandler},
{http.MethodConnect, connectPath, connectHandler},
{http.MethodOptions, optionsPath, optionsHandler},
{http.MethodTrace, tracePath, traceHandler},
}
_ = r.Get(getPath, getHandler)
_ = r.Head(headPath, headHandler)
_ = r.Post(postPath, postHandler)
_ = r.Put(putPath, putHandler)
_ = r.Patch(patchPath, patchHandler)
_ = r.Delete(deletePath, deleteHandler)
_ = r.Connect(connectPath, connectHandler)
_ = r.Options(optionsPath, optionsHandler)
_ = r.Trace(tracePath, traceHandler)
for _, test := range tests {
t.Run("register handler for correct http method & path", func(t *testing.T) {
path := []string{strings.Split(test.path, "/")[1]}
h, ok := r.(*router).matcher.Find(test.method, path)
if !ok || h.HTTPHandler != test.handler {
t.Fatalf(
"must register handler(%+v) for the path(%s) but got %+v",
test.handler,
test.path,
h.HTTPHandler,
)
}
})
}
t.Run("when HTTP handler registration fails", func(t *testing.T) {
err := r.Get("/some", nil)
if err == nil {
t.Fatalf("registration of handler must fail handler is nil")
}
})
}
type fakeInterceptor struct {
name string
}
func (m *fakeInterceptor) Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
m.name = "called"
h.ServeHTTP(rw, req)
})
}
type fakeHandler struct {
bodyText string
}
func (h fakeHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
_, _ = rw.Write([]byte(h.bodyText))
}
<file_sep>/handler/internalservererror_test.go
package handler
import (
"io"
"net/http"
"net/http/httptest"
"testing"
)
func TestServeHTTP(t *testing.T) {
internalServerError := InternalServerError{}
tests := []struct {
handlerFunc http.HandlerFunc
statusCode int
}{
{
handlerFunc: func(rw http.ResponseWriter, req *http.Request) {
defer internalServerError.ServeHTTP(rw, req)
_, _ = io.WriteString(rw, "<html><body>Hello World!</body></html>")
},
statusCode: http.StatusOK,
},
{
handlerFunc: func(rw http.ResponseWriter, req *http.Request) {
defer internalServerError.ServeHTTP(rw, req)
panic("ohh no!")
},
statusCode: http.StatusInternalServerError,
},
}
for _, test := range tests {
t.Run("has correct status code", func(t *testing.T) {
req := httptest.NewRequest("GET", "http://example.com/foo", nil)
rw := httptest.NewRecorder()
test.handlerFunc(rw, req)
resp := rw.Result()
if resp.StatusCode != test.statusCode {
t.Fatalf(
"want status code %d, but got %d",
test.statusCode,
resp.StatusCode,
)
}
})
}
}
<file_sep>/handler/internelservererror.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
package handler
import (
"net/http"
)
// InternalServerError implements http.Handler
type InternalServerError struct{}
// ServeHTTP implements http handler func for http.Handler interface
func (h InternalServerError) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if err := recover(); err != nil {
http.Error(rw,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
}
}
<file_sep>/handler/handler_test.go
package handler
import (
"net/http"
"reflect"
"testing"
)
func TestNew(t *testing.T) {
tests := []struct {
path string
segments []string
params map[string]int
errMessage string
}{
{
path: "/",
segments: []string{""},
params: make(map[string]int),
},
{
path: "/posts",
segments: []string{"posts"},
params: make(map[string]int),
},
{
path: "/posts/:id",
segments: []string{"posts", ":id"},
params: map[string]int{"id": 1},
},
{
path: "/posts/:id/comments",
segments: []string{"posts", ":id", "comments"},
params: map[string]int{"id": 1},
},
{
path: "/posts/:id/comments/:commentID",
segments: []string{"posts", ":id", "comments", ":commentID"},
params: map[string]int{"id": 1, "commentID": 3},
},
{
path: "",
errMessage: "path can't be empty",
},
{
path: "x",
errMessage: "path must start with '/' char",
},
}
for _, test := range tests {
h, err := New(test.path, testHTTPHandler{})
t.Run("has correct error message", func(t *testing.T) {
if test.errMessage != "" && err.Error() != test.errMessage {
t.Fatalf(
"must result with err(%s) for path %s but got err(%s)",
test.errMessage,
test.path,
err.Error(),
)
}
})
if err != nil {
continue
}
t.Run("has correct segmentation", func(t *testing.T) {
if !reflect.DeepEqual(test.segments, h.Segments()) {
t.Fatalf("want: %+v, got: %+v", test.segments, h.Segments())
}
})
t.Run("has correct params", func(t *testing.T) {
if !reflect.DeepEqual(test.params, h.params) {
t.Fatalf("want: %+v, got: %+v", test.params, h.params)
}
})
}
t.Run("without handler", func(t *testing.T) {
_, err := New("/valid", nil)
if err.Error() != "handler can't be nil" {
t.Fatalf("should not allow initialization with nil http handler")
}
})
}
func TestParams(t *testing.T) {
tests := []struct {
path string
segments []string
requestSegments []string
params map[string]string
}{
{
path: "/",
segments: []string{},
requestSegments: []string{},
params: make(map[string]string),
},
{
path: "/:name",
segments: []string{":name"},
requestSegments: []string{"test"},
params: map[string]string{"name": "test"},
},
{
path: "/posts",
segments: []string{"posts"},
requestSegments: []string{"posts"},
params: make(map[string]string),
},
{
path: "/posts/:id",
segments: []string{"posts", ":id"},
requestSegments: []string{"posts", "1"},
params: map[string]string{"id": "1"},
},
{
path: "/posts/:id/comments",
segments: []string{"posts", ":id", "comments"},
requestSegments: []string{"posts", "1", "comments"},
params: map[string]string{"id": "1"},
},
{
path: "/posts/:id/comments/:commentID",
segments: []string{"posts", ":id", "comments", ":commentID"},
requestSegments: []string{"posts", "1", "comments", "99"},
params: map[string]string{"id": "1", "commentID": "99"},
},
}
for _, test := range tests {
t.Run("build correct params", func(t *testing.T) {
h, _ := New(test.path, testHTTPHandler{})
params := h.Params(test.requestSegments)
if !reflect.DeepEqual(test.params, params) {
t.Fatalf("want: %+v, got: %+v", test.params, params)
}
})
}
}
type testHTTPHandler struct{}
func (h testHTTPHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
<file_sep>/matcher/matcher_test.go
package matcher
import (
"net/http"
"testing"
chandler "github.com/mustafaturan/compass/handler"
)
func TestNew(t *testing.T) {
tests := []struct {
method string
want bool
}{
{http.MethodGet, true},
{http.MethodHead, true},
{http.MethodPost, true},
{http.MethodPut, true},
{http.MethodPatch, true},
{http.MethodDelete, true},
{http.MethodConnect, true},
{http.MethodOptions, true},
{http.MethodTrace, true},
{"na", false},
}
m := New()
t.Run("inits with right keys", func(t *testing.T) {
for _, test := range tests {
if _, got := m.nodes[test.method]; got != test.want {
t.Fatalf("New() expected to register %s node as %v", test.method, test.want)
}
}
})
}
func TestRegister(t *testing.T) {
routes := []struct {
method string
path string
}{
{
method: http.MethodGet,
path: "/posts",
},
{
method: http.MethodGet,
path: "/posts/:id",
},
{
method: http.MethodGet,
path: "/posts/:id/comments",
},
{
method: http.MethodGet,
path: "/posts/:id/comments/commentID",
},
{
method: http.MethodGet,
path: "/posts/:id/reviews",
},
{
method: http.MethodGet,
path: "/posts/:id/reviews/:reviewID",
},
}
m := New()
t.Run("first time registrations should not return error", func(t *testing.T) {
for _, route := range routes {
handler, _ := chandler.New(route.path, testHTTPHandler{})
if err := m.Register(route.method, handler); err != nil {
t.Fatalf(
"Register(%s, %+v) SHOULD NOT return err %s",
route.method,
handler,
err,
)
}
}
})
t.Run("registrations for the same route should return error", func(t *testing.T) {
for _, route := range routes {
handler, _ := chandler.New(route.path, testHTTPHandler{})
if err := m.Register(route.method, handler); err == nil {
t.Fatalf(
"Register(%s, %+v) SHOULD return err",
route.method,
handler,
)
}
}
})
t.Run("registration of the same path should return error", func(t *testing.T) {
handler, _ := chandler.New("/posts/:id/reviews/9", testHTTPHandler{})
if err := m.Register(http.MethodGet, handler); err == nil {
t.Fatalf(
"Register(%s, %+v) SHOULD return err",
http.MethodGet,
handler,
)
}
})
}
func TestFind(t *testing.T) {
routes := []struct {
path string
method string
handler *chandler.Handler
}{
{
path: "/",
method: http.MethodGet,
},
{
path: "/posts",
method: http.MethodGet,
},
{
path: "/posts/-1",
method: http.MethodGet,
},
{
path: "/posts/:id",
method: http.MethodGet,
},
{
path: "/posts/:id/comments",
method: http.MethodGet,
},
{
path: "/posts/:id/comments/:commentID",
method: http.MethodGet,
},
{
path: "/posts/:id/reviews",
method: http.MethodGet,
},
{
path: "/posts/:id/reviews/:reviewID",
method: http.MethodGet,
},
{
path: "/posts/:id/reviews/101/likers",
method: http.MethodGet,
},
{
path: "/posts/:id/reviews/:reviewID/likers/:liker",
method: http.MethodGet,
},
}
m := New()
for i, route := range routes {
routes[i].handler, _ = chandler.New(route.path, testHTTPHandler{})
if err := m.Register(route.method, routes[i].handler); err != nil {
panic(err)
}
}
tests := []struct {
method string
path []string
wantHandler *chandler.Handler
wantResult bool
}{
// Available routes
{http.MethodGet, []string{}, routes[0].handler, true},
{http.MethodGet, []string{"posts"}, routes[1].handler, true},
{http.MethodGet, []string{"posts", "99"}, routes[3].handler, true},
{http.MethodGet, []string{"posts", "99", "comments"}, routes[4].handler, true},
{http.MethodGet, []string{"posts", "99", "comments", "56"}, routes[5].handler, true},
{http.MethodGet, []string{"posts", "99", "reviews"}, routes[6].handler, true},
{http.MethodGet, []string{"posts", "99", "reviews", "56"}, routes[7].handler, true},
{http.MethodGet, []string{"posts", "99", "reviews", "101", "likers"}, routes[8].handler, true},
{http.MethodGet, []string{"posts", "99", "reviews", "56", "likers", "33"}, routes[9].handler, true},
{http.MethodGet, []string{"posts", "-1"}, routes[2].handler, true},
// Non-existed routes
{http.MethodGet, []string{"comments"}, nil, false},
{http.MethodGet, []string{"comments", "76"}, nil, false},
{http.MethodGet, []string{"reviews"}, nil, false},
{http.MethodGet, []string{"reviews", "33"}, nil, false},
{http.MethodGet, []string{"posts", "99", "reviews", "56", "likers"}, nil, false},
}
for _, test := range tests {
gotHandler, gotResult := m.Find(test.method, test.path)
t.Run("correct handler match", func(t *testing.T) {
if gotHandler != test.wantHandler {
t.Fatalf(
"Find(%s, %v) should result with %+v but got %+v",
test.method,
test.path,
test.wantHandler,
gotHandler,
)
}
})
t.Run("route matching estimations", func(t *testing.T) {
if gotResult != test.wantResult {
t.Fatalf(
"Find(%s, %v) should result with %v but got %v",
test.method,
test.path,
test.wantResult,
gotResult,
)
}
})
}
}
type testHTTPHandler struct{}
func (h testHTTPHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
<file_sep>/compass.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
package compass
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
chandler "github.com/mustafaturan/compass/handler"
cinterceptor "github.com/mustafaturan/compass/interceptor"
cmatcher "github.com/mustafaturan/compass/matcher"
)
// Router is an internal router for HTTP routing with interceptor support
type Router interface {
http.Handler
// Get registers handler for GET method
Get(path string, handler http.Handler) error
// Head registers handler for HEAD method
Head(path string, handler http.Handler) error
// Post registers handler for POST method
Post(path string, handler http.Handler) error
// Put registers handler for PUT method
Put(path string, handler http.Handler) error
// Patch registers handler for PATCH method
Patch(path string, handler http.Handler) error
// Delete registers handler for DELETE method
Delete(path string, handler http.Handler) error
// Connect registers handler for CONNECT method
Connect(path string, handler http.Handler) error
// Options registers handler for OPTIONS method
Options(path string, handler http.Handler) error
// Trace registers handler for TRACE method
Trace(path string, handler http.Handler) error
}
// router is an implementation of Router
type router struct {
interceptors []cinterceptor.Interceptor
matcher *cmatcher.Matcher
// Schemes allows access to the provided schemes only
// The default value catches `http` and `https` schemes
schemes map[string]struct{}
// Hostnames allows access to the provided hostnames only
// The default value catches all hostnames (`*`)
hostnames map[string]struct{}
// NotFound http handler
notfound http.Handler
// InternalServerError http handler for panic recovery
internalservererror http.Handler
}
// Option is a router option
type Option func(*router) error
type ctxKey int8
const (
// CtxParams params context key
CtxParams = ctxKey(0)
// matchall char to match any hostname or scheme
matchall = "*"
)
// New returns a new Router with default handlers
func New(options ...Option) (Router, error) {
r := &router{
interceptors: make([]cinterceptor.Interceptor, 0),
matcher: cmatcher.New(),
schemes: map[string]struct{}{matchall: {}},
hostnames: map[string]struct{}{matchall: {}},
notfound: http.NotFoundHandler(),
internalservererror: chandler.InternalServerError{},
}
for _, o := range options {
if err := o(r); err != nil {
return nil, err
}
}
return r, nil
}
// WithSchemes option sets allowed schemes
func WithSchemes(schemes ...string) Option {
return func(r *router) error {
for s := range r.schemes {
delete(r.schemes, s)
}
for _, s := range schemes {
r.schemes[s] = struct{}{}
}
return nil
}
}
// WithHostnames option sets allowed hostnames
func WithHostnames(hostnames ...string) Option {
return func(r *router) error {
for h := range r.hostnames {
delete(r.hostnames, h)
}
for _, h := range hostnames {
r.hostnames[h] = struct{}{}
}
return nil
}
}
// WithHandler option registers default handlers for NotFound and
// InternalServerError error status codes
func WithHandler(statusCode int, h http.Handler) Option {
return func(r *router) error {
if h == nil {
return errors.New("handler can't be nil")
}
switch statusCode {
case 404:
r.notfound = h
case 500:
r.internalservererror = h
default:
return fmt.Errorf("can't set a default handler for status code %d", statusCode)
}
return nil
}
}
// WithInterceptors appends a interceptor.Interceptor to the chain. Interceptor
// can be used to intercept or otherwise modify requests and/or responses, and
// are executed in the order that they are applied to the Router.
func WithInterceptors(interceptors ...cinterceptor.Interceptor) Option {
return func(r *router) error {
r.interceptors = append(r.interceptors, interceptors...)
return nil
}
}
// Params provides access to compass params
func Params(ctx context.Context) map[string]string {
return ctx.Value(CtxParams).(map[string]string)
}
// ServeHTTP implements http.Handler interface with interceptors
func (r *router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
defer r.internalservererror.ServeHTTP(rw, req)
var h http.Handler
var params map[string]string
if !r.isAllowedScheme(req.URL.Scheme) || !r.isAllowedHostname(req.URL.Hostname()) {
h, params = r.notfound, make(map[string]string)
} else {
h, params = r.match(req)
}
// Attach params to request with context
ctx := context.WithValue(req.Context(), CtxParams, params)
req = req.WithContext(ctx)
for i := len(r.interceptors) - 1; i >= 0; i-- {
h = r.interceptors[i].Middleware(h)
}
h.ServeHTTP(rw, req)
}
// Get registers handler for GET method
func (r *router) Get(path string, handler http.Handler) error {
return r.registerHandler(http.MethodGet, path, handler)
}
// Head registers handler for HEAD method
func (r *router) Head(path string, handler http.Handler) error {
return r.registerHandler(http.MethodHead, path, handler)
}
// Post registers handler for POST method
func (r *router) Post(path string, handler http.Handler) error {
return r.registerHandler(http.MethodPost, path, handler)
}
// Put registers handler for PUT method
func (r *router) Put(path string, handler http.Handler) error {
return r.registerHandler(http.MethodPut, path, handler)
}
// Patch registers handler for PATCH method
func (r *router) Patch(path string, handler http.Handler) error {
return r.registerHandler(http.MethodPatch, path, handler)
}
// Delete registers handler for DELETE method
func (r *router) Delete(path string, handler http.Handler) error {
return r.registerHandler(http.MethodDelete, path, handler)
}
// Connect registers handler for CONNECT method
func (r *router) Connect(path string, handler http.Handler) error {
return r.registerHandler(http.MethodConnect, path, handler)
}
// Options registers handler for OPTIONS method
func (r *router) Options(path string, handler http.Handler) error {
return r.registerHandler(http.MethodOptions, path, handler)
}
// Trace registers handler for TRACE method
func (r *router) Trace(path string, handler http.Handler) error {
return r.registerHandler(http.MethodTrace, path, handler)
}
func (r *router) registerHandler(method, path string, handler http.Handler) error {
h, err := chandler.New(path, handler)
if err != nil {
return err
}
return r.matcher.Register(method, h)
}
func (r *router) isAllowedHostname(hostname string) bool {
if _, hasHostname := r.hostnames[hostname]; hasHostname {
return true
}
_, hasMatchAll := r.hostnames[matchall]
return hasMatchAll
}
func (r *router) isAllowedScheme(scheme string) bool {
if _, hasScheme := r.schemes[scheme]; hasScheme {
return true
}
_, hasMatchAll := r.schemes[matchall]
return hasMatchAll
}
func (r *router) match(req *http.Request) (http.Handler, map[string]string) {
path := req.URL.EscapedPath()
segments := strings.Split(path[1:], "/")
if h, found := r.matcher.Find(req.Method, segments); found {
return h.HTTPHandler, h.Params(segments)
}
return r.notfound, make(map[string]string)
}
<file_sep>/doc.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
/*
Package compass is a HTTP server router library with middleware support.
Via go packages:
go get github.com/mustafaturan/compass
Version
Compass is using semantic versioning rules for versioning.
Usage
### Configure
Init router with options
router := compass.New(
// register allowed schemes
compass.WithSchemes("http", "https"),
// register allowed hostnames
compass.WithHostnames("localhost", "yourdomain.com"),
// register not found handler
compass.WithHandler(404, http.NotFoundHandler()),
// register internal server error handler
compass.WithHandler(500, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
if err := recover(); err != nil {
http.Error(rw,
http.StatusText(http.StatusInternalServerError),
http.StatusInternalServerError,
)
}
})),
// register interceptors(middlewares)
compass.WithInterceptors(interceptor1, interceptor2, interceptor3),
)
### Routes
// pass options to New function as in the configure section
// there are currently 3 options available
// scheme registry: compass.WithSchemes("http", "https"), default: "*"
// hostname registry: compass.WithHostnames("localhost"), default: "*"
// interceptor registry: compass.WithInterceptor(interceptor1), no default
router := compass.New()
// <Method>: Get, Head, Post, Put, Patch, Delete, Connect, Options, Trace
// <path>: routing path with params
// <http.Handler>: any implementation of net/http.Handler
router.<Method>(<path>, <http.Handler>)
**Path examples:**
"/posts" -> params: nil
"/posts/:id" -> params: id
"/posts/:id/comments" -> params: id
"/posts/:id/comments/:commentID/likes" -> params: id, commentID
"/posts/:id/reviews" -> params: id
"/posts/:id/reviews/:reviewID" -> params: id, reviewID
### Serving
router := compass.New()
srv := &http.Server{
Handler: router, // compass.Router
Addr: "127.0.0.1:8000",
// Set server options as usual
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
### Accessing Routing Params
Compass writes routing params to request's context, to access params, `Params`
function can be used:
// returns map[string]string
params := compass.Params(ctx)
### Interceptors
Interceptors are basically middlewares. The interceptors are compatible with
popular muxer `gorilla/mux` library middlewares which implements also the same
`Middleware(handler http.Handler) http.Handler` function. So, `gorilla/mux`
middlewares can directly be used as `Interceptor`.
**Creating a new interceptor:**
Option 1) Implement the `interceptor.Interceptor` interface:
import (
"github.com/mustafaturan/compass/interceptor"
...
)
...
type myinterceptor struct {}
func (i *myinterceptor) Middleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("X-Middleware", "compass")
h.ServeHTTP(rw, req)
})
}
// init router with interceptor/middleware
i := &myinterceptor{}
router := compass.New(router.WithInterceptors(i))
Option 2) Use home-ready implementation of Interceptor function
`interceptor.Func`
import (
"github.com/mustafaturan/compass/interceptor"
...
)
...
myMiddleware := interceptor.Func(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("X-Middleware", "compass")
h.ServeHTTP(rw, req)
})
})
// init router with interceptor/middleware
router := compass.New(router.WithInterceptors(myMiddleware))
*/
package compass
<file_sep>/matcher/matcher.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
package matcher
import (
"errors"
"net/http"
chandler "github.com/mustafaturan/compass/handler"
)
const (
pathvar = ":"
)
// Matcher is a modified version of Radix tree for HTTP Routing
type Matcher struct {
nodes map[string]*node
}
type node struct {
handler *chandler.Handler
nodes map[string]*node
}
// New inits a new matcher
func New() *Matcher {
return &Matcher{nodes: map[string]*node{
http.MethodGet: {nodes: make(map[string]*node)},
http.MethodHead: {nodes: make(map[string]*node)},
http.MethodPost: {nodes: make(map[string]*node)},
http.MethodPut: {nodes: make(map[string]*node)},
http.MethodPatch: {nodes: make(map[string]*node)},
http.MethodDelete: {nodes: make(map[string]*node)},
http.MethodConnect: {nodes: make(map[string]*node)},
http.MethodOptions: {nodes: make(map[string]*node)},
http.MethodTrace: {nodes: make(map[string]*node)},
}}
}
// Find finds the top priority HTTP handler
func (m *Matcher) Find(method string, segments []string) (*chandler.Handler, bool) {
if len(segments) == 0 {
return m.nodes[method].handler, m.nodes[method].handler != nil
}
var pn node
m.nodes[method].search(segments, 0, &pn)
return pn.handler, pn.handler != nil
}
// Register adds a new handler for the given path
func (m *Matcher) Register(method string, h *chandler.Handler) error {
n := m.nodes[method].insert(h.Segments(), 0)
if n.handler != nil {
return errors.New("path is already registered for another handler")
}
n.handler = h
return nil
}
func (n *node) search(segments []string, index int, pn *node) {
if pn.handler != nil {
return
}
if n == nil {
return
}
if len(segments) == index {
pn.handler = n.handler
return
}
segment := segments[index]
n.nodes[segment].search(segments, index+1, pn)
n.nodes[pathvar].search(segments, index+1, pn)
}
func (n *node) insert(segments []string, index int) *node {
if len(segments) == index {
return n
}
segment := segments[index]
if len(segment) > 0 && segment[0] == pathvar[0] {
segment = pathvar
}
if next, ok := n.nodes[segment]; ok {
return next.insert(segments, index+1)
}
if segment != pathvar &&
n.nodes[pathvar] != nil &&
n.nodes[pathvar].handler != nil &&
len(segments) == index+1 {
return n.nodes[pathvar]
}
next := &node{nodes: make(map[string]*node)}
n.nodes[segment] = next
return next.insert(segments, index+1)
}
<file_sep>/handler/handler.go
// Copyright 2021 <NAME>. All rights reserved.
// Use of this source code is governed by a Apache License 2.0 license that can
// be found in the LICENSE file.
package handler
import (
"errors"
"net/http"
)
// Handler is a http.handler for given matcher
type Handler struct {
HTTPHandler http.Handler
segments []string
params map[string]int
}
const (
separator = '/'
paramInitialChar = ':'
)
// New returns a new Handler
func New(path string, h http.Handler) (*Handler, error) {
segments := make([]string, 0)
params := make(map[string]int)
if len(path) < 1 {
return nil, errors.New("path can't be empty")
}
if path[0] != '/' {
return nil, errors.New("path must start with '/' char")
}
if h == nil {
return nil, errors.New("handler can't be nil")
}
if len(path) == 1 {
segments = []string{""}
}
for i := 1; i < len(path); i++ {
start := i
for i < len(path) {
if path[i] == separator {
break
}
i++
}
segment := path[start:i]
if segment[0] == paramInitialChar {
params[segment[1:]] = len(segments)
}
segments = append(segments, segment)
}
return &Handler{
HTTPHandler: h,
segments: segments,
params: params,
}, nil
}
// Params extracts and return params from the given path segments
func (h *Handler) Params(segments []string) map[string]string {
params := make(map[string]string, len(h.params))
for name, index := range h.params {
params[name] = segments[index]
}
return params
}
// Segments returns segments
func (h *Handler) Segments() []string {
return h.segments
}
<file_sep>/interceptor/interceptor_test.go
package interceptor
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestMiddleware(t *testing.T) {
mfn := Func(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("X-Middleware", "compass")
h.ServeHTTP(rw, req)
})
})
hfn := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
_, _ = rw.Write([]byte("pong"))
})
rw := httptest.NewRecorder()
req := httptest.NewRequest("GET", "http://example.com/ping", nil)
mfn.Middleware(hfn).(http.Handler).ServeHTTP(rw, req)
resp := rw.Result()
t.Run("verify interceptor effect with http header", func(t *testing.T) {
if resp.Header.Get("X-Middleware") != "compass" {
t.Fatalf("interceptor Middleware() should call Middleware() with effects")
}
if body, err := ioutil.ReadAll(resp.Body); string(body) != "pong" || err != nil {
t.Fatalf("interceptor Middleware() should call Middleware() with effects %+v", err)
}
})
}
<file_sep>/go.mod
module github.com/mustafaturan/compass
go 1.14
|
c86a6feaa3ad4eea7faa0f060c0a0faf843b4b03
|
[
"Markdown",
"Go Module",
"Go"
] | 13 |
Markdown
|
mustafaturan/compass
|
ab4f646a30632aac33ffc6282c264d8c3a6bcd48
|
bd5dd27f9368ebcaf9ef579f713ff154180175b1
|
refs/heads/master
|
<file_sep>package com.example.uts
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.uts.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val data = createFac()
rv_list_main.layoutManager = LinearLayoutManager(this)
rv_list_main.setHasFixedSize(true)
rv_list_main.adapter = adapter_fak(data, { onItem: data_fak ->
onItemClicked(onItem) })
}
private fun onItemClicked(onItem: data_fak) {
val showDetailActivityIntent = Intent(this, detail_fak::class.java)
showDetailActivityIntent.putExtra(Intent.EXTRA_TEXT, onItem.imgFac)
showDetailActivityIntent.putExtra(Intent.EXTRA_TITLE, onItem.nameFac)
showDetailActivityIntent.putExtra(Intent.EXTRA_TEMPLATE, onItem.descFac)
showDetailActivityIntent.putExtra(Intent.EXTRA_SUBJECT, onItem.descDet)
startActivity(showDetailActivityIntent)
}
private fun createFac(): List<data_fak> {
val rvList = ArrayList<data_fak>()
rvList.add(
data_fak(
R.drawable.logo,
"Fakultas Ilmu Komputer",
"Fakultas Ilmu Komputer\n" +
"adalah satu dari dari 7\n" +
"program studi di UPN\n" +
"VETERAN JATIM",
"1. Teknik Informatika\n" +
"2. Sistem Informasi"
)
)
rvList.add(
data_fak(
R.drawable.logo,
"Fakultas Teknik",
"Fakultas Teknik\n" +
"merupakan salah satu dari 7\n" +
"Fakultas 'Veteran' Jawa\n" +
"Timur. Yang terdiri dari program\n" +
"studi: ",
"1. Teknik Kimia\n" +
"2. Teknik Industri\n" +
"3. Teknik Sipil\n" +
"4. Teknik Lingkungan\n" +
"5. Teknologi Pangan"
)
)
rvList.add(
data_fak(
R.drawable.logo,
"Fakultas Ekonomi dan Bisnis",
"Fakultas Ekonomi dan Bisnis\n" +
"merupakan salah satu dari 7\n" +
"Fakultas 'Veteran' Jawa\n" +
"Timur. Yang terdiri dari program\n" +
"studi: ",
"1. Ekonomi Pembangunan\n" +
"2. Akuntansi\n" +
"3. Manajemen"
)
)
rvList.add(
data_fak(
R.drawable.logo,
"Fakultas Pertanian",
"Fakultas Pertanian\n" +
"merupakan salah satu dari 7\n" +
"Fakultas 'Veteran' Jawa\n" +
"Timur. Yang terdiri dari program\n" +
"studi: ",
"1. Agroteknologi\n" +
"2. Agribisnis"
)
)
rvList.add(
data_fak(
R.drawable.januar,
"Short Profile",
"Nama : <NAME>\n"+
"Tempat Tanggal Lahir : Surabaya, 20 Januari 2000\n" +
"Alamat : PBI Blok H-12\n" +
"No. Telepon : 085155306005\n" +
"Email : <EMAIL>\n" +
"Github : https://github.com/yayan2130\n",
"Riwayat Pendidikan : \n" +
"\t\t 1. SD Al Kautsar \n" +
"\t\t 2. SMPI Al - Mizan \n" +
"\t\t 3. SMA Wijaya Putra \n\n" +
"Penghargaan : \n" +
"none"
)
)
return rvList
}
}<file_sep>package com.example.uts
data class data_fak(
val imgFac: Int,
val nameFac: String,
val descFac: String,
val descDet: String
)
|
89cd24436220521b2e3a5a9b8d1e1c24818cebe1
|
[
"Kotlin"
] | 2 |
Kotlin
|
yayan2130/UTS2Mobile_18082010027
|
c4f82e6ef4e410d92f6cef19bb5205e778d184bb
|
9c38572c6708ef3a06ae6c12b159449967c12dbf
|
refs/heads/master
|
<file_sep><?php
$error = $message = "";
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*500; //500 kb
$path = "uploads/"; // Upload directory
$count = 0;
$pid = $_REQUEST["pid"];
if(isset($_POST["submit"])){
if($_POST["submit"] == "addproductimage" && isset($_REQUEST["pid"]) && $_REQUEST["pid"] > 0){
/* echo '<pre>';
print_r($_FILES);
echo '</pre>'; */
if( !productExist($pid) ){
$error .= "Product is not exist.";
}else{
// Loop $_FILES to exeicute all files
foreach ($_FILES['image']['name'] as $f => $name) {
if ($_FILES['image']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['image']['error'][$f] == 0) {
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
if ($_FILES['image']['size'][$f] > $max_file_size) {
$error_arr[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array($extension, $valid_formats) ){
$error_arr[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if( is_uploaded_file($_FILES["image"]["tmp_name"][$f]) ){
$directoryName = $path.$pid."/";
//Check if the directory already exists.
if(!is_dir($directoryName)){
//Directory does not exist, so lets create it.
mkdir($directoryName, 0755, true);
}
$filename = $directoryName.time().rand(1111, 9999).".".$extension;
if(move_uploaded_file($_FILES["image"]["tmp_name"][$f], $filename)){
$count++; // Number of successfully uploaded file
$insert_query = "INSERT INTO `images` ";
$insert_query .= "(`product_id`, `name`, `post_date`) ";
$insert_query .= "VALUES (";
$insert_query .= $pid.", ";
$insert_query .= "'".$filename."', ";
$insert_query .= "NOW()";
$insert_query .= ")";
if ($db->query($insert_query) === TRUE) {
header("location:index.php?page=productimage&pid=".$pid."&message=success");
} else {
$error .= "Error: " . $insert_query . "<br>" . $db->error;
}
}
}
}
}
}
if( isset( $error_arr ) && !empty($error_arr) ){
$error .= implode("<br>", $error_arr);
}
}
}else{
$error .= "Product is not exist.";
}
}
if( isset($_GET['message']) ){
if( $_GET['message'] == "success" ){
$message .= "Image is uploaded successfully";
}
}
$image_arr = getproductImages($pid);
?><file_sep><?php
include("config.php");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php include("common/head.php");?>
</head>
<body>
<div class="container">
<header>
<?php include("common/header.php");?>
</header>
<main>
<?php include("template/".$page_name.".php");?>
</main>
<footer>
<?php include("common/footer.php");?>
</footer>
</div>
</body>
</html><file_sep><title>Chocolate | <?php echo ucfirst($page_title);?> Page</title>
<style>
body{
margin:0;
padding:0;
background:#CCC;
color:#000;
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
.container{
width: 1024px;
margin:0px auto;
background:#FFF;
}
nav ul{
margin:0;
padding:0;
list-style-type:none;
text-align:center;
}
nav ul li{
display:inline-block;
padding:5px 10px;
}
header, footer{
background:#FF9;
color:#900;
padding:20px 0;
}
main{
background:#FFF;
margin:20px 0;
}
.wrapper{
padding:0 20px;
}
.hide{
display:none;
}
label[for='image']{
background:#03F;
color:#FFF;
padding:5px 10px;
margin-bottom:10px;
display:inline-block;
}
.productContainer .panel{
display:inline-block;
vertical-align:top;
box-sizing: border-box;
}
.productContainer .leftPanel{
width: 25%;
}
.productContainer .rightPanel{
width: 74%;
}
.productContainer .filternav{
margin-right:5px;
min-height:300px;
}
.productContainer .itemlists{
margin-left:5px;
}
.productContainer .itemlists > ul {
margin: 0;
padding: 0;
list-style-type: none;
/* background:#939; */
}
.productContainer .itemlists > ul.grid > li{
display:inline-block;
width:33%;
vertical-align:top;
}
.productContainer .itemlists > ul > li{
margin-bottom:13px;
/* background:#03C; */
}
.productContainer .itemlists > ul > li > .box{
min-height:200px;
box-sizing: border-box;
margin:0 5px;
padding:10px;
border:1px solid #000;
/* background:#9C0; */
}
.filterItem{
margin:0;
padding:0;
list-style-type:none;
}
div.pagination {
padding: 3px;
margin: 3px;
}
div.pagination a {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #AAAADD;
text-decoration: none; /* no underline */
color: #000099;
}
div.pagination a:hover, div.pagination a:active {
border: 1px solid #000099;
color: #000;
}
div.pagination span.current {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #000099;
font-weight: bold;
background-color: #000099;
color: #FFF;
}
div.pagination span.disabled {
padding: 2px 5px 2px 5px;
margin: 2px;
border: 1px solid #EEE;
color: #DDD;
}
.homeSubNav{
margin:0;
padding:0;
list-style-type:none;
text-align:center;
}
.homeSubNav li{
display:inline-block;
padding:5px 10px;
}
.subNav a, .actionColumn a{
display:inline-block;
padding:5px 10px;
}
.itemlists .box .action a{
display:inline-block;
padding:5px 10px;
}
.imageGrid{
margin:0;
padding:0;
list-style-type:none;
}
.imageGrid li{
display:inline-block;
border:2px solid #06F;
margin:5px;
}
</style><file_sep><h1 align="center">Products Image</h1>
<section class="wrapper">
<?php if( isset($message) ){?>
<p class="message"><?php echo $message ?></p>
<?php }?>
<?php if( isset($error) ){?>
<p class="message"><?php echo $error ?></p>
<?php }?>
<form name="productImageForm" id="productImageFormId" method="post" enctype="multipart/form-data">
<div class="fieldGroup">
<label for="image">Choose Image</label>
<input name="image[]" id="image" type="file" class="hide" multiple onchange="showInfo(this);" />
<span id="fileInfo"></span>
</div>
<div class="button">
<input name="submit" type="hidden" value="addproductimage" />
<input name="save" id="save" type="submit" value="Upload" />
<input name="back" id="back" type="button" value="Back" onclick="javascript:(window.location='index.php?page=product');" />
</div>
</form>
<?php if (!empty($image_arr)): ?>
<ul class="imageGrid">
<?php foreach($image_arr as $item){?>
<?php
$productImage = "common/images/no-image-available.png";
if( is_file( $item->name ) ){
$productImage = $item->name;
}
?>
<li>
<img src="<?php echo $productImage ?>" alt="Image" width="300px" />
</li>
<?php }?>
</ul>
<?php endif;?>
</section>
<script>
function showInfo(obj){
var inpFiles = obj;
var names = "";
for (var i = 0; i < inpFiles.files.length; ++i) {
if( names !== "" )
names += "; ";
names += inpFiles.files.item(i).name;
}
document.getElementById("fileInfo").innerHTML = names;
}
</script><file_sep># chocolate
It's just our first attemt to build frontend a POC(Point of Concept) with Angular JS by <NAME> and myself <NAME><file_sep><?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chocolate";
// Create connection
$db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($db->connect_error > 0) {
die("Connection failed: " . $db->connect_error);
}
function productExist($pid){
global $db;
// Select Product Query
$select_product = $db->prepare("SELECT COUNT(`product_id`) AS total FROM `product` WHERE `product_id` = ?");
$select_product->bind_param('i', $pid);
$select_product->execute();
$select_product->bind_result($returned_number);
$select_product->fetch();
$select_product->free_result();
//echo $returned_number;
if(!$returned_number){
return false;
}
return true;
}
function filterIdExist($table, $field, $id){
global $db;
// Select Query
$select_record = $db->prepare("SELECT COUNT(`".$field."`) AS total FROM `".$table."` WHERE `".$field."` = ?");
$select_record->bind_param('i', $id);
$select_record->execute();
$select_record->bind_result($returned_number);
$select_record->fetch();
$select_record->free_result();
$select_record->close();
//echo $returned_number;
if(!$returned_number){
return false;
}
return true;
}
function filterNameExist($table, $name){
global $db;
// Select Query
$select_record = $db->prepare("SELECT COUNT(`name`) AS total FROM `".$table."` WHERE `name` = ?");
$select_record->bind_param('s', $name);
$select_record->execute();
$select_record->bind_result($returned_number);
$select_record->fetch();
$select_record->free_result();
$select_record->close();
//echo $returned_number;
if(!$returned_number){
return false;
}
return true;
}
function filterNameExistOnEdit($table, $notfield, $id, $name){
global $db;
// Select Query
$select_record = $db->prepare("SELECT COUNT(`".$notfield."`) AS total FROM `".$table."` WHERE `name` = ? AND `".$notfield."` != ?");
$select_record->bind_param('si', $name, $id);
$select_record->execute();
$select_record->bind_result($returned_number);
$select_record->fetch();
$select_record->free_result();
$select_record->close();
//echo $returned_number;
if(!$returned_number){
return false;
}
return true;
}
function getResultCount($query){
global $db;
// Select Product Query
$select_product = $db->prepare($query);
$select_product->execute();
$select_product->bind_result($returned_number);
$select_product->fetch();
$select_product->free_result();
//echo $returned_number;
return $returned_number;
}
function getproductImages($pid){
global $db;
// Select Product Images Query
$image_arr = array();
$select_images = "SELECT i.* FROM `images` AS i WHERE i.`product_id` = ".(int)$pid;
$result = $db->query($select_images);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$row->name = stripslashes($row->name);
$image_arr[] = $row;
}
// Free result set
$result->close();
}
/* echo '<pre>';
print_r($image_arr);
echo '</pre>'; */
return $image_arr;
}
$limit = 6;
function getpagination($total_pages = 0, $targetpage = "index.php?a=1", $adjacents = 3){
global $limit; //how many items to show per page
$page = isset($_GET['pno']) ? (int)$_GET['pno'] : 1;
/* Setup page vars for display. */
if ($page == 0) $page = 1; //if no page var is given, default to 1.
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
$lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up.
$lpm1 = $lastpage - 1; //last page minus 1
/*
Now we apply our rules and draw the pagination object.
We're actually saving the code to a variable in case we want to draw it more than once.
*/
$pagination = "";
if($lastpage > 1)
{
$pagination .= "<div class=\"pagination\">";
//previous button
if ($page > 1)
$pagination.= "<a href=\"$targetpage&pno=$prev\"><< previous</a>";
else
$pagination.= "<span class=\"disabled\"><< previous</span>";
//pages
if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage&pno=$counter\">$counter</a>";
}
}
elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
{
//close to beginning; only hide later pages
if($page < 1 + ($adjacents * 2))
{
for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage&pno=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage&pno=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage&pno=$lastpage\">$lastpage</a>";
}
//in middle; hide some front and some back
elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
{
$pagination.= "<a href=\"$targetpage&pno=1\">1</a>";
$pagination.= "<a href=\"$targetpage&pno=2\">2</a>";
$pagination.= "...";
for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage&pno=$counter\">$counter</a>";
}
$pagination.= "...";
$pagination.= "<a href=\"$targetpage&pno=$lpm1\">$lpm1</a>";
$pagination.= "<a href=\"$targetpage&pno=$lastpage\">$lastpage</a>";
}
//close to end; only hide early pages
else
{
$pagination.= "<a href=\"$targetpage&pno=1\">1</a>";
$pagination.= "<a href=\"$targetpage&pno=2\">2</a>";
$pagination.= "...";
for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page)
$pagination.= "<span class=\"current\">$counter</span>";
else
$pagination.= "<a href=\"$targetpage&pno=$counter\">$counter</a>";
}
}
}
//next button
if ($page < $counter - 1)
$pagination.= "<a href=\"$targetpage&pno=$next\">next >></a>";
else
$pagination.= "<span class=\"disabled\">next >></span>";
$pagination.= "</div>\n";
}
return $pagination;
}
function rm_rf($path) {
if (@is_dir($path) && is_writable($path)) {
$dp = opendir($path);
while ($ent = readdir($dp)) {
if ($ent == '.' || $ent == '..') {
continue;
}
$file = $path . DIRECTORY_SEPARATOR . $ent;
if (@is_dir($file)) {
rm_rf($file);
} elseif (is_writable($file)) {
unlink($file);
} else {
//echo $file . "is not writable and cannot be removed. Please fix the permission or select a new path.\n";
}
}
closedir($dp);
return rmdir($path);
} else {
return @unlink($path);
}
}
?><file_sep><section>
<div class="header">
<h1 align="center">Welcome to Admin Section</h1>
<?php include("common/home_menu.php"); ?>
</div>
<div class="body">
</div>
</section>
<file_sep><h1 align="center"><?php echo $page_mode === "edit" ? "Edit" : "Add"; ?> Products</h1>
<section class="wrapper">
<?php if( isset($message) ){?>
<p class="message"><?php echo $message ?></p>
<?php }?>
<?php if( isset($error) ){?>
<p class="message"><?php echo $error ?></p>
<?php }?>
<form name="productForm" id="productFormId" method="post">
<div class="fieldGroup">
<label for="title">Title</label>
<input name="product[title]" id="title" type="text"
value="<?php echo isset($_POST["product"]["title"]) ? $_POST["product"]["title"] : isset($product_row) ? $product_row->title : ""?>" />
</div>
<div class="fieldGroup">
<label for="short_description">Short Description</label>
<textarea name="product[short_description]" id="short_description" cols="" rows="5"><?php echo isset($_POST["product"]["short_description"]) ? $_POST["product"]["short_description"] : isset($product_row) ? $product_row->short_description : ""?></textarea>
</div>
<div class="fieldGroup">
<label for="price">Price</label>
<input name="product[price]" id="price" type="text"
value="<?php echo isset($_POST["product"]["price"]) ? $_POST["product"]["price"] : isset($product_row) ? $product_row->price : 0?>" />
</div>
<div class="fieldGroup">
<label for="color">Color</label>
<select name="product[color]" id="color">
<option value="">Select Color</option>
<?php
if( isset($color_arr) && !empty($color_arr) ){
foreach( $color_arr as $color){
$selected = ((isset($_POST["product"]["color"]) && $color->color_id == $_POST["product"]["color"]) || (isset($product_row) && $product_row->color_id == $color->color_id)) ? 'selected = "selected"' : "";
?>
<option value="<?php echo $color->color_id ?>" <?php echo $selected ?>><?php echo $color->name ?></option>
<?php
}
}
?>
</select>
</div>
<div class="fieldGroup">
<label for="flavour">Flavour</label>
<select name="product[flavour]" id="flavour">
<option value="">Select Flavour</option>
<?php
if( isset($flavour_arr) && !empty($flavour_arr) ){
foreach( $flavour_arr as $flavour){
$selected = ((isset($_POST["product"]["flavour"]) && $flavour->flavour_id == $_POST["product"]["flavour"]) || (isset($product_row) && $product_row->flavour_id == $flavour->flavour_id)) ? 'selected = "selected"' : "";
?>
<option value="<?php echo $flavour->flavour_id ?>" <?php echo $selected ?>><?php echo $flavour->name ?></option>
<?php
}
}
?>
</select>
</div>
<div class="fieldGroup">
<label for="type">Type</label>
<select name="product[type]" id="type">
<option value="">Select Type</option>
<?php
if( isset($type_arr) && !empty($type_arr) ){
foreach( $type_arr as $type){
$selected = ((isset($_POST["product"]["type"]) && $type->type_id == $_POST["product"]["type"]) || (isset($product_row) && $product_row->type_id == $type->type_id)) ? 'selected = "selected"' : "";
?>
<option value="<?php echo $type->type_id ?>" <?php echo $selected ?>><?php echo $type->name ?></option>
<?php
}
}
?>
</select>
</div>
<div class="fieldGroup">
<label for="cocoa">Cocoa (%)</label>
<input name="product[cocoa]" id="cocoa" type="text"
value="<?php echo isset($_POST["product"]["cocoa"]) ? $_POST["product"]["cocoa"] : isset($product_row) ? $product_row->cocoa : 0?>" />
</div>
<div class="fieldGroup">
<label for="weight">Weight (gms)</label>
<input name="product[weight]" id="weight" type="text"
value="<?php echo isset($_POST["product"]["weight"]) ? $_POST["product"]["weight"] : isset($product_row) ? $product_row->weight : 0?>" />
</div>
<div class="button">
<?php if ($page_mode == "edit"): ?>
<input name="pid" type="hidden" value="<?php echo isset($product_row) ? $product_row->product_id : "" ?>" />
<input name="submit" type="hidden" value="edit" />
<?php else : ?>
<input name="submit" type="hidden" value="add" />
<?php endif;?>
<input name="save" id="save" type="submit" value="Save" />
<input name="cancel" id="cancel" type="reset" value="Cancel" />
</div>
</form>
</section><file_sep><h1 align="center">Products List</h1>
<section class="wrapper">
<div class="subNav productlist">
<a href="index.php?page=product&mode=add">Add Product</a> <a href="index.php?page=product">Clear Filters</a>
</div>
<div class="searchArea" align="right">
<form action="index.php?" method="get">
<input type="text" name="s" value="<?php echo $searchText ?>" /> <input type="submit" value="Search" />
<input name="page" type="hidden" value="product" />
</form>
</div>
<?php if( isset($message) ){?>
<p class="message"><?php echo $message ?></p>
<?php }?>
<?php if( isset($error) ){?>
<p class="message"><?php echo $error ?></p>
<?php }?>
<div class="productContainer">
<aside class="leftPanel panel">
<div class="filternav">
<div class="filterBlock">
<form action="index.php?" method="get" name="filter" id="filterForm">
<input name="pno" type="hidden" value="<?php echo $page_no ?>" />
<input name="page" type="hidden" value="product" />
<input name="s" type="hidden" value="<?php echo $searchText ?>" />
<fieldset>
<legend>Colour</legend>
<div class="fieldsArea">
<?php if (isset($color_arr) && !empty($color_arr)): ?>
<ul class="filterItem">
<?php foreach($color_arr as $item):?>
<?php $checked = !empty($getColors) && in_array($item->color_id, $getColors) ? "checked=\"checked\"" : "" ?>
<li>
<input name="color[]" type="checkbox" id="color_<?php echo $item->color_id;?>" <?php echo $checked ?> value="<?php echo $item->color_id;?>"
onclick="javascript:document.getElementById('filterForm').submit();" />
<label for="color_<?php echo $item->color_id;?>"><?php echo $item->name;?></label></li>
<?php endforeach;?>
</ul>
<?php endif;?>
</div>
</fieldset>
<fieldset>
<legend>Type</legend>
<div class="fieldsArea">
<?php if (isset($type_arr) && !empty($type_arr)): ?>
<ul class="filterItem">
<?php foreach($type_arr as $item):?>
<?php $checked = !empty($getTypes) && in_array($item->type_id, $getTypes) ? "checked=\"checked\"" : "" ?>
<li>
<input name="type[]" type="checkbox" id="type_<?php echo $item->type_id;?>" <?php echo $checked ?> value="<?php echo $item->type_id;?>"
onclick="javascript:document.getElementById('filterForm').submit();" />
<label for="type_<?php echo $item->type_id;?>"><?php echo $item->name;?></label></li>
<?php endforeach;?>
</ul>
<?php endif;?>
</div>
</fieldset>
<fieldset>
<legend>Flavour</legend>
<div class="fieldsArea">
<?php if (isset($flavour_arr) && !empty($flavour_arr)): ?>
<ul class="filterItem">
<?php foreach($flavour_arr as $item):?>
<?php $checked = !empty($getFlavors) && in_array($item->flavour_id, $getFlavors) ? "checked=\"checked\"" : "" ?>
<li>
<input name="flavor[]" type="checkbox" id="flavor_<?php echo $item->flavour_id;?>" <?php echo $checked ?> value="<?php echo $item->flavour_id;?>"
onclick="javascript:document.getElementById('filterForm').submit();" />
<label for="flavor_<?php echo $item->flavour_id;?>"><?php echo $item->name;?></label></li>
<?php endforeach;?>
</ul>
<?php endif;?>
</div>
</fieldset>
</form>
</div>
</div>
</aside>
<aside class="rightPanel panel">
<?php if( isset( $product_arr ) && !empty($product_arr) ){?>
<div class="itemlists">
<ul class="grid">
<?php foreach($product_arr as $item){?>
<?php
$productImage = "common/images/icon-no-image.png";
if( !empty($item->images) ){
if( is_file( $item->images[0]->name ) ){
$productImage = $item->images[0]->name;
}
}
?>
<li>
<div class="box">
<div><?php echo $item->title; ?></div>
<div><img src="<?php echo $productImage ?>" alt="Image" width="200px" /></div>
<div class="action">
<a href="javascript:void(0);" onclick="javascript:if(confirm('Do you want to delete this product?')){document.getElementById('deletepid').value=<?php echo $item->product_id; ?>;document.getElementById('deleteProductForm').submit();}">Delete</a>
<a href="index.php?page=productimage&pid=<?php echo $item->product_id; ?>">Manage Images</a>
</div>
</div>
</li>
<?php }?>
</ul>
</div>
<?php }?>
<form action="" method="post" name="deleteProduct" id="deleteProductForm">
<input name="mode" type="hidden" value="delete" />
<input name="pid" id="deletepid" type="hidden" value="" />
</form>
</aside>
</div>
<div class="pagination"><?php echo isset($pagination) ? $pagination : ""; ?></div>
</section>
<file_sep><?php
$error = $message = "";
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
$pid = isset($_GET["pid"]) ? $_GET["pid"] : "";
if(isset($_POST["submit"])){
if($_POST["submit"] == "add" || $_POST["submit"] == "edit"){
$pid = isset($_POST["pid"]) ? $_POST["pid"] : "";
if( $page_mode === "edit" ){
if(!productExist($pid)){
header("location:index.php?page=product&mode=".$page_mode . "&pid=".(int)$pid ."&message=notexist");
exit();
}
}
/* echo '<pre>';
print_r($_POST);
echo '</pre>'; */
if( isset($_POST["product"]) && is_array($_POST["product"]) ){
foreach( $_POST["product"] as $key => $value ){
if( trim($value) == "" ){
$error .= $key." is empty"."<br>";
}
}
if( !strlen($error) ){
if( $page_mode === "add" ){
$insert_query = "INSERT INTO `product` ";
$insert_query .= "(`title`, `short_description`, `price`, `color_id`, `flavour_id`, `type_id`, `post_date`, `cocoa`, `weight`) ";
$insert_query .= "VALUES (";
$insert_query .= "'".$db->escape_string($_POST["product"]['title'])."', ";
$insert_query .= "'".$db->escape_string($_POST["product"]['short_description'])."', ";
$insert_query .= "'".$_POST["product"]['price']."', ";
$insert_query .= $_POST["product"]['color'].", ";
$insert_query .= $_POST["product"]['flavour'].", ";
$insert_query .= $_POST["product"]['type'].", ";
$insert_query .= "NOW(), ";
$insert_query .= $_POST["product"]['cocoa'].", ";
$insert_query .= $_POST["product"]['weight'];
$insert_query .= ")";
$query = $insert_query;
}else{
$update_query = "UPDATE `product` SET ";
$update_query .= "`title` = '".$db->escape_string($_POST["product"]['title'])."', ";
$update_query .= "`short_description` = '".$db->escape_string($_POST["product"]['short_description'])."', ";
$update_query .= "`price` = '".$_POST["product"]['price']."', ";
$update_query .= "`color_id` = ".$_POST["product"]['color'].", ";
$update_query .= "`flavour_id` = ".$_POST["product"]['flavour'].", ";
$update_query .= "`type_id` = ".$_POST["product"]['type'].", ";
$update_query .= "`cocoa` = ".$_POST["product"]['cocoa'].", ";
$update_query .= "`weight` = ".$_POST["product"]['weight'];
$update_query .= " WHERE `product`.`product_id` = ".(int)$pid;
$query = $update_query;
}
if ($db->query($query) === TRUE) {
header("location:index.php?page=product&mode=".$page_mode . ($page_mode === "edit" ? "&pid=".(int)$pid : "") ."&message=success");
} else {
$error .= "Error: " . $query . "<br>" . $db->error;
}
}
}
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if( isset($_GET['message']) ){
if( $_GET['message'] == "success" ){
if( $page_mode == "add" ){
$message .= "New record created successfully";
}else{
$message .= "Product updated successfully";
}
}else if( $_GET['message'] == "notexist" ){
$error .= "Product is not exist";
}
}
// Colour Query
$select_color = "SELECT * FROM `colour`";
$result = $db->query($select_color);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$color_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_color . "<br>" . $db->error;
}
/* echo '<pre>';
print_r($color_arr);
echo '</pre>'; */
// Flavour Query
$select_flavour = "SELECT * FROM `flavour`";
$result = $db->query($select_flavour);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$flavour_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_flavour . "<br>" . $db->error;
}
// Type Query
$select_type = "SELECT * FROM `type`";
$result = $db->query($select_type);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$type_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_type . "<br>" . $db->error;
}
// Product Query
$select_product = "SELECT p.`product_id`, p.`title`, p.`short_description`, p.`price`, p.`cocoa`, p.`weight`, p.`color_id`, p.`flavour_id`, p.`type_id` FROM `product` AS p WHERE p.`product_id` = ".(int)$pid;
$result = $db->query($select_product);
if($result){
// Cycle through results
$product_row = $result->fetch_object();
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_product . "<br>" . $db->error;
}
/* echo '<pre>';
print_r($product_row);
echo '</pre>'; */
?><file_sep><?php
?>
<pre>
//Github
https://github.com/maheshmondal84/chocolate
// Site
Url: http://cpanel.2freehosting.com/
Email: <EMAIL>
Password: <PASSWORD>
//Go To Cpanel:-
http://cpanel.2freehosting.com/switcher
maveri.3eeweb.com
http://cpanel.2freehosting.com/index
//Add product images:-
http://maveri.3eeweb.com/chocolate/index.php?page=productimage&pid=27
//API Call List:-
1) Color List:-
http://maveri.3eeweb.com/chocolate/index.php?cat=color&callfrom=api&calltype=getcolors
Color Object:-
http://maveri.3eeweb.com/chocolate/index.php?cat=color&callfrom=api&calltype=getcolor&id=2
2) Product Details:-
http://maveri.3eeweb.com/chocolate/index.php?page=product&callfrom=api&calltype=getproduct&id=17
Product List:-
http://maveri.3eeweb.com/chocolate/index.php?page=product&callfrom=api&calltype=getproducts
3) Flavour List:-
http://maveri.3eeweb.com/chocolate/index.php?cat=flavor&callfrom=api&calltype=getflavors
Flavour Object:-
http://maveri.3eeweb.com/chocolate/index.php?cat=flavor&callfrom=api&calltype=getflavor&id=2
4) Type List:-
http://maveri.3eeweb.com/chocolate/index.php?cat=type&callfrom=api&calltype=gettypes
Type Object:-
http://maveri.3eeweb.com/chocolate/index.php?cat=type&callfrom=api&calltype=gettype&id=2
</pre><file_sep><?php
//http://www.bigbasket.com/pc/branded-foods/chocolates-sweets/?nc=bc
$error = $message = "";
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
//rm_rf("uploads/24");
if(isset($_POST["mode"]) && $_POST["mode"] == "delete"){
$pid = $_POST["pid"];
/* echo '<pre>';
print_r($_SERVER);
echo '</pre>'; */
if( productExist($pid) ){
//rm_rf("uploads/16");
$image_sql = "SELECT `image_id`, `name` FROM `images` WHERE `product_id` = ".(int)$pid;
$image_result = $db->query($image_sql);
if ($image_result->num_rows > 0) {
// output data of each row
while($image_row = $image_result->fetch_object()) {
if( is_file($image_row->name) ){
unlink($image_row->name);
}
// query to delete a record
$deleteimage = "DELETE FROM `images` WHERE `image_id` = ".(int)$image_row->image_id;
if ($db->query($deleteimage) !== TRUE) {
$error .= "Error: <br>" . $db->error;
}
}
}
if (is_dir('uploads/'.(int)$pid)){
rmdir('uploads/'.(int)$pid);
}
// query to delete a record
$delete_product = "DELETE FROM `product` WHERE `product_id` = ".(int)$pid;
if ($db->query($delete_product) !== TRUE) {
$error .= "Error: <br>" . $db->error;
}
header("location:index.php?".$_SERVER['QUERY_STRING']. ( strlen($_SERVER['QUERY_STRING']) ? "&" : "" ) ."message=deleted");
exit();
}else{
$message .= "Product is not exist";
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if( isset( $_GET['callfrom'] ) && $_GET['callfrom'] == "api" ){
if( isset( $_GET['calltype'] ) && $_GET['calltype'] == "getproduct" ){
$getId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if( productExist($getId) ){
$select_product = "SELECT p.`product_id`, p.`title`, p.`short_description`, p.`price`, p.`cocoa`, p.`weight`, c.`name` AS color, f.`name` AS flavor, t.`name` AS type FROM `product` AS p ";
$select_product .= "INNER JOIN `colour` AS c ON p.`color_id` = c.`color_id` ";
$select_product .= "INNER JOIN `flavour` AS f ON p.`flavour_id` = f.`flavour_id` ";
$select_product .= "INNER JOIN `type` AS t ON p.`type_id` = t.`type_id` ";
$select_product .= " WHERE `product_id` = ".$getId;
$result = $db->query($select_product);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$row->images = getproductImages($row->product_id);
$row->short_description = stripslashes($row->short_description);
$product_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_product . "<br>" . $db->error;
}
$return['query'] = $select_product;
$return['error'] = $error;
$return['results'] = isset( $product_arr ) ? $product_arr : array();
}
header('Access-Control-Allow-Origin: *');
echo json_encode($return);
exit();
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if( isset($_GET['message']) ){
if( $_GET['message'] == "deleted" ){
$message .= "Product deleted successfully";
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// Colour Query
$select_color = "SELECT * FROM `colour`";
$result = $db->query($select_color);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$color_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_color . "<br>" . $db->error;
}
/* echo '<pre>';
print_r($color_arr);
echo '</pre>'; */
// Flavour Query
$select_flavour = "SELECT * FROM `flavour`";
$result = $db->query($select_flavour);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$flavour_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_flavour . "<br>" . $db->error;
}
// Type Query
$select_type = "SELECT * FROM `type`";
$result = $db->query($select_type);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$type_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_type . "<br>" . $db->error;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
$getColors = isset($_GET['color']) ? $_GET['color'] : array();
$getTypes = isset($_GET['type']) ? $_GET['type'] : array();
$getFlavors = isset($_GET['flavor']) ? $_GET['flavor'] : array();
$searchText = isset($_GET['s']) ? trim($_GET['s']) : "";
// Product Query
$page_no = isset($_GET['pno']) ? (int)$_GET['pno'] : 1;
if($page_no)
$start = ($page_no - 1) * $limit; //first item to display on this page
else
$start = 0; //if no pno var is given, set start to 0
$count_product = "SELECT COUNT(p.`product_id`) FROM `product` AS p ";
$select_product = "SELECT p.`product_id`, p.`title`, p.`short_description`, p.`price`, p.`cocoa`, p.`weight`, c.`name` AS color, f.`name` AS flavor, t.`name` AS type FROM `product` AS p ";
$join_product = "INNER JOIN `colour` AS c ON p.`color_id` = c.`color_id` ";
$join_product .= "INNER JOIN `flavour` AS f ON p.`flavour_id` = f.`flavour_id` ";
$join_product .= "INNER JOIN `type` AS t ON p.`type_id` = t.`type_id` ";
$where_product = "WHERE 1 ";
$where_product .= strlen($searchText) ? "AND (p.`title` LIKE \"%".$db->escape_string($searchText)."%\" || p.`short_description` LIKE \"%".$db->escape_string($searchText)."%\") " : " ";
$where_product .= !empty($getColors) ? "AND p.`color_id` IN (". implode(", ", $getColors) .") " : " ";
$where_product .= !empty($getTypes) ? "AND p.`type_id` IN (". implode(", ", $getTypes) .") " : " ";
$where_product .= !empty($getFlavors) ? "AND p.`flavour_id` IN (". implode(", ", $getFlavors) .") " : " ";
$orderby_product = "ORDER BY p.`product_id` DESC ";
$limit_query = "LIMIT $start, $limit";
//echo $select_product.$join_product.$limit_query;
$total_records = getResultCount($count_product.$join_product.$where_product);
$result = $db->query($select_product.$join_product.$where_product.$orderby_product.$limit_query);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$row->images = getproductImages($row->product_id);
$row->short_description = stripslashes($row->short_description);
$product_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_product . "<br>" . $db->error;
}
//$pagination = getpagination($total_records, "index.php?page=product");
if( isset( $_GET['pno'] ) ){
$pno = $_GET['pno'];
unset($_GET['pno']); // delete edit parameter;
}
//$_GET['pagenum'] = 5; // change page number
$get_query_string = http_build_query($_GET);
if( isset( $pno ) ){
$_GET['pno'] = $pno;
}
$pagination = getpagination($total_records, "index.php?".$get_query_string);
/* echo '<pre>';
print_r($product_arr);
echo '</pre>'; */
if( isset( $_GET['callfrom'] ) && $_GET['callfrom'] == "api" ){
if( isset( $_GET['calltype'] ) && $_GET['calltype'] == "getproducts" ){
$return['query'] = $select_product.$join_product.$where_product.$orderby_product.$limit_query;
$return['error'] = $error;
$return['results'] = isset( $product_arr ) ? $product_arr : array();
$return['pagination'] = $pagination;
header('Access-Control-Allow-Origin: *');
echo json_encode($return);
exit();
}
}
?><file_sep><?php
/*$dir_name = dirname(__FILE__);
$docroot = str_replace("/", "\\", $_SERVER['DOCUMENT_ROOT']);
$project_dir = str_replace($docroot, "", $dir_name);
$self = str_replace("/".$project_dir."/", "", $_SERVER['PHP_SELF']);
switch($self){
case "user.php":
$page_name = "user";
$page_title = "User";
break;
case "product.php":
$page_name = "product";
$page_title = "Product";
break;
default:
$page_name = "home";
$page_title = "Home";
break;
}*/
$pages = array("home", "user", "product","productimage" );
$modes = array("add", "edit", "delete");
$cat_arr = array("color", "flavor", "type");
$page_name = isset( $_GET['page'] ) && in_array( $_GET['page'], $pages ) ? trim(strtolower($_GET['page'])) : "home";
$page_mode = isset( $_GET['mode'] ) && in_array( $_GET['mode'], $modes ) ? trim(strtolower($_GET['mode'])) : "";
$get_cat = isset( $_GET['cat'] ) && in_array( $_GET['cat'], $cat_arr ) ? trim(strtolower($_GET['cat'])) : "";
switch($page_name){
case "user":
$page_title = "User";
break;
case "product":
switch($page_mode){
case "add":
case "edit":
$page_name = "product_add";
$page_title = $page_mode === "edit" ? "Edit Product" : "Add Product";
break;
default:
$page_title = "Product";
break;
}
break;
case "productimage":
$page_title = "Product Images";
$page_name = "product_image";
break;
default:
switch($get_cat){
case "color":
$page_title = "Home | Color";
$page_name = "home_color";
break;
case "flavor":
$page_name = "home_flavor";
$page_title = "Home | Flavour";
break;
case "type":
$page_title = "Home | Type";
$page_name = "home_type";
break;
default:
$page_title = "Home";
break;
}
break;
}
include("common/database.php");
include("pages/".$page_name.".php");
$db->close();
?><file_sep><?php
$error = $message = "";
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
$id = isset($_GET["id"]) ? $_GET["id"] : "";
if(isset($_POST["submit"])){
if($_POST["submit"] == "add" || $_POST["submit"] == "edit"){
$id = isset($_POST["id"]) ? $_POST["id"] : "";
if( $page_mode === "edit" ){
if(!filterIdExist("type", "type_id", $id)){
header("location:index.php?cat=type&mode=".$page_mode . "&id=".(int)$id ."&message=notexist");
exit();
}
}
if( isset($_POST["name"]) ){
if( trim($_POST["name"]) == "" ){
$error .= "name is empty"."<br>";
}
if( !strlen($error) ){
if( $page_mode === "edit" ){
if( filterNameExistOnEdit("type", "type_id", $id, $db->escape_string($_POST["name"]) ) ){
$error .= "name is already exist"."<br>";
unset($_GET['message']);
}
}else if( filterNameExist("type", $db->escape_string($_POST["name"])) ){
$error .= "name is already exist"."<br>";
unset($_GET['message']);
}
}
}
if( !strlen($error) ){
if( $page_mode === "add" ){
$insert_query = "INSERT INTO `type` ";
$insert_query .= "(`name`) ";
$insert_query .= "VALUES (";
$insert_query .= "'".$db->escape_string($_POST["name"])."'";
$insert_query .= ")";
$query = $insert_query;
}else{
$update_query = "UPDATE `type` SET ";
$update_query .= "`name` = '".$db->escape_string($_POST["name"])."'";
$update_query .= " WHERE `type_id` = ".(int)$id;
$query = $update_query;
}
if ($db->query($query) === TRUE) {
header("location:index.php?cat=type&mode=".$page_mode . ($page_mode === "edit" ? "&id=".(int)$id : "") ."&message=success");
} else {
$error .= "Error: " . $query . "<br>" . $db->error;
}
}
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if(isset($_POST["mode"]) && $_POST["mode"] == "delete"){
$id = $_POST["id"];
if( filterIdExist("type", "type_id", $id) ){
// query to delete a record
$delete_record = "DELETE FROM `type` WHERE `type_id` = ".(int)$id;
if ($db->query($delete_record) !== TRUE) {
$error .= "Error: <br>" . $db->error;
}
header("location:index.php?cat=type&message=deleted");
exit();
}else{
$message .= "Record is not exist";
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
$select_record = "SELECT * FROM `type`";
$result = $db->query($select_record);
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$record_arr[] = $row;
}
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_record . "<br>" . $db->error;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if( isset($_GET['message']) ){
if( $_GET['message'] == "success" ){
if( $page_mode == "add" ){
$message .= "New record created successfully";
}else{
$message .= "Record updated successfully";
}
}else if( $_GET['message'] == "notexist" ){
$error .= "Record is not exist";
}else if( $_GET['message'] == "deleted" ){
$message .= "Record is deleted successfully";
}
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// Select Query
$select_record = "SELECT * FROM `type` WHERE `type_id` = ".(int)$id;
$result = $db->query($select_record);
if($result){
$row = $result->fetch_object();
// Free result set
$result->close();
}else{
$error .= "Error: " . $select_record . "<br>" . $db->error;
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++
if( isset( $_GET['callfrom'] ) && $_GET['callfrom'] == "api" ){
if( isset( $_GET['calltype'] ) && $_GET['calltype'] == "gettypes" ){
$return['error'] = $error;
$return['results'] = isset( $record_arr ) ? $record_arr : array();
header('Access-Control-Allow-Origin: *');
echo json_encode($return);
exit();
}
if( isset( $_GET['calltype'] ) && $_GET['calltype'] == "gettype" && isset( $_GET['id'] ) ){
$return['error'] = $error;
$return['results'] = isset( $row ) ? $row : NULL;
header('Access-Control-Allow-Origin: *');
echo json_encode($return);
exit();
}
}
?><file_sep><section class="wrapper">
<div class="header">
<h1 align="center">Flavours</h1>
<?php include("common/home_menu.php"); ?>
</div>
<div class="body">
<div><a href="index.php?cat=flavor&mode=add">Add Flavor</a></div>
<?php /* =============================================== */?>
<?php if( isset($message) ){?>
<p class="message"><?php echo $message ?></p>
<?php }?>
<?php if( isset($error) ){?>
<p class="message"><?php echo $error ?></p>
<?php }?>
<?php /* =============================================== */?>
<?php if ($page_mode == "add" || $page_mode == "edit"): ?>
<section class="formSection">
<p>
<form action="" method="post" name="addFilter">
<div class="fieldGroup">
<label for="name">Name</label>
<input name="name" id="name" type="text"
value="<?php echo isset($_POST["name"]) ? $_POST["name"] : isset($row) ? $row->name : ""?>" />
</div>
<p class="button">
<?php if ($page_mode == "edit"): ?>
<input name="id" type="hidden" value="<?php echo isset($row) ? $row->flavour_id : "" ?>" />
<input name="submit" type="hidden" value="edit" />
<?php else : ?>
<input name="submit" type="hidden" value="add" />
<?php endif;?>
<input name="save" id="save" type="submit" value="Save" />
<input name="cancel" id="cancel" type="reset" value="Cancel" />
</p>
</form>
</p>
</section>
<?php endif;?>
<?php /* =============================================== */?>
<section class="listSection">
<p>
<table width="50%" border="1" cellspacing="0" cellpadding="0">
<tr>
<th width="25%" align="left" valign="top">Sl. No.</th>
<th width="38%" align="left" valign="top">Name</th>
<th width="37%" align="left" valign="top">Action</th>
</tr>
<?php if( isset($record_arr) && !empty($record_arr) ):?>
<?php foreach( $record_arr as $key=>$item ):?>
<tr>
<td align="left" valign="top"><?php echo $key ?></td>
<td align="left" valign="top"><?php echo $item->name ?></td>
<td align="left" valign="top" class="actionColumn"><a href="index.php?cat=flavor&mode=edit&id=<?php echo $item->flavour_id ?>">Edit</a> <a href="javascript:void(0);" onclick="javascript:if(confirm('Do you want to delete this record?')){document.getElementById('deleteid').value=<?php echo $item->flavour_id; ?>;document.getElementById('deleteFilterForm').submit();}">Delete</a></td>
</tr>
<?php endforeach;?>
<?php else : ?>
<tr>
<td colspan="3" align="center" valign="top">No Records found</td>
</tr>
<?php endif;?>
</table>
</p>
</section>
<?php /* =============================================== */?>
<form action="" method="post" name="deleteFilter" id="deleteFilterForm">
<input name="mode" type="hidden" value="delete" />
<input name="id" id="deleteid" type="hidden" value="" />
</form>
</div>
</section>
|
6e0f4d6dc7a185310f1fb21412cad4edaa170a05
|
[
"Markdown",
"PHP"
] | 15 |
PHP
|
maheshmondal84/chocolate
|
ebb75def01b66cbf2b41c99457a71f3f3fece2fe
|
adcc7d1fbb118dbf0bae75f223170514cf5701bb
|
refs/heads/master
|
<file_sep>imgurtools
==========
Lulz for great justice!
### Scripts for OS X :
* imgurme [keyword] - spitout an imgur URL from the ~/imgurlist text file and copy the URL to your pasteboard.
* uploadimgur [file] - Upload an image file to imgur and copy the URL to your pasteboard.
#LICENSE:
WTFPL except uploadimgur which is Creative Commons Attribution 3.0 Unported License
<file_sep>#!/bin/bash
FOUND=`cat ~/imgurlist | grep $1`
echo $FOUND
echo $FOUND | awk '{print $2}' | pbcopy
<file_sep>#!/bin/bash
#"Installs" all this crap in /usr/local/bin and also your home dir. Feel free to
#change all of this around.
cp ./imgurlist ~/imgurlist
cp ./imgurme /usr/local/bin/imgurme
cp ./uploadimgur /usr/local/bin/uploadimgur
chmod +x /usr/local/bin/imgurme
chmod +x /usr/local/bin/uploadimgur
echo "Yay done have fun."
|
c77a42e6ba48170d70854764e404aa664e1bc057
|
[
"Markdown",
"Shell"
] | 3 |
Markdown
|
aashay/imgurtools
|
b4552b0f4423b2ab65e1d81cf68e03f7ff5405e5
|
d9346bc3e23245fb82c174fce57250f894f3226a
|
refs/heads/master
|
<repo_name>volpe28v/EmberGihyo<file_sep>/no5/app.js
App = Ember.Application.create();
App.Router.map(function() {
this.resource('products', {path: '/'}, function() {
this.route('show', {path: '/products/:id'});
});
this.resource('cart');
});
App.ProductsRoute = Ember.Route.extend({
model: function(){
return App.Product.all();
}
/*
// ใใฃใกใซๅฎ็พฉใใฆใๅใ
actions: {
addCart: function(product){
this.controllerFor('cart').pushObject(product);
this.transitionTo('cart');
}
}
*/
});
App.ProductsShowRoute = Ember.Route.extend({
model: function(params) {
return this.modelFor('products').filter(function(product){
return product.id === Number(params.id);
})[0];
},
actions: {
addCart: function(product){
this.controllerFor('cart').pushObject(product);
this.controllerFor('cart').save();
this.transitionTo('cart');
console.log("ProductsShowRoute");
}
}
});
App.CartController = Ember.ArrayController.extend({
uniqProductCount: function(){
return this.mapBy('id').uniq().get('length');
}.property('length'),
totalPrice: function(){
return this.mapBy('price').reduce(function(total, price) {
return total + price;
}, 0);
}.property('@each.price'), // length ใงใๅใใจๆใ
save: function(){
var ids = JSON.stringify(this.mapBy('id'));
localStorage.setItem('cart-product-ids', ids);
},
restore: function(){
var idsString = localStorage.getItem('cart-product-ids');
var ids;
if (idsString) {
ids = JSON.parse(idsString);
} else {
ids = [];
}
var products = ids.map(function(id) {
return App.Product.find(id);
});
products = products.compact();
this.set('model', products);
}
});
App.Product = Ember.Object.extend({
id: null,
name: null,
price: 0,
url: null
});
App.Product.reopenClass({
data: [],
all: function(){
return App.Product.data;
},
find: function(id){
return this.all().findBy('id', Number(id));
}
});
App.Product.data.pushObjects([
App.Product.create({
id: 1,
name: 'ในใใใซใผ',
price: 6.0,
url: 'http://devswag.com/products/ember-sticker'
}),
App.Product.create({
id: 2,
name: 'Tใทใฃใ',
price: 22.0,
url: 'http://devswag.com/products/ember-js-tshirt'
}),
App.Product.create({
id: 3,
name: 'ใฌใใใใฟ',
price: 10.0,
url: 'http://devswag.com/products/ember-mascot-tomster'
})
]);
App.initializer({
name: 'restore-cart',
initialize: function(container, app){
container.lookup('controller:cart').restore();
}
});
<file_sep>/no3/app.js
App = Ember.Application.create();
App.Router.map(function() {
this.resource('posts', function() {
this.route('show', {path: '/:post_id'});
});
});
// ใใผใฟ
var posts = [{
id: 1,
title: 'ใฏใใใฆใฎ Ember.js',
body: 'ใใใใ Ember.js ใๅงใใใใจใใๆนๅใใฎ่จไบใงใใ'
}, {
id: 2,
title: 'ๅ
ฌๅผใตใคใใฎๆญฉใๆน',
body: 'http://emberjs.com/ ใฎ่งฃ่ชฌใงใใ'
}, {
id: 3,
title: '2.0 ใฎใญใผใใใใ',
body: 'Ember.js 2.0 ใฎใญใผใใใใใฏใใกใใงๅ
ฌ้ใใใฆใใพใใhttps://github.com/emberjs/rfcs/pull/15'
}];
// Route ๅฎ็พฉ
App.PostsRoute = Ember.Route.extend({
model: function() {
return $.getJSON('http://emberjs.jsbin.com/goqene/2.json');
// return posts;
}
});
App.PostsShowRoute = Ember.Route.extend({
model: function(params) {
var id = Number(params.post_id);
var posts = this.modelFor('posts');
return posts.filter(function(post) {
return post.id === id;
})[0];
}
});
App.LoadingRoute = Ember.Route.extend({
activate: function(){
console.log('่ชญ่พผไธญ');
}
});
<file_sep>/no4/app.js
App = Ember.Application.create();
App.Router.map(function() {
this.resource('posts', {path: '/'}, function() {
this.route('show', {path: '/posts/:post_id'});
});
});
App.PostsRoute = Ember.Route.extend({
model: function(){
return [{
id: 1,
title: 'Ember.js ๅ
ฌๅผใตใคใใฎๆญฉใๆน',
body: 'Ember.js ใฎๅ
ฌๅผใตใคใ(http://emberjs.com/)ใงใฏใใพใใใใใใผใธใฎใตใณใใซใๅใใใฆใฟใใจใใใงใใใใEmber.js ใงใฉใใชใใจใใงใใใฎใใใใฃใใใใใใพใใ'
},{
id: 2,
title: 'Ember.jsใฎใใฃในใซใใทใงใณใใฉใผใฉใ ',
body: 'Ember.js ใซใคใใฆใฎ็ๅใป่ณชๅใปๆฐใใๆๆกใชใฉใEmber.js ใซ้ขใใใใจใๅธธใซ่ญฐ่ซใใใฆใใพใใ http://discuss.emberjs.com/'
}];
}
});
App.PostsShowRoute = Ember.Route.extend({
model: function(params) {
return this.modelFor('posts').filter(function(post){
return post.id === Number(params.post_id);
})[0];
},
setupController: function(controller, model) {
controller.set('model', model);
}
});
App.PostsController = Ember.Controller.extend({
pageTitle: 'Ember.js ้ข้ฃใฎ่จไบ'
});
Ember.Handlebars.helper('truncate', function(value, options) {
var length = options.hash.length;
if (value.length > length) {
return value.slice(0, length) + '...';
} else {
return value;
}
});
App.TruncateTextComponent = Ember.Component.extend({
text: null,
length: 20,
isExpanded: false,
expandText: 'ใใฃใจ่ฆใ',
actions: {
expand: function() {
this.set('isExpanded', true);
}
}
});
|
0a9c1cafea14ca5b990de996e22431695131316c
|
[
"JavaScript"
] | 3 |
JavaScript
|
volpe28v/EmberGihyo
|
3ffea54c25975f146cc254994e2fc49a8e04a4af
|
5b455ed250f7562b07860493605d00924c71a454
|
refs/heads/master
|
<repo_name>Emiliano1973/jsonImporter<file_sep>/demostCommandLine/src/test/resources/schema-hsqldb.sql
drop table events if exists ;
create table events (
event_id varchar(255) not null,
alert boolean not null,
event_duration bigint not null,
host varchar(255),
type varchar(255),
primary key (event_id)
);
<file_sep>/demostCommandLine/src/main/java/ie/demo/demost/services/impl/EventServiceImpl.java
package ie.demo.demost.services.impl;
import ie.demo.demost.entities.Event;
import ie.demo.demost.repositories.EventRepository;
import ie.demo.demost.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class EventServiceImpl implements EventService {
@Autowired
private EventRepository eventRepository;
@Override
public void save(Event event) {
this.eventRepository.save(event);
}
@Override
public Optional<Event> findById(String id) {
return this.eventRepository.findById(id);
}
}
<file_sep>/demostCommandLine/settings.gradle
rootProject.name = 'demost'
<file_sep>/demostCommandLine/src/main/java/ie/demo/demost/services/EventService.java
package ie.demo.demost.services;
import ie.demo.demost.entities.Event;
import java.util.Optional;
public interface EventService {
void save(Event event);
Optional<Event> findById(String id);
}
<file_sep>/demostBatch/src/main/java/ie/demo/demost/config/BatchConfig.java
package ie.demo.demost.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.net.MalformedURLException;
/**
* Created by Echinofora1973 on 22/05/2017.
*/
@Configuration
public class BatchConfig {
private static final Logger logger = LoggerFactory.getLogger(BatchConfig.class);
@Value("classpath:org/springframework/batch/core/schema-drop-hsqldb.sql")
private org.springframework.core.io.Resource dropReopsitoryTables;
@Value("classpath:org/springframework/batch/core/schema-hsqldb.sql")
private org.springframework.core.io.Resource dataReopsitorySchema;
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean(name = "eventJob")
public Job job(@Qualifier("step1") Step step1) {
return jobs.get("eventJob")
.start(step1).build();
}
@Bean
protected Step step1(@Qualifier("eventTasklet") Tasklet tasklet) {
return steps.get("eventStep")
.tasklet(tasklet)
.build();
}
@Bean("jobRepository")
public JobRepository jobRepository(DataSource dataSource,
@Qualifier("internalTransactionManager") PlatformTransactionManager internalTransactionManager) {
logger.info("--------------Init batch repository");
JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
jobRepositoryFactoryBean.setDataSource(dataSource);
jobRepositoryFactoryBean.setTransactionManager(internalTransactionManager);
jobRepositoryFactoryBean.setDatabaseType("hgsqldb");
try {
jobRepositoryFactoryBean.afterPropertiesSet();
logger.info("--------------End Init batch repository");
return (JobRepository) jobRepositoryFactoryBean.getObject();
} catch (Exception e) {
logger.error("error in config :" + e.getMessage(), e);
throw new RuntimeException("error in config :" + e.getMessage(), e);
}
}
@Bean("internalTransactionManager")
protected PlatformTransactionManager internalTransactionManager() {
return new ResourcelessTransactionManager();
}
@Bean("jobLauncher")
public JobLauncher getJobLauncher(@Qualifier("jobRepository") JobRepository jobRepository) {
logger.info("--------------Init Job launcher");
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
try {
jobLauncher.afterPropertiesSet();
logger.info("--------------End Init Job launcher");
} catch (Exception e) {
logger.error("error in config :" + e.getMessage(), e);
throw new RuntimeException("error in config :" + e.getMessage(), e);
}
return jobLauncher;
}
@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") DataSource dataSource) throws MalformedURLException {
logger.info("--------------Init Batch dataSourceInitializer");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(dropReopsitoryTables);
databasePopulator.addScript(dataReopsitorySchema);
databasePopulator.setIgnoreFailedDrops(true);
DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator);
logger.info("--------------Init Batch dataSourceInitializer finished");
return initializer;
}
}
<file_sep>/demostBatch/src/test/java/ie/demo/demost/events/EventDtoReaderTest.java
package ie.demo.demost.events;
import ie.demo.demost.dtos.EventDto;
import ie.demo.demost.readers.Reader;
import ie.demo.demost.readers.impl.EventDtoReader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertTrue;
/*
Test the eventReader
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventDtoReaderTest {
private static final Logger logger = LoggerFactory.getLogger(EventDtoReaderTest.class);
@Value("${event.app.json.toWork.path}")
private String sourceDirName;
@Value("${event.app.json.worked.path}")
private String workedFilesDirName;
//move the files from the destinations if aothet test are executed to source where the test read
@Before
public void setUp() throws Exception {
File dest = new File(workedFilesDirName);
File[] files = dest.listFiles();
if (files.length > 0) {
for (File file : files) {
String soourceFile = sourceDirName + File.separator + file.getName();
Files.move(Paths.get(file.toURI()), Paths.get(soourceFile));
}
}
}
@Test
public void moveNextTest() throws Exception {
logger.info("Init moveNextTest running");
Reader<EventDto> eventDtoReader = new EventDtoReader(sourceDirName + File.separator + "testIn.json");
assertTrue("not json object find out", eventDtoReader.moveNext());
logger.info("moveNextTest finished");
}
@Test
public void readTest() throws Exception {
logger.info("Init readTest running");
Reader<EventDto> eventDtoReader = new EventDtoReader(sourceDirName + File.separator + "testIn.json");
assertTrue("not json object find out", eventDtoReader.moveNext());
assertTrue("The eventDto is null", eventDtoReader.moveNext());
logger.info("readTest finished");
}
}
<file_sep>/demostCommandLine/src/test/java/ie/demo/demost/events/EventManagerServiceTest.java
package ie.demo.demost.events;
import ie.demo.demost.entities.Event;
import ie.demo.demost.services.EventManagerService;
import ie.demo.demost.services.EventService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventManagerServiceTest {
private static final Logger logger=LoggerFactory.getLogger(EventManagerServiceTest.class);
@Autowired
private EventManagerService eventManagerService;
@MockBean
private EventService eventService;
private static final String SOURCE_DIR_NAME ="./jsonManageTest";
@Test
public void storeEventsTest() throws Exception{
logger.info("Init storeEventsTest");
doNothing().when(eventService).save(any(Event.class));
spy(eventService).save(any(Event.class));
eventManagerService.storeEvents(SOURCE_DIR_NAME+File.separator+"testIn.json");
logger.info("storeEventsTest finished");
}
}
<file_sep>/demostCommandLine/src/main/resources/schema-hsqldb.sql
create table if not exists events (
event_id varchar(255) not null,
alert boolean not null,
event_duration bigint not null,
host varchar(255),
type varchar(255),
primary key (event_id)
);
<file_sep>/demostBatch/src/main/java/ie/demo/demost/readers/impl/EventDtoReader.java
package ie.demo.demost.readers.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import ie.demo.demost.dtos.EventDto;
import ie.demo.demost.readers.Reader;
import ie.demo.demost.readers.ReaderException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
/*
This class reads a jsonlines file and
*/
public class EventDtoReader implements Reader<EventDto> {
private static final Logger logger = LoggerFactory.getLogger(EventDtoReader.class);
private static final boolean IS_DEBUG = logger.isDebugEnabled();
private Scanner scanner;
private ObjectMapper objectMapper = null;
private EventDto eventDto = null;
/**
* Istsance a EventDtoReader
*
* @param fileName
* @throws ReaderException
*/
public EventDtoReader(String fileName) throws ReaderException {
try {
logger.info("Json line file to import :" + fileName);
this.scanner = new Scanner(new FileInputStream(new File(fileName)));
this.objectMapper = new ObjectMapper();
} catch (FileNotFoundException e) {
throw new ReaderException("File " + fileName + " not found :" + e.getMessage(), e);
}
}
@Override
public boolean moveNext() throws ReaderException {
//I am reading the record from file
try {
this.eventDto = null;
if (!this.scanner.hasNextLine())
return false;
String record = this.scanner.nextLine();
if ((record == null) || (record.trim().equals("")))
return false;
if (IS_DEBUG) logger.debug("Json line format :" + record);
this.eventDto = this.objectMapper.readValue(record, EventDto.class);
if (IS_DEBUG) logger.debug("Json line format converted id java object :" + this.eventDto);
return true;
} catch (IOException e) {
throw new ReaderException("Impossible to read the record from file :" + e.getMessage(), e);
}
}
@Override
public EventDto read() {
return this.eventDto;
}
@Override
public void close() throws IOException {
eventDto = null;
if (IS_DEBUG) logger.debug("Closing file....");
if (this.scanner != null)
this.scanner.close();
if (IS_DEBUG) logger.debug("File closed.");
}
}
<file_sep>/demostBatch/src/test/java/ie/demo/demost/events/EventManagerServiceTest.java
package ie.demo.demost.events;
import ie.demo.demost.entities.Event;
import ie.demo.demost.services.EventManagerService;
import ie.demo.demost.services.EventService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventManagerServiceTest {
private static final Logger logger = LoggerFactory.getLogger(EventManagerServiceTest.class);
@Autowired
private EventManagerService eventManagerService;
@MockBean
private EventService eventService;
@Value("${event.app.json.toWork.path}")
private String sourceDirName;
@Value("${event.app.json.worked.path}")
private String workedFilesDirName;
//move the files from the destinations if aothet test are executed to source where the test read
@Before
public void setUp() throws Exception {
File dest = new File(workedFilesDirName);
File[] files = dest.listFiles();
if (files.length > 0) {
for (File file : files) {
String soourceFile = sourceDirName + File.separator + file.getName();
Files.move(Paths.get(file.toURI()), Paths.get(soourceFile));
}
}
}
@Test
public void storeEventsTest() throws Exception {
logger.info("Init storeEventsTest");
doNothing().when(eventService).save(any(Event.class));
spy(eventService).save(any(Event.class));
eventManagerService.storeEvents(sourceDirName + File.separator + "testIn.json");
logger.info("storeEventsTest finished");
}
}
<file_sep>/demostBatch/src/test/resources/data-hsqldb.sql
--init brewery location
INSERT INTO events (event_id, event_duration, type, host, alert) VALUES ('test0', 6, null, 'host1', true);
|
3298dc3143458ab84f2085f0b34bdc09c7d1d058
|
[
"Java",
"SQL",
"Gradle"
] | 11 |
SQL
|
Emiliano1973/jsonImporter
|
7e1e7ce0cef9b1c0ae04d133d518e8a7de688fc0
|
d0204717f6eaa2447cc26f970839f2f77005fdf5
|
refs/heads/master
|
<repo_name>alexishuf/ine5410-t2-2019.2-initial<file_sep>/src/test/java/br/ufsc/ine5410/floripaland/SafetyItemsTest.java
package br.ufsc.ine5410.floripaland;
import br.ufsc.ine5410.floripaland.mocks.MockPerson;
import br.ufsc.ine5410.floripaland.safety.SafetyItem;
import org.junit.Test;
import javax.annotation.Nonnull;
import java.util.*;
import static br.ufsc.ine5410.floripaland.Attraction.Type.RAFTING;
import static br.ufsc.ine5410.floripaland.Attraction.Type.RAPPELLING;
import static br.ufsc.ine5410.floripaland.safety.SafetyItem.Type.HELMET;
import static br.ufsc.ine5410.floripaland.safety.SafetyItem.Type.LIFE_JACKET;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
public class SafetyItemsTest extends AttractionTestBase {
@Test
public void testAttractionWithoutHelmets() throws InterruptedException {
attraction = build().withItem(HELMET, 0).getOpen(RAPPELLING);
MockPerson person = new MockPerson(false);
assertTrue(attraction.enter(person));
assertFalse(person.waitForEnterAttraction(100));
attraction.closeAttraction();
assertEquals(1, person.getExitQueueCalls());
}
@Test
public void testWaitsAndReturnHelmet() {
attraction = build().withItem(HELMET, 1).withTime(200).getOpen(RAPPELLING);
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 2; i++) {
personList.add(new MockPerson(false));
assertTrue("i="+i, attraction.enter(personList.get(i)));
}
assertTrue(personList.get(0).waitForEnterAttraction(100));
assertFalse(personList.get(1).waitForEnterAttraction(100));
assertTrue(personList.get(1).waitForEnterAttraction(100+100));
assertEquals(1, personList.get(0).getExitCalls());
assertTrue(personList.get(1).waitForExitAttraction(200+100));
}
@Test
public void testReceivesHelmetLate() {
attraction = build().withItem(HELMET, 0).withTime(200).getOpen(RAPPELLING);
MockPerson alice = new MockPerson();
assertTrue(attraction.enter(alice));
assertFalse(alice.waitForEnterAttraction(100));
attraction.deliver(Collections.singletonList(new SafetyItem(HELMET)));
assertTrue(alice.waitForEnterAttraction(100));
assertTrue(alice.waitForExitAttraction(200+100));
assertEquals(0, alice.getExitQueueCalls());
}
@Test
public void testReceivesExtraHelmet() {
attraction = build().withItem(HELMET, 1).withTime(200).getOpen(RAPPELLING);
MockPerson alice = new MockPerson(), bob = new MockPerson();
assertTrue(attraction.enter(alice));
assertTrue(attraction.enter(bob));
assertTrue(alice.waitForEnterAttraction(100));
assertFalse(bob.waitForEnterAttraction(100));
attraction.deliver(Collections.singletonList(new SafetyItem(HELMET)));
assertTrue(bob.waitForEnterAttraction(100));
assertTrue(alice.waitForExitAttraction(100+100));
assertTrue(bob.waitForExitAttraction(100+100));
assertEquals(0, alice.getExitQueueCalls());
}
@Test
public void testPersonReallyWearsHelmet() {
attraction = build().withItem(HELMET, 1).withTime(200).getOpen(RAPPELLING);
MockPerson alice = new MockPerson();
assertTrue(attraction.enter(alice));
assertTrue(alice.waitForEnterAttraction(100));
Set<SafetyItem> wearing = alice.getWearing();
assertEquals(1, wearing.size());
SafetyItem helmet = wearing.iterator().next();
assertEquals(HELMET, helmet.getType());
assertTrue(helmet.isInUse());
assertEquals(alice, helmet.getPersonWearing());
assertTrue(alice.waitForExitAttraction(200+100));
assertFalse(helmet.isInUse());
assertNull(helmet.getPersonWearing());
assertEquals(Collections.emptySet(), alice.getWearing());
assertEquals(Collections.emptyList(), alice.getWearErrors());
}
@Test
public void testHelmetIsReturned() {
attraction = build().withItem(HELMET, 1).withTime(200).getOpen(RAPPELLING);
MockPerson alice = new MockPerson(), bob = new MockPerson();
assertTrue(attraction.enter(alice));
assertTrue(attraction.enter(bob));
assertTrue(alice.waitForEnterAttraction(100));
Set<SafetyItem> wearing = new HashSet<>(alice.getWearing());
assertEquals(1, wearing.size());
SafetyItem helmet = wearing.iterator().next();
assertEquals(HELMET, helmet.getType());
assertTrue(bob.waitForEnterAttraction(200+100));
assertEquals(wearing, bob.getWearing());
assertTrue(bob.waitForExitAttraction(200+100));
assertEquals(Collections.emptyList(), alice.getWearErrors());
assertEquals(Collections.emptyList(), bob.getWearErrors());
}
public void queueProcessTest(@Nonnull Builder builder, int queueSize, int maxVisitors,
@Nonnull Attraction.Type type) {
attraction = builder.getOpen(type);
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < queueSize; i++) {
personList.add(new MockPerson().withRequiredItems(builder.getRequiredItems()));
assertTrue("i="+i, attraction.enter(personList.get(i)));
}
assertTrue(personList.get(queueSize-1)
.waitForExitAttraction(builder.getMaxTime()*queueSize+100));
assertEquals(maxVisitors, visitor.maxVisitors());
List<String> errors = personList.stream()
.flatMap(p -> p.getWearErrors().stream()).collect(toList());
assertEquals(Collections.emptyList(), errors);
}
@Test
public void testTwoItemsRequired() {
queueProcessTest(build().withItem(LIFE_JACKET, 1)
.withItem(HELMET, 1).withTime(100), 3, 1, RAFTING);
}
@Test
public void testTwoItemsRequiredUnbalanced() {
queueProcessTest(build().withItem(LIFE_JACKET, 1)
.withItem(HELMET, 2).withTime(100), 3, 1, RAFTING);
}
@Test
public void testTwoItemsRequiredWithConcurrency() {
queueProcessTest(build().withItem(LIFE_JACKET, 2)
.withItem(HELMET, 2).withTime(100), 3, 2, RAFTING);
}
@Test
public void testOneItemStress() {
queueProcessTest(build().withItem(HELMET, 2)
.withTime(1, 4), 2000, 2, RAPPELLING);
}
@Test
public void testTwoItemStress() {
queueProcessTest(build().withItem(LIFE_JACKET, 2)
.withItem(HELMET, 2).withTime(1, 4), 2000, 2, RAFTING);
}
@Test
public void testTwoItemUnbalancedStress() {
queueProcessTest(build().withItem(LIFE_JACKET, 3)
.withItem(HELMET, 2).withTime(1, 4), 2000, 2, RAFTING);
}
}
<file_sep>/Makefile
#Esse makefile sรณ serve para fazer o arquivo a ser enviado pro moodle
.PHONY: all package verify compile submission clean
MVN=mvn
ifeq ($(wildcard .mvn mvnw), .mvn mvnw)
MVN=./mvnw
endif
$(shell chmod +x mvnw || true)
all: package
package:
$(MVN) -DskipTests=true package
verify:
$(MVN) verify
compile:
$(MVN) compile
# Prepara .tar.gz pra submissรฃo no moodle
# Note que antes de preparar o tar.gz, รฉ feito um clean
submission: clean
$(MVN) verify || true
@echo "Envio deve ser feito via git push!!!!"
# Limpa binรกrios
clean:
rm -fr target dependency-reduced-pom.xml
<file_sep>/README.md
# INE5410 -- T2 -- 2019.2
Descriรงรฃo completa no [moodle](https://moodle.ufsc.br/mod/assign/view.php?id=1907944)
<file_sep>/src/test/java/br/ufsc/ine5410/floripaland/AttractionQueueingTest.java
package br.ufsc.ine5410.floripaland;
import br.ufsc.ine5410.floripaland.mocks.MockPerson;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static br.ufsc.ine5410.floripaland.Attraction.Type.FERRIS_WHEEL;
import static org.junit.Assert.*;
public class AttractionQueueingTest extends AttractionTestBase {
@Test
public void testGroupSize() {
attraction = build().withGroupSize(2).getOpen(FERRIS_WHEEL);
MockPerson bob = new MockPerson(false), alice = new MockPerson(false);
attraction.enter(alice);
assertFalse(alice.waitForEnterAttraction(200));
assertEquals(0, alice.getExitCalls());
assertEquals(0, alice.getExitQueueCalls());
attraction.enter(bob);
assertTrue(bob.waitForEnterAttraction(200));
assertTrue(alice.waitForEnterAttraction(200));
assertTrue(bob.waitForExitAttraction(100));
assertTrue(alice.waitForExitAttraction(100));
assertEquals(0, alice.getExitQueueCalls());
assertEquals(0, bob.getExitQueueCalls());
}
@Test
public void testGroupCapacity() {
attraction = build().withGroupCapacity(2).withTime(400).getOpen(FERRIS_WHEEL);
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
personList.add(new MockPerson(false));
attraction.enter(personList.get(i));
}
assertTrue(personList.get(1).waitForEnterAttraction(100));
assertEquals(1, personList.get(0).getEnterCalls());
assertFalse(personList.get(2).waitForEnterAttraction(100));
assertTrue(personList.get(2).waitForEnterAttraction(400));
assertTrue(personList.get(2).waitForExitAttraction(500));
for (MockPerson person : personList)
assertEquals("person=" + person, 0, person.getExitQueueCalls());
}
@Test
public void testPremiumHasPriority() {
attraction = build().withGroupCapacity(1).withTime(200).getOpen(FERRIS_WHEEL);
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 4; i++) {
personList.add(new MockPerson(i > 2));
attraction.enter(personList.get(i));
}
assertTrue(personList.get(3).waitForEnterAttraction(200+100));
assertFalse(personList.get(2).waitForEnterAttraction(200*2-100));
assertTrue(personList.get(2).waitForEnterAttraction(200*3+100));
assertTrue(personList.get(2).waitForExitAttraction(200+100));
for (MockPerson person : personList) {
String msg = "person=" + person;
assertEquals(msg, 1, person.getEnterCalls());
assertEquals(msg, 1, person.getExitCalls());
assertEquals(msg, 0, person.getExitQueueCalls());
}
}
@Test
public void testExpelledFromQueue() throws InterruptedException {
attraction = build().withGroupCapacity(1).withTime(300).getOpen(FERRIS_WHEEL);
MockPerson alice = new MockPerson(), bob = new MockPerson();
assertTrue(attraction.enter(alice));
assertTrue(attraction.enter(bob));
assertTrue(alice.waitForEnterAttraction(100));
assertFalse(bob.waitForEnterAttraction(100));
attraction.closeAttraction();
assertEquals(1, alice.getExitCalls());
assertEquals(1, bob.getExitQueueCalls());
}
public void stressTest(Builder builder, int groupSize) {
attraction = builder.withTime(1, 2).withGroupSize(groupSize).getOpen(FERRIS_WHEEL);
List<MockPerson> list = new ArrayList<>(2000*groupSize);
for (int i = 0; i < 2000; i++) {
list.add(new MockPerson(i % 5 == 0));
attraction.enter(list.get(i));
}
for (MockPerson person : list)
person.waitForExitAttraction(Integer.MAX_VALUE);
assertEquals(0, list.stream().filter(p -> p.getEnterCalls() != 1).count());
assertEquals(0, list.stream().filter(p -> p.getExitCalls() != 1).count());
assertEquals(0, list.stream().filter(p -> p.getExitQueueCalls() > 0).count());
}
@Test(timeout = 2000*10)
public void testStressSingletonsNoSafetyItems() {
stressTest(build(), 1);
}
@Test(timeout = 2000*2*10)
public void testStressPairsNoSafetyItems() {
stressTest(build(), 2);
}
@Test(timeout = 1000*10)
public void testConcurrentlyEnter() throws InterruptedException {
attraction = build().withTime(1).withGroupSize(2).getOpen(FERRIS_WHEEL);
List<MockPerson> list = new ArrayList<>(6000);
ExecutorService exec = Executors.newCachedThreadPool();
try {
for (int i = 0; i < 6000; i++) {
MockPerson person = new MockPerson(i % 5 == 0);
list.add(person);
exec.submit(() -> attraction.enter(person));
}
} finally {
exec.shutdown();
exec.awaitTermination(500, TimeUnit.MILLISECONDS);
}
for (MockPerson person : list)
person.waitForExitAttraction(Integer.MAX_VALUE);
assertEquals(0, list.stream().filter(p -> p.getEnterCalls() != 1).count());
assertEquals(0, list.stream().filter(p -> p.getExitCalls() != 1).count());
assertEquals(0, list.stream().filter(p -> p.getExitQueueCalls() > 0).count());
}
}
<file_sep>/src/main/java/br/ufsc/ine5410/floripaland/movement/InternManager.java
package br.ufsc.ine5410.floripaland.movement;
import br.ufsc.ine5410.floripaland.safety.SafetyItem;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.concurrent.Semaphore;
import static java.lang.Math.*;
public class InternManager {
private Semaphore idleInterns;
private final int hiredInterns;
public InternManager(int interns) {
this.hiredInterns = interns;
this.idleInterns = new Semaphore(interns);
}
public void transport(@Nonnull Collection<SafetyItem> items,
@Nonnull Point from, @Nonnull Point to) {
idleInterns.acquireUninterruptibly();
try {
Thread.sleep((int)floor(from.distanceTo(to)));
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // preserva estado de interrompida
} finally {
idleInterns.release();
}
}
public int getHiredInterns() {
return hiredInterns;
}
}
<file_sep>/src/main/java/br/ufsc/ine5410/floripaland/mocks/TimedVisitor.java
package br.ufsc.ine5410.floripaland.mocks;
import br.ufsc.ine5410.floripaland.AttractionVisitor;
import br.ufsc.ine5410.floripaland.Person;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class TimedVisitor implements AttractionVisitor {
private int minTime, maxTime;
private @Nonnull ScheduledExecutorService executor;
private @Nonnull AtomicInteger visiting = new AtomicInteger(0);
private @Nonnull AtomicInteger maxVisiting = new AtomicInteger(0);
public TimedVisitor(int minTime, int maxTime) {
Preconditions.checkArgument(maxTime >= minTime);
this.minTime = minTime;
this.maxTime = maxTime;
RejectedExecutionHandler rejection = new ThreadPoolExecutor.CallerRunsPolicy();
executor = new ScheduledThreadPoolExecutor(0, rejection);
}
public TimedVisitor() {
this(1, 1);
}
public void reset() {
Preconditions.checkState(!hasVisitor());
Preconditions.checkState(!executor.isShutdown());
visiting.set(0);
maxVisiting.set(0);
}
public @Nonnull ScheduledExecutorService getExecutor() {
return executor;
}
public boolean hasVisitor() {
return visiting.get() > 0;
}
public int maxVisitors() {
return maxVisiting.get();
}
@Override
public void visit(@Nonnull Collection<Person> groupWearingSafetyItems,
@Nonnull Consumer<Collection<Person>> exitCallback) {
Stopwatch sw = Stopwatch.createStarted();
int observed = visiting.incrementAndGet();
for (int current = maxVisiting.get(); observed > current; current = maxVisiting.get()) {
if (maxVisiting.compareAndSet(current, observed))
break;
}
int duration = minTime + (int) Math.round(Math.random() * (maxTime - minTime));
executor.schedule(() -> {
visiting.decrementAndGet();
exitCallback.accept(groupWearingSafetyItems);
}, duration, MILLISECONDS);
}
@Override
public void close() {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
<file_sep>/src/test/java/br/ufsc/ine5410/floripaland/SafetyItemsBalancerTest.java
package br.ufsc.ine5410.floripaland;
import br.ufsc.ine5410.floripaland.mocks.MockPerson;
import br.ufsc.ine5410.floripaland.safety.SafetyItem;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static br.ufsc.ine5410.floripaland.Attraction.Type.*;
import static br.ufsc.ine5410.floripaland.safety.SafetyItem.Type.HELMET;
import static br.ufsc.ine5410.floripaland.safety.SafetyItem.Type.LIFE_JACKET;
import static org.junit.Assert.*;
public class SafetyItemsBalancerTest extends AttractionTestBase {
@Test
public void testTwoAttractionStealAll() {
Builder builder = build().withTime(20);
Attraction r = builder.withItem(HELMET, 0).getOpen(RAPPELLING);
Attraction f = builder.withItem(HELMET, 3).getOpen(FERRIS_WHEEL);
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 50; i++) {
personList.add(new MockPerson());
assertTrue("i="+i, f.enter(personList.get(i)));
}
assertTrue(personList.get(49).waitForExitAttraction((20*50)/3 + 100));
checkPersonList(personList);
personList.clear();
for (int i = 0; i < 50; i++) {
personList.add(new MockPerson().withRequiredItems(HELMET));
assertTrue("i="+i, r.enter(personList.get(i)));
}
// r deve receber os capacetes em f
assertTrue(personList.get(49).waitForExitAttraction((50*20) / 3 + 200));
checkPersonList(personList);
// hรก um ponto onde r pega todos os capacetes
assertEquals(3, visitors.get(0).maxVisitors());
}
@Test
public void testDistributeInEqualDemand() {
Builder builder = build().withGroupCapacity(10).withTime(50);
Attraction[] r = {
builder.withItem(HELMET, 0).getOpen(RAPPELLING),
builder.withItem(HELMET, 10).getOpen(RAPPELLING)
};
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 50; i++) {
personList.add(new MockPerson().withRequiredItems(HELMET));
assertTrue("i="+i, r[i%2].enter(personList.get(i)));
}
int timeout = (50 * 50) + 100;
assertTrue(personList.get(49).waitForExitAttraction(timeout));
assertTrue(personList.get(48).waitForExitAttraction(timeout));
checkPersonList(personList);
assertTrue(visitors.get(0).maxVisitors() >= 3);
assertTrue(visitors.get(1).maxVisitors() >= 3);
}
@Test
public void testDistributeInEqualDemandDifferentNeeds() {
Builder builder = build().withGroupCapacity(10).withTime(50)
.withItem(HELMET, 5).withItem(LIFE_JACKET, 5);
Attraction[] r = {
builder.withItem(HELMET, 5).getOpen(RAPPELLING),
builder.withItem(HELMET, 5).getOpen(FERRIS_WHEEL),
builder.withItem(HELMET, 5).getOpen(RAFTING),
builder.withItem(HELMET, 5).getOpen(BANANA_BOAT)
};
List<MockPerson> personList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
List<SafetyItem.Type> required = r[i % 4].getType().getRequiredSafetyItems();
personList.add(new MockPerson().withRequiredItems(required));
assertTrue("i="+i, r[i%4].enter(personList.get(i)));
}
int timeout = (100 * 50) + 100;
for (int i = 96; i < 100; i++)
assertTrue("i="+i, personList.get(i).waitForExitAttraction(timeout));
checkPersonList(personList);
for (int i = 0; i < 4; i++)
assertTrue("i=" + i, visitors.get(i).maxVisitors() >= 3);
}
private void checkPersonList(List<MockPerson> personList) {
assertEquals(0, personList.stream().filter(p -> p.getEnterCalls() == 0).count());
assertEquals(0, personList.stream().filter(p -> p.getEnterCalls() > 1).count());
assertEquals(0, personList.stream().filter(p -> p.getExitCalls() == 0).count());
assertEquals(0, personList.stream().filter(p -> p.getExitCalls() > 1).count());
List<String> errors = personList.stream().flatMap(p -> p.getWearErrors().stream())
.collect(Collectors.toList());
assertEquals(Collections.emptyList(), errors);
}
}
<file_sep>/src/main/java/br/ufsc/ine5410/floripaland/mocks/MockPerson.java
package br.ufsc.ine5410.floripaland.mocks;
import br.ufsc.ine5410.floripaland.Attraction;
import br.ufsc.ine5410.floripaland.Person;
import br.ufsc.ine5410.floripaland.safety.SafetyItem;
import com.google.common.base.Stopwatch;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import static java.lang.String.format;
public class MockPerson implements Person {
private static AtomicInteger nextId = new AtomicInteger(1);
private boolean premium;
private int id;
private int exitQueueCalls = 0, enterCalls = 0, exitCalls = 0;
private @Nonnull Set<SafetyItem.Type> requiredItems = new HashSet<>();
private @Nonnull Set<SafetyItem> wearing = new HashSet<>();
private @Nonnull List<String> wearErrors = new ArrayList<>();
public MockPerson() {
this(false);
}
public MockPerson(boolean premium) {
this.id = nextId.getAndIncrement();
this.premium = premium;
}
public synchronized @Nonnull
MockPerson withRequiredItems(SafetyItem.Type... items) {
return withRequiredItems(Arrays.asList(items));
}
public synchronized @Nonnull
MockPerson withRequiredItems(Collection<SafetyItem.Type> types) {
requiredItems.clear();
requiredItems.addAll(types);
return this;
}
@Override
public boolean isPremium(@Nonnull Attraction.Type attractionType) {
return premium;
}
@Override
public synchronized void exitQueue(@Nonnull Attraction attraction) {
++exitQueueCalls;
notifyAll();
}
@Override
public synchronized void notifyEnterAttraction(@Nonnull Attraction a) {
++enterCalls;
for (SafetyItem.Type type : requiredItems) {
long count = wearing.stream().filter(i -> i.getType() == type).count();
if (count == 0)
wearErrors.add(format("%s entered %s not wearing a %s", this, a, type));
if (count > 1)
wearErrors.add(format("%s entered %s wearing %d %ss", this, a, count, type));
}
notifyAll();
}
@Override
public synchronized void notifyExitAttraction(@Nonnull Attraction attraction) {
++exitCalls;
notifyAll();
}
public int getEnterCalls() {
return enterCalls;
}
public int getExitCalls() {
return exitCalls;
}
public int getExitQueueCalls() {
return exitQueueCalls;
}
private synchronized boolean waitForCall(int milliseconds, int number,
@Nonnull Supplier<Integer> counter) {
Stopwatch sw = Stopwatch.createStarted();
while (counter.get() < number) {
long available = milliseconds - sw.elapsed(TimeUnit.MILLISECONDS);
try {
if (available <= 0)
return false;
wait(available);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
return true;
}
public boolean waitForExitAttraction(int milliseconds) {
return waitForExitAttraction(milliseconds, 1);
}
public boolean waitForExitAttraction(int milliseconds, int number) {
return waitForCall(milliseconds, number, () -> exitCalls);
}
public boolean waitForEnterAttraction(int milliseconds) {
return waitForEnterAttraction(milliseconds, 1);
}
public boolean waitForEnterAttraction(int milliseconds, int number) {
return waitForCall(milliseconds, number, () -> enterCalls);
}
public boolean waitForExitQueue(int milliseconds) {
return waitForExitQueue(milliseconds, 1);
}
public boolean waitForExitQueue(int milliseconds, int number) {
return waitForCall(milliseconds, number, () -> exitQueueCalls);
}
@Override
public void wear(@Nonnull SafetyItem item) {
if (item.isInUse() && !wearing.contains(item)) {
wearErrors.add(format("Tried to wear(%s), already in use by another Person", item));
} else if (!wearing.add(item)) {
wearErrors.add(format("Tried to wear(%s), but is already wearing it", item));
} else {
item.use(this);
}
}
@Override
public void takeOff(@Nonnull SafetyItem item) {
if (!wearing.remove(item)) {
wearErrors.add(format("Tried to takeOff(%s), but is not wearing it", item));
} else if (item.getPersonWearing() != null && item.getPersonWearing() != this) {
wearErrors.add(format("%s tried to takeOff(%s), being used by %s",
this, item, item.getPersonWearing()));
} else {
item.takeOff();
}
}
public int getId() {
return id;
}
public @Nonnull Set<SafetyItem> getWearing() {
return wearing;
}
public @Nonnull List<String> getWearErrors() {
return wearErrors;
}
@Override
public String toString() {
return format("Person(%d)", id);
}
public synchronized void reset() {
wearErrors.clear();
wearing.clear();
exitQueueCalls = 0;
enterCalls = 0;
exitCalls = 0;
}
}
|
ffe2d6782a2b6121c21f9481bac3e2582c205fa0
|
[
"Markdown",
"Java",
"Makefile"
] | 8 |
Java
|
alexishuf/ine5410-t2-2019.2-initial
|
a275188538c5fe9e13bbcafdff9aa6407548b504
|
149f32ba587794a51cddd66418cb2c177de8dd79
|
refs/heads/master
|
<repo_name>ivan-leschinsky/nbrb-api<file_sep>/spec/nbrb-api_spec.rb
#encoding: utf-8
require 'spec_helper'
describe Nbrb::Api do
subject { Nbrb::Api }
describe "currencies rates" do
describe ".daily_rates" do
let(:simple_response) { fixture('response/daily_rates_simple.xml') }
let(:scaled_response) { fixture('response/daily_rates_scaled.xml') }
it 'returns properly structured hash for each currency rate' do
savon.expects(:ex_rates_daily).with(message: {on_date: DateTime.now}).returns(simple_response)
#intentionally failing
expect(subject.daily_rates).to eql(1)
end
end
end
describe ".call" do
it 'throws OperationNotFound exception on invalid call' do
expect { subject.call(:asdasdads) }.to raise_exception Nbrb::Api::OperationNotFound
end
it 'delegates the call to soap client' do
sample_operation = subject.client.operations.first
subject.client.should_receive(:call).with(sample_operation, anything)
subject.call(sample_operation)
end
end
end
|
c232f9b517c5aa3957b3bb81f946075451957a4b
|
[
"Ruby"
] | 1 |
Ruby
|
ivan-leschinsky/nbrb-api
|
1f7b12932afc45c1e23227e328b71f581f42323c
|
629b645958ef1e45371e8fb631e9f89396fd5712
|
refs/heads/master
|
<repo_name>TheCrappiest/CommandCore<file_sep>/src/com/thecrappiest/cmdcore/item/ItemBuilder.java
package com.thecrappiest.cmdcore.item;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.thecrappiest.cmdcore.CommandCore;
import com.thecrappiest.cmdcore.methods.MessageUtil;
import com.thecrappiest.cmdcore.methods.NBTUtil;
public class ItemBuilder {
@SuppressWarnings("deprecation")
public static ItemStack createItem(Player p, ConfigurationSection cs, Map<String, String> placeholders) {
Material mat = Material.BARRIER;
String name = "";
List<String> lore = new ArrayList<>();
boolean glow = false;
boolean hideAttributes = false;
short durability = 0;
MessageUtil msgUtil = MessageUtil.utils();
for (String pathKey : cs.getKeys(false)) {
String value = cs.getString(pathKey);
switch (pathKey) {
case "Material":
if (Material.valueOf(value.toUpperCase()) != null) {
mat = Material.valueOf(value.toUpperCase());
}
break;
case "Name":
name = value.equals("") ? null : msgUtil.color(msgUtil.addPlaceHolders(p, value));
break;
case "Lore":
if (!value.equals("")) {
List<String> loreEdit = new ArrayList<>();
for (String loreLine : cs.getStringList(pathKey)) {
loreEdit.add(msgUtil.color(loreLine));
}
loreEdit = msgUtil.addPlaceHolders(p, loreEdit);
lore = loreEdit;
}
break;
case "Glow":
if (CommandCore.glow != null) {
glow = cs.getBoolean(pathKey);
}
break;
case "HideAttributes":
hideAttributes = cs.getBoolean(pathKey);
break;
case "Durability":
durability = Integer.valueOf(cs.getString(pathKey)).shortValue();
break;
}
}
ItemStack item = new ItemStack(mat);
if (cs.contains("Skull")) {
item = SkullCreation.getInstance().createSkullItem(msgUtil.addPlaceHolders(p, cs.getString("Skull")));
}
ItemMeta itemMeta = item.getItemMeta();
if (name == null) {
itemMeta.setDisplayName(msgUtil.color("&f"));
} else {
itemMeta.setDisplayName(name);
}
if (!lore.isEmpty()) {
itemMeta.setLore(lore);
}
if (glow) {
itemMeta.addEnchant(CommandCore.glow, 1, true);
}
if (hideAttributes) {
itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
}
item.setItemMeta(itemMeta);
if (cs.contains("Enchants")) {
item = addEnchants(cs.getStringList("Enchants"), item);
}
String materialName = mat.name();
if (materialName.contains("LEATHER") && (materialName.contains("HELMET") || materialName.contains("CHESTPLATE")
|| materialName.contains("LEGGINGS") || materialName.contains("BOOTS"))) {
if (cs.contains("Color")) {
item = ArmorColor.setColor(item, cs.getString("Color"));
}
}
if (cs.contains("NBTTags")) {
for (String NBTKey : cs.getConfigurationSection("NBTTags").getKeys(true)) {
item = NBTUtil.getNBTUtils().addNBTTagString(item, NBTKey, cs.getString("NBTTags." + NBTKey), null);
}
}
if (durability > 0) {
item.setDurability(durability);
}
return item;
}
@SuppressWarnings("deprecation")
public static ItemStack createItem(Player p, String data, Map<String, String> placeholders) {
Material mat = Material.BARRIER;
String name = null;
List<String> lore = null;
boolean glow = false;
boolean hideAttributes = false;
List<String> enchants = null;
String color = null;
short durability = 0;
MessageUtil msgUtil = MessageUtil.utils();
ItemStack item = new ItemStack(Material.BARRIER);
ItemMeta itemMeta = item.getItemMeta();
JSONObject jsonData = null;
try {
jsonData = (JSONObject) new JSONParser().parse(data);
} catch (ParseException e) {
e.printStackTrace();
}
if (jsonData != null) {
for (Object entry : jsonData.keySet()) {
String key = String.valueOf(entry);
String value = String.valueOf(jsonData.get(key));
switch (key) {
case "Material":
if (Material.valueOf(value.toUpperCase()) != null) {
mat = Material.valueOf(value.toUpperCase());
item.setType(mat);
}
break;
case "Skull":
item = SkullCreation.instance.createSkullItem(msgUtil.addPlaceHolders(p, value));
itemMeta = item.getItemMeta();
break;
case "Name":
name = msgUtil.color(msgUtil.addPlaceHolders(p, value));
break;
case "Lore":
List<String> loreFromData = new ArrayList<>();
for (String line : value.split("\\|")) {
loreFromData.add(String.valueOf(msgUtil.color(msgUtil.addPlaceHolders(p, line))));
}
lore = loreFromData;
break;
case "Enchants":
List<String> enchantsFromData = new ArrayList<>();
for (String line : value.split(",")) {
enchantsFromData.add(line);
}
enchants = enchantsFromData;
break;
case "Glow":
if (glow) {
itemMeta.addEnchant(CommandCore.glow, 1, true);
}
break;
case "HideAttributes":
hideAttributes = Boolean.valueOf(value);
break;
case "Color":
color = value;
break;
case "Durability":
durability = Integer.valueOf(value).shortValue();
break;
}
}
}
if (name == null) {
itemMeta.setDisplayName(msgUtil.color("&f"));
} else {
itemMeta.setDisplayName(name);
}
if (lore != null && !lore.isEmpty()) {
itemMeta.setLore(lore);
}
if (glow) {
itemMeta.addEnchant(CommandCore.glow, 1, true);
}
if (hideAttributes) {
itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
}
item.setItemMeta(itemMeta);
if (enchants != null) {
item = addEnchants(enchants, item);
}
String materialName = mat.name();
if (materialName.contains("LEATHER") && (materialName.contains("HELMET") || materialName.contains("CHESTPLATE")
|| materialName.contains("LEGGINGS") || materialName.contains("BOOTS"))) {
if (color != null) {
item = ArmorColor.setColor(item, color);
}
}
if (durability > 0) {
item.setDurability(durability);
}
return item;
}
public static ItemStack addEnchants(List<String> enchants, ItemStack item) {
for (String eandl : enchants) {
String enchant = eandl.split("\\|")[0];
int level = Integer.valueOf(eandl.split("\\|")[1]);
if (Enchantment.getByKey(NamespacedKey.minecraft(enchant)) != null) {
item.addUnsafeEnchantment(Enchantment.getByKey(NamespacedKey.minecraft(enchant)), level);
}
}
return item;
}
}
<file_sep>/src/com/thecrappiest/cmdcore/objects/CustomizedCommand.java
package com.thecrappiest.cmdcore.objects;
import java.util.ArrayList;
import java.util.List;
public class CustomizedCommand {
private String base = null;
private List<String> actions = new ArrayList<>();
private double cost = 0;
private String invalidFunds = null;
private String permission = null;
private String noPermission = null;
public CustomizedCommand(String commandBase, List<String> commandActions, double commandCost, String invalidFunds,
String permNode, String noPerm) {
base = commandBase;
actions = commandActions;
cost = commandCost;
permission = permNode;
noPermission = noPerm;
}
public String getBase() {
return base;
}
public void setBase(String cmd) {
base = cmd;
}
public List<String> retrieveActions() {
return actions;
}
public void addAction(String action) {
actions.add(action);
}
public void addActions(List<String> actions) {
this.actions.addAll(actions);
}
public void clearActions() {
actions.clear();
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String retrieveInvalidFundsMessage() {
return invalidFunds;
}
public void setInvalidFundsMessage(String message) {
invalidFunds = message;
}
public String getPermission() {
return permission;
}
public void setPermission(String permNode) {
permission = permNode;
}
public String getNoPermMessage() {
return noPermission;
}
public void setNoPermMessage(String noPerm) {
noPermission = noPerm;
}
}
<file_sep>/src/com/thecrappiest/cmdcore/item/SkullCreation.java
package com.thecrappiest.cmdcore.item;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.thecrappiest.cmdcore.CommandCore;
public class SkullCreation {
private CommandCore cmdCore = CommandCore.getCMDCore();
public static SkullCreation instance;
public static SkullCreation getInstance() {
if (instance == null) {
instance = new SkullCreation();
}
return instance;
}
public Map<String, ItemStack> loadedSkulls = new HashMap<>();
public Map<String, String> savedTexturesData = new HashMap<>();
public Map<String, String> nameToUUID = new HashMap<>();
public String getUUIDFromUsername(String name) {
if (nameToUUID.containsKey(name)) {
return nameToUUID.get(name);
}
if (Bukkit.getPlayerExact(name) != null && Bukkit.getOnlineMode()) {
String uuid = Bukkit.getPlayerExact(name).getUniqueId().toString().replace("-", "");
nameToUUID.put(name, uuid);
return uuid;
}
try {
String UUIDJson = "";
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + name);
InputStream inputStream = url.openStream();
try {
UUIDJson = org.bukkit.craftbukkit.libs.org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8");
} catch (Exception e) {
cmdCore.getLogger().warning("[Mojang API] Error on data retrieving. (" + name + ")");
e.printStackTrace();
}
inputStream.close();
if (UUIDJson.isEmpty()) {
inputStream.close();
cmdCore.getLogger().warning("[Mojang API] Returned no data from the username. (" + name + ")");
return null;
}
JSONObject UUIDObject = (JSONObject) JSONValue.parseWithException(UUIDJson);
inputStream.close();
nameToUUID.put(name, UUIDObject.get("id").toString());
return UUIDObject.get("id").toString();
} catch (IOException | ParseException e) {
return null;
}
}
public String getPlayerSkullTexture(String uuid) {
if (savedTexturesData.containsKey(uuid)) {
return savedTexturesData.get(uuid);
}
try {
String UUIDJson = "";
URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
InputStream inputStream = url.openStream();
try {
UUIDJson = org.bukkit.craftbukkit.libs.org.apache.commons.io.IOUtils.toString(inputStream, "UTF-8");
} catch (Exception e) {
cmdCore.getLogger().warning("[Mojang API] Error on data uuid retrieving. (" + uuid + ")");
e.printStackTrace();
}
inputStream.close();
if (UUIDJson.isEmpty()) {
inputStream.close();
cmdCore.getLogger().warning("[Mojang API] Returned no data from the uuid. (" + uuid + ")");
return null;
}
JSONObject UUIDObject = (JSONObject) JSONValue.parseWithException(UUIDJson);
inputStream.close();
JSONArray properties = (JSONArray) UUIDObject.get("properties");
JSONObject propertiesArray = (JSONObject) properties.get(0);
String texturesvalue = propertiesArray.get("value").toString();
if (texturesvalue != null) {
savedTexturesData.put(uuid, texturesvalue);
return texturesvalue;
} else {
cmdCore.getLogger().warning("[Mojang API] No texture value found. (" + uuid + ")");
cmdCore.getLogger().warning("[Mojang API] Possible cause -> To many requests.");
return null;
}
} catch (ParseException | IOException e) {
cmdCore.getLogger().warning("[Mojang API] Could not open API Stream (" + uuid + ")");
cmdCore.getLogger().warning("[Mojang API] Possible causes;");
cmdCore.getLogger().warning(
"[Mojang API] To many API requests, SessionServer may be down, UUID got passed username check.");
return null;
}
}
@SuppressWarnings("deprecation")
public ItemStack createSkullItem(String username) {
ItemStack head = new ItemStack(Material.PLAYER_HEAD);
SkullMeta headMeta = (SkullMeta) head.getItemMeta();
if (username.startsWith("MHF")) {
headMeta.setOwner(username);
head.setItemMeta(headMeta);
return head;
}
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
byte[] encodedData = null;
if (username.toLowerCase().startsWith("base64:")) {
encodedData = username.split(":")[1].getBytes();
} else {
encodedData = getPlayerSkullTexture(getUUIDFromUsername(username)).getBytes();
}
if (encodedData != null) {
profile.getProperties().put("textures", new Property("textures", new String(encodedData)));
Field profileField = null;
try {
profileField = headMeta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(headMeta, profile);
} catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
head.setItemMeta(headMeta);
return head;
}
return head;
}
}
<file_sep>/src/com/thecrappiest/cmdcore/methods/Actions.java
package com.thecrappiest.cmdcore.methods;
import org.bukkit.Bukkit;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.thecrappiest.cmdcore.CommandCore;
import com.thecrappiest.cmdcore.item.ItemBuilder;
public class Actions {
public enum Action {
MESSAGE("message"),
BROADCAST("broadcast"),
BROADCAST_TITLE("title"),
BROADCAST_SUBTITLE("subtitle"),
BROADCAST_FULLTITLE("fulltitle"),
PLAYER_TITLE("playerTitle"),
PLAYER_SUBTITLE("playerSubtitle"),
PLAYER_FULLTITLE("playerFulltitle"),
HOTBARSLOT("hotbarSlot"),
CONSOLE_COMMAND("consoleCommand"),
PLAYER_COMMAND("playerCommand"),
PLAYER_CHAT("playerChat"),
CLOSE_INVENTORY("closeInventory"),
SEND_SERVER("sendServer"),
PLAY_SOUND("SOUND"),
GIVE_ITEM("giveItem");
private String action;
Action(String action) {
this.action = action;
}
public String getAction() {
return action;
}
public static Action getAction(String s) {
for (Action action : Action.values()) {
if(s.equalsIgnoreCase(action.getAction())) {
return action;
}
}
return null;
}
}
public static void runAction(Player p, String fullAction, String[] args) {
MessageUtil msgUtil = MessageUtil.utils();
if (!fullAction.startsWith("[")) {
return;
}
Action action = null;
String actionName = null;
if (fullAction.split(" ").length > 0) {
actionName = fullAction.split(" ")[0].replaceFirst("\\[", "").replaceFirst("]", "");
action = Action.getAction(actionName);
} else {
actionName = fullAction.split("]")[0].replaceFirst("\\[", "");
action = Action.getAction(actionName);
}
if (action == null) {
return;
}
String performString = msgUtil.addPlaceHolders(p,
modifyArgs(fullAction.replace("[" + actionName + "] ", "").replace("[" + actionName + "]", ""), args));
switch (action) {
case MESSAGE:
p.sendMessage(msgUtil.color(performString));
break;
case PLAYER_TITLE:
p.sendTitle(msgUtil.color(performString), "", 20, 50, 10);
break;
case PLAYER_SUBTITLE:
p.sendTitle("", msgUtil.color(performString), 20, 50, 10);
break;
case PLAYER_FULLTITLE:
p.sendTitle(msgUtil.color(performString).split("\\|")[0], msgUtil.color(performString).split("\\|")[1], 20,
50, 10);
break;
case PLAYER_COMMAND:
p.performCommand(performString);
break;
case PLAYER_CHAT:
p.chat(msgUtil.color(performString));
break;
case CLOSE_INVENTORY:
p.closeInventory();
break;
case PLAY_SOUND:
if (Sound.valueOf(performString) != null) {
p.playSound(p.getLocation(), Sound.valueOf(performString), 1.0F, 1.0F);
}
break;
case GIVE_ITEM:
CommandCore cmd = CommandCore.getCMDCore();
ItemStack item = null;
if (performString.startsWith("%")) {
String phItem = performString.replace("%", "");
if (cmd.getConfig().isSet("Place-Holder_Items." + phItem)) {
item = ItemBuilder.createItem(p,
cmd.getConfig().getConfigurationSection("Place-Holder_Items." + phItem), null);
}
} else {
item = ItemBuilder.createItem(p, performString, null);
}
if (item != null) {
if (p.getInventory().firstEmpty() == -1) {
p.getWorld().dropItemNaturally(p.getLocation(), item);
} else {
p.getInventory().addItem(item);
}
}
break;
case HOTBARSLOT:
p.getInventory().setHeldItemSlot(Integer.valueOf(performString));
break;
case BROADCAST:
Bukkit.broadcastMessage(msgUtil.color(performString));
break;
case BROADCAST_TITLE:
Bukkit.getOnlinePlayers().stream().forEach(player -> {
player.sendTitle(msgUtil.color(performString), "", 20, 50, 10);
});
break;
case BROADCAST_SUBTITLE:
Bukkit.getOnlinePlayers().stream().forEach(player -> {
player.sendTitle("", msgUtil.color(performString), 20, 50, 10);
});
break;
case BROADCAST_FULLTITLE:
Bukkit.getOnlinePlayers().stream().forEach(player -> {
player.sendTitle(msgUtil.color(performString).split("\\|")[0],
msgUtil.color(performString).split("\\|")[1], 20, 50, 10);
});
break;
case CONSOLE_COMMAND:
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), performString);
break;
case SEND_SERVER:
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(performString);
p.sendPluginMessage(CommandCore.getCMDCore(), "BungeeCord", out.toByteArray());
break;
}
}
private static String modifyArgs(String s, String[] args) {
if (args == null) {
return s;
}
if (args.length == 0) {
return s;
}
if (s.contains(" ")) {
for (int i = 0; i < args.length; i++) {
s = s.replace("%arg_" + (i + 1) + "%", args[i]);
}
} else {
if (s.equalsIgnoreCase("%arg_1%") && args.length > 0) {
s = s.replace("%arg_1%", args[0]);
}
}
if (s.contains("%arg_all%")) {
StringBuilder build = new StringBuilder();
for (String arg : args) {
build.append(arg).append(" ");
}
s = s.replace("%arg_all%", build.substring(0, build.length() - 1));
}
return s;
}
}
|
e10840120dba1f162d7965427c7f757c6fc8e3d8
|
[
"Java"
] | 4 |
Java
|
TheCrappiest/CommandCore
|
e55deb1e1e2b85156a0e62728c288a387a91c5ce
|
619b9df095d47963b80472598a284e7483fde391
|
refs/heads/master
|
<file_sep>"""
module to access RTC resources.
"""
import sys
import os
# flag to identify the path correction
is_arrow_path_adjusted = False
# RTC jars must add into path at first.
def fix_path():
global is_arrow_path_adjusted
if( not is_arrow_path_adjusted ):
arrow_lib = os.path.join(os.environ["ARROW_HOME"], "lib")
[ sys.path.append(os.path.join(arrow_lib, x))
for x in os.listdir(arrow_lib) if x.endswith(".jar") or
x.endswith(".zip")]
is_arrow_path_adjusted = True
fix_path()
import java.util.Date as Date
class RJC(object):
def __init__(self, repository_address, username, password):
self.repository_address = repository_address
self.username = username
self.password = <PASSWORD>
def login(self):
print self.repository_address
print Date()
if __name__ == "__main__":
rjc = RJC("https://hub.jazz.net/ccm01","bar","foo")
rjc.login()
<file_sep># JYTHON JAVA EXAMPLE
## Usage
shoot PYTHON_FILE
example
shoot modules/entry.py
## Project
run jython with jvm and fix classpath so python script can import java Lib
check out *modules/entry.py* for more info.
All jar should put under *lib* .
## Lib
<file_sep>#! /bin/bash
###########################################
# RapidApps BVT Work Item Handler
###########################################
# constants
baseDir=$(cd `dirname "$0"`;pwd)
export ARROW_HOME=$baseDir
# functions
# is java home available
function verifyJavaHome(){
if [ ! -z $JAVA_HOME ]; then
echo "JAVA_HOME="$JAVA_HOME
java -version
if [ ! "$?" -eq 0 ]; then
echo "java is not in the path now."
exit 1;
fi
else
echo "set JAVA_HOME as an environment variable."
exit 2;
fi
}
function run(){
verifyJavaHome
echo "execute your script ..."
java -jar $ARROW_HOME/lib/jython-standalone-2.5.3.jar $*
}
# main
[ -z "${BASH_SOURCE[0]}" -o "${BASH_SOURCE[0]}" = "$0" ] || return
run $*
|
ab239a70ebcd5b32e00c1f664e200df18eb46731
|
[
"Markdown",
"Python",
"Shell"
] | 3 |
Python
|
Samurais/jython-example
|
8a3b001030e91cc6c9983ade2b4c1130aab1b601
|
38d1e224c6b827a82b7f7d880e7e65b7feef9e20
|
refs/heads/main
|
<file_sep>package com.hrms.hrms.busniess.abstracts;
import java.util.List;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.Employers;
public interface EmployersService {
DataResult<List<Employers>> getAll();
Result add(Employers employers);
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts.jobDao;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.hrms.hrms.entities.concretes.jobs.Jobs;
public interface JobDao extends JpaRepository<Jobs, Integer> {
List<Jobs> getByStatus(boolean status);
List<Jobs> getByStatus(Sort sort,boolean status);
List<Jobs> getByEmployer_CompanyName(String companyName);
List<Jobs> getByEmployer_CompanyNameAndStatus(String companyName,boolean status);
@Transactional
@Modifying
@Query("Update Jobs set status=:status where id=:id")
void updateStatusById(@Param("status") boolean status,@Param("id") int id);
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts.userDao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hrms.hrms.entities.concretes.users.Employee;
public interface EmployeeDao extends JpaRepository<Employee, Integer>{
boolean existsEmployerByTcNo(String tcNo);
boolean existsEmployerByEmail(String email);
}
<file_sep>package com.hrms.hrms.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hrms.hrms.busniess.abstracts.jobService.CityService;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.jobs.City;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
@RestController
@RequestMapping("/api/cities")
public class CitiesController {
private CityService cityService;
@Autowired
public CitiesController(CityService cityService) {
super();
this.cityService = cityService;
}
@GetMapping("/getAll")
public DataResult<List<City>> getAll(){
return cityService.getAll();
}
@PostMapping("/add")
public Result add(@RequestBody City city) {
return cityService.add(city);
}
}
<file_sep>package com.hrms.hrms.entities.concretes.users;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.hrms.hrms.entities.abstracts.Users;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@EqualsAndHashCode(callSuper = false)
@PrimaryKeyJoinColumn(name="user_id")
@Table(name="employee")
public class Employee extends Users{
@NotNull
@Column(name="name")
private String name;
@NotNull
@Column(name="surname")
private String surname;
@NotNull
@Column(name="national_identity")
private String tcNo;
@NotNull
@Column(name="year_of_birth")
private int birthOfYear;
}
<file_sep>package com.hrms.hrms.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.hrms.hrms.busniess.abstracts.jobService.JobService;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.jobs.Jobs;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
@RestController
@RequestMapping(name="/api/jobs")
public class JobsController {
private JobService jobService;
@Autowired
public JobsController(JobService jobService) {
super();
this.jobService = jobService;
}
@GetMapping("/getAll")
public DataResult<List<Jobs>> getAll(){
return jobService.getAll();
}
@GetMapping("/getStatusTrue")
public DataResult<List<Jobs>> getStatusTrue(){
return jobService.getStatusTrue();
}
@GetMapping("/getStatusTrueSorted")
public DataResult<List<Jobs>> getStatusTrueSorted(){
return jobService.getStatusTrueSorted();
}
@GetMapping("/getAllCompanyJobs")
public DataResult<List<Jobs>> getAllCompanyJobs(@RequestBody String companyName){
return jobService.getAllCompanyJobs(companyName);
}
@GetMapping("/getCompanyJobs")
public DataResult<List<Jobs>> getCompanyJobs(@RequestBody String companyName){
return jobService.getCompanyJobs(companyName);
}
@PostMapping("/updateByStatus")
public Result updateByStatus(@RequestParam("jobsId") int jobsId, @RequestParam("status") boolean status){
return jobService.updateByStatus(jobsId, status);
}
@PostMapping("/add")
public Result add(@RequestBody Jobs jobs) {
return jobService.add(jobs);
}
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts.userDao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hrms.hrms.entities.concretes.users.Employers;
public interface EmployersDao extends JpaRepository<Employers, Integer>{
boolean existsEmployerByEmail(String email);
}
<file_sep>package com.hrms.hrms.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hrms.hrms.busniess.abstracts.userService.EmployersService;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.users.Employers;
@RestController
@RequestMapping("/api/employers")
public class EmployersController {
private EmployersService employerService;
@Autowired
public EmployersController(EmployersService employerService) {
super();
this.employerService = employerService;
}
@GetMapping("/getAllEmployers")
public DataResult<List<Employers>> getAllEmployers(){
return this.employerService.getAll();
}
@PostMapping("/addEmployer")
public Result add(@RequestBody Employers employers) {
return this.employerService.add(employers);
}
}
<file_sep>package com.hrms.hrms.busniess.abstracts.userService;
import java.rmi.RemoteException;
import java.util.List;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.users.Employee;
public interface EmployeeService {
DataResult<List<Employee>> getAll();
Result add(Employee employee);
}
<file_sep>package com.hrms.hrms.busniess.concretes;
import java.rmi.RemoteException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hrms.hrms.busniess.abstracts.EmployeeService;
import com.hrms.hrms.core.mernis.MernisControl;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.ErrorResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.core.utilities.results.SuccessDataResult;
import com.hrms.hrms.dataAccess.abstracts.EmployeeDao;
import com.hrms.hrms.entities.concretes.Employee;
import com.hrms.hrms.core.utilities.results.SuccessResult;
import com.hrms.hrms.core.verifications.abstracts.EmailVerificationService;
import com.hrms.hrms.core.verifications.concretes.EmailVerificationServiceImpl;
@Service
public class EmployeeServiceImpl implements EmployeeService{
private EmployeeDao employeeDao;
@Autowired(required = false)
private MernisControl mernisControl;
private EmailVerificationService emailVerificationService = new EmailVerificationServiceImpl();
@Autowired
public EmployeeServiceImpl(EmployeeDao employeeDao) {
super();
this.employeeDao = employeeDao;
}
@Override
public DataResult<List<Employee>> getAll() {
return new SuccessDataResult<List<Employee>>(this.employeeDao.findAll(),"Data listelendi");
}
private boolean mernis(Employee employee) {
try {
if(!mernisControl.checkMernis(Long.valueOf( employee.getTcNo() ) , employee.getName() , employee.getSurname() , employee.getBirthOfYear())) {
return false;
}
} catch (NumberFormatException | RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
@Override
public Result add(Employee employee){
if(checkNull(employee)) {
return new ErrorResult("Tรผm Alanlar Zorunludur.");
}
/*else if(mernis(employee)) {
return new ErrorResult("Kiลi bilgileri doฤru deฤil");
}*/
else if(this.employeeDao.existsEmployerByTcNo(employee.getTcNo())) {
return new ErrorResult("Tc Kimlik No Sisteme Kayฤฑtlฤฑ.");
}
else if(this.employeeDao.existsEmployerByEmail(employee.getEmail())) {
return new ErrorResult("Email Sisteme Kayฤฑtlฤฑ.");
}
else if(this.emailVerificationService.isVerified(employee.getEmail())) {
return new ErrorResult("Mail Doฤrulamasฤฑ Yapฤฑlamadฤฑ.");
}
else {
this.employeeDao.save(employee);
return new SuccessResult("Kiลi eklendi");
}
}
private boolean checkNull(Employee employee) {
if( employee.getEmail()==null || employee.getName()==null || employee.getPass() == null ||
employee.getPassAgain() == null || employee.getTcNo()==null || employee.getBirthOfYear()==0 ) {
return true;
}
return false;
}
}
<file_sep>package com.hrms.hrms.busniess.abstracts.userService;
import java.util.List;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.entities.concretes.users.Employers;
import com.hrms.hrms.entities.concretes.users.SystemPersonel;
public interface SystemPersonelService {
DataResult<List<SystemPersonel>> getAll();
Result add(SystemPersonel systemPersonel);
DataResult<List<Employers>> getNewEmployers();
Result setStatus(int employer_id, boolean status);
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts.userDao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hrms.hrms.entities.concretes.users.SystemPersonel;
public interface SystemPersonelDao extends JpaRepository<SystemPersonel, Integer>{
}
<file_sep>package com.hrms.hrms.busniess.concretes.userServiceImpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import com.hrms.hrms.busniess.abstracts.userService.SystemPersonelService;
import com.hrms.hrms.core.utilities.results.DataResult;
import com.hrms.hrms.core.utilities.results.Result;
import com.hrms.hrms.core.utilities.results.SuccessDataResult;
import com.hrms.hrms.core.utilities.results.SuccessResult;
import com.hrms.hrms.dataAccess.abstracts.userDao.EmployersDao;
import com.hrms.hrms.dataAccess.abstracts.userDao.SystemPersonelDao;
import com.hrms.hrms.entities.concretes.users.Employers;
import com.hrms.hrms.entities.concretes.users.SystemPersonel;
@Service
public class SystemPersonelServiceImpl implements SystemPersonelService {
private SystemPersonelDao systemPersonelDao;
private EmployersDao employersDao;
@Autowired
public SystemPersonelServiceImpl(SystemPersonelDao systemPersonelDao, EmployersDao employersDao) {
super();
this.systemPersonelDao = systemPersonelDao;
this.employersDao = employersDao;
}
@Override
public DataResult<List<SystemPersonel>> getAll() {
return new SuccessDataResult<List<SystemPersonel>>(this.systemPersonelDao.findAll(), "Sistem personelleri listelendi");
}
@Override
public Result add(SystemPersonel systemPersonel) {
this.systemPersonelDao.save(systemPersonel);
return new SuccessResult("Sistem personeli kaydedildi");
}
public DataResult<List<Employers>> getNewEmployers(){
// Servisten mi รงekmek gerekiyor yoksa daodan mฤฑ sorulacak!!
List<Employers> employers = employersDao.findAll();
List<Employers> newEmployers = new ArrayList<Employers>();
for(Employers employer : employers) {
if(employer.getStatus()==null) {
newEmployers.add(employer);
}
}
return new SuccessDataResult<List<Employers>>(newEmployers, "Yeni iลverenler getirildi.");
}
@Override
public Result setStatus(int employer_id, boolean status) {
/*List<Employers> employers = employersDao.findAll();
for(Employers employer : employers) {
if(employer.getId() == employer_id) {
employer.setStatus(status);
}
}*/
/*List<Employers> employers = employersDao.findByStatus(status);
System.out.println(employers);*/
return null;
}
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hrms.hrms.entities.concretes.Employers;
public interface EmployersDao extends JpaRepository<Employers, Integer>{
boolean existsEmployerByEmail(String email);
}
<file_sep>package com.hrms.hrms.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import com.hrms.hrms.entities.concretes.Employee;
public interface EmployeeDao extends JpaRepository<Employee, Integer>{
boolean existsEmployerByTcNo(String tcNo);
boolean existsEmployerByEmail(String email);
}
|
d1d4bfb9a18b06eeb338cdd66b7dbe453d3e2806
|
[
"Java"
] | 15 |
Java
|
AnLDemirci/JavaKampHrms
|
063e0863305e6681a073e3ea9c73f2f051779e69
|
e78172637008e5b5bb7c86c702b5e498dbaaca3d
|
refs/heads/main
|
<file_sep>import React, { useCallback } from 'react'
import { useEffect } from 'react';
import { useState } from 'react';
import { Main } from './components/Main';
import firebase from './firebase'
export const App = () => {
const db = firebase.firestore();
return (
<React.Fragment>
<Main />
</React.Fragment>
)
}
|
c13e5ca706d5d7be39668d897279ca4226fa0dbd
|
[
"JavaScript"
] | 1 |
JavaScript
|
drea713/ReactJS_Marvel
|
f6f06bd4d34f918a2febaa86ad4302d0a0f83a9c
|
3aa0a385ce82c5abccb3dadc7b78142d6d77825c
|
refs/heads/main
|
<file_sep>jdbc.driverClassName=org.h2.Driver
jdbc.dialect=org.hibernate.dialect.H2Dialect
jdbc.databaseurl=jdbc:h2:mem:testdb
jdbc.username=sa
jdbc.password=<PASSWORD><file_sep># phase3project
phase3 project -- Sporty Shoes E Commerce Web Site
Build the WAR File
$$$$ cd phase3project
This will build the war file in the target directory.
$$$$ mvn clean install
Deploy the war to a tomcat server
$$$ cd tomcat/webapps
$$$ cp /phase3project/targer/SportyShoes.war .
start the tomcat server
$$$ bin/catalina.sh start
Access the webapp in the below url in a browser:
Admin Screen :
http://localhost:8080/SportyShoes/adminlogin
User Screen
http://localhost:8080/SportyShoes/login
HAPPY CODING !!!
<file_sep>package com.ecommerce.dao;
import com.ecommerce.dto.ProductDTO;
import com.ecommerce.entity.Product;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.hibernate.transform.ResultTransformer;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
@Repository
@Component
public class ProductDAO {
@Autowired
private SessionFactory sessionFactory;
@SuppressWarnings("unchecked")
public Product getProductById(long id) {
String strId = String.valueOf(id);
List<Product> list = this.sessionFactory.getCurrentSession().createQuery("from Product where id=" + strId).list();
if (list.size() > 0)
return (Product) list.get(0);
else
return null;
}
@SuppressWarnings("unchecked")
public void updateProduct(Product product) {
String sql = "";
if (product.getID() == 0)
this.sessionFactory.getCurrentSession().save(product);
else if (product.getID() > 0) {
sql = "update Product set name=:name, price=:price, category_id=:category_id where " +
" ID=:id";
Query query = this.sessionFactory.getCurrentSession().createQuery(sql);
query.setParameter("name", product.getName());
query.setParameter("price", product.getPrice());
query.setParameter("category_id", product.getCategoryId());
query.setParameter("id", product.getID());
query.executeUpdate();
}
}
@SuppressWarnings("unchecked")
public void deleteProduct(long id) {
// delete all purchase items for this product before deleting this product
// Pending:Purchase total is not updated in the purchase total - it shows the old value
String sql = "";
sql = "delete from PurchaseItem where product_id=:id";
Query query = this.sessionFactory.getCurrentSession().createQuery(sql);
query.setParameter("id", id);
sql = "delete from Product where ID=:id";
query = this.sessionFactory.getCurrentSession().createQuery(sql);
query.setParameter("id", id);
query.executeUpdate();
}
@SuppressWarnings("unchecked")
public List<Product> getAllProducts() {
List<Product> list = this.sessionFactory.getCurrentSession().createQuery("from Product order by name").list();
return list;
}
public List<ProductDTO> getAllProductsWithJoin() {
String sql = "SELECT p.ID, p.name, p.price, p.date_added, c.name as category from eproduct p, category c where p.category_id=c.ID order by p.name";
SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);
List list = query.setResultTransformer(new ResultTransformer() {
@Override
public Object transformTuple(
Object[] tuple,
String[] aliases) {
return new ProductDTO(
(BigInteger) tuple[0], (String) tuple[1], (BigDecimal) tuple[2], (Date) tuple[3], (String) tuple[4]
);
}
@Override
public List transformList(List tuples) {
return tuples;
}
}).list();
return list;
}
public List<ProductDTO> getAllProducts(String pname, String cname) {
String sql = "SELECT p.ID, p.name, p.price, p.date_added, c.name as category from eproduct p, category c where p.category_id=c.ID order by p.name";
if ((pname != null && !pname.isEmpty()) && (cname != null && !cname.isEmpty()))
sql = "SELECT p.ID, p.name, p.price, p.date_added, c.name as category from eproduct p, category c where p.category_id=c.ID and p.name like '%" + pname + "%' c.name like '%" + cname + "%' order by p.name";
else if ((pname != null && !pname.isEmpty()) && (cname == null || cname.isEmpty()))
sql = "SELECT p.ID, p.name, p.price, p.date_added, c.name as category from eproduct p, category c where p.category_id=c.ID and p.name like '%" + pname + "%' order by p.name";
else if ((pname == null || pname.isEmpty()) && (cname != null && !cname.isEmpty()))
sql = "SELECT p.ID, p.name, p.price, p.date_added, c.name as category from eproduct p, category c where p.category_id=c.ID and c.name like '%" + cname + "%' order by p.name";
SQLQuery query = this.sessionFactory.getCurrentSession().createSQLQuery(sql);
List list = query.setResultTransformer(new ResultTransformer() {
@Override
public Object transformTuple(
Object[] tuple,
String[] aliases) {
return new ProductDTO(
(BigInteger) tuple[0], (String) tuple[1], (BigDecimal) tuple[2], (Date) tuple[3], (String) tuple[4]
);
}
@Override
public List transformList(List tuples) {
return tuples;
}
}).list();
return list;
}
}
<file_sep>package com.ecommerce.dto;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
public class ProductDTO {
private BigInteger ID;
private String name;
private BigDecimal price;
private Date dateAdded;
private String category;
public ProductDTO(BigInteger ID, String name, BigDecimal price, Date dateAdded, String category) {
this.ID = ID;
this.name = name;
this.price = price;
this.dateAdded = dateAdded;
this.category = category;
}
public BigInteger getID() {
return this.ID;
}
public String getName() {
return this.name;
}
public BigDecimal getPrice() {
return this.price;
}
public Date getDateAdded() {
return this.dateAdded;
}
public void setID(BigInteger id) {
this.ID = id;
}
public void setName(String value) {
this.name = value;
}
public void setPrice(BigDecimal value) {
this.price = value;
}
public void setDateAdded(Date date) {
this.dateAdded = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
<file_sep>
/*
THIS DATA WILL BE LOADED ON THE STARTUP OF THE APPLICATION.
*/
/*
inserting an Admin user
username: admin
password: <PASSWORD>
*/
INSERT INTO admin(ID,admin_id,admin_pwd) VALUES (1,'admin', '<PASSWORD>')
/*
inserting product categories
*/
INSERT INTO category (ID,name) VALUES (1,'Category1')
INSERT INTO category (ID,name) VALUES (2,'Category2')
INSERT INTO category (ID,name) VALUES (3,'Category3')
INSERT INTO category (ID,name) VALUES (4,'Category4')
INSERT INTO category (ID,name) VALUES (5,'Category5')
/*
inserting products
*/
INSERT INTO eproduct (ID, category_id, date_added, name, price) VALUES (1, 1, now(), 'Product1', 1000)
INSERT INTO eproduct (ID, category_id, date_added, name, price) VALUES (2, 2, now(), 'Product2', 1001)
INSERT INTO eproduct (ID, category_id, date_added, name, price) VALUES (3, 3, now(), 'Product3', 1003)
INSERT INTO eproduct (ID, category_id, date_added, name, price) VALUES (4, 4, now(), 'Product4', 1004)
INSERT INTO eproduct (ID, category_id, date_added, name, price) VALUES (5, 1, now(), 'Product5', 1005)
<file_sep>package com.ecommerce.service;
import java.util.List;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.ecommerce.dao.ProductDAO;
import com.ecommerce.entity.Product;
import com.ecommerce.dto.ProductDTO;
@Component
public class ProductService {
@Autowired
private ProductDAO productDAO;
@Transactional
public Product getProductById(long id) {
return productDAO.getProductById(id);
}
@Transactional
public void updateProduct(Product product) {
productDAO.updateProduct(product);
}
@Transactional
public void deleteProduct(long id) {
productDAO.deleteProduct(id);
}
@Transactional
public List<Product> getAllProducts() {
return productDAO.getAllProducts();
}
@Transactional
public List<ProductDTO> getAllProductsWithJoin() {
return productDAO.getAllProductsWithJoin();
}
@Transactional
public List<ProductDTO> getAllProducts(String pname, String cname) {
return productDAO.getAllProducts(pname,cname);
}
}
|
6debdf71429fcda760af21f12587d1557ec86199
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 6 |
INI
|
sandycaltechpgp/phase3project
|
403907ae731db17e97e7db476d48b586572217fe
|
46870adcbac0f8f54c6f28af83ede9d1aa1f7cb8
|
refs/heads/main
|
<repo_name>woodpecker007/MicroserviceArchitecture<file_sep>/README.md
# MicroserviceArchitecture
ๅพฎๆๅก
|
8ed850371c26fa0bc179cdf2965eac294387af87
|
[
"Markdown"
] | 1 |
Markdown
|
woodpecker007/MicroserviceArchitecture
|
3628d8cab6654a7d13a91b1977a6befb3566cc97
|
6f24ee2e80d0d175c081199525d162ec40b2b980
|
refs/heads/main
|
<file_sep>package com.example;
public interface EnumGroup {
String getGroup();
String name();
public static EnumGroup valueOf(String v) {
// are we okay with this?
try {
return Group1.valueOf(v);
} catch (IllegalArgumentException e) {
return Group2.valueOf(v);
}
}
public enum Group1 implements EnumGroup {
A,B,C;
@Override
public String getGroup() {
return "Group1";
}
}
public enum Group2 implements EnumGroup {
D,E,F;
@Override
public String getGroup() {
return "Group2";
}
}
}
<file_sep>package com.example;
public enum BadEnum {
A, B, C;
private int hello;
public BadEnum setHello(int i) {
hello = i;
return this;
}
public int getHello() {
return hello;
}
}
<file_sep>package com.example;
import java.util.stream.Stream;
public enum EnumWithValue {
A("a"), B("b"), C("c");
private final String lowercase;
EnumWithValue(String lowercase) {
this.lowercase = lowercase;
}
public String getLowercase() {
return lowercase;
}
public static EnumWithValue find(String lowercase) {
return Stream.of(EnumWithValue.values()).filter(e -> e.lowercase.equals(lowercase)).findAny().orElse(null);
}
}
|
3cd3b0707300eee29a442ea91d04ef10bd0c3779
|
[
"Java"
] | 3 |
Java
|
voidlps/java-something
|
2f502f28f8735d292c843f7c1c0041ad7622b304
|
c0936fbe25167f79f730b2c9a9fce2699b656d12
|
refs/heads/master
|
<file_sep>from django.conf.urls import patterns, include, url
from views import *
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'trivia_final.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^registro/', registro_view, name="registro"),
url(r'^login/', login_view, name="login"),
url(r'^logout/', logout_view, name="logout"),
url(r'^actualisar/', actualisar_perfil_view, name="actualisar"),
url(r'^tema/', temas_view, name="tema"),
)<file_sep>from django.shortcuts import render,render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from form import *
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login , authenticate , logout
from django.contrib.auth.models import User
from models import *
import pdb
# Create your views here.
def temas_view(request):
if request.user.is_authenticated():
usuario=request.user
if request.method=="POST":
auxform=formulario_temas(request.POST)
#datouser=User.objects.get(username=usuario)
if auxform.is_valid():
#pdb.set_trace()
post = auxform.save(commit=False)
post.username = usuario
post.save()
return HttpResponseRedirect("/")
else:
auxform=formulario_temas()
return render_to_response("sistema/temas.html",{"form_tema":auxform},context_instance=RequestContext(request))
else:
return HttpResponse("no esta logeado")
def registro_view(request):
if request.method=="POST":
auxform=formulario_usuario_registro(request.POST)
if auxform.is_valid():
usuario=request.POST['username']
auxform.save()
usuariodato=User.objects.get(username=usuario)
#pdb.set_trace()
perfil=datos_adicionales_usuario.objects.create(username=usuariodato)
return HttpResponseRedirect("/")
else:
auxform = formulario_usuario_registro()
return render_to_response("usuario/registro.html",{"form_regi":auxform},context_instance=RequestContext(request))
def login_view(request):
if request.method=="POST":
auxform=AuthenticationForm(data=request.POST)
#pdb.set_trace()
if request.session['con']>3:
form_captcha=formulario_capcha(request.POST)
if form_captcha.is_valid():
pass
else:
datos={"form_login":auxform,"form_chaptcha":form_captcha}
return render_to_response("usuario/login.html",datos,context_instance=RequestContext(request))
if auxform.is_valid():
usuario=request.POST['username']
contrasena=request.POST['password']
acceso=authenticate(username=usuario,password=<PASSWORD>)
#pdb.set_trace()
if acceso is not None:
del request.session['con']
login(request,acceso)
return HttpResponseRedirect("/")
else:
request.session['con']=request.session['con']+1
auxcon=request.session["con"]
estado=True
mensaje="Error en los datos "+str(auxcon)
if auxcon>3:
estado=False
form_captcha=formulario_capcha()
return render_to_response("usuario/login.html",{"form_login":auxform,"estado":estado,"mensaje":mensaje,"form_chaptcha":form_captcha},context_instance=RequestContext(request))
else:
return render_to_response("usuario/login.html",{"form_login":auxform,"estado":estado,"mensaje":mensaje},context_instance=RequestContext(request))
else:
request.session['con']=0
auxform=AuthenticationForm()
return render_to_response("usuario/login.html",{"form_login":auxform},context_instance=RequestContext(request))
def logout_view(request):
logout(request)
return HttpResponseRedirect("/")
def actualisar_perfil_view(request):
if request.user.is_authenticated():
usuario=request.user
if request.method=="POST":
auxform=formulario_de_perfil(data=request.POST)
datouser=User.objects.get_by_natural_key(username=usuario)
datosadiuser=datos_adicionales_usuario.objects.get(username=datouser)
auxform=formulario_de_perfil(request.POST,request.FILES,instance=datosadiuser)
if auxform.is_valid():
auxform.save()
return HttpResponseRedirect("/")
else:
return HttpResponse("algo salio mal")
else:
auxform=formulario_de_perfil()
return render_to_response("usuario/actualisar.html",{"form_actua":auxform},context_instance=RequestContext(request))
else:
return HttpResponse("no esta logeado")<file_sep>from django.db import models
from thumbs import ImageWithThumbsField
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class datos_adicionales_usuario(models.Model):
username=models.OneToOneField(User, unique=True)
pais=models.CharField(max_length=100, null=True)
avatar=ImageWithThumbsField(upload_to="avatares/", sizes=((50,50),(200,200)), null=True)
def __unicode__(self):
return self.username.username
class Meta:
verbose_name = _('Datos Adicionales de usuario')
verbose_name_plural = _('Datos Adicionales de usuarios')
class temas(models.Model):
username=models.ForeignKey(User)
tema=models.CharField(max_length=100, null=True)
class Meta:
verbose_name = _('Tema')
verbose_name_plural = _('Temas')
class preguntas(models.Model):
username=models.ForeignKey(User)
temas=models.ManyToManyField(temas)
pregunta=models.CharField(max_length=100, null=True)
class Meta:
verbose_name = _('Pregunta')
verbose_name_plural = _('Preguntas')
class respuestas(models.Model):
preguntas=models.ForeignKey(preguntas)
respuesta=models.CharField(max_length=100)
class Meta:
verbose_name = _('Respuestas')
verbose_name_plural = _('Respuestas')
class rate(models.Model):
preguntas=models.ForeignKey(preguntas)
rates=((0,0),(1,1),(2,2),(3,3),(4,4),(5,5))
rate=models.IntegerField(choices=rates,default=0)
class Meta:
verbose_name = _('Rate')
verbose_name_plural = _('Rate')
|
0e0fe0c5e5a35ea34c3c2cafd26998cba102ea62
|
[
"Python"
] | 3 |
Python
|
alvaropablo/segundo_sprint
|
d8faefef5c536760804beb352f98975554c39b95
|
460afdf87c1dc107856024044982889a6d377303
|
refs/heads/master
|
<repo_name>PuppetJs/PuppeteerJs<file_sep>/examples/todomvc/README.md
# TodoMVC demo in Polymer + PuppetJS
In this demo, we will enhance Polymer TodoMVC. We will replace client side logic and using `localStorage` as database
with Starcounter. After our changes, client will only contain the presentation and all the business logic and storage
will be handled by server, updating the client using JSON Patch (RFC 6902).
# Changes in master.html
Remove the line that imports `td-model` custom element.
Remove the line that inserts `<td-model>` instance to the DOM.
Change `<td-model modelId="model">` to `<td-todos storageId="storage">`. By removing model we
removed one line of concern to the application design. Now the presentation binds directly to the data model
that comes from server.
Load scripts `/puppet.js` and it's dependency, `/json-patch-duplex.js`.
Place a `/` before all resource URLs (scripts, styles and HTML imports) to make the paths absolute. Our app
will use a multi-level URL scheme to access the task lists and their filters, so relative URLs would no longer work.
# Changes in lib-elements/polymer-localstorage.html
Actually this file should be placed under a new name, but for the sake of presentation
we apply the changes in the existing file.
In JS controller, add `value: {}` property. This will be the object, in which PuppetJs
inserts data model obtained from the server on page load.
In `load` method, replace the contents with `new Puppet(null, null, this.value);`. This
creates an instance of PuppetJs that binds the server data model with the `value` object
and sets up observation of the changes.
Remove the contents of the `save` method. Local changes in the data model are
automatically observed and there is no need to imperatively call the save method.
# Changes in elements/td-todos.html
Remove the line that imports `flatiron-director` custom element (client side routing). Instead,
routing is be done by switching the window location using HTML5 History API. We intercept
HTML5 history changes and send them as JSON Patches to the server, which decides whether
new data and template should be sent to the client.
Change observable attribute `modelId` to `storageId`.
Remove the line that inserts `<flatiron-director>` instance to the DOM.
Remove value binding `checked="{{model.allCompleted}}"` from the "Complete All" input field. This field
now becomes just a trigger (implemented in method `toggleAllCompletedAction` below).
Change the line that iterates over `model.filtered` to `model.items`. Server exposes only a
single array of items to the client, that is already a result of an SQL query. If the
query returns only filtered items, this is what the client receives as the items array.
Change the conditional attribute value `model.items.length === 0` to `model.activeCount + model.completedCount === 0`.
This is because the `items` array no longer contains all items from the database, but only the part that the server
decided to return for the current filter.
Change filter selector attribute `selected="{{route || 'all'}}"` to `selected="{{model.filterOption}}"`, because we
no longer use client side routing. Now the server decides which link is highlighted by setting the `filterOption`
property to the appropriate value.
Change filter links from `../#/` to `{{model.taskListUrl}}`, `../#active` to `{{model.taskListUrl}}/active`,
`.../#completed` to `{{model.taskListUrl}}/completed`. We switch from fake URLs that use the hash character,
to clean, easily bookmarkable URLs that point to a task list with a certain filter.
These links are required to expose the `click` event outside of the Shadow DOM by using
`on-click="fireAction"` attribute. This enables PuppetJs to intercept the click event, and replace it with a
HTML5 History API entry and a JSON Patch that is sent to server. Server responds with
only the partial data for what has changed on screen. A partial template can be also returned from server but this is
not in scope of this demo.
In JS controller replace `modelIdChanged` method name to `storageIdChanged`. Inside that method,
bind model property directly to the storage value:
`this.model = document.querySelector('#' + this.storageId).value;`
In the `addTodoAction` method, replace `this.model.newItem(this.$['new-todo'].value);`
with simpler assignment to the object property: `this.model.newItemTitle$ = this.$['new-todo'].value;`
After that add a line that triggers the `blur` event outside of Shadow DOM, so that PuppetJS
can observe the change (it listens for the `click` and `blur` events).
Replace contents of in `destroyItemAction` with a trigger `detail.remove$ = null`. This trigger
will be sent in JSON Patch and handled by the server.
Replace contents of in `toggleAllCompletedAction` with a trigger `this.model.allCompleted$ = null`. This trigger
will be sent in JSON Patch and handled by the server.
Replace contents of in `clearCompletedAction` with a trigger `this.model.clearCompleted$ = null`. This trigger
will be sent in JSON Patch and handled by the server.
Remove the contents of `itemChangedAction`. Those actions are handled by server now.
At the end, add a handler for `fireAction` that triggers the `click` event outside of the
Shadow DOM.
# Changes in elements/td-item.html
Replace all the references to `item.completed` with `item.completed$` (2 changes).
The `$` character is a Starcounter convention to describe all the JSON properties that
are writable. The properties that do not have the `$` character in their name, are
regarded as read-only.
Replace all the references to `item.title` with `item.title$` (4 changes) for the same reason.
# Delete files
File `elements/td-model.html` can be removed, because client side logic is no longer used.
File `lib-elements/flatiron-director.html` can be removed, because client side routing is no longer used.
<file_sep>/README.md
PuppeteerJs
===========
Nothing to see here yet.
Server side view-models for Web Components or AngularJs using NodeJs.
## License
MIT
<file_sep>/examples/todomvc/public/puppet.js
(function (global) {
var lastClickHandler
, lastPopstateHandler
, lastBlurHandler;
/**
* Defines a connection to a remote PATCH server, returns callback to a object that is persistent between browser and server
* @param remoteUrl If undefined, current window.location.href will be used as the PATCH server URL
* @param callback Called after initial state object is received from the server
*/
function Puppet(remoteUrl, callback, obj) {
this.debug = true;
this.remoteUrl = remoteUrl;
this.callback = callback;
this.obj = obj || {};
this.observer = null;
this.referer = null;
this.queue = [];
this.handleResponseCookie();
this.xhr(this.remoteUrl, 'application/json', null, this.bootstrap.bind(this));
}
/**
* PuppetJsClickTrigger$ contains Unicode symbols for "NULL" text rendered stylized using Unicode
* character "SYMBOL FOR NULL" (2400)
*
* With PuppetJs, any property having `null` value will be rendered as stylized "NULL" text
* to emphasize that it probably should be set as empty string instead.
*
* The benefit of having this string is that any local change to `null` value (also
* from `null` to `null`) can be detected and sent as `null` to the server.
*/
var PuppetJsClickTrigger$ = "\u2400";
function markObjPropertyByPath(obj, path) {
var keys = path.split('/');
var len = keys.length;
if (keys.length > 2) {
for (var i = 1; i < len - 1; i++) {
obj = obj[keys[i]];
}
}
recursiveMarkObjProperties(obj, keys[len - 1]);
}
function placeMarkers(parent, key) {
var subject = parent[key];
if (subject === null) {
parent[key] = PuppetJsClickTrigger$;
}
else if (typeof subject === 'object' && !subject.hasOwnProperty('$parent')) {
Object.defineProperty(subject, '$parent', {
enumerable: false,
get: function () {
return parent;
}
});
}
}
function recursiveMarkObjProperties(parent, key) {
if (key && parent) {
placeMarkers(parent, key);
parent = parent[key];
}
if (parent) {
for (var i in parent) {
if (parent.hasOwnProperty(i) && typeof parent[i] === 'object') {
recursiveMarkObjProperties(parent, i);
}
}
}
}
function recursiveExtend(par, obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
if(typeof obj[i] === 'object' && par.hasOwnProperty(i)) {
recursiveExtend(par[i], obj[i]);
}
else {
par[i] = obj[i];
}
}
}
}
Puppet.prototype.bootstrap = function (event) {
var tmp = JSON.parse(event.target.responseText);
recursiveExtend(this.obj, tmp);
recursiveMarkObjProperties(this.obj);
this.observe();
if (this.callback) {
this.callback(this.obj);
}
if (lastClickHandler) {
document.body.removeEventListener('click', lastClickHandler);
window.removeEventListener('popstate', lastPopstateHandler);
document.body.removeEventListener('blur', lastBlurHandler, true);
}
document.body.addEventListener('click', lastClickHandler = this.clickHandler.bind(this));
window.addEventListener('popstate', lastPopstateHandler = this.historyHandler.bind(this)); //better here than in constructor, because Chrome triggers popstate on page load
document.body.addEventListener('blur', lastBlurHandler = this.sendLocalChange.bind(this), true);
};
Puppet.prototype.handleResponseHeader = function (xhr) {
var location = xhr.getResponseHeader('X-Location') || xhr.getResponseHeader('Location');
if (location) {
this.referer = location;
}
};
/**
* JavaScript cannot read HTTP "Location" header for the main HTML document, but it can read cookies
* So if you want to establish session in the main HTML document, send "Location" value as a cookie
* The cookie will be erased (replaced with empty value) after reading
*/
Puppet.prototype.handleResponseCookie = function () {
var location = cookie.read('Location');
if (location) { //if cookie exists and is not empty
this.referer = location;
cookie.erase('Location');
}
};
Puppet.prototype.observe = function () {
this.observer = jsonpatch.observe(this.obj, this.queueLocalChange.bind(this));
};
Puppet.prototype.unobserve = function () {
if (this.observer) { //there is a bug in JSON-Patch when trying to unobserve something that is already unobserved
jsonpatch.unobserve(this.obj, this.observer);
this.observer = null;
}
};
Puppet.prototype.queueLocalChange = function (patches) {
Array.prototype.push.apply(this.queue, patches);
if ((document.activeElement.nodeName !== 'INPUT' && document.activeElement.nodeName !== 'TEXTAREA') || document.activeElement.getAttribute('update-on') === 'input') {
if (this.queue.length) {
this.flattenPatches(this.queue);
this.handleLocalChange(this.queue);
this.queue.length = 0;
}
}
};
Puppet.prototype.sendLocalChange = function () {
jsonpatch.generate(this.observer);
if (this.queue.length) {
this.flattenPatches(this.queue);
this.handleLocalChange(this.queue);
this.queue.length = 0;
}
};
//merges redundant patches
Puppet.prototype.flattenPatches = function (patches) {
var seen = {};
for (var i = patches.length - 1; i >= 0; i--) {
if (patches[i].op === 'replace') {
if (seen[patches[i].path]) {
patches.splice(i, 1);
}
else {
seen[patches[i].path] = true;
}
}
}
};
Puppet.prototype.handleLocalChange = function (patches) {
var txt = JSON.stringify(patches);
if (txt.indexOf('__Jasmine_been_here_before__') > -1) {
throw new Error("PuppetJs did not handle Jasmine test case correctly");
}
//"referer" should be used as the url when sending JSON Patches (see https://github.com/PuppetJs/PuppetJs/wiki/Server-communication)
this.xhr(this.referer || this.remoteUrl, 'application/json-patch+json', txt, this.handleRemoteChange.bind(this));
//this.xhr(this.remoteUrl, 'application/json-patch+json', txt, this.handleRemoteChange.bind(this));
var that = this;
this.unobserve();
patches.forEach(function (patch) {
if ((patch.op === "add" || patch.op === "replace" || patch.op === "test") && patch.value === null) {
patch.value = PuppetJsClickTrigger$;
jsonpatch.apply(that.obj, [patch]);
}
markObjPropertyByPath(that.obj, patch.path);
});
this.observe();
};
Puppet.prototype.handleRemoteChange = function (event) {
if (!this.observer) {
return; //ignore remote change if we are not watching anymore
}
var patches = JSON.parse(event.target.responseText || '[]'); //fault tolerance - empty response string should be treated as empty patch array
if (patches.length === void 0) {
throw new Error("Patches should be an array");
}
this.unobserve();
jsonpatch.apply(this.obj, patches);
var that = this;
patches.forEach(function (patch) {
if (patch.op === "add" || patch.op === "replace" || patch.op === "test") {
markObjPropertyByPath(that.obj, patch.path);
}
});
this.observe();
if (this.onRemoteChange) {
this.onRemoteChange(patches);
}
};
Puppet.prototype.isApplicationLink = function (href) {
return (href.protocol == window.location.protocol && href.host == window.location.host);
};
Puppet.prototype.changeState = function (href) {
this.xhr(href, 'application/json-patch+json', null, this.handleRemoteChange.bind(this));
};
Puppet.prototype.clickHandler = function (event, url) {
if(event.detail && event.detail.target) {
//detail is Polymer
event = event.detail;
}
var target = event.target;
if (window.PuppetExternalLink) {
target = window.PuppetExternalLink;
window.PuppetExternalLink = null;
}
if (target.href && this.isApplicationLink(target)) {
event.preventDefault();
history.pushState(null, null, target.href);
this.changeState(target.href);
}
else if (target.type === 'submit') {
event.preventDefault();
}
else {
this.sendLocalChange(); //needed for checkbox
}
};
Puppet.prototype.historyHandler = function (/*event*/) {
this.changeState(location.href);
};
Puppet.prototype.showError = function (heading, description) {
if (this.debug) {
var DIV = document.getElementById('puppetjs-error');
if(!DIV) {
DIV = document.createElement('DIV');
DIV.id = 'puppetjs-error';
DIV.style.border = '1px solid #dFb5b4';
DIV.style.background = '#fcf2f2';
DIV.style.padding = '10px 16px';
if (document.body.firstChild) {
document.body.insertBefore(DIV, document.body.firstChild);
}
else {
document.body.appendChild(DIV);
}
}
var H1 = document.createElement('H1');
H1.innerHTML = heading;
var PRE = document.createElement('PRE');
PRE.innerHTML = description;
PRE.style.whiteSpace = 'pre-wrap';
DIV.appendChild(H1);
DIV.appendChild(PRE);
}
throw new Error(description);
};
Puppet.prototype.xhr = function (url, accept, data, callback) {
//this.handleResponseCookie();
cookie.erase('Location'); //more invasive cookie erasing because sometimes the cookie was still visible in the requests
var req = new XMLHttpRequest();
var that = this;
req.addEventListener('load', function (event) {
that.handleResponseCookie();
that.handleResponseHeader(event.target);
if (event.target.status >= 400 && event.target.status <= 599) {
that.showError('PuppetJs JSON response error', 'Server responded with error ' + event.target.status + ' ' + event.target.statusText + '\n\n' + event.target.responseText);
}
else {
callback.call(that, event);
}
}, false);
url = url || window.location.href;
if (data) {
req.open("PATCH", url, true);
req.setRequestHeader('Content-Type', 'application/json-patch+json');
}
else {
req.open("GET", url, true);
}
if (accept) {
req.setRequestHeader('Accept', accept);
}
if (this.referer) {
req.setRequestHeader('X-Referer', this.referer);
}
req.send(data);
};
Puppet.prototype.catchExternaLink = function (element) {
element.addEventListener("click", function (event) {
window.PuppetExternalLink = event.target;
});
};
/**
* Cookie helper
* reference: http://www.quirksmode.org/js/cookies.html
* reference: https://github.com/js-coder/cookie.js/blob/gh-pages/cookie.js
*/
var cookie = {
create: function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + '; path=/';
},
readAll: function readCookies() {
if (document.cookie === '') return {};
var cookies = document.cookie.split('; ')
, result = {};
for (var i = 0, l = cookies.length; i < l; i++) {
var item = cookies[i].split('=');
result[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
}
return result;
},
read: function readCookie(name) {
return cookie.readAll()[name];
},
erase: function eraseCookie(name) {
cookie.create(name, "", -1);
}
};
global.Puppet = Puppet;
})(window);<file_sep>/examples/basic/model.js
var characters = [
{
name: 'Fred',
description: 'I am the BrontoCrane operator in the Rock and Gravel company. I enjoy bowling and a nice Brontoburgers, Brontosaurus Ribs. I have 3 toes on each on my feet. I love my wife, Wilma.'
},
{
name: 'Wilma',
description: 'I spend days raising up my daughter, despite the fact I am more intelligent than my husband. This house would be a ruin if not for me. I am the best dressed woman of Bedrock.'
},
{
name: 'Pebbles',
description: 'I have red hair. I always smile. My best friend is Bamm-Bamm.'
},
{
name: 'Dino',
description: 'I am a friendly dinsosaur. I love to welcome Fred when he comes back home by jumping on his chest.'
},
{
name: 'Barney',
description: 'I am Bedrock\'s master in bowling. I am also a drummer and piano player. I am a member of Loyal Order of Water Buffalos'
},
{
name: 'Betty',
description: 'I am Barney\'s wife. I always wear blue. My best friend is Wilma. I enjoy shopping and volunteering for various charitable organizations in Bedrock.'
},
{
name: 'Bamm-Bamm',
description: 'Bamm bamm bamm bamm bamm!'
}
];
module.exports = {
list: function(search) {
var out = [];
characters.map(function (character) {
if (search) {
if (character.name.toLowerCase().indexOf(search.toLowerCase()) === 0) {
out.push(character.name);
}
}
else {
out.push(character.name);
}
});
return out;
},
single: function(search) {
var found = characters.filter(function (character) {
return character.name === search;
});
if (found.length) {
return found[0];
}
else {
return {
name: '',
description: ''
};
}
}
};
|
27a6cd7bf3886151a07f563a6504d1580337d9d4
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
PuppetJs/PuppeteerJs
|
c0ab5a91cf3a2b107b9da08dd8400800c13d2401
|
2a80068ceb1f07a433d517e322e877904df13e46
|
refs/heads/master
|
<repo_name>johnotu/devless-docker-install<file_sep>/devless_docker_install.sh
#!/bin/bash
if [ $(uname) == "Linux" ]; then
. /etc/lsb-release
DISTRO=$DISTRIB_ID
CODENAME=$DISTRIB_CODENAME
if [ $DISTRO == "Ubuntu" ]; then
echo "______ _ "
echo "| _ \ | | "
echo "| | | |_____ _| | ___ ___ ___ "
echo "| | | / _ \ \ / / |/ _ \/ __/ __|"
echo "| |/ / __/\ V /| | __/\__ \__ \\"
echo "|___/ \___| \_/ |_|\___||___/___/"
echo "Prepping Linux box for Docker install ..."
apt-get update
apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY>
apt-add-repository \
"deb https://apt.dockerproject.org/repo \
ubuntu-$CODENAME \
main"
apt-get update
apt-cache policy docker-engine
echo "Installing Docker..."
apt-get install -y docker-engine
if [[ "$(docker images -q eddymens/devless 2> /dev/null)" == "" ]]; then
echo "Found a DevLess container"
echo "Running DevLess container on port 8080 ..."
docker run -p 8080:80 eddymens/devless
else
echo "Pulling DevLess container ..."
docker pull eddymens/devless
echo "Running DevLess container on port 8080 ..."
docker run -p 8080:80 eddymens/devless
fi
else
echo "Your Linux distro is not supported"
echo "Please chaeck https://docs.docker.com/engine/installation/ for more options"
fi
else
echo "Your OS is not supported"
echo "Please chaeck https://docs.docker.com/engine/installation/ for more options"
fi<file_sep>/README.MD
# Install and run DevLess at once
This script helps you to install and run Devless on your local machine for development.
# Instructions
1. Clone the repo `git clone https://github.com/johnotu/devless-docker-install.git`
2. Go into the directory `cd devless-docker-install`
3. Make the script executable `sudo chmod +x devless_docker_install.sh`
4. Run the script `sudo ./devless_docker_install.sh`
5. Open a browser and go to `http://localhost:8085`
|
0cfbf69f74b469970f572a64b38ffe79c1dc1083
|
[
"Markdown",
"Shell"
] | 2 |
Shell
|
johnotu/devless-docker-install
|
d93c14a99e00a08287124fab1c3786565f506f78
|
5a9f60aec9d3be7fd0c303d4f120f1a0035e186c
|
refs/heads/master
|
<file_sep>๏ปฟusing Microsoft.AspNet.Mvc;
namespace jaruss.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
if (!HttpContext.Request.Path.Value.Contains("index"))
return RedirectToAction("Index");
return View();
}
public IActionResult Services()
{
return View();
}
public IActionResult Contact()
{
return View();
}
public IActionResult Faq()
{
return View();
}
public IActionResult ChestOfDrawers()
{
return View();
}
public IActionResult Cupboard()
{
return View();
}
}
}
<file_sep># jaruss
Jaruss web site
<file_sep>๏ปฟusing Microsoft.AspNet.Mvc;
namespace jaruss.Controllers
{
public class ErrorController : Controller
{
public IActionResult PageNotFound()
{
return View();
}
}
}
<file_sep>๏ปฟ/// <autosync enabled="true" />
/// <reference path="../gulpfile.js" />
/// <reference path="js/bootstrap.min.js" />
/// <reference path="js/jquery-1.11.2.min.js" />
/// <reference path="js/main.js" />
/// <reference path="js/photoswipe.min.js" />
/// <reference path="js/photoswipe-ui-default.min.js" />
/// <reference path="js/plugin.js" />
/// <reference path="js/send-mail.js" />
/// <reference path="js/site.js" />
/// <reference path="lib/bootstrap/dist/js/bootstrap.js" />
/// <reference path="lib/jquery/dist/jquery.js" />
/// <reference path="lib/jquery-validation/dist/jquery.validate.js" />
/// <reference path="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" />
|
cdf5a8e3b541c3e8f7ae8662fc4bd9a20abd078d
|
[
"Markdown",
"C#",
"JavaScript"
] | 4 |
C#
|
garilla/jaruss
|
d5bdca4be33c0770deb160f9fdf823230c1368f6
|
87a9cf7aa8d985344d8563f0f228475bcec8517b
|
refs/heads/master
|
<file_sep>var express = require('express'),
app = express(),
PORT = process.env.PORT || 3000;
//c001
app.use( '/', express.static(__dirname + '/public') );
app.use( '/css', express.static(__dirname + '/src/css') );
app.use( '/img', express.static(__dirname + '/src/img') );
app.use( '/js', express.static(__dirname + '/src/js') );
app.get('/heartbeat', function(req, res) {
res.json({
is: 'working'
})
});
app.listen(PORT, function() {
console.log(`The server at port ${PORT} is listening.`);
});
<file_sep># Portfolio
Portfolio for <NAME> (deepbsd)
## Live Site
[<NAME>'s Thinkful Portfolio](http://deepbsd-portfolio.herokuapp.com)
The site features several animations, including UNIX fortunes (simulated) and a little Bash joke, reminiscent of HAL from <NAME>'s _2001: A Space Odyssey_.
## Features
* Mocha (testing)
* Chai (testing)
* Mongoose (for Mongo DB connectivity)
* Express
* Sass
* Gulp
* Passport (user authentication)
## Running Locally
* git clone <EMAIL>:deepbsd/portfolio.git
* npm install (make sure gulp is installed)
* Running *gulp watch* in the terminal provides a local server at port 3000 as well as watch tasks that compile SCSS to CSS and browser refresh when HTML files in the public folder change
|
87b2ab1b3d4a0f019e07a8bd581b4af05827e41b
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
deepbsd/portfolio
|
2345036d86b9aa3f90a1a0ee2f026e09f2a3fda3
|
5bfd6fb673e79669d30547b49ef8b7c771a04b45
|
refs/heads/master
|
<repo_name>JuanGongora/sinatra-mvc-lab-v-000<file_sep>/models/piglatinizer.rb
class PigLatinizer
def piglatinize(phrase)
current = phrase.split(" ")
current.map do |word|
# If a word starts with a consonant and a vowel, put the first letter of the word at the end of the word and add "ay."
if word =~ /\b[^aeiouAEIOU][aeiou]/
consonant = word[0]
stripped_word = word[1..-1].strip
word.clear
word << stripped_word << consonant << "ay"
# If a word starts with two or more consonants move the consonants to the end of the word and add "ay."
elsif word =~ /\b[^aeiouAEIOU]+/
consonants = word.match(/\b[^aeiouAEIOU]+/)
stripped_word = word.match(/[aeiouAEIOU][a-zA-Z]+|[a-zA-Z]$/)
word.clear
word << "#{stripped_word}#{consonants}ay"
# If a word starts with a vowel add the word "way" at the end of the word.
else word =~ /\b[aeiouAEIOU]/
word << "way"
end
end
current.join(" ")
end
end
|
2513adbdb7e3430891345d87bd011e392de6d5c7
|
[
"Ruby"
] | 1 |
Ruby
|
JuanGongora/sinatra-mvc-lab-v-000
|
740274ac68ee54885a511aed0fb1ee784408ada2
|
a8342fb812132c523936944f541385c3a32f4ba1
|
refs/heads/master
|
<file_sep>var Promise = require('bluebird');
var fetch = require('fetch');
var jp = require('jsonpath');
function rangeProp(value, key, up, low, result) {
if(!value) {
result[key] = 'Unknown';
} else {
value = parseFloat(value.value);
if(value > up)
result[key] = 'Red';
else if(value < low)
result[key] = 'Green';
else result[key] = 'Amber';
}
return result;
}
function computeScore(item) {
return new Promise(function (resolve, reject) {
fetch.fetchUrl('https://test.holmusk.com/food/search?q=' + item + '&page=0&limit=1', function (error, meta, body) {
var response = JSON.parse(body.toString());
if(response.length > 0) {
var result = {};
rangeProp(jp.query(response, '$..total_fats')[0], 'fat', 21, 3, result);
rangeProp(jp.query(response, '$..saturated')[0], 'saturated', 6, 1.5, result);
rangeProp(jp.query(response, '$..sugar')[0], 'sugar', 27, 5, result);
rangeProp(jp.query(response, '$..sodium')[0], 'salt', 1800, 300, result);
resolve(result);
} else {
resolve('Not Found');
}
});
});
}
module.exports = {
create: function (req, res) {
var items = req.body.items;
Promise.resolve(items)
.map(function (item) {
item = item.name;
return computeScore(item);
})
.then(function (results) {
res.ok(results);
})
.catch(function (error) {
sails.log.error(error);
});
}
};
|
bf16f069197b192c01e9bcd0aaa0da6d7e2a16f7
|
[
"JavaScript"
] | 1 |
JavaScript
|
lhtrieu87/holmusk-hackathon
|
74cbe9d5a7ec09512b90cb5691efc1da26f3782e
|
ee76e3aadd7b9d0ee5848a7542ddce7a63ef22d2
|
refs/heads/master
|
<repo_name>sametsafkan/angular2<file_sep>/angular2-master/app/ts/app.component.ts
import {Component} from 'angular2/core';
@Component({
//html ler burda
selector: 'my-app',
template: '<h1>Angular 2 Example</h1><br><button>Tฤฑkla</button>{{value}}'
})
export class AppComponent {
//kodlar fonksiyonlar burda
value = 1234;
click(){
alert('Hello World');
}
}
<file_sep>/angular2-master/app/ts/deneme.ts
import {Component} from 'angular2/core';
@Component({
selector:"example",
template:`<div><h1><NAME></h1></div><br>
<input type="text" [(ngModel)]="model" placeholder = "<NAME>"/>{{model}}<br>
<button (click)="click(model)">TIKLA</button><br>
<input type="text" (keyup.enter)="click2()"/>`
})
export class deneme{
click(text){
alert(text);
}
click2(){
alert("Hello World222!");
}
}
|
150dfeb3bf3150f3c24419d95ea2917593ef1525
|
[
"TypeScript"
] | 2 |
TypeScript
|
sametsafkan/angular2
|
e616799552594d065dba1304efd6dbb365ad12e0
|
6ebadcf3c89d768368f1579622be253494c406a3
|
refs/heads/master
|
<repo_name>emsonder/ms_feature_extractor<file_sep>/src/msfe/constants.py
#chemical_mix_id = '1'
msfe_version = '0.3.12'
chemical_mix_id = '20190522_4GHz'
""" Mass-spec features extractor constants """
# qc_log_location = "/mnt/nas2/fiaqc-out/qc_logs.txt"
qc_log_location = '/Users/emanuelsonder/PycharmProjects/ms_feature_extractor-master/data/annotated_peaks.txt'
#qc_log_location = "/Users/andreidm/ETH/projects/ms_feature_extractor/res/qc_logs.txt"
# tune_log_location = "/mnt/nas2/fiaqc-out/tune_logs.txt"
# '/Users/emanuelsonder/Documents/CBB/AS_19/Labrotation_1/sample_qc_matrix.db'
#tune_log_location = "/Users/emanuelsonder/Documents/CBB/AS_19/Labrotation_1/tune_logs.txt"
tune_log_location = "/Users/andreidm/ETH/projects/ms_feature_extractor/res/tune_logs.txt"
# feature_matrix_file_path = "/mnt/nas2/fiaqc-out/f_matrix.json"
feature_matrix_file_path = '/Users/emanuelsonder/PycharmProjects/ms_feature_extractor-master/outputs/feature_matrix.json'
#feature_matrix_file_path = "/Users/andreidm/ETH/projects/ms_feature_extractor/res/feature_matrix.json"
# ms_settings_matrix_file_path = "/mnt/nas2/fiaqc-out/s_matrix.json"
ms_settings_matrix_file_path = "/Users/andreidm/ETH/projects/ms_feature_extractor/res/ms_settings_matrix.json"
expected_peaks_file_path = "/Users/emanuelsonder/PycharmProjects/ms_feature_extractor-master/data/expected_peaks_top_intensity.json"
parser_comment_symbol = '#'
parser_description_symbols = '()'
minimal_normal_peak_intensity = 100
minimal_background_peak_intensity = 1
number_of_normal_scans = 3 # for Michelle's method main scans are defined by TIC maxima
# for Michelle's method
chemical_noise_features_scans_indexes = []
instrument_noise_features_scans_indexes = []
normal_scans_indexes_window = [0, 30]
peak_widths_levels_of_interest = [0.2, 0.5, 0.8]
saturation_intensity = 1000000
allowed_ppm_error = 25
peak_region_factor = 3 # 3 times resolution is a region for extracting information
maximum_number_of_subsequent_peaks_to_consider = 5 # initial guess
normal_scan_mz_frame_size = 50 # for frames [50, 100], [100, 150] ... [1000, 1050]
normal_scan_number_of_frames = 20
chemical_noise_scan_mz_frame_size = 100 # for frames [50, 150], [150, 250] ... [950, 1050]
chemical_noise_scan_number_of_frames = 10
instrument_noise_mz_frame_size = 200 # for frames [50, 250], [250, 450] ... [850, 1050]
instrument_noise_scan_number_of_frames = 5
number_of_top_noisy_peaks_to_consider = 10
no_signal_intensity_value = 0.
frame_intensity_percentiles = [25, 50, 75]
""" QC metrics generator constants """
qc_matrix_file_path = feature_matrix_file_path.replace('feature_matrix','qc_matrix')
qc_database_path = '/Users/emanuelsonder/PycharmProjects/ms_feature_extractor-master/outputs/aa_runs.db'
#qc_database_path = '/Users/andreidm/ETH/projects/qc_metrics/res/qc_matrix.db'
# features names
resolution_200_features_names = []
resolution_700_features_names = []
accuracy_features_names = []
dirt_features_names = []
instrument_noise_tic_features_names = []
instrument_noise_percentiles_features_names = []
isotopic_presence_features_names = []
transmission_features_names = []
fragmentation_features_names = []
baseline_150_250_features_names = []
baseline_650_750_features_names = []
signal_features_names = []
s2b_features_names = []
s2n_features_names = []
# resolution_200_features_names = ['absolute_mass_accuracy_Caffeine_i1_mean', 'widths_Caffeine_i1_1_mean'] # 193.0725512871
# resolution_700_features_names = ['absolute_mass_accuracy_Perfluorotetradecanoic_acid_i1_mean', 'widths_Perfluorotetradecanoic_acid_i1_1_mean'] # 712.94671694
#
#
# accuracy_features_names = ['absolute_mass_accuracy_Caffeine_i1_mean', 'absolute_mass_accuracy_Caffeine_i2_mean', 'absolute_mass_accuracy_Caffeine_i3_mean', 'absolute_mass_accuracy_Caffeine_f1_mean',
# 'absolute_mass_accuracy_Fluconazole_i1_mean', 'absolute_mass_accuracy_Fluconazole_i2_mean', 'absolute_mass_accuracy_Fluconazole_i3_mean', 'absolute_mass_accuracy_Fluconazole_f1_mean',
# 'absolute_mass_accuracy_3-(Heptadecafluorooctyl)aniline_i1_mean', 'absolute_mass_accuracy_3-(Heptadecafluorooctyl)aniline_i2_mean', 'absolute_mass_accuracy_3-(Heptadecafluorooctyl)aniline_i3_mean',
# 'absolute_mass_accuracy_Albendazole_i1_mean', 'absolute_mass_accuracy_Albendazole_i2_mean', 'absolute_mass_accuracy_Albendazole_i3_mean', 'absolute_mass_accuracy_Albendazole_f1_mean', 'absolute_mass_accuracy_Albendazole_f2_mean',
# 'absolute_mass_accuracy_Triamcinolone_acetonide_i1_mean', 'absolute_mass_accuracy_Triamcinolone_acetonide_i2_mean', 'absolute_mass_accuracy_Triamcinolone_acetonide_i3_mean', 'absolute_mass_accuracy_Triamcinolone acetonide_f1_mean', 'absolute_mass_accuracy_Triamcinolone acetonide_f2_mean',
# 'absolute_mass_accuracy_Perfluorodecanoic_acid_i1_mean', 'absolute_mass_accuracy_Perfluorodecanoic_acid_i2_mean', 'absolute_mass_accuracy_Perfluorodecanoic_acid_i3_mean', 'absolute_mass_accuracy_Perfluorodecanoic acid_f1_mean',
# 'absolute_mass_accuracy_Tricosafluorododecanoic_acid_i1_mean', 'absolute_mass_accuracy_Tricosafluorododecanoic_acid_i2_mean', 'absolute_mass_accuracy_Tricosafluorododecanoic_acid_i3_mean', 'absolute_mass_accuracy_Tricosafluorododecanoic acid_f1_mean',
# 'absolute_mass_accuracy_Perfluorotetradecanoic_acid_i1_mean', 'absolute_mass_accuracy_Perfluorotetradecanoic_acid_i2_mean', 'absolute_mass_accuracy_Perfluorotetradecanoic_acid_i3_mean', 'absolute_mass_accuracy_Perfluorotetradecanoic acid_f1_mean', 'absolute_mass_accuracy_Perfluorotetradecanoic acid_f2_mean',
# 'absolute_mass_accuracy_Pentadecafluoroheptyl_i1_mean', 'absolute_mass_accuracy_Pentadecafluoroheptyl_i2_mean', 'absolute_mass_accuracy_Pentadecafluoroheptyl_i3_mean']
#
# dirt_features_names = ['intensity_sum_chem_50_150', 'intensity_sum_chem_150_250', 'intensity_sum_chem_250_350', 'intensity_sum_chem_350_450', 'intensity_sum_chem_450_550',
# 'intensity_sum_chem_550_650','intensity_sum_chem_650_750', 'intensity_sum_chem_750_850', 'intensity_sum_chem_850_950', 'intensity_sum_chem_950_1050']
#
#
# instrument_noise_tic_features_names = ['intensity_sum_bg_50_250', 'intensity_sum_bg_250_450', 'intensity_sum_bg_450_650', 'intensity_sum_bg_650_850', 'intensity_sum_bg_850_1050']
#
# instrument_noise_percentiles_features_names = ['percentiles_bg_50_250_1', 'percentiles_bg_250_450_1', 'percentiles_bg_450_650_1', 'percentiles_bg_650_850_1', 'percentiles_bg_850_1050_1']
#
# isotopic_presence_features_names = ['isotopes_ratios_diffs_Caffeine_i1_0_mean', 'isotopes_ratios_diffs_Caffeine_i1_1_mean', 'isotopes_ratios_diffs_Caffeine_i1_2_mean',
# 'isotopes_ratios_diffs_Fluconazole_i1_0_mean', 'isotopes_ratios_diffs_Fluconazole_i1_1_mean', 'isotopes_ratios_diffs_Fluconazole_i1_2_mean',
# 'isotopes_ratios_diffs_3-(Heptadecafluorooctyl)aniline_i1_0_mean', 'isotopes_ratios_diffs_3-(Heptadecafluorooctyl)aniline_i1_1_mean', 'isotopes_ratios_diffs_3-(Heptadecafluorooctyl)aniline_i1_2_mean',
# 'isotopes_ratios_diffs_Albendazole_i1_0_mean', 'isotopes_ratios_diffs_Albendazole_i1_1_mean', 'isotopes_ratios_diffs_Albendazole_i1_2_mean',
# 'isotopes_ratios_diffs_Triamcinolone_acetonide_i1_0_mean', 'isotopes_ratios_diffs_Triamcinolone_acetonide_i1_1_mean', 'isotopes_ratios_diffs_Triamcinolone_acetonide_i1_2_mean',
# 'isotopes_ratios_diffs_Perfluorodecanoic_acid_i1_0_mean', 'isotopes_ratios_diffs_Perfluorodecanoic_acid_i1_1_mean', 'isotopes_ratios_diffs_Perfluorodecanoic_acid_i1_2_mean',
# 'isotopes_ratios_diffs_Tricosafluorododecanoic_acid_i1_0_mean', 'isotopes_ratios_diffs_Tricosafluorododecanoic_acid_i1_1_mean', 'isotopes_ratios_diffs_Tricosafluorododecanoic_acid_i1_2_mean',
# 'isotopes_ratios_diffs_Perfluorotetradecanoic_acid_i1_0_mean', 'isotopes_ratios_diffs_Perfluorotetradecanoic_acid_i1_1_mean', 'isotopes_ratios_diffs_Perfluorotetradecanoic_acid_i1_2_mean',
# 'isotopes_ratios_diffs_Pentadecafluoroheptyl_i1_0_mean', 'isotopes_ratios_diffs_Pentadecafluoroheptyl_i1_1_mean', 'isotopes_ratios_diffs_Pentadecafluoroheptyl_i1_2_mean']
#
# transmission_features_names = ['intensity_Perfluorotetradecanoic_acid_i1_mean', 'intensity_Fluconazole_i1_mean']
#
# fragmentation_features_names = ['fragments_ratios_Fluconazole_i1_0_mean',
# 'fragments_ratios_Perfluorotetradecanoic_acid_i1_0_mean']
#
# baseline_150_250_features_names = ['percentiles_chem_150_250_0', 'percentiles_chem_150_250_1']
# baseline_650_750_features_names = ['percentiles_chem_650_750_0', 'percentiles_chem_650_750_1']
#
# signal_features_names = [feature_name.replace('absolute_mass_accuracy', 'intensity') for feature_name in accuracy_features_names]
#
#
# s2b_features_names = ['intensity_3-(Heptadecafluorooctyl)aniline_i1_mean', 'percentiles_norm_500_550_0_mean']
#
# s2n_features_names = ['intensity_3-(Heptadecafluorooctyl)aniline_i1_mean', 'percentiles_norm_500_550_0_mean', 'percentiles_norm_500_550_1_mean']
#
<file_sep>/src/msfe/logger.py
from src.msfe.constants import qc_log_location, tune_log_location
def print_qc_info(info, file=qc_log_location):
with open(file, 'a') as log:
log.write(info + "\n")
def print_tune_info(info, file=tune_log_location):
with open(file, 'a') as log:
log.write(info + "\n")
<file_sep>/src/msfe/parser.py
from src.msfe.constants import parser_comment_symbol as sharp
from src.msfe.constants import parser_description_symbols as brackets
from src.msfe.constants import ms_settings_matrix_file_path
from src.msfe.constants import chemical_mix_id, msfe_version
from src.msfe.constants import qc_database_path
from src.qcmg import metrics_generator
from src.msfe import logger
from pyopenms import EmpiricalFormula, CoarseIsotopePatternGenerator
import json, os, datetime
def parse_expected_ions(file_path, scan_type):
""" Since >v.0.1.8 JSON file is used for input. The information about expected ions is extracted from there.
The resulting data structure is almost the same with the old version (to integrate to old code). """
assert scan_type == "normal" or scan_type == "chemical_noise"
ions_ids = []
expected_ions_mzs = []
expected_isotopic_ratios = []
fragmentation_lists = []
isotopic_lists = []
with open(file_path) as input_file:
all_expected_ions = json.load(input_file)
# correct ions names: all uppercase with no '-' in the end
for i in range(len(all_expected_ions[scan_type])):
for j in range(1, len(all_expected_ions[scan_type][i])):
if all_expected_ions[scan_type][i][j][-1] == '-':
# if there is - in the end of the ion name, remove it
all_expected_ions[scan_type][i][j] = all_expected_ions[scan_type][i][j][:-1]
else:
# if not, just make sure it's uppercase
all_expected_ions[scan_type][i][j] = all_expected_ions[scan_type][i][j]
# iterate over ions to parse information
for ion in all_expected_ions[scan_type]:
# get the list of mzs of isotopes of the main guy + isotopic intensity ratios
# (abundance of isotope in relation to the main guy)
ion_isotopes = EmpiricalFormula(ion[1]).getIsotopeDistribution(CoarseIsotopePatternGenerator(3)).getContainer()
isotopes_mzs = [iso.getMZ() for iso in ion_isotopes]
isotopes_intensity_ratios = [iso.getIntensity() for iso in ion_isotopes]
# add ids of the ion isotopes
ids = [ion[0].replace(" ", "_") + "_i" + str(i+1) for i in range(len(ion_isotopes))]
# if there is any expected fragment
if len(ion) > 1:
# get the list of mzs of ions fragments including mz of the main guy
fragments_list = [EmpiricalFormula(fragment).getMonoWeight() for fragment in ion[1:]]
# add ids of the ion fragments
ids.extend([ion[0] + "_f" + str(i+1) for i in range(len(fragments_list[1:]))])
else:
fragments_list = []
# append / extend
# the following two lists are of the same size == number of all mz values incl. main guys, isotopes, fragments
ions_ids.extend(ids)
expected_ions_mzs.extend([*isotopes_mzs, *fragments_list[1:]])
# the following three lists are of the same size == number of main guys
expected_isotopic_ratios.append(isotopes_intensity_ratios)
fragmentation_lists.append(fragments_list)
isotopic_lists.append(isotopes_mzs)
# compose and return info
expected_ions_info = {
'ions_ids': ions_ids,
'expected_mzs': expected_ions_mzs,
'expected_isotopic_ratios': expected_isotopic_ratios, # instead of "theoretical" intensities
'fragments_mzs': fragmentation_lists,
'isotopes_mzs': isotopic_lists
}
return expected_ions_info
def parse_expected_ions_old_version(file_path):
""" Deprecated since v.0.1.8.
This method parses information about expected ions. """
with open(file_path) as file:
all_of_it = file.read()
pieces = all_of_it.split(sharp)
expected_ions_mzs = []
expected_ions_intensities = []
fragmentation_lists = []
isotopic_lists = []
for piece in pieces:
if piece.split(brackets[0])[0].lower().find('ions') >= 0:
ions_info = piece.split(brackets[1])[1].split('\n')
for ion in ions_info:
if ion != "":
expected_ions_mzs.append(float(ion.split(",")[0]))
expected_ions_intensities.append(float(ion.split(",")[1]))
elif piece.split(brackets[0])[0].lower().find('fragments') >= 0:
fragmentation_info = piece.split(brackets[1])[1].split('\n')
for fragments_list_info in fragmentation_info:
if fragments_list_info != "":
fragments_list = [float(value) for value in fragments_list_info.split(',')]
fragmentation_lists.append(fragments_list)
elif piece.split(brackets[0])[0].lower().find('isotopes') >= 0:
isotopes_info = piece.split(brackets[1])[1].split('\n')
for isotope_list_info in isotopes_info:
if isotope_list_info != "":
isotopes_list = [float(value) for value in isotope_list_info.split(',')]
isotopic_lists.append(isotopes_list)
expected_ions_info = {
'expected_mzs': expected_ions_mzs,
'expected_intensities': expected_ions_intensities,
'fragments_mzs': fragmentation_lists,
'isotopes_mzs': isotopic_lists
}
return expected_ions_info
def parse_instrument_settings_from_multiple_ms_runs(list_of_paths):
""" This method reads instrument settings from previously generated files (paths provided),
and adds information to the general ms_settings_matrix, which is stored as another json. """
if not os.path.isfile(ms_settings_matrix_file_path):
# if the file does not exist yet, create empty one
s_matrix = {'ms_runs': []}
with open(ms_settings_matrix_file_path, 'w') as new_file:
json.dump(s_matrix, new_file)
else:
pass
for path in list_of_paths:
parse_ms_run_instrument_settings(path)
def parse_ms_run_instrument_settings(file_path):
""" This method reads instrument settings from newly generated file (after it's uploaded on server)
and adds information to the general ms_settings_matrix, which is stored as another json. """
# read newly generated ms settings file
with open(file_path) as file:
new_data = json.load(file)
# compose data structure to collect data
meta = {'keys': [], 'values': []}
actuals = {'keys': [], 'values': []}
cals = {'keys': [], 'values': []}
for key in new_data:
if key == "Actuals":
for actual in new_data[key]:
actuals['keys'].append(actual.replace(" ","_"))
actuals['values'].append(new_data[key][actual])
elif key == "Cal":
for mode in ['defaultPos', 'defaultNeg']:
for type in ['traditional', 'polynomial']:
for i in range(len(new_data[key][mode][type])):
cals['keys'].append(mode + "_" + type + "_" + str(i))
cals['values'].append(new_data[key][mode][type][i])
else:
meta["keys"].append(key)
meta["values"].append(new_data[key])
logger.print_tune_info(datetime.datetime.now().strftime("%Y-%m-%dT%H%M%S") + ": new tunes collected")
# open old ms settings file
with open(ms_settings_matrix_file_path) as general_file:
s_matrix = json.load(general_file)
# add new data to old file
s_matrix['ms_runs'].append({
'meta': meta,
'actuals': actuals,
'cals': cals
})
# dump updated file to the same place
with open(ms_settings_matrix_file_path, 'w') as updated_file:
json.dump(s_matrix, updated_file)
logger.print_tune_info("MS settings matrix updated\n")
def update_feature_matrix(extracted_features, features_names, feature_matrix_file_path, ms_run_ids, scans_processed):
""" This method gets results of single MS run feature extraction
and updates the general feature matrix. """
new_ms_run = {
'processing_date': ms_run_ids['processing_date'],
'acquisition_date': ms_run_ids['original_filename'],
'chemical_mix_id': chemical_mix_id,
'msfe_version': msfe_version,
'scans_processed': scans_processed,
'features_values': extracted_features,
'features_names': features_names
}
# entry point for qcm to process new_ms_run and insert into QC database
#metrics_generator.calculate_and_save_qc_metrics_for_ms_run(new_ms_run)
if not os.path.isfile(feature_matrix_file_path):
# if the file does not exist yet, create empty one
f_matrix = {'ms_runs': []}
with open(feature_matrix_file_path, 'w') as new_file:
json.dump(f_matrix, new_file)
else:
pass
# TODO: substitute JSON with SQLite as well, to save time reading (eventually) large files
# read existing file
with open(feature_matrix_file_path) as general_file:
f_matrix = json.load(general_file)
# add new processed ms run
f_matrix['ms_runs'].append(new_ms_run)
# dump updated file to the same place
with open(feature_matrix_file_path, 'w') as updated_file:
json.dump(f_matrix, updated_file)
if __name__ == "__main__":
# parse_instrument_settings_from_multiple_ms_runs(["/Users/andreidm/ETH/projects/ms_feature_extractor/data/ms_settings.json"])
print()
<file_sep>/src/qcmg/db_connector.py
import os, sqlite3, json
from src.msfe.constants import qc_matrix_file_path, qc_database_path
def create_connection(db_file):
""" Creates a database connection to the SQLite database specified by db_file. """
db = None
try:
db = sqlite3.connect(db_file)
return db
except Exception as e:
print(e)
return db
def create_table(db, create_table_sql):
""" Creates a table from the create_table_sql statement. """
try:
c = db.cursor()
c.execute(create_table_sql)
except Exception as e:
print(e)
def insert_qc_values(db, qc_values):
""" Adds last runs QC values to the table. """
sql = ''' INSERT INTO qc_values(acquisition_date,quality,resolution_200,resolution_700,
average_accuracy,chemical_dirt,instrument_noise,isotopic_presence,
transmission,fragmentation_305,fragmentation_712,baseline_25_150,
baseline_50_150,baseline_25_650,baseline_50_650,signal,
s2b,s2n)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) '''
cur = db.cursor()
cur.execute(sql, qc_values)
db.commit()
return cur.lastrowid
def insert_qc_meta(db, qc_meta):
""" Adds last runs meta info to the table. """
sql = ''' INSERT INTO qc_meta(processing_date,acquisition_date,quality,user_comment,
chemical_mix_id,msfe_version,norm_scan_1,norm_scan_2,
norm_scan_3,chem_scan_1,inst_scan_1)
VALUES(?,?,?,?,?,?,?,?,?,?,?) '''
cur = db.cursor()
cur.execute(sql, qc_meta)
db.commit()
return cur.lastrowid
def create_qc_database(db_path='/Users/andreidm/ETH/projects/qc_metrics/res/qc_matrix.db'):
sql_create_qc_meta_table = """ CREATE TABLE IF NOT EXISTS qc_meta (
processing_date text PRIMARY KEY,
acquisition_date text,
quality integer,
user_comment text,
chemical_mix_id integer,
msfe_version text,
norm_scan_1 integer,
norm_scan_2 integer,
norm_scan_3 integer,
chem_scan_1 integer,
inst_scan_1 integer
); """
sql_create_qc_values_table = """ CREATE TABLE IF NOT EXISTS qc_values (
acquisition_date text PRIMARY KEY,
quality integer,
resolution_200 integer,
resolution_700 integer,
average_accuracy real,
chemical_dirt integer,
instrument_noise integer,
isotopic_presence real,
transmission real,
fragmentation_305 real,
fragmentation_712 real,
baseline_25_150 integer,
baseline_50_150 integer,
baseline_25_650 integer,
baseline_50_650 integer,
signal integer,
s2b real,
s2n real
); """
# create a database connection
qc_database = create_connection(qc_database_path)
# create tables
if qc_database is not None:
# create projects table
create_table(qc_database, sql_create_qc_meta_table)
create_table(qc_database, sql_create_qc_values_table)
else:
print("Error! cannot create the database connection.")
def create_and_fill_qc_database(qc_matrix, debug=False):
""" This method creates a new QC database out of a qc_matrix object. """
create_qc_database(qc_database_path)
qc_database = create_connection(qc_database_path)
for qc_run in qc_matrix['qc_runs']:
run_meta = (
qc_run['processing_date'],
qc_run['acquisition_date'],
qc_run['quality'],
qc_run['user_comment'],
qc_run['chemical_mix_id'],
qc_run['msfe_version'],
qc_run['scans_processed']['normal'][0],
qc_run['scans_processed']['normal'][1],
qc_run['scans_processed']['normal'][2],
qc_run['scans_processed']['chemical_noise'][0],
qc_run['scans_processed']['instrument_noise'][0]
)
run_values = (
qc_run['acquisition_date'],
qc_run['quality'],
*qc_run['qc_values']
)
# inserting values into the new database
last_row_number_1 = insert_qc_meta(qc_database, run_meta)
last_row_number_2 = insert_qc_values(qc_database, run_values)
if debug:
print("inserted: meta:", last_row_number_1, 'values:', last_row_number_2)
def insert_new_qc_run(qc_run, in_debug_mode=False):
""" This method form objects with pre-computed values to insert into (already existing) database. """
qc_database = create_connection(qc_database_path)
run_meta = (
qc_run['processing_date'],
qc_run['acquisition_date'],
qc_run['quality'],
qc_run['user_comment'],
qc_run['chemical_mix_id'],
qc_run['msfe_version'],
qc_run['scans_processed']['normal'][0],
qc_run['scans_processed']['normal'][1],
qc_run['scans_processed']['normal'][2],
qc_run['scans_processed']['chemical_noise'][0],
qc_run['scans_processed']['instrument_noise'][0]
)
run_values = (
qc_run['acquisition_date'],
qc_run['quality'],
*qc_run['qc_values']
)
# inserting values into the new database
last_row_number_1 = insert_qc_meta(qc_database, run_meta)
last_row_number_2 = insert_qc_values(qc_database, run_values)
if in_debug_mode:
print("inserted 1 row at position: meta:", last_row_number_1, 'values:', last_row_number_2)
if __name__ == '__main__':
pass
<file_sep>/src/msfe/stuff/tries.py
# isotopes = EmpiricalFormula("C13H11F2N6O-").getIsotopeDistribution(CoarseIsotopePatternGenerator(3))
# isotopes1 = EmpiricalFormula("C7H7N4O2-").getIsotopeDistribution(CoarseIsotopePatternGenerator(3))
# isotopes2 = EmpiricalFormula("C7H7N4O2").getIsotopeDistribution(CoarseIsotopePatternGenerator(3))
#
# isotopes1 = isotopes1.getContainer()
# isotopes2 = isotopes2.getContainer()
#
# for i in range(len(isotopes1)):
# if isotopes1[i].getMZ() == isotopes2[i].getMZ() and isotopes1[i].getIntensity() == isotopes2[i].getIntensity():
# print(True)
#
# ions_ids = ["damn" + "it" + str(i) for i in range(len(isotopes))]
# llist = ["Caffeine", "C8H9N4O2-", "C7H7N4O2-"]
#
# # correct ions names: all uppercase + no - in the end
# for i in range(1,len(llist)):
# if llist[i][-1] == '-':
# llist[i] = llist[i][:-1].upper()
# else:
# llist[i] = llist[i].upper()
#
# print(llist)
a = []
import numpy
print(sum(numpy.array(a) != -1.))
|
20df778e18adbb84e8b811d9ea6aafe1b552a908
|
[
"Python"
] | 5 |
Python
|
emsonder/ms_feature_extractor
|
0acb470ea2a565ce7297baac232329f2eeddcf0e
|
cbd669df87f3ae17f5b5ad02343247ab46601ce3
|
refs/heads/master
|
<file_sep>package numbers.graphic;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import resource.ResourceLoader;
import numbers.engine.NumberEngine;
/**
* @author <NAME> <<EMAIL>>
* @version 1.0
* @since 23.05.2015
*/
public class NumberGraphic extends View {
private static final long serialVersionUID = 1988;
private int checkButton_Number = 0;
private int id = 0;
private String text = "The number is already generated.";
private NumberEngine numbEng;
public NumberGraphic(){
super();
setTitle("Numbers");
setIconImage(ResourceLoader.loadImage("Numbers-icon.png"));
numbEng = new NumberEngine();
numbEng.setRandomNumber();
// text = "" + numbEng.getRandomNumber();//ะฟะตัะตะฒััะบะฐ, ะะธะดะฐะปะธัะธ
textLabel.setText(text);
}
@Override
protected void useButton_Number(String nameButton, JButton button){
if(text.equals(textLabel.getText())){
textLabel.setText("");
}
textLabel.setText(textLabel.getText() + nameButton);
setEnabledButton_OK_clean(true);
checkButton_Number++;
if(checkButton_Number>=2){
setButtonEnable(false);
}
if(textLabel.getText().equals("10")){
buttons[0].setEnabled(true);
buttons[0].setFocusable(true);
}
}
@Override
protected void useButton_clean(){
setEnabledButton_OK_clean(false);
textLabel.setText("");
setButtonEnable(true);
checkButton_Number = 0;
}
@Override
protected void useButton_OK(){
numbEng.setResult(textLabel.getText());
String numbID = (++id)<10 ? " "+id : " "+id;
textArea.setText(textArea.getText()+numbID+" - "+numbEng.getResult()+"\n");
textLabel.setText("");
checkButton_Number = 0;
if(numbEng.getCheckWin()){
setButtonEnable(false);
JOptionPane.showMessageDialog(rootPane,"You Win!\n"+numbEng.getResult(),
"Result",JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(ResourceLoader.loadImage("win.png")));
textLabel.setText("You Win!!!");
}else{
setButtonEnable(true);
text = "Try to guess!";
textLabel.setText(text);
}
setEnabledButton_OK_clean(false);
}
@Override
protected void setNewGame(){
numbEng.setResetCheckWin();
numbEng.setRandomNumber();
// text = "" + numbEng.getRandomNumber();//ะฟะตัะตะฒััะบะฐ, ะะธะดะฐะปะธัะธ
textLabel.setText(text);
textArea.setText("");
setButtonEnable(true);
}
private void setButtonEnable(boolean check){
for(int i=0; i<buttons.length-2;i++){
buttons[i].setEnabled(check);
buttons[i].setFocusable(check);
}
}
private void setEnabledButton_OK_clean(boolean check){
buttons[10].setEnabled(check);
buttons[10].setFocusable(check);
buttons[11].setEnabled(check);
buttons[11].setFocusable(check);
}
}
|
18fd0e60bde8ed9ab9cdf9d6eb56abb110f91d82
|
[
"Java"
] | 1 |
Java
|
fordmay/Numbers_java
|
a3dd01864356a1e08cf1d7e5d62efef4027029af
|
a276cbfc9ed4ec72eb28eae5f96c2d375f5f7b6a
|
refs/heads/master
|
<repo_name>helciodasilva/alura-mock<file_sep>/teste-de-unidade/test/br/com/caelum/leilao/servico/EncerradorDeLeilaoTest.java
package br.com.caelum.leilao.servico;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mockito;
import br.com.caelum.leilao.builder.CriadorDeLeilao;
import br.com.caelum.leilao.dominio.Leilao;
import br.com.caelum.leilao.infra.dao.LeilaoDao;
import br.com.caelum.leilao.infra.dao.RepositorioDeLeiloes;
import br.com.caelum.leilao.infra.email.EnviadorDeEmail;
public class EncerradorDeLeilaoTest {
@Test
public void deveEncerrarLeiloesQueComecaramUmaSemanaAtras() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
Leilao leilao2 = new CriadorDeLeilao().para("Geladeira").naData(antiga).constroi();
List<Leilao> leiloesAntigos = Arrays.asList(leilao1, leilao2);
RepositorioDeLeiloes daoFalso = Mockito.mock(LeilaoDao.class);
Mockito.when(daoFalso.correntes()).thenReturn(leiloesAntigos);
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Assert.assertEquals(2, encerrador.getTotalEncerrados());
Assert.assertTrue(leilao1.isEncerrado());
Assert.assertTrue(leilao2.isEncerrado());
}
@Test
public void naoDeveEncerrarLeiloesQueComecaramMenosDeUmaSemanaAtras() {
Calendar ontem = Calendar.getInstance();
ontem.add(Calendar.DAY_OF_MONTH, -1);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(ontem).constroi();
Leilao leilao2 = new CriadorDeLeilao().para("Geladeira").naData(ontem).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1, leilao2));
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Assert.assertEquals(0, encerrador.getTotalEncerrados());
Assert.assertFalse(leilao1.isEncerrado());
Assert.assertFalse(leilao2.isEncerrado());
Mockito.verify(daoFalso, Mockito.never()).atualiza(leilao1);
Mockito.verify(daoFalso, Mockito.never()).atualiza(leilao2);
}
@Test
public void naoDeveEncerrarLeiloesCasoNaoHajaNenhum() {
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(new ArrayList<Leilao>());
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Assert.assertEquals(0, encerrador.getTotalEncerrados());
}
@Test
public void deveAtualizarLeiloesEncerrados() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1));
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
// verificando que o metodo atualiza foi realmente invocado!
Mockito.verify(daoFalso, Mockito.times(1)).atualiza(leilao1);
}
@Test
public void deveEnviarEmailAposPersistirLeilaoEncerrado() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1));
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
InOrder inOrder = Mockito.inOrder(daoFalso, carteiroFalso);
inOrder.verify(daoFalso, Mockito.times(1)).atualiza(leilao1);
inOrder.verify(carteiroFalso, Mockito.times(1)).envia(leilao1);
}
@Test
public void deveContinuarAExecucaoMesmoQuandoDaoFalha() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
Leilao leilao2 = new CriadorDeLeilao().para("Geladeira").naData(antiga).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1, leilao2));
Mockito.doThrow(new RuntimeException()).when(daoFalso).atualiza(leilao1);
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Mockito.verify(daoFalso).atualiza(leilao2);
Mockito.verify(carteiroFalso).envia(leilao2);
}
@Test
public void deveContinuarAExecucaoMesmoQuandoEnviadorDeEmaillFalha() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
Leilao leilao2 = new CriadorDeLeilao().para("Geladeira").naData(antiga).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1, leilao2));
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
Mockito.doThrow(new RuntimeException()).when(carteiroFalso).envia(leilao1);
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Mockito.verify(daoFalso).atualiza(leilao2);
Mockito.verify(carteiroFalso).envia(leilao2);
}
@Test
public void deveDesistirSeDaoFalhaPraSempre() {
Calendar antiga = Calendar.getInstance();
antiga.set(1999, 1, 20);
Leilao leilao1 = new CriadorDeLeilao().para("TV de plasma").naData(antiga).constroi();
Leilao leilao2 = new CriadorDeLeilao().para("Geladeira").naData(antiga).constroi();
RepositorioDeLeiloes daoFalso = Mockito.mock(RepositorioDeLeiloes.class);
Mockito.when(daoFalso.correntes()).thenReturn(Arrays.asList(leilao1, leilao2));
EnviadorDeEmail carteiroFalso = Mockito.mock(EnviadorDeEmail.class);
Mockito.doThrow(new RuntimeException()).when(daoFalso).atualiza(Mockito.any(Leilao.class));
EncerradorDeLeilao encerrador = new EncerradorDeLeilao(daoFalso, carteiroFalso);
encerrador.encerra();
Mockito.verify(carteiroFalso, Mockito.never()).envia(Mockito.any(Leilao.class));
}
}
<file_sep>/teste-de-unidade/test/br/com/caelum/leilao/servico/GeradorDePagamentoTest.java
package br.com.caelum.leilao.servico;
import java.util.Arrays;
import java.util.Calendar;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import br.com.caelum.leilao.builder.CriadorDeLeilao;
import br.com.caelum.leilao.dominio.Leilao;
import br.com.caelum.leilao.dominio.Pagamento;
import br.com.caelum.leilao.dominio.Usuario;
import br.com.caelum.leilao.infra.dao.RepositorioDeLeiloes;
import br.com.caelum.leilao.infra.dao.RepositorioDePagamentos;
import br.com.caelum.leilao.infra.relogio.Relogio;
public class GeradorDePagamentoTest {
@Test
public void deveGerarPagamentoParaUmLeilaoEncerrado() {
RepositorioDeLeiloes leiloes = Mockito.mock(RepositorioDeLeiloes.class);
RepositorioDePagamentos pagamentos = Mockito.mock(RepositorioDePagamentos.class);
Leilao leilao = new CriadorDeLeilao().para("Playstation").lance(new Usuario("<NAME>"), 2000.0)
.lance(new Usuario("<NAME>"), 2500.0).constroi();
Mockito.when(leiloes.encerrados()).thenReturn(Arrays.asList(leilao));
// aqui passamos uma instรขncia concreta de Avaliador
GeradorDePagamento gerador = new GeradorDePagamento(leiloes, pagamentos, new Avaliador());
gerador.gera();
ArgumentCaptor<Pagamento> argumento = ArgumentCaptor.forClass(Pagamento.class);
Mockito.verify(pagamentos).salva(argumento.capture());
Pagamento pagamentoGerado = argumento.getValue();
Assert.assertEquals(2500.0, pagamentoGerado.getValor(), 0.00001);
}
@Test
public void deveEmpurrarParaOProximoDiaUtil() {
RepositorioDeLeiloes leiloes = Mockito.mock(RepositorioDeLeiloes.class);
RepositorioDePagamentos pagamentos = Mockito.mock(RepositorioDePagamentos.class);
Relogio relogio = Mockito.mock(Relogio.class);
// dia 7/abril/2012 eh um sabado
Calendar sabado = Calendar.getInstance();
sabado.set(2012, Calendar.APRIL, 7);
// ensinamos o mock a dizer que "hoje" รฉ sabado!
Mockito.when(relogio.hoje()).thenReturn(sabado);
Leilao leilao = new CriadorDeLeilao().para("Playstation").lance(new Usuario("<NAME>"), 2000.0)
.lance(new Usuario("<NAME>"), 2500.0).constroi();
Mockito.when(leiloes.encerrados()).thenReturn(Arrays.asList(leilao));
GeradorDePagamento gerador = new GeradorDePagamento(leiloes, pagamentos, new Avaliador(), relogio);
gerador.gera();
ArgumentCaptor<Pagamento> argumento = ArgumentCaptor.forClass(Pagamento.class);
Mockito.verify(pagamentos).salva(argumento.capture());
Pagamento pagamentoGerado = argumento.getValue();
Assert.assertEquals(Calendar.MONDAY, pagamentoGerado.getData().get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(9, pagamentoGerado.getData().get(Calendar.DAY_OF_MONTH));
}
@Test
public void deveEmpurrarPagamentoNoDomingoParaOProximoDiaUtil() {
RepositorioDeLeiloes leiloes = Mockito.mock(RepositorioDeLeiloes.class);
RepositorioDePagamentos pagamentos = Mockito.mock(RepositorioDePagamentos.class);
Relogio relogio = Mockito.mock(Relogio.class);
Calendar domingo = Calendar.getInstance();
domingo.set(2012, Calendar.APRIL, 8);
Mockito.when(relogio.hoje()).thenReturn(domingo);
Leilao leilao = new CriadorDeLeilao().para("Playstation").lance(new Usuario("<NAME>"), 2000.0)
.lance(new Usuario("<NAME>"), 2500.0).constroi();
Mockito.when(leiloes.encerrados()).thenReturn(Arrays.asList(leilao));
GeradorDePagamento gerador = new GeradorDePagamento(leiloes, pagamentos, new Avaliador(), relogio);
gerador.gera();
ArgumentCaptor<Pagamento> argumento = ArgumentCaptor.forClass(Pagamento.class);
Mockito.verify(pagamentos).salva(argumento.capture());
Pagamento pagamentoGerado = argumento.getValue();
Assert.assertEquals(Calendar.MONDAY, pagamentoGerado.getData().get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(9, pagamentoGerado.getData().get(Calendar.DAY_OF_MONTH));
}
}
|
a472b7f842689e0da50225bdd8a377d13d20f51b
|
[
"Java"
] | 2 |
Java
|
helciodasilva/alura-mock
|
81fa2a0e7683dc7885ab3dd8889671cc705390d4
|
148195624975ce83971bfb659eb8939e8bbefea0
|
refs/heads/master
|
<repo_name>Jack-ee/ee-snippets<file_sep>/README.md
# eehub
hub for GEE community to shared the script [https://code.earthengine.google.com/?accept_repo=eehub](https://code.earthengine.google.com/?accept_repo=eehub )
## Array and Matrix
<NAME>
array-based mosaic
creatediagonalmatrix
## Chart and Plot
chart array with dates
image Time Series By Region
sigs stat by class - chart
sigs stat by class - chart1
## Datasets
USDA CDL pick
USDA NASS CDL
rasterized geometries on PFAF12
## FeatureCollection
TunisiaDataSpatialCorrelation
error matrix from FC
feature kmean classify
get a value from a fusion table column
get images that only fully contain the targeted area
join columns featureCollection
paint to Raster
random samples - add geo - get value
random split
retrieve Times Series Collection
## ImageCollection
- areaComputation
- chirp annual series chart
- quality mosaic with greeness
- urban mask from nightLights
- water mask using MOD44W - GLCF
## Misc
- Dever NDVI Abnomal
- LULC map with legend
- Precipitation Map extract
- Sentinel-2 visualization
- Surface water change detection
- Tile on Server Side
- export video - water body
- qualityMosaic
- sort the cluster
- zoom-in video
## Reducer
- Reduce and chart band values for a series of buffers
- a multiple regression model
- separate a year-long collection into two halves
## SAR
- Sentinel-1 IW single polarization properties
## Sentinel-2
- Sentinel 1
- sentinal_region_grow_angles
- sentinal_region_visualizer
- sentinel_edge
- sentinel_edge_with_existing_ndvi_image
- sentinel_region_grow
- sentinel_region_grow_with_phase_amplitude
- sentinel_region_vectors
- stripe-detection-testing
## Server Side
- getInfo call back
## UI Widgets
- Category Droplist
- Output NDVI trajectory for multiple user-defined points
- Scarbar in GEE
- Sentinel Explorer
- Two Chart Inspector
- custom button click function
- linked view
- publisher-ready map
- quick move
<file_sep>/Misc/zoom-in video.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var geometry = /* color: #d63000 */ee.Geometry.Polygon(
[[[-122.54837036132812, 37.73352554959531],
[-122.35576629638672, 37.73298250331026],
[-122.3550796508789, 37.819276821747295],
[-122.5469970703125, 37.819276821747295]]]),
geometry2 = /* color: #98ff00 */ee.Geometry.MultiPoint();
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var image = ee.Image('UMD/hansen/global_forest_change_2015').resample()
.visualize({bands:['treecover2000'], min:0, max:100, palette:['000000', '008000']});
var center = geometry.centroid().coordinates();
var dst_proj = ee.Projection('EPSG:4326', [1, 0, center.get(0), 0, 1, center.get(1)]);
var images = ee.ImageCollection(ee.List.sequence(100, 0, -1).map(function (i) {
var scale = ee.Number(2).pow(ee.Number(i).divide(10));
var src_proj = dst_proj.scale(scale, scale);
return image.changeProj(src_proj, dst_proj);
}));
Export.video.toCloudStorage({
collection: images,
description: 'VideoZoomTest',
bucket: 'mdh-test',
fileNamePrefix: 'VideoZoomTest',
framesPerSecond: 10,
dimensions: 1000,
region: geometry,
});
<file_sep>/UI/custom-button-click-function.js
Map.setCenter(-47.6735, -0.6344, 12);
var L8 = ee.ImageCollection('LANDSAT/LC8_L1T');
var img = ee.Algorithms.Landsat.simpleComposite({
collection: L8.filterDate('2015-1-1', '2015-7-1'),
asFloat: true});
var viz1 = {bands: 'B7,B6,B1', max: [0.3, 0.4, 0.3]}
var viz2 = {bands: 'B5,B4,B3', max: [0.3, 0.4, 0.3]}
function b1(){
Map.addLayer(img, viz1, 'b1')
}
function b2(){
// can we hide b1 then add b2?
Map.addLayer(img, viz2, 'b2')
}
var panel = ui.Panel()
panel.style().set('width', '80px')
var nav = [{name:'Layer1', func:b1},{name:'Layer2', func:b2}]
.map(function (button){return ui.Button(button.name, button.func)})
panel.add(ui.Panel(nav, ui.Panel.Layout.flow('vertical')))
ui.root.insert(0, panel);<file_sep>/FeatureCollection/feature-kmean-classify.js
var image = ee.Image('LE7_TOA_1YEAR/2001')
var region = ee.Geometry.Rectangle(29.7, 30, 32.5, 31.7);
var training = image.sample({
region: region,
scale: 30,
numPixels: 5000
})
var data = image.sample({
region: region,
scale: 30,
numPixels: 800
})
// print(data)
var clusterer = ee.Clusterer.wekaKMeans(25).train(training)
var result = data.cluster(clusterer)
print(result)
// var result = image.cluster(clusterer);
// Map.addLayer(result.randomVisualizer())
<file_sep>/Misc/getInfo-callback.js
// Settings
var STATENAME = 'California' ;
var CROPYEAR = 2015 ;
var CROPNUMBER = 0 ; //use CDLcropland_class_values and CDLcropland_class_names
var SCALE = 30 ; //Calculation is at 30m resolution
// Load states of the US
var statesCollection = ee.FeatureCollection('ft:1fRY18cjsHzDgGiJiS2nnpUU3v9JPDc2HNaR7Xk8');
var stateCollection = statesCollection.filterMetadata('Name', 'equals', STATENAME);
var state = ee.Feature(stateCollection.first());
// import crop layer
var CDLCollection = ee.ImageCollection('USDA/NASS/CDL');
var filterYear = ee.Filter.calendarRange(CROPYEAR,CROPYEAR,'year');
var CDLImage = ee.Image(CDLCollection
.filter(filterYear)
.select('cropland')
.first());
var CDLPropertyNames = CDLImage.propertyNames();
var CDLcropland_class_values = ee.List(CDLImage.get("cropland_class_values"));
var CDLcropland_class_names = ee.List(CDLImage.get("cropland_class_names"));
var CDLcropland_class_palettes = ee.List(CDLImage.get("cropland_class_palette"));
var CDLcropland_class_value = ee.Number(CDLcropland_class_values.get(CROPNUMBER));
var CDLcropland_class_name = ee.String(CDLcropland_class_names.get(CROPNUMBER));
var CDLcropland_class_palette = ee.String(CDLcropland_class_palettes.get(CROPNUMBER));
print(CDLcropland_class_value,CDLcropland_class_name,CDLcropland_class_palette)
// --------- PROBLEM: --------
// CDLcropland_class_name and CDLcropland_class_palette still seem to be objects and not strings. Print works but I can't use the values in
// -----------------------------
var cropImage = CDLImage.eq(CDLcropland_class_value);
// calculate percentage crop
var meanCrop = cropImage.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: state.geometry(),
scale: SCALE,
maxPixels: 1e9
});
var cropImageVisParam = {"opacity":1,"bands":["cropland"],"palette":["000000","ff0000"]};
var cropImageMasked = cropImage.updateMask(cropImage.eq(1));
Map.addLayer(state, {}, STATENAME,1,0.5);
Map.addLayer(cropImage,cropImageVisParam,'This is working',0,1);
// get map layers collection
var layers = Map.layers()
// create a new layer and remember it
var layer = ui.Map.Layer(cropImageMasked,cropImageVisParam,'loading ...', 1, 1)
// add layer
layers.add(layer)
// update layer name
function updateLayerName(name) {
layer.setName(name)
}
// force getInfo(), asynchroneous call
CDLcropland_class_name.getInfo(updateLayerName)
<file_sep>/Chart/sigs-stat-by-class-chart.js
var geometry = /* color: #00ffff */ee.Geometry.Polygon(
[[[103.00609970676544, 5.080687938498982],
[102.97999389449274, 5.082056531970339],
[102.97552846810947, 5.057421487138437],
[103.00575617406821, 5.056395011958857]]]),
l8_toa = ee.ImageCollection("LANDSAT/LC8_L1T_8DAY_TOA");
/*
Author: <NAME>
Date: March 15, 2015
*/
var NUM_CLUSTERS = 20;
// image you are using
var image = l8_toa.mean().clip(geometry);
// features to train cluster
var trainingFeatures = image.sample({
region:geometry,
scale:30,
numPixels: 5e6
});
// cluster with minimal parameters
var clusterer = ee.Clusterer.wKMeans({nClusters: NUM_CLUSTERS});
clusterer = clusterer.train(trainingFeatures)
// image classified
var clusterImage = image.cluster(clusterer)
var stats = computeStatistics(image, clusterImage, NUM_CLUSTERS);
print('stats', stats); // look in properties
Map.centerObject(geometry)
Map.addLayer(clusterImage, {min:0, max: NUM_CLUSTERS});
function computeStatistics(image, clusterImage) {
var numClasses = clusterImage.reduceRegion({
geometry: geometry,
reducer: ee.Reducer.max(),
scale: 30,
bestEffort: true,
maxPixels: 1e6,
});
var classes = ee.List.sequence(0, numClasses.get('cluster')).map(function(i) {
var oneClass = image.mask(clusterImage.eq(ee.Number(i)));
var reducer = ee.Reducer.median()
.combine(ee.Reducer.mean(), null, true)
.combine(ee.Reducer.max(), null, true)
.combine(ee.Reducer.min(), null, true)
.combine(ee.Reducer.stdDev(), null, true);
var stats = oneClass.reduceRegion({
geometry: geometry,
reducer: reducer,
scale: 30,
bestEffort: true,
maxPixels: 1e6,
});
return ee.Feature(null, stats);
});
return classes;
}
print(stats)
// Export.table(stats, 'class_stats', {driveFolder: ''}); <file_sep>/Sentinel-2/sentinal-region-grow-angles.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var sentinel = ee.ImageCollection("COPERNICUS/S2"),
geometry = /* color: ffc82d */ee.Geometry.Polygon(
[[[-3.2564163208007812, 33.4386348485769],
[3.2701492309570312, 34.99319027261741],
[3.2540130615234375, 36.97214207343772],
[-3.7882232666015625, 35.52974174046386]]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
////// Constants //////
var START_YEAR = 2015;
var END_YEAR = 2016;
var MAX_OBJECT_SIZE = 256,
THRESHOLD_START =.5,
THRESHOLD_END = 1.5,
THRESHOLD_STEP = 0.5,
USE_COSINE = false,
USE_PIXELCOORDS = false;
sentinel = sentinel.filterDate(START_YEAR.toString() + '-01-01', END_YEAR.toString() + '-12-31')
.map(function(img) {
// Opaque and cirrus cloud masks cause bits 10 and 11 in QA60 to be set,
// so values less than 1024 are cloud-free
var mask = ee.Image(0).where(img.select('QA60').gte(1024), 1).not();
return img.updateMask(mask);
})
.map(function(img) {
return img.select(['B4','B8'], ['red', 'nir']);
});
var collection = sentinel;
// w is reference point for green and brightness
// brightness if reference point for green
// [red, nir] TODO find actual values
var g = [.02, .61];
var b = [.41, .47];
var w = [.025, .05];
var angle_w_b = ee.Number((b[1] - w[1]) /(b[0] - w[0])).atan().multiply(180).divide(Math.PI);
var angle_w_g = ee.Number((g[1] - w[1]) /(g[0] - w[0])).atan().multiply(180).divide(Math.PI);
var temp = collection;
var mean = temp.mean();
temp = temp.map(function (img) {
var nir = img.select('nir');
var red = img.select('red');
var aw = nir.subtract(w[1]).divide(red.subtract(w[0])).atan().multiply(180).divide(Math.PI).subtract(angle_w_b);
var ab = ee.Image(angle_w_b).subtract(nir.subtract(b[1]).divide(red.subtract(b[0])).atan().multiply(180).divide(Math.PI));
var ag = nir.subtract(g[1]).divide(red.subtract(g[0])).atan().multiply(180).divide(Math.PI).subtract(angle_w_g);
var dw = nir.subtract(w[1]).pow(2).add(red.subtract(w[0]).pow(2)).sqrt();
var db = nir.subtract(b[1]).pow(2).add(red.subtract(b[0]).pow(2)).sqrt();
var dg = nir.subtract(g[1]).pow(2).add(red.subtract(g[0]).pow(2)).sqrt();
// distance from point p
var distance = mean.select('nir').subtract(nir).pow(2).add(mean.select('red').subtract(red).pow(2)).sqrt();
return img.select([])
.addBands(distance.select([0], ['distance']))
.addBands(aw.select([0], ['aw']))
.addBands(ab.select([0], ['ab']))
.addBands(ag.select([0], ['ag']))
// .addBands(dw.select([0], ['dw']))
// .addBands(db.select([0], ['db']))
// .addBands(dg.select([0], ['dg']))
.addBands(img.normalizedDifference(['nir', 'red']).select([0], ['ndvi']));
});
var reducer = ee.Reducer.median()
// .combine(ee.Reducer.mean(), null, true)
// .combine(ee.Reducer.sum(), null, true)
.combine(ee.Reducer.max(), null, true)
.combine(ee.Reducer.min(), null, true)
// .combine(ee.Reducer.stdDev(), null, true);
var out = temp.reduce(reducer, 1);
var maxVals = out.reduceRegion({
reducer: ee.Reducer.max(),
geometry: geometry,
scale: 10000,
bestEffort: true
});
var normalized = ee.Image(out.bandNames().iterate(function (band, img) {
img = ee.Image(img)
band = ee.String(band);
return img.addBands((out.select(band).divide(ee.Number(maxVals.get(band)).abs()).float().select([0],[ee.String("B_").cat(band).cat("_norm")])));
}, out.select([])));
var image = normalized;
image = image.focal_mean({
radius: 1.5,
kernelType: 'square',
iterations: 1
});
if (USE_PIXELCOORDS) {
image = image.addBands(ee.Image.pixelCoordinates(ee.Projection("epsg:3857")).multiply(0.0005).select([0,1],["B_X", "B_Y"]))
}
var results = ee.Image(ee.List.sequence(THRESHOLD_START,THRESHOLD_END,THRESHOLD_STEP).iterate(function(threshold, image) {
threshold = ee.Number(threshold);
image = ee.Image(image);
var imageClustered = ee.apply("Test.Clustering.RegionGrow", {
"image": image.select("^(B).*$"),
"useCosine": USE_COSINE,
secondPass: true,
"threshold": threshold,
"maxObjectSize": MAX_OBJECT_SIZE,
});
var imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageClustered,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageConsistent,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = imageConsistent.select("^(B).*$").addBands(imageConsistent.select('clusters'))
return ee.Image(ee.Algorithms.If(image.bandNames().contains('clusters'), imageConsistent.addBands(image.select("^(cl).*$")), imageConsistent));
}, image));
// Visualize All Levels
var hierarchy = results.select("^(cl).*$").bandNames().getInfo();
for (var i = 0; i< hierarchy.length; i++) {
Map.addLayer(results.select(hierarchy[i]).randomVisualizer(),{},hierarchy[i],0);
}
Map.addLayer(image,{}, 'image',0);
// Export
var exportId = 'sgmnts_' + Date.now().toString();
Export.image.toAsset({
image:results.select("^(cl).*$").int64(),
assetId: exportId,
description: exportId,
region: geometry,
scale:10,
maxPixels: 1e13
});
<file_sep>/SAR/sentinel1-IW-single-polarization-properties.js
// Sentinel-1 IW single polarization properties
var point = ee.Geometry.Point([6,51]);
var collection =
ee.ImageCollection('COPERNICUS/S1_GRD')
.filterBounds(point)
.filter(ee.Filter.eq('instrumentMode', 'IW'))
.filter(ee.Filter.eq('orbitProperties_pass', 'ASCENDING'))
.filter(ee.Filter.eq('resolution_meters', 10))
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV'));
var image = ee.Image(collection.first()).select('VV');
print('MinMax');
var geom = image.geometry();
var reduce_params = {reducer: ee.Reducer.minMax(), geometry: geom, scale: 10, maxPixels: 1e9};
var minmax = image.reduceRegion(reduce_params);
print('Max:',minmax.get('VV_max'))
print('Min:',minmax.get('VV_min'))
var reduce_params = {reducer: ee.Reducer.mean(), geometry: geom, scale: 10, maxPixels: 1e9};
var mean = image.reduceRegion(reduce_params);
print('Mean:',mean.get('VV'))
<file_sep>/Misc/quality-mosaic.js
//Get images
var l8s = ee.ImageCollection('LC8_L1T_TOA')
.filterDate(ee.Date.fromYMD(2015,1,1),ee.Date.fromYMD(2015,12,31))
.select([1,2,3,4,5,9,6],['blue','green','red','nir','swir1','temp','swir2']);
//Add NDVI
l8s = l8s.map(function(img){
var ndvi = img.normalizedDifference(['nir','red']).rename(['NDVI']);
return img.addBands(ndvi);
});
//Find pixel values corresonding the the max NDVI
var maxNDVIComposite = l8s.qualityMosaic('NDVI');
Map.addLayer(maxNDVIComposite,{'min': 0.05,'max': [0.3,0.6,0.35], 'bands':'swir1,nir,red'},'Max NDVI Composite');
<file_sep>/ImageCollection/chirp-annual-series-chart.js
// Map.setCenter(9.5032, 34.2918, 12)
var d0 = ee.Date('2004-1-1');
var images = ee.List.sequence(0, 10).map(function(i) {
var start = d0.advance(i, 'year'), end = start.advance(1, 'year')
return ee.ImageCollection("UCSB-CHG/CHIRPS/PENTAD").filterDate(start, end).sum().set('system:time_start', start)
})
var geometry = /* color: #0B4A8B */ee.Geometry.Polygon(
[[[30.7177734375, 0.9887204566941844],
[42.7587890625, 0.39550467153201946],
[44.40673828125, 10.163560279490476],
[32.58544921875, 10.962764256386823]]])
Map.centerObject(geometry,8)
var prcpSeries = ui.Chart.image.seriesByRegion({
imageCollection: ee.ImageCollection.fromImages(images),
regions: ee.Feature(geometry, {"label": "East Africa"}),
reducer: ee.Reducer.mean(),
band: 'precipitation',
scale: 5e3,
xProperty: 'system:time_start',
seriesProperty: 'label'
});
prcpSeries.setOptions({
title: 'Precipitation over time',
vAxis: {
title: 'Precipitation (mm)'
},
});
print(prcpSeries);<file_sep>/Reducer/multiple-regression-model.js
// Take an image
var image = ee.Image('LANDSAT/LT5_SR/LT50110291984196');
// Add a spectral indice
image = image.addBands(image.normalizedDifference(['B4', 'B3']).rename('NDVI'));
// Select only the desired bands for the regression
image = image.select(['B1', 'B2', 'B3', 'NDVI']);
// Create a multiple regression model (Dependent variable: 'NDVI', Independent variables: 'B1', 'B2', 'B3')
var regressionOutput = image.reduceRegion({
reducer: ee.Reducer.linearRegression({numX: 3, numY: 1}),
maxPixels: 1e10
});
var coefficents = regressionOutput.select(['coefficients']);
print(coefficents.values());<file_sep>/UI/scalebar.js
/***
* Scalebar, userful for figures.
*
* Author: <NAME> (<EMAIL>)
*/
var geometry = /* color: #98ff00 */ee.Geometry.LineString(
[[-122.11803800178996, 37.46989834041986],
[-122.05706255876578, 37.46989834041986]]);
var geometry2 = /* color: #00ff00 */ee.Geometry.LineString(
[[-122.11803800178996, 37.47989834041986],
[-122.05706255876578, 37.47989834041986]]);
var geometry3 = /* color: #0000ff */ee.Geometry.LineString(
[[-122.11803800178996, 37.48989834041986],
[-122.05706255876578, 37.48989834041986]]);
Map.centerObject(geometry, 12)
function app() {
// default
var scalebar = Scalebar.draw(geometry)
Map.addLayer(scalebar)
// custom1
var scalebar = Scalebar.draw(geometry2, {palette: ['5ab4ac', 'f5f5f5'], steps: 3, multiplier: 1609.34, units: 'mile', format: '%.1f'})
Map.addLayer(scalebar)
// custom2
var scalebar = Scalebar.draw(geometry3, {steps:6, format: '%.1f'})
Map.addLayer(scalebar)
}
// ============================= generated: utils.js
function translate(pt, x, y) {
var pt = ee.Geometry(pt)
var coords = pt.coordinates()
var x1 = ee.Number(coords.get(0)).subtract(x)
var y1 = ee.Number(coords.get(1)).subtract(y)
return ee.Algorithms.GeometryConstructors.Point(ee.List([x1, y1]))
}
/***
* Draws text as an image
*/
var Text = {
draw: function draw(text, pos, scale, props) {
text = ee.String(text);
var ascii = {};
for (var i = 32; i < 128; i++) {
ascii[String.fromCharCode(i)] = i;
}
ascii = ee.Dictionary(ascii);
var fontSize = '16';
if (props && props.fontSize) {
fontSize = props.fontSize;
}
var glyphs = ee.Image('users/gena/fonts/Arial' + fontSize);
var proj = glyphs.projection();
glyphs = glyphs.changeProj(proj, proj.scale(1, -1));
// get font info
var font = {
height: ee.Number(glyphs.get('height')),
width: ee.Number(glyphs.get('width')),
cellHeight: ee.Number(glyphs.get('cell_height')),
cellWidth: ee.Number(glyphs.get('cell_width')),
charWidths: ee.String(glyphs.get('char_widths')).split(',').map(ee.Number.parse)
};
font.columns = font.width.divide(font.cellWidth);
font.rows = font.height.divide(font.cellHeight);
function toAscii(text) {
return ee.List(text.split('').iterate(function (char, prev) {
return ee.List(prev).add(ascii.get(char));
}, ee.List([])));
}
function moveChar(image, xmin, xmax, ymin, ymax, x, y) {
var ll = ee.Image.pixelLonLat();
var nxy = ll.floor().round().changeProj(ll.projection(), image.projection());
var nx = nxy.select(0);
var ny = nxy.select(1);
var mask = nx.gte(xmin).and(nx.lt(xmax)).and(ny.gte(ymin)).and(ny.lt(ymax));
return image.mask(mask).translate(ee.Number(xmin).multiply(-1).add(x), ee.Number(ymin).multiply(-1).subtract(y));
}
var codes = toAscii(text);
// compute width for every char
var charWidths = codes.map(function (code) {
return ee.Number(font.charWidths.get(ee.Number(code)));
});
// compute xpos for every char
var charX = ee.List(charWidths.iterate(function (w, list) {
list = ee.List(list);
var lastX = ee.Number(list.get(-1));
var x = lastX.add(w);
return list.add(x);
}, ee.List([0]))).slice(0, -1);
var charPositions = charX.zip(ee.List.sequence(0, charX.size()));
// compute char glyph positions
var charGlyphPositions = codes.map(function (code) {
code = ee.Number(code).subtract(32); // subtract start star (32)
var y = code.divide(font.columns).floor().multiply(font.cellHeight);
var x = code.mod(font.columns).multiply(font.cellWidth);
return [x, y];
});
var charGlyphInfo = charGlyphPositions.zip(charWidths).zip(charPositions);
pos = ee.Geometry(pos).transform(proj).coordinates();
var xpos = ee.Number(pos.get(0));
var ypos = ee.Number(pos.get(1));
// 'look-up' and draw char glyphs
var textImage = ee.ImageCollection(charGlyphInfo.map(function (o) {
o = ee.List(o);
var glyphInfo = ee.List(o.get(0));
var gw = ee.Number(glyphInfo.get(1));
var glyphPosition = ee.List(glyphInfo.get(0));
var gx = ee.Number(glyphPosition.get(0));
var gy = ee.Number(glyphPosition.get(1));
var charPositions = ee.List(o.get(1));
var x = ee.Number(charPositions.get(0));
var i = ee.Number(charPositions.get(1));
var glyph = moveChar(glyphs, gx, gx.add(gw), gy, gy.add(font.cellHeight), x, 0, proj);
return glyph.changeProj(proj, proj.translate(xpos, ypos).scale(scale, scale));
})).mosaic();
textImage = textImage.mask(textImage);
if (props) {
props = {
textColor: props.textColor || 'ffffff',
outlineColor: props.outlineColor || '000000',
outlineWidth: props.outlineWidth || 0,
textOpacity: props.textOpacity || 0.9,
textWidth: props.textWidth || 1,
outlineOpacity: props.outlineOpacity || 0.4
};
var textLine = textImage.visualize({ opacity: props.textOpacity, palette: [props.textColor], forceRgbOutput: true });
if (props.textWidth > 1) {
textLine.focal_max(props.textWidth);
}
if (!props || props && !props.outlineWidth) {
return textLine;
}
var textOutline = textImage.focal_max(props.outlineWidth).visualize({ opacity: props.outlineOpacity, palette: [props.outlineColor], forceRgbOutput: true });
return ee.ImageCollection.fromImages(ee.List([textOutline, textLine])).mosaic();
} else {
return textImage;
}
}
};
/***
* Draws scalebar
*/
var Scalebar = {
draw: function (pos, props) {
var scale = Map.getScale()
var width = 200
var units = 'km'
var steps = 5
var multiplier = 1000
var palette = ['000000', 'ffffff']
var format = '%.0f'
var round = true
if(props) {
scale = props.scale || scale
units = props.units || units
steps = props.steps || steps
multiplier = props.multiplier || multiplier
palette = props.palette || palette
format = props.format || format
round = props.round !== 'undefined' ? props.round : round
}
var p = ee.Number(Map.getScale()).divide(ee.Image().projection().nominalScale())
var pt0 = ee.Geometry.Point(pos.coordinates().get(0))
var pt1 = ee.Geometry.Point(pos.coordinates().get(1))
// scalebar
var bounds = pos.buffer(Map.getScale() * 2).bounds()
var ll = ee.List(ee.List(bounds.coordinates().get(0)).get(0))
var ur = ee.List(ee.List(bounds.coordinates().get(0)).get(2))
var width = ee.Number(ur.get(0)).subtract(ll.get(0))
var height = ee.Number(ur.get(1)).subtract(ll.get(1))
var origin = ee.Image.constant(ll.get(0)).addBands(ee.Image.constant(ll.get(1)))
var scalebar = ee.Image.pixelLonLat()
.subtract(origin)
.divide([width, height]).multiply([steps, 1])
.toInt().reduce(ee.Reducer.sum()).bitwiseAnd(1)
.clip(bounds)
// units
var point = translate(pt1, p.multiply(-8), p.multiply(-7))
var imageUnits = Text.draw(units, point, scale, {fontSize:14, textColor: '000000'})
// define base images
var images = ee.List([
scalebar.visualize({min:0, max:1, forceRgbOutput: true, palette: palette}),
ee.Image().paint(bounds, 1, 1).visualize({palette:['000000']}),
imageUnits,
])
// add labels
var boundsMeters = bounds.transform(ee.Projection('EPSG:3857'), ee.ErrorMargin(1))
var ll = ee.List(ee.List(boundsMeters.coordinates().get(0)).get(0))
var ur = ee.List(ee.List(boundsMeters.coordinates().get(0)).get(2))
var widthTargetUnits = ee.Number(ur.get(0)).floor().subtract(ee.Number(ll.get(0)).ceil())
for(var i=0; i<steps+1; i++) {
var markerText = widthTargetUnits.divide(steps * multiplier).multiply(i).format(format)
var point = translate(
pt0,
width.divide(steps).multiply(i).multiply(-1).add(p.multiply(5)),
p.multiply(-15)
)
var imageLabel = Text.draw(markerText, point, scale, {fontSize:14, textColor: '000000'})
images = images.add(imageLabel)
}
return ee.ImageCollection.fromImages(images).mosaic()
},
}
app()<file_sep>/Reducer/reduce-and-chart-band-values-for-a-series-of-buffers.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var region = /* color: #d63000 */ee.Geometry.Polygon(
[[[-122.607421875, 43.447934055374034],
[-122.16796875, 44.835421613637564],
[-123.486328125, 44.52294742992487]]]),
line = /* color: #98ff00 */ee.Geometry.LineString(
[[-120.05859375, 44.648139323193966],
[-124.27734375, 43.766135280960974]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var startDate = '2005-06-01';
var endDate = '2005-09-30';
// Get collection
var c = ee.ImageCollection('LANDSAT/LT5_L1T_TOA')
.filterDate(startDate,endDate)
.filterBounds(region)
// Create a median mosaic from the collection
// *Not* the best way to do this, but just for simplicity
var medImage = c.median();
// Calculate NDVI
var ndvi = medImage.normalizedDifference(['B4', 'B3']);
// Create a list of distances
var distances = ee.List.sequence(1000, 5000, 1000);
// Map over these distances and return mean values
var means = distances.map(function(d) {
var b = line.buffer(d);
var m = ndvi.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: b,
scale: 30,
maxPixels: 1e9
});
return m.get('nd');
});
// Graph the NDVI values across buffer widths
var chart = ui.Chart.array.values(means, 0, distances)
.setChartType('ColumnChart');
print(chart);
<file_sep>/Datasets/HydroBASINS-raster.js
/***
* Author: <NAME> (<EMAIL>)
*/
// rasterized geometries on PFAF12
var HydroBASINSimage = ee.Image("users/rutgerhofste/PCRGlobWB20V04/support/global_Standard_lev00_30sGDALv01");
var HydroBASINSimageProjection = HydroBASINSimage.projection();
var HydroBASINSimageNominalScale = HydroBASINSimageProjection.nominalScale();
var Levels = {
"Level 1": 1,
"Level 2": 2,
"Level 3": 3,
"Level 4": 4,
"Level 5": 5,
"Level 6": 6,
"Level 7": 7,
"Level 8": 8,
"Level 9": 9,
"Level 10": 10,
"Level 11": 11,
"Level 12": 12,
};
// Create an empty panel in which to arrange widgets.
// The layout is vertical flow by default.
var panel = ui.Panel({style: {width: '400px'}})
.add(ui.Label('Select HydroBasins Level:'))
.add(ui.Select({
items: Object.keys(Levels),
onChange: function(key) {
var newBasinPFAFLevel =Levels[key]
var newHydroBASINimage = HydroBASINSimage.divide(ee.Number(10).pow(ee.Number(12).subtract(newBasinPFAFLevel))).floor();
Map.addLayer(newHydroBASINimage.randomVisualizer(), {opacity: 1},"HydroBasins", true)
print("added level: " + Levels[key]);
}
})
);
ui.root.add(panel);
<file_sep>/Array/savitzky-golay-smoothing.js
// Savitzky Golay smoothing
//
// Transcribed from:
//
// http://www2.geog.ucl.ac.uk/~plewis/eoldas/plot_directive/savitzky_golay.py
//
// Author: <NAME> - EC JRC, 2017-02-23
//
// Get some data to smooth.
// MOD09A1 (8-day composite surface reflectance) for Fuentes, Andalucia (Spain)
// Derived from colum 7 and 8 of:
// http://www2.geog.ucl.ac.uk/~plewis/eoldas/data/FuentesAndalucia_MOD09A1.txt
//
// This would normally be a time-series extracted from your favourite image collection
var y = ee.List([ 0.2848061, 0.30228013, 0.34789697, 0.32501599, 0.39469027, 0.4377276,
0.33893395, 0.37984496, 0.39857228, 0.39573634, 0.47152728, 0.47152728,
0.47924113, 0.39227134, 0.32331224, 0.2087859, 0.20336943, 0.20721056,
0.19288119, 0.18133762, 0.17329094, 0.16575934, 0.16575934, 0.1612529,
0.15125293, 0.15, 0.15096154, 0.15008432, 0.15085739, 0.13942904,
0.14469453, 0.15195531, 0.14524043, 0.14524043, 0.15950435, 0.15972414,
0.15228758, 0.15082444, 0.15223881, 0.14943074, 0.18042813, 0.2026749,
0.20156897, 0.19865571, 0.19865571, 0.23084913, 0.19461078, 0.183271,
0.21911197, 0.25281271, 0.25281271, 0.29778934, 0.33450241, 0.3513862,
0.34829884, 0.41832669, 0.4115899, 0.49730942, 0.35539881, 0.45935484,
0.3550206, 0.3550206, 0.46144549, 0.50094928, 0.50684932, 0.50809492,
0.54877014, 0.49391727, 0.61421935, 0.40859525, 0.32255083, 0.33121861,
0.33121861, 0.28408357, 0.26169539, 0.20380048, 0.20922075, 0.21085336,
0.19551364, 0.20337553, 0.19558499, 0.19014778, 0.18839836, 0.18839836,
0.1738367, 0.17821782, 0.19377163, 0.17986366, 0.19295371, 0.22772277,
0.17810897, 0.26148705, 0.20528087, 0.2055958, 0.2055958, 0.2309217,
0.21856867, 0.23418424, 0.31344284, 0.42614933, 0.40538991, 0.47488038,
0.40963139, 0.53891941, 0.69198966, 0.58185297, 0.65561044, 0.7715852,
0.84103434, 0.74339454, 0.74779807, 0.74779807, 0.7285576, 0.70140628,
0.69911504, 0.53225806, 0.47955936, 0.36809138, 0.3962766, 0.3330139,
0.37059484, 0.39720646, 0.39720646, 0.2823741, 0.24439377, 0.22083614,
0.22766784, 0.20806634, 0.21386403, 0.2324159, 0.21760138, 0.20263202,
0.21859436, 0.21859436, 0.18293839, 0.19146184, 0.20522388, 0.21745949,
0.23439667, 0.21584424, 0.19299674, 0.21705724, 0.24536465, 0.19491275,
0.19491275, 0.18128964, 0.16930257, 0.17865676, 0.22205663, 0.26136758,
0.24858757, 0.24618878, 0.30006398, 0.292764, 0.34330794, 0.5065312,
0.4456338, 0.43773764, 0.36156187, 0.43247269, 0.40318627, 0.40318627,
0.38701127, 0.38603033, 0.29321534, 0.2702588, 0.2668899, 0.36302411,
0.44280763, 0.67062193, 0.72665348, 0.58686888, 0.58686888, 0.48899756,
0.45064205, 0.30582524, 0.27057812, 0.22242446, 0.22719914, 0.21802227,
0.2240672, 0.21699079, 0.21996584, 0.21996584, 0.20253918, 0.20034881,
0.19817134, 0.18880811, 0.19576508, 0.1764432, 0.2200709, 0.23420847,
0.22808958, 0.25047081, 0.25047081, 0.19158361, 0.21023766, 0.22650104,
0.29181355, 0.32668781])
print(y.length())
var window_size = 11
var half_window = (window_size - 1)/2
var deriv = 0
var order = 2
var order_range = ee.List.sequence(0,order)
var k_range = ee.List.sequence(-half_window, half_window)
//b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)])
var b = ee.Array(k_range.map(function (k) { return order_range.map(function(o) { return ee.Number(k).pow(o)})}))
print(b)
// m = np.linalg.pinv(b).A[deriv]
var mPI = ee.Array(b.matrixPseudoInverse())
print(mPI)
var impulse_response = (mPI.slice({axis: 0, start: deriv, end: deriv+1})).project([1])
print(impulse_response)
//firstvals = y[0] - np.abs( y[1:half_window+1][::-1] - y[0] )
var y0 = y.get(0)
var firstvals = y.slice(1, half_window+1).reverse().map(
function(e) { return ee.Number(e).subtract(y0).abs().multiply(-1).add(y0) }
)
print(firstvals)
//lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
var yend = y.get(-1)
var lastvals = y.slice(-half_window-1,-1).reverse().map(
function(e) { return ee.Number(e).subtract(yend).abs().add(yend) }
)
print(lastvals)
// y = np.concatenate((firstvals, y, lastvals))
var y_ext = firstvals.cat(y).cat(lastvals)
print(y_ext.length())
// np.convolve( m, y, mode='valid')
var runLength = ee.List.sequence(0, y_ext.length().subtract(window_size))
var smooth = runLength.map(function(i) {
return ee.Array(y_ext.slice(ee.Number(i), ee.Number(i).add(window_size))).multiply(impulse_response).reduce("sum", [0]).get([0])
})
print(smooth)
// Chart
var yValues = ee.Array.cat([y, smooth], 1);
var chart = ui.Chart.array.values(yValues, 0).setSeriesNames(['Raw', 'Smoothed']).setOptions(
{
title: '<NAME> (ES)' + ' Window: ' + window_size + ' Order: ' + order,
hAxis: {title: 'Time (x 8 days)'}, vAxis: {title: 'MOD09A1 NDVI'},
legend: null,
series: {
0: { lineWidth: 0},
1: { lineWidth: 2, pointSize: 0 }}
})
print(chart)
<file_sep>/FeatureCollection/error-matrix-from-feature-collection.js
// var roi = Map.getBounds(true)
// // ee.FeatureCollection.randomPoints(region, points, seed, maxError)
// var random = ee.FeatureCollection.randomPoints(roi, 5e2, 10)
// .map(function (f) {
// f = f.set('x',f.geometry().centroid().coordinates().get(0));
// f = f.set('y',f.geometry().centroid().coordinates().get(1));
// return f;
// });
// var confusionMatrix = random.randomColumn('r1',4).randomColumn('r2',3)
// .map(function (f){
// return f.set('truth', ee.Number(f.get('r1')).gte(0.5)).set('pred', ee.Number(f.get('r2')).gte(0.5));
// }).errorMatrix('truth', 'pred');
var ft = ee.FeatureCollection('ft:1wUJ-s-G9xbCOJHwMlOIEa2WMclyFAl2IdgVViMjE')
var confusionMatrix = ft.errorMatrix('class', 'type');
print('Confusion Matrix', confusionMatrix);
print('Accuracy', confusionMatrix.accuracy());
print('Consumers Accuracy', confusionMatrix.consumersAccuracy());
print('Producers Accuracy', confusionMatrix.producersAccuracy());
print('Kappa', confusionMatrix.kappa());
Export.table.toDrive({
folder: 'fusiontable',
description: 'testConfusionMatrixExport',
fileFormat: 'csv',
collection: ee.FeatureCollection([ee.Feature(null, {'matrix':ee.Array(confusionMatrix.array()).toList()})])
})<file_sep>/UI/quick-move.js
var places = ee.FeatureCollection([
ee.Feature(ee.Geometry.Point([31.982574462890625, 30.474715811513853]),{"name": "egypt.irri"}),
ee.Feature(ee.Geometry.Point([9.62377, 36.67923]),{"name": "tun.big"}),
ee.Feature(ee.Geometry.Point([8.87352, 36.50025]),{"name": "tun.sm"}),
ee.Feature(ee.Geometry.Point([39.9511, 8.83673]),{"name": "eth.farm"}),
ee.Feature(ee.Geometry.Point([39.2278, 8.97559]),{"name": "eth.sm"}),
ee.Feature(ee.Geometry.Point([38.897653, 8.250736]),{"name": "eth.s1"}),
ee.Feature(ee.Geometry.Point([36.539454, -0.863918]),{"name": "ken.s1"}),
ee.Feature(ee.Geometry.Point([29.350426, -3.197833]),{"name": "rwa.s1"}),
ee.Feature(ee.Geometry.Point([29.52072, -3.307664]),{"name": "rwa.s2"}),
ee.Feature(ee.Geometry.Point([35.475368, -15.502256]),{"name": "mal.s1"}),
ee.Feature(ee.Geometry.Point([30.53598, -29.88281]),{"name": "sa.sugar"}),
ee.Feature(ee.Geometry.Point([28.48394, -26.8279]),{"name": "sa.corn"})
]);
function goto(m, place, zoom){
if (typeof zoom === "undefined") zoom = 14
var dest = places.filter(ee.Filter.eq('name', place))
m.centerObject(dest, zoom)
}
goto(Map, 'egypt.irri')
// Map.
// var ref = ee.Image('users/JunXiong1981/ref/SA_ctype_ref')
// var ce = ee.Image("users/JunXiong1981/release/GFSAD30AFCE001")
// var image2 = ee.Image("users/JunXiong1981/ref/ghana_landsat_lulc_12c")
// var image3 = ee.Image("users/JunXiong1981/ref/kzn_land_cover")
// var image4 = ee.Image("users/JunXiong1981/ref/murali-tunisia-croptype")
// var image5 = ee.Image("users/JunXiong1981/ref/southafrica_nlc2008")
// Map.addLayer(ref.mask(ref), {palette:'00ff00', opacity:.6})
// var ft = ee.FeatureCollection('ft:1wiRq9P92gZwR8yCeWCH-X5VNOUV3EjJetQRA9sXH') // Africa ground samples (1380)
// Map.addLayer(ft, {color:'ffff00'})
<file_sep>/FeatureCollection/random-samples-add-geo-get-value.js
var roi = Map.getBounds(true)
// ee.FeatureCollection.randomPoints(region, points, seed, maxError)
var random = ee.FeatureCollection.randomPoints(roi, 5e2, 10)
.map(function (f) {
f = f.set('x',f.geometry().centroid().coordinates().get(0));
f = f.set('y',f.geometry().centroid().coordinates().get(1));
return f;
});
Export.table.toDrive({
collection: random.select(['x', 'y'], null, false),
description: 'randomPoints',
folder: 'fusiontable',
fileNamePrefix: 'randomPoints2000Europe3',
fileFormat: 'csv'
})<file_sep>/UI/linked-view.js
var map = [];
'Left Right'.split(' ').forEach(function(name, index) {
var m = ui.Map();
m.setCenter(31.99974, 30.46969, 13)
m.setOptions('SATELLITE').setControlVisibility(null, null, false, false, false).style().set('cursor', 'crosshair')
map.push(m);
});
ui.root.widgets().reset([
ui.Panel(
[map[0]],
ui.Panel.Layout.Flow('vertical'),
{stretch: 'both'}),
ui.Panel(
[map[1]],
ui.Panel.Layout.Flow('vertical'),
{stretch: 'both'}),
]);
ui.Map.Linker(map);<file_sep>/Chart/sigs-stat-by-class-chart1.js
var image = ee.Image('LANDSAT/LC8_L1T_TOA/LC80440342014077LGN00')
Map.centerObject(image, 14)
var geometry = Map.getBounds(true)
print(geometry)
var training = image.sample({region: geometry, scale: 30, numPixels: 500})
var classified = image.cluster(ee.Clusterer.wekaKMeans(8).train(training)).rename('class');
var palette = ['#66c2a5','#fc8d62','#8da0cb','#e78ac3','#a6d854','#ffd92f','#e5c494','#b3b3b3']
Map.addLayer(classified, {min:1, max:8, palette:palette}, 'Unsupervised Classification')
var bands = ['B1','B2','B3','B4','B5','B6','B7','B8']
// print(classified)
// var chart = ui.Chart.image.byClass(image.addBands(classified), 'class', geometry//.aside(print)//, null, 30, null, null).aside(print)
// print(chart)
// ui.Chart.image.byClass(image, classBand, region, reducer, scale, classLabels, xLabels)
var chart = ui.Chart.image.byClass({image:image.select(bands).addBands(classified), classBand:'class', region:ee.Feature(geometry)})
print(chart)
// function computeStatistics(image, clusterImage) {
// var numClasses = clusterImage.reduceRegion({
// geometry: geometry,
// reducer: ee.Reducer.max(),
// scale: 30,
// bestEffort: true,
// maxPixels: 1e6,
// });
// var classes = ee.List.sequence(0, numClasses.get('cluster')).map(function(i) {
// var oneClass = image.mask(clusterImage.eq(ee.Number(i)));
// var reducer = ee.Reducer.mean()
// // .combine(ee.Reducer.median(), null, true)
// // .combine(ee.Reducer.max(), null, true)
// // .combine(ee.Reducer.min(), null, true)
// .combine(ee.Reducer.stdDev(), null, true);
// var stats = oneClass.reduceRegion({
// geometry: geometry,
// reducer: reducer,
// scale: 30,
// bestEffort: true,
// maxPixels: 1e6,
// });
// return ee.Feature(null, stats);
// });
// return classes;
// }
// print(image)
// var stats = computeStatistics(image, classified, 8);
// print('stats', stats); // look in properties
// var profile = ee.List.sequence(1,8).map(function(i){
// i = ee.Number(i).int(); // need to cast to number and int
// return image_stack
// .updateMask(memb.eq(i))
// .reduceRegion({
// reducer: ee.Reducer.mean(),
// geometry: memb.geometry(),
// scale: 5000, // pixel size
// bestEffort: true
// });
// });
// print(profile);
// var arry = ee.List.sequence(1,8).map(function (i) {
// i = ee.Number(i).int();
// var classData = ee.Dictionary(profile.get(i.subtract(1)));
// return ee.List(classData.toArray());//.map(function (v) {return ee.Number(v).int();});
// });
// print(arry);
// print(Chart.array.values(arry, 1))
// var fc = ee.FeatureCollection(profile.map(function (f){ return ee.Feature(null, f); }));
// print(Chart.feature.byProperty(fc));<file_sep>/Misc/surface-water-change-detection.js
/***
* Surface water change detection (copied from http://aqua-monitor.appspot.com)
*
* Citation: Donchyts, Gennadii, et al. "Earth's surface water change over the past 30 years." Nature Climate Change 6.9 (2016): 810-813.
*
* License: LGPL
*
* See original code on http://github.com/deltares/aqua-monitor
*/
var hand = ee.ImageCollection("users/gena/global-hand/hand-100"),
countries = ee.FeatureCollection("ft:1tdSwUL7MVpOauSgRzqVTOwdfy17KDbw-1d9omPw"),
glcf = ee.ImageCollection("GLCF/GLS_WATER"),
geometry = /* color: d63000 */ee.Geometry.MultiPoint();
function renderLandsatMosaic(options, dateIntervalIndex) {
var percentile = options.percentile;
var start = options.dateIntervals[dateIntervalIndex][0];
var stop = options.dateIntervals[dateIntervalIndex][1];
var sharpen = options.sharpen;
var smoothen = options.smoothen;
var filterCount = options.filterCount;
var bands = ['swir1', 'nir', 'green'];
var l8 = new ee.ImageCollection('LANDSAT/LC8_L1T_TOA').filterDate(start, stop).select(['B6', 'B5', 'B3'], bands);
var l7 = new ee.ImageCollection('LANDSAT/LE7_L1T_TOA').filterDate(start, stop).select(['B5', 'B4', 'B2'], bands);
var l5 = new ee.ImageCollection('LANDSAT/LT5_L1T_TOA').filterDate(start, stop).select(['B5', 'B4', 'B2'], bands);
var l4 = new ee.ImageCollection('LANDSAT/LT4_L1T_TOA').filterDate(start, stop).select(['B5', 'B4', 'B2'], bands);
var images = ee.ImageCollection(l8.merge(l7).merge(l5).merge(l4))
//images = ee.ImageCollection(images.limit(100))
//var images = ee.ImageCollection(l7.merge(l5).merge(l4))
if(smoothen) {
images = images.map(function(i) { return i.resample('bicubic'); })
}
var image = images
//.filterMetadata('SUN_AZIMUTH', 'greater_than', 5) // almost empty
.reduce(ee.Reducer.percentile([percentile]))
.rename(bands)
if(filterCount > 0) {
image = image.mask(images.select(0).count().gt(filterCount));
}
Map.addLayer(images.select(0).count(), {min:filterCount, max:200, palette:['ff0000', '00ff00']}, 'count', false)
if(sharpen) {
// LoG
image = image.subtract(image.convolve(ee.Kernel.gaussian(30, 20, 'meters')).convolve(ee.Kernel.laplacian8(0.4)))
}
return image.visualize({min: 0.05, max: [0.5, 0.5, 0.6], gamma: 1.4})
}
// A helper to apply an expression and linearly rescale the output.
var rescale = function (img, thresholds) {
return img.subtract(thresholds[0]).divide(ee.Number(thresholds[1]).subtract(thresholds[0]))
.copyProperties(img)
.copyProperties(img, ['system:time_start']);
};
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
var generateGrid = function(xmin, ymin, xmax, ymax, dx, dy) {
var xx = ee.List.sequence(xmin, ee.Number(xmax).subtract(dx), dx);
var yy = ee.List.sequence(ymin, ee.Number(ymax).subtract(dx), dy);
var polys = xx.map(function(x) {
return yy.map(function(y) {
var x1 = ee.Number(x)
var x2 = ee.Number(x).add(dx)
var y1 = ee.Number(y)
var y2 = ee.Number(y).add(dy)
var coords = ee.List([x1, y1, x2, y2]);
return ee.Feature(ee.Algorithms.GeometryConstructors.Rectangle(coords));
})
}).flatten()
return ee.FeatureCollection(polys);
}
function getIntersection(left, right) {
var spatialFilter = ee.Filter.intersects({leftField: '.geo', rightField: '.geo', maxError: 1000});
var saveAllJoin = ee.Join.saveAll({matchesKey: 'match'});
var intersectJoined = saveAllJoin.apply(left, right, spatialFilter);
return intersectJoined.map(function(f) {
var match = ee.List(f.get('match'));
return f.set('count', match.length())
}).filter(ee.Filter.gt('count', 0))
}
function getEdge(i) {
var canny = ee.Algorithms.CannyEdgeDetector(i, 0.99, 0);
canny = canny.mask(canny)
return canny;
}
function createTimeBand(img) {
var date = ee.Date(img.get('system:time_start'));
var year = date.get('year').subtract(1970);
return ee.Image(year).byte().addBands(img)
}
// TODO: split it into smaller functions
function renderWaterTrend(options) {
var dateIntervals = options.dateIntervals;
var percentile = options.percentile;
var slopeThreshold = options.slopeThreshold;
var slopeThresholdRatio = options.slopeThresholdRatio;
var refine = options.refine;
var slopeThresholdRefined = options.slopeThresholdRefined;
var ndviFilter = options.ndviFilter;
var filterCount = options.filterCount;
var showEdges = options.showEdges;
var smoothen = options.smoothen;
var includeBackgroundSlope = options.includeBackgroundSlope;
var backgroundSlopeOpacity = options.backgroundSlopeOpacity;
var refineFactor = options.refineFactor;
var ndwiMaxLand = options.ndwiMaxLand;
var ndwiMinWater = options.ndwiMinWater;
var bands = ['green', 'swir1'];
var bands8 = ['B3', 'B6'];
var bands7 = ['B2', 'B5'];
if(ndviFilter > -1) {
bands = ['green', 'swir1', 'nir', 'red'];
bands8 = ['B3', 'B6', 'B5', 'B4'];
bands7 = ['B2', 'B5', 'B4', 'B3'];
}
var images = new ee.ImageCollection([])
var images_l8 = new ee.ImageCollection('LANDSAT/LC8_L1T_TOA').select(bands8, bands);
images = new ee.ImageCollection(images.merge(images_l8));
var images_l7 = new ee.ImageCollection('LANDSAT/LE7_L1T_TOA').select(bands7, bands);
images = new ee.ImageCollection(images.merge(images_l7));
var images_l5 = new ee.ImageCollection('LANDSAT/LT5_L1T_TOA').select(bands7, bands);
images = new ee.ImageCollection(images.merge(images_l5));
var images_l4 = new ee.ImageCollection('LANDSAT/LT4_L1T_TOA').select(bands7, bands);
images = new ee.ImageCollection(images.merge(images_l4));
// images = ee.ImageCollection(images.limit(100))
var list = ee.List(dateIntervals);
// add percentile images for debugging
if(options.debugMapLayers) {
list.getInfo().map(function (i) {
var start = ee.Date(i[0].value);
var stop = ee.Date(i[1].value);
var filtered = images.filterDate(start, stop)
var percentiles = ee.List.sequence(0, 100, 1)
var result = filtered
.reduce(ee.Reducer.percentile(percentiles))
.set('system:time_start', start)
Map.addLayer(result, {}, 'all percentiles ' + start.format('YYYY-MM-dd').getInfo(), false)
});
}
// compute a single annual percentile
var annualPercentile = ee.ImageCollection(list.map(function (i) {
var l = ee.List(i);
var start = l.get(0);
var stop = l.get(1);
var filtered = images.filterDate(start, stop)
if(smoothen) {
filtered = filtered.map(function(i) { return i.resample('bicubic'); })
}
var image = filtered
.reduce(ee.Reducer.percentile([percentile])).rename(bands)
var result = image
.normalizedDifference(['green', 'swir1']).rename('water')
.set('system:time_start', start);
if(ndviFilter > -1) {
var ndvi = image.normalizedDifference(['nir', 'red']).rename('ndvi');
result = result.addBands(ndvi)
}
if(filterCount > 0) {
result = result.addBands(filtered.select(0).count().rename('count'));
}
return result
}));
var mndwi = annualPercentile.select('water')
if(ndviFilter > -1) {
var ndvi = annualPercentile.select('ndvi')
}
var fit = mndwi
.map(function(img) {
return rescale(img, [-0.6, 0.6]);
})
.map(createTimeBand)
.reduce(ee.Reducer.linearFit().unweighted());
var scale = fit.select('scale')
var scaleMask = scale.mask();
if(options.debugMapLayers) {
Map.addLayer(scaleMask, {}, 'scale original mask', false)
Map.addLayer(scale, {
min: -slopeThreshold * slopeThresholdRatio,
max: slopeThreshold * slopeThresholdRatio,
palette: ['00ff00', '000000', '00d8ff'],
}, 'scale', false)
}
var mndwiMin = mndwi.min();
var mndwiMax = mndwi.max();
if(ndviFilter > -1) {
var ndviMin = ndvi.min();
}
if(options.debugMapLayers) {
Map.addLayer(mndwiMin, {}, 'mndwi min (raw)', false)
Map.addLayer(mndwiMax, {}, 'mndwi max (raw)', false)
if(ndviFilter > -1) {
Map.addLayer(ndvi.min(), {}, 'ndvi min (raw)', false)
Map.addLayer(ndvi.max(), {}, 'ndvi max (raw)', false)
}
}
if(options.useSwbdMask) {
var swbd = ee.Image('MODIS/MOD44W/MOD44W_005_2000_02_24').select('water_mask')
var swbdMask = swbd.unmask().not()
.focal_max(10000, 'square', 'meters').reproject('EPSG:4326', null, 1000)
}
// computes a mask representing a surface water change using a given slope (linear fit scale) threshold
function computeSlopeMask(threshold) {
var minWaterMask = mndwiMax.gt(ndwiMinWater) // maximum looks like water
var maxLandMask = mndwiMin.lt(ndwiMaxLand) // minimum looks like land
var mask = scale.unmask().abs().gt(threshold)
.multiply(minWaterMask)
.multiply(maxLandMask)
if(ndviFilter > -1) {
var ndviMask = ndviMin.lt(ndviFilter)
mask = mask.multiply(ndviMask) // deforestation?
}
if(filterCount > 0) {
var countMask = annualPercentile.select('count').min().gt(filterCount)
mask = mask.multiply(countMask);
}
if(options.useSwbdMask) {
mask = mask.multiply(swbdMask)
}
// add eroded original scale mask (small scale-friendly erosion, avoid kernel too large)
var erodedScaleMask = scaleMask
.focal_min(10000, 'square', 'meters').reproject('EPSG:4326', null, 1000)
mask = mask.multiply(erodedScaleMask)
if(options.debugMapLayers) {
Map.addLayer(minWaterMask.not().mask(minWaterMask.not()), {}, 'min water mask', false)
Map.addLayer(maxLandMask.not().mask(maxLandMask.not()), {}, 'max land mask', false)
if(ndviFilter > -1) {
Map.addLayer(ndviMask.not().mask(ndviMask.not()), {}, 'ndvi mask', false)
}
if(filterCount > 0) {
Map.addLayer(countMask.not().mask(countMask.not()), {}, 'count mask', false)
}
if(options.useSwbdMask) {
Map.addLayer(swbdMask.not().mask(swbdMask.not()), {}, 'swbd mask', false)
}
Map.addLayer(erodedScaleMask.not().mask(erodedScaleMask.not()), {}, 'scale original mask (eroded)', false)
}
return mask;
}
print('slope threshold: ', slopeThresholdRatio * slopeThreshold)
var mask = computeSlopeMask(slopeThresholdRatio * slopeThreshold);
if(refine) {
// this should be easier, maybe use SRTM projection
mask = mask.reproject('EPSG:4326', null, 30)
var prj = mask.projection();
// more a buffer around larger change
var maskBuffer = mask
.reduceResolution(ee.Reducer.max(), true)
.focal_max(refineFactor)
.reproject(prj.scale(refineFactor, refineFactor))
.focal_mode(ee.Number(refineFactor).multiply(30), 'circle', 'meters')
print('slope threshold (refined): ', slopeThresholdRefined * slopeThresholdRatio)
var maskRefined = computeSlopeMask(slopeThresholdRefined * slopeThresholdRatio).mask(maskBuffer)
if(options.debugMapLayers) {
Map.addLayer(mask.mask(mask), {}, 'mask (raw)', false)
Map.addLayer(maskBuffer.mask(maskBuffer), {}, 'mask buffer (raw)', false)
Map.addLayer(maskRefined.mask(maskRefined), {}, 'mask refined (raw)', false)
}
// smoothen scale and mask
if(smoothen) {
scale = scale
.focal_median(25, 'circle', 'meters', 3);
mask = mask
.focal_mode(35, 'circle', 'meters', 3)
}
}
if(options.debugMapLayers) {
Map.addLayer(scale, {}, 'scale (raw)', false)
}
var results = [];
// background
var bg = ee.Image(1).toInt().visualize({palette: '000000', opacity: 0.4});
if(includeBackgroundSlope) {
bg = scale.visualize({
min: -slopeThreshold * slopeThresholdRatio,
max: slopeThreshold * slopeThresholdRatio,
palette: ['00ff00', '000000', '00d8ff'], opacity: backgroundSlopeOpacity
});
// exclude when both are water
bg = bg.mask(ee.Image(backgroundSlopeOpacity).toFloat().multiply(mndwiMin.gt(0.4).focal_mode(1).not()))
}
if(filterCount > 0) {
bg = bg.multiply(annualPercentile.select('count').min().gt(filterCount));
}
if(options.useSwbdMask) {
bg = bg.multiply(swbdMask.gt(0))
}
results.push(bg);
// surface water change
if(refine) {
if(options.debug) {
var maskBufferVis = maskBuffer.mask(maskBuffer).visualize({palette:['ffffff', '000000'], opacity:0.5})
results.push(maskBufferVis);
}
var edgeWater = getEdge(mask.mask(scale.gt(0))).visualize({palette: '00d8ff'})
var edgeLand = getEdge(mask.mask(scale.lt(0))).visualize({palette: '00ff00'})
scale = scale.mask(maskRefined)
var scaleRefined = scale.visualize({
min: -slopeThreshold * slopeThresholdRatio,
max: slopeThreshold * slopeThresholdRatio,
palette: ['00ff00', '000000', '00d8ff'],
opacity: showEdges ? 0.3 : 1.0
})
results.push(scaleRefined)
if(showEdges) {
results.push(edgeWater, edgeLand)
}
} else {
scale = scale.mask(mask)
var change = scale.visualize({
min: -slopeThreshold * slopeThresholdRatio,
max: slopeThreshold * slopeThresholdRatio,
palette: ['00ff00', '000000', '00d8ff'],
})
results.push(change);
}
return {changeVis: ee.ImageCollection.fromImages(results).mosaic(), change: scale.toFloat()};
}
function computeAggregatedSurfaceWaterChangeArea(scale, options) {
// add aggregated version of change
var changeAggregatedWater = scale.gt(0).multiply(ee.Image.pixelArea())
.reproject('EPSG:4326', null, 30)
.reduceResolution(ee.Reducer.sum(), false, 100)
.reproject('EPSG:4326', null, 300)
var changeAggregatedLand = scale.lt(0).multiply(ee.Image.pixelArea())
.reproject('EPSG:4326', null, 30)
.reduceResolution(ee.Reducer.sum(), false, 100)
.reproject('EPSG:4326', null, 300)
var maxArea = 300
var changeAggregatedWaterVis = changeAggregatedWater
.visualize({
min: 0,
max: maxArea,
palette: ['000000', '00d8ff'],
})
var changeAggregatedLandVis = changeAggregatedLand
.visualize({
min: 0,
max: maxArea,
palette: ['000000', '00ff00'],
})
Map.addLayer(changeAggregatedWater, {}, 'scale aggregated water (raw)', false)
Map.addLayer(changeAggregatedLand, {}, 'scale aggregated land (raw)', false)
Map.addLayer(changeAggregatedWaterVis.mask(changeAggregatedWater.divide(maxArea)), {}, 'change aggregated (water => land)', false)
Map.addLayer(changeAggregatedLandVis.mask(changeAggregatedLand.divide(maxArea)), {}, 'change aggregated (land => water)', false)
return {water: changeAggregatedWater.toFloat(), land: changeAggregatedLand.toFloat()};
}
function getWaterTrendChangeRatio(start, stop) {
return (15 / (stop - start)); // empiricaly found ratio
}
// ======================================================= PARAMETERS AND SCRIPT
// start / stop times and averaging periods (in months)
var time0 = [ee.Date.fromYMD(2000, 1, 1), 24];
var time1 = [ee.Date.fromYMD(2015, 1, 1), 24];
// larger periods, more robust, slower, may contain less changes (used to compute results reported in the paper)
// var time0 = [ee.Date.fromYMD(1984, 1, 1), 240];
// var time1 = [ee.Date.fromYMD(2013, 1, 1), 48];
var options = {
// intervals used for averaging and linear regression (the web site may use multiple intervals here)
dateIntervals: [
[time0[0], time0[0].advance(time0[1], 'month')],
//[time0[0].advance(12, 'month'), time0[0].advance(time0[1]+12, 'month')],
//[time1[0].advance(-12, 'month'), time1[0].advance(time1[1]-12, 'month')],
[time1[0], ee.Date.fromYMD(2016, 5, 6)] // time1[0].advance(time1[1], 'month')
],
percentile: 15,
slopeThreshold: 0.025,
slopeThresholdRatio: getWaterTrendChangeRatio(1984, 2015),
slopeThresholdRefined: 0.015,
//refine: true, // more expensive
refine: false,
refineFactor: 5,
ndviFilter: 0.08, // the highest NDVI value for water
//ndviFilter: -1,
ndwiMinWater: -0.05, // minimum value of NDWI to assume as water
ndwiMaxLand: 0.5, // maximum value of NDWI to assume as land
filterCount: 10,
//useSwbdMask: true,
useSwbdMask: false,
//showEdges: true,
showEdges: false,
includeBackgroundSlope: false,
//includeBackgroundSlope: true,
backgroundSlopeOpacity: 0.5,
smoothen: false,
//smoothen: true,
//debug: false, // shows a buffer used to refine changes
debug: false,
//debugMapLayers: true,
debugMapLayers: false,
sharpen: true,
//sharpen: false,
};
print(options.dateIntervals[0][0].format('YYYY-MM-dd').getInfo() + ' - ' + options.dateIntervals[0][1].format('YYYY-MM-dd').getInfo());
print(options.dateIntervals[1][0].format('YYYY-MM-dd').getInfo() + ' - ' + options.dateIntervals[1][1].format('YYYY-MM-dd').getInfo());
// background
Map.addLayer(ee.Image(1).toInt(), {palette:['000000']}, 'bg (black)', false);
Map.addLayer(ee.Image(1).toInt(), {palette:['ffffff']}, 'bg (white)', false);
// average images
var timeCount = options.dateIntervals.length;
Map.addLayer(renderLandsatMosaic(options, 0), {}, options.dateIntervals[0][0].format('YYYY-MM-dd').getInfo(), true);
Map.addLayer(renderLandsatMosaic(options, timeCount - 1), {}, options.dateIntervals[timeCount - 1][0].format('YYYY-MM-dd').getInfo(), true);
// country boundaries
Map.addLayer(countries.map(function(f) { return f.buffer(15000) }), {}, 'countries', false);
// GLCF water
var water = glcf.map(function(i){return i.eq(2)}).mosaic();
Map.addLayer(water.mask(water), {palette:['2020aa'], opacity: 0.5}, 'GLCF water', false);
// surface water change trend
var trend1 = renderWaterTrend(options);
Map.addLayer(trend1.changeVis, {}, '1987 - 2015 (water change)', true);
/*
options.refine = false;
options.debugMapLayers = false;
var trend1 = renderWaterTrend(options)[0];
Map.addLayer(trend1.changeVis, {}, '1987 - 2015 (water change, no refine)', true)
*/
// temporary compute aggregated version here
var trend1Aggregated = computeAggregatedSurfaceWaterChangeArea(trend1.change, options);
// HAND
var handThreshold = 50;
var handBuffer = 150;
Map.addLayer(ee.Image(1).mask(hand.mosaic().gt(handThreshold)
.focal_max(handBuffer, 'circle', 'meters')
.focal_min(handBuffer, 'circle', 'meters')
),
{palette:['000000']}, 'HAND > ' + handThreshold + ' (+' + handBuffer + 'm closing)', false);
Map.addLayer(ee.Image(1).mask(hand.mosaic().gt(50)), {palette:['000000']}, 'HAND > ' + handThreshold + 'm', false);
// set map options
Map.setOptions('SATELLITE')
// center to a specific location
print(Map.getCenter())
// Map.setCenter(55.06, 25.04, 12) // Dubai
// export
return // skip
// generate global grid
var xmin = -180, xmax = 180, ymin = -75, ymax = 85, dx = 20, dy = 20;
//var xmin = -180, xmax = 180, ymin = -80, ymax = 85, dx = 15, dy = 15;
var grid = generateGrid(xmin, ymin, xmax, ymax, dx, dy);
//var grid = ee.FeatureCollection('ft:1CH6u9UdsYgU6qsEtbsHxvYBf8ucnflmtbRVeTrU_'); // 4 degrees
//var grid = ee.FeatureCollection('ft:1cmASWugzqQBLH93vRf9t7Zvfpx_RvtmVhy8IGd6H') // 3 degrees
print('Total cell count: ', grid.size())
Map.addLayer(grid, {}, 'grid', false)
var cmd = false;
// cmd = true;
if(cmd) {
var offset = parseInt(args[1])
var maxIndex = parseInt(args[2])
var type = args[3]
} else {
var offset = 125
var maxIndex = 144
var type = 'scale'
}
var count = maxIndex - offset
grid = grid.toList(count, offset);
var l8 = new ee.ImageCollection('LANDSAT/LC8_L1T_TOA').filterDate('2014-01-01', '2015-01-01');
for(var i = offset; i < maxIndex; i++) {
var f = ee.Feature(grid.get(i - offset))
var geometry = f.geometry()
if(type == 'water') {
var name = 'water_' + pad(i, 4);
var image = trend1Aggregated.water;
var s = 300
} else if(type == 'land') {
var name = 'land_' + pad(i, 4);
var image = trend1Aggregated.land;
var s = 300
} else if(type == 'scale') {
var name = 'scale_' + pad(i, 4);
var image = trend1.change;
var s = 30
}
var any = l8.filterBounds(f.geometry()).toList(1).size().getInfo()
if(cmd) {
if(any) {
print('Downloading ' + pad(i, 4) + ' ...');
var url = image.getDownloadURL({
name: name,
scale: s,
region: JSON.stringify(geometry.coordinates().getInfo()[0]),
});
print(url)
download(url, name)
validate_zip(name)
}
var path = require('path');
var idx_path = path.join(process.cwd(), 'download.last');
save(i + 1, idx_path)
} else {
if(any) {
Export.image(image, name, {
scale: s,
region: JSON.stringify(geometry.getInfo()),
driveFileNamePrefix: name,
maxPixels: 1e12
})
//Map.addLayer(geometry, {}, 'cell ' + i)
//Map.centerObject(geometry)
}
}
}
<file_sep>/Misc/sentinel2-visualization.js
// A UI to interactively filter a collection, select an individual image
// from the results, display it with a variety of visualizations, and export it.
// The namespace for our application. All the state is kept in here.
var app = {};
/** Creates the UI panels. */
app.createPanels = function() {
/* The introduction section. */
app.intro = {
panel: ui.Panel([
ui.Label({
value: 'Sentinel Explorer',
style: {fontWeight: 'bold', fontSize: '24px', margin: '10px 5px'}
}),
ui.Label('This app allows you to filter and export images ' +
'from the Sentinel 2 collection.')
])
};
/* The collection filter controls. */
app.filters = {
mapCenter: ui.Checkbox({label: 'Filter to map center', value: true}),
startDate: ui.Textbox('YYYY-MM-DD', '2015-06-23'),
endDate: ui.Textbox('YYYY-MM-DD', '2017-01-01'),
applyButton: ui.Button('Apply filters', app.applyFilters),
loadingLabel: ui.Label({
value: 'Loading...',
style: {stretch: 'vertical', color: 'gray', shown: false}
})
};
/* The panel for the filter control widgets. */
app.filters.panel = ui.Panel({
widgets: [
ui.Label('1) Filter date', {fontWeight: 'bold'}),
ui.Label('Start date', app.HELP_TEXT_STYLE), app.filters.startDate,
ui.Label('End date', app.HELP_TEXT_STYLE), app.filters.endDate,
app.filters.mapCenter,
ui.Panel([
app.filters.applyButton,
app.filters.loadingLabel
], ui.Panel.Layout.flow('horizontal'))
],
style: app.SECTION_STYLE
});
/* The image picker section. */
app.picker = {
// Create a select with a function that reacts to the "change" event.
select: ui.Select({
placeholder: 'Select an image ID',
onChange: app.refreshMapLayer
}),
// Create a button that centers the map on a given object.
centerButton: ui.Button('Center on map', function() {
Map.centerObject(Map.layers().get(0).get('eeObject'));
})
};
/* The panel for the picker section with corresponding widgets. */
app.picker.panel = ui.Panel({
widgets: [
ui.Label('2) Select an image', {fontWeight: 'bold'}),
ui.Panel([
app.picker.select,
app.picker.centerButton
], ui.Panel.Layout.flow('horizontal'))
],
style: app.SECTION_STYLE
});
/* The visualization section. */
app.vis = {
label: ui.Label(),
// Create a select with a function that reacts to the "change" event.
select: ui.Select({
items: Object.keys(app.VIS_OPTIONS),
onChange: function() {
// Update the label's value with the select's description.
var option = app.VIS_OPTIONS[app.vis.select.getValue()];
app.vis.label.setValue(option.description);
// Refresh the map layer.
app.refreshMapLayer();
}
})
};
/* The panel for the visualization section with corresponding widgets. */
app.vis.panel = ui.Panel({
widgets: [
ui.Label('3) Select a visualization', {fontWeight: 'bold'}),
app.vis.select,
app.vis.label
],
style: app.SECTION_STYLE
});
// Default the select to the first value.
app.vis.select.setValue(app.vis.select.items().get(0));
/* The export section. */
app.export = {
button: ui.Button({
label: 'Export the current image to Drive',
// React to the button's click event.
onClick: function() {
// Select the full image id.
var imageIdTrailer = app.picker.select.getValue();
var imageId = app.COLLECTION_ID + '/' + imageIdTrailer;
// Get the visualization options.
var visOption = app.VIS_OPTIONS[app.vis.select.getValue()];
// Export the image to Drive.
Export.image.toDrive({
image: ee.Image(imageId).select(visOption.visParams.bands),
description: 'S2_Export-' + imageIdTrailer,
});
}
})
};
/* The panel for the export section with corresponding widgets. */
app.export.panel = ui.Panel({
widgets: [
ui.Label('4) Start an export', {fontWeight: 'bold'}),
app.export.button
],
style: app.SECTION_STYLE
});
};
/** Creates the app helper functions. */
app.createHelpers = function() {
/**
* Enables or disables loading mode.
* @param {boolean} enabled Whether loading mode is enabled.
*/
app.setLoadingMode = function(enabled) {
// Set the loading label visibility to the enabled mode.
app.filters.loadingLabel.style().set('shown', enabled);
// Set each of the widgets to the given enabled mode.
var loadDependentWidgets = [
app.vis.select,
app.filters.startDate,
app.filters.endDate,
app.filters.applyButton,
app.filters.mapCenter,
app.picker.select,
app.picker.centerButton,
app.export.button
];
loadDependentWidgets.forEach(function(widget) {
widget.setDisabled(enabled);
});
};
/** Applies the selection filters currently selected in the UI. */
app.applyFilters = function() {
app.setLoadingMode(true);
var filtered = ee.ImageCollection(app.COLLECTION_ID);
// Filter bounds to the map if the checkbox is marked.
if (app.filters.mapCenter.getValue()) {
filtered = filtered.filterBounds(Map.getCenter());
}
// Set filter variables.
var start = app.filters.startDate.getValue();
if (start) start = ee.Date(start);
var end = app.filters.endDate.getValue();
if (end) end = ee.Date(end);
if (start) filtered = filtered.filterDate(start, end);
app.ImageCollection_filtered = filtered
// Get the list of computed ids.
var computedIds = filtered
.limit(app.IMAGE_COUNT_LIMIT)
.reduceColumns(ee.Reducer.toList(), ['system:index'])
.get('list');
computedIds.evaluate(function(ids) {
// Update the image picker with the given list of ids.
app.setLoadingMode(false);
app.picker.select.items().reset(ids);
// Default the image picker to the first id.
app.picker.select.setValue(app.picker.select.items().get(0));
});
};
/** Refreshes the current map layer based on the UI widget states. */
app.refreshMapLayer = function() {
Map.clear();
var imageId = app.picker.select.getValue();
if (imageId) {
// If an image id is found, create an image.
var image = ee.Image(app.COLLECTION_ID + '/' + imageId);
var layer;
if (app.vis.select.getValue() === 'NDVI (B8-B4/B8+B4)') {
layer = s2ndvi(image);
} else {
layer = image;
}
var layer2;
if (app.vis.select.getValue() === 'NDWI (B3-B8/B3+B8)') {
layer = s2ndwi(image);
} else {
layer2 = image;
}
// Add the image to the map with the corresponding visualization options.
var visOption = app.VIS_OPTIONS[app.vis.select.getValue()];
Map.addLayer(layer, visOption.visParams, imageId);
///NDVI and NDWI ADD BANDS to image
/////////////// Create chart ///////////////
// Create a panel to hold our widgets.
var panel2 = ui.Panel();
panel2.style().set('width', '300px');
// Create an intro panel with labels.
var intro2 = ui.Panel([
ui.Label({
value: 'Chart Inspector',
style: {fontSize: '20px', fontWeight: 'bold'}
}),
ui.Label('Click a point on the map to inspect.')
]);
panel2.clear();
panel2.add(intro2);
// Create panels to hold lon/lat values.
var lon = ui.Label();
var lat = ui.Label();
panel2.add(ui.Panel([lon, lat], ui.Panel.Layout.flow('horizontal')));
// Register a callback on the default map to be invoked when the map is clicked.
Map.onClick(function(coords) {
// Update the lon/lat panel with values from the click event.
lon.setValue('lon: ' + coords.lon.toFixed(2)),
lat.setValue('lat: ' + coords.lat.toFixed(2));
// Add a red dot for the point clicked on.
var point = ee.Geometry.Point(coords.lon, coords.lat);
var dot = ui.Map.Layer(point, {color: 'FF0000'});
Map.layers().set(1, dot);
// Create an Band spectrum chart.
var bandsChart = ui.Chart.image.series(app.ImageCollection_filtered.select('B8', 'B4', 'B3'), point)
.setOptions({
title: 'bands Reflectance Over Time',
vAxis: {title: 'Bands value'},
hAxis: {title: 'Date', format: 'dd-MM-yy', gridlines: {count: 7}},
});
panel2.widgets().set(2, bandsChart);
var ndviChart = ui.Chart.image.series({
imageCollection: app.ImageCollection_filtered.map(function(img) {
return img.normalizedDifference(['B8', 'B4'])
.rename('NDVI')
.copyProperties(img, ['system:time_start']);
}),
region: point
}).setOptions({
title: 'NDVI Over Time',
vAxis: {title: 'ndvi (nd)'},
hAxis: {title: 'Date', format: 'dd-MM-yy', gridlines: {count: 7}},
});
panel2.widgets().set(3, ndviChart);
});
Map.style().set('cursor', 'crosshair');
ui.root.insert(2, panel2);
}
};
};
////////////////////////////////////////
function s2ndvi(image){
var ndvi = image.normalizedDifference(['B8', 'B4']);
return image.addBands(ndvi);
}
function s2ndwi(image){
var ndwi = image.normalizedDifference(['B3', 'B8']);
return image.addBands(ndwi);
}
var palette = [ 'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',
'74A901', '66A000', '529400', '3E8601', '207401', '056201',
'004C00', '023B01', '012E01', '011D01', '011301'];
var palette2 = [ '0000ff', '00ffff', 'ffff00', 'ff0000', 'ffffff'];
/** Creates the app constants. */
app.createConstants = function() {
app.ImageCollection_filtered = ee.ImageCollection('COPERNICUS/S2');
app.COLLECTION_ID = 'COPERNICUS/S2';
app.SECTION_STYLE = {margin: '20px 0 0 0'};
app.HELPER_TEXT_STYLE = {
margin: '8px 0 -3px 8px',
fontSize: '12px',
color: 'gray'
};
app.IMAGE_COUNT_LIMIT = 10;
app.VIS_OPTIONS = {
'False color (B5/B4/B3)': {
description: 'Vegetation is shades of red, urban areas are ' +
'cyan blue, and soils are browns.',
visParams: {gamma: 1, min: 500, max: 7000, bands: ['B5', 'B4', 'B3']}
},
'Natural color (B4/B3/B2)': {
description: 'Ground features appear in colors similar to their ' +
'appearance to the human visual system.',
visParams: {gamma: 1.3, min: 500, max: 7000, bands: ['B4', 'B3', 'B2']}
},
'Color Infrared (B8/B4/B3)': {
description: 'Coast lines and shores are well-defined. ' +
'Vegetation appears blue.',
visParams: {gamma: 1.3, min: 500, max: 7000, bands: ['B8', 'B4', 'B3']}
},
'Agriculture (B11/B8A/B2)': {
description: 'Vegetation features appear in greens ' +
'humidity in blues.',
visParams: {gamma: 1.3, min: 500, max: 7000, bands: ['B11', 'B8A', 'B2']}
},
'SWIR (B12/B8/B4)': {
description: 'Vegetation features appear in greens ' +
'humidity in blues.',
visParams: {gamma: 1.3, min: 500, max: 7000, bands: ['B12', 'B8', 'B4']}
},
'NDVI (B8-B4/B8+B4)': {
description: 'Vegetation index ' +
'',
visParams: {min: 0, max: 0.7, palette:palette, bands: ['nd']}
},
'NDWI (B3-B8/B3+B8)': {
description: 'Normalized Difference Water Index ' +
'',
visParams: {min: -0.6, max: 0.1, palette:palette2, bands: ['nd']}
},
};
};
/** Creates the application interface. */
app.boot = function() {
app.createConstants();
app.createHelpers();
app.createPanels();
var main = ui.Panel({
widgets: [
app.intro.panel,
app.filters.panel,
app.picker.panel,
app.vis.panel,
app.export.panel
],
style: {width: '320px', padding: '8px'}
});
//Monegros Center//
Map.setCenter(-0.1081, 41.4208, 12);
//La Mancha Center//
//Map.setCenter(-3.1242,39.5062, 11);
ui.root.insert(0, main);
app.applyFilters();
// Add the panel to the ui.root.
};
app.boot();
<file_sep>/UI/ndvi-trajectory.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var app = {};
/***** End of imports. If edited, may not auto-convert in the playground. *****/
// Create the UI panels
app.createPanels = function() {};
// GUI
app.intro = {
panel: ui.Panel([
ui.Label({
value: 'NDVI time series generator',
style: {fontWeight: 'bold', fontSize: '24px', margin: '10px 5px'}
}),
ui.Label('Choose your sites by clicking on the map. Then press the button below to generate time series index.')
])
};
// NDVI button controls
app.buttons = {
applyNDVIButton: ui.Button({
label: "Generate NDVI time series data for sites",
onClick: function() {
// Ensure there are sites set
if (app.sites) {
app.applyNDVI();
// Output to console
print(app.sites);
} else {
// Output to console
print('No sites were set.')
}
}
}),
};
// The panel for the widgets
app.buttons.panel = ui.Panel({
widgets: [
ui.Panel([
app.buttons.applyNDVIButton,
])
]
});
app.applyNDVI = function() {
var NDVIpts = app.sites
print(NDVIpts)
// add explicit coordinates as a property to feature collection
var NDVIpts2 = NDVIpts.map(function(f) {
var g = f.geometry().coordinates();
return f.set('lat', g.get(1),'long', g.get(0));
});
// Collect data and filter by regions and dates
var filtered =
ee.ImageCollection('LANDSAT/LT5_L1T_32DAY_NDVI')
.filterDate('1984-10-01', '2013-01-01');
//Create data for table
var ndviData = filtered.map(function(img) {
var date = ee.Number(img.get('system:time_start'));
// Add a band to the nd image representing that number
img = img.addBands(date).rename(['mean_ndvi', 'date']);
var reduced = img.reduceRegions({
collection: app.sites,
reducer: ee.Reducer.mean(),
scale: 30
});
return reduced;
});
Export.table.toDrive(ndviData.flatten(), 'output');
};
// User selects sites for which NDVI data will be exported
app.applyGetSites = function() {
Map.style().set('cursor', 'crosshair');
Map.onClick(function(coords) {
// if app.sites is undefined - create it
if (!app.sites) {
app.sites = ee.FeatureCollection(ee.Geometry.Point(coords.lon, coords.lat));
Map.addLayer(app.sites, {color: "blue"}, 'sites')
// app.sites is defined - new digitized points are added to the layer and displayed
} else {
app.sites = app.sites.merge(ee.FeatureCollection(ee.Geometry.Point(coords.lon, coords.lat)));
print(app.sites)
// Add a new layer each time the map is clicked
Map.layers().reset([ui.Map.Layer(app.sites, {color: "blue"}, 'sites')]);
}
});
};
// App constructor - is run once on startup
app.boot = function() {
app.createPanels();
var main = ui.Panel({
widgets: [
app.intro.panel,
app.buttons.panel,
],
style: {width: '320px', padding: '8px'}
});
ui.root.insert(0, main);
app.applyGetSites();
};
app.boot();
<file_sep>/Sentinel-2/sentinal-region-visualizer.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var image = ee.Image("users/JustinPoehnelt/sgmnts_1469561047524_2015_8_01_2016_04_01_150_256_false_100_1200_100_B2B3B4B5B6B7B8B11B12B_NDVI");
/***** End of imports. If edited, may not auto-convert in the playground. *****/
// Visualize All Levels
var hierarchy = image.select("^(cl).*$").bandNames().getInfo();
for (var i = 0; i< hierarchy.length; i++) {
Map.addLayer(image.select(hierarchy[i]).randomVisualizer(),{},hierarchy[i],0);
}
Map.centerObject(image);
Map.addLayer(image.select('clusters').focal_mode({iterations: 2, radius:3, kernelType: 'cross'}).randomVisualizer())
<file_sep>/Sentinel-2/sentinel-edge-with-existing-ndvi-image.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var image = ee.Image("users/JustinPoehnelt/sentinel_ndvi_image_1466195511191");
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var bands = [3,22,32],
MAX_OBJECT_SIZE = 256,
THRESHOLD_START = 0,
THRESHOLD_END = 0.3,
THRESHOLD_STEP = 0.05,
USE_COSINE = false;
var geometry = image.geometry();
Map.addLayer(image,{},'all');
Map.addLayer(image.select(bands),{})
image = image.fastGaussianBlur(8);
Map.addLayer(image.select(bands),{})
// image = image.select(bands);
var results = ee.Image(ee.List.sequence(THRESHOLD_START,THRESHOLD_END,THRESHOLD_STEP).iterate(function(threshold, image) {
threshold = ee.Number(threshold);
image = ee.Image(image);
var imageClustered = ee.apply("Test.Clustering.RegionGrow", {
"image": image.select("^(B).*$"),
"useCosine": USE_COSINE,
secondPass: true,
"threshold": threshold,
"maxObjectSize": MAX_OBJECT_SIZE,
});
var imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageClustered,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageConsistent,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = imageConsistent.select("^(B).*$").addBands(imageConsistent.select('clusters'))
return ee.Image(ee.Algorithms.If(image.bandNames().contains('clusters'), imageConsistent.addBands(image.select("^(cl).*$")), imageConsistent));
}, image));
// Visualize All Levels
var hierarchy = results.select("^(cl).*$").bandNames().getInfo();
for (var i = 0; i< hierarchy.length; i++) {
Map.addLayer(results.select(hierarchy[i]).randomVisualizer(),{},hierarchy[i],0);
}
// Map.addLayer(results.select("^(cl).*$"),{}, 'results',0);
// Export
var exportId = 'sgmnts_' + Date.now().toString();
Export.image.toAsset({
image:results.select("^(cl).*$").int64(),
assetId: exportId,
description: exportId,
region: geometry,
scale:10,
maxPixels: 1e13
});
var canny = ee.Algorithms.CannyEdgeDetector(image, 0.005).reduce(ee.Reducer.sum());
// Mask the image with itself to get rid of 0 pixels.
// canny = canny.updateMask(canny);
Map.addLayer(canny,{min:0,max:5}, 'Canny Blur')
<file_sep>/Datasets/USDA-NASS-CDL.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var cdl = ee.ImageCollection("USDA/NASS/CDL");
/***** End of imports. If edited, may not auto-convert in the playground. *****/
print(cdl)
print(cdl.aggregate_array('system:index'))<file_sep>/Misc/tile-on-server-side.js
/*
Construct a polygon from min/max coordinates
*/
function boundingBox(minx, miny, maxx, maxy) {
return ee.Geometry.Polygon([
[[minx, miny], [minx, maxy], [maxx, maxy], [maxx, miny], [minx, miny]]
]
)}
var zoom = 14;
/*
get the x/y coordinate
*/
function getTileLL(i, j, z) {
var x = ee.Number(360).divide(ee.Number(2).leftShift(z)).multiply(i).subtract(180);
var y = ee.Number(180).divide(ee.Number(1).leftShift(z)).multiply(j).subtract(90);
return [x,y];
}
function getTile(lon, lat, zoom) {
/*
* Looking for the first tile from left
*/
var nX = 2 << zoom; //tiles for x at zoom
//var nY = 1 << zoom; //tiles for y at zoom
var step = 360 / nX; //tile width
var Xt = Math.floor((lon + 180) / step);
var Yt = Math.floor((lat + 90) / step);
return [Xt, Yt, zoom];
}
var ll = getTile(10, 4, zoom);
var ur = getTile(12, 6, zoom);
var ix = ee.List.sequence(ll[0], ur[0])
var iy = ee.List.sequence(ll[1], ur[1])
var tiles = ix.map(function(i) {
return iy.map(function(j) {
var ii = ee.Number(i)
var jj = ee.Number(j)
var tileLL = getTileLL(ii, jj, zoom);
var tileUR = getTileLL(ii.add(1), jj.add(1), zoom);
var poly = boundingBox(tileLL[0], tileLL[1], tileUR[0], tileUR[1]);
var tileId = ee.String('').cat(ii.int()).cat('_').cat(jj.int())
return ee.Feature(poly, {tileId: tileId});
})
}).flatten()
var tileGeometries = ee.FeatureCollection(tiles);
Map.addLayer(tileGeometries);
<file_sep>/Sentinel-2/sentinel-region-grow.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var sentinel = ee.ImageCollection("COPERNICUS/S2"),
geometry = /* color: d63000 */ee.Geometry.Polygon(
[[[2.997465133666992, 36.53661880969908],
[3.0173778533935547, 36.53675673546427],
[3.0138587951660156, 36.55461604314137],
[2.9954051971435547, 36.55454709622043]]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var PERIOD_LENGTH = 150,
START = '2015-8-01',
END = '2016-04-01',
MAX_OBJECT_SIZE = 256,
THRESHOLD_START = 100,
THRESHOLD_END = 1200,
THRESHOLD_STEP = 100,
USE_COSINE = false,
BANDS = ["B2","B3","B4","B5","B6","B7","B8","B11","B12","B_NDVI"];
// BANDS = ["B_NDVI"];
print(ee.List.sequence(THRESHOLD_START,THRESHOLD_END,THRESHOLD_STEP))
var serializedParameters = [
START,END,
PERIOD_LENGTH.toString(),
MAX_OBJECT_SIZE.toString(),
USE_COSINE.toString(),
THRESHOLD_START.toString(),
THRESHOLD_END.toString(),
THRESHOLD_STEP.toString(),
BANDS.toString()
].join("_").replace(/-/g,"_").replace(/,/g,"").replace(/0\./g,"");
print(serializedParameters)
//// TODO ////
// 1. Handle masked bands in region grow
// 2. Detect roads?
var collection = sentinel
// .filterDate(START,END)
// .filterMetadata('CLOUDY_PIXEL_PERCENTAGE','less_than', 10)
.filterBounds(geometry)
.map(function(img) {
img = img.addBands(img.normalizedDifference(['B8', 'B4']).multiply(10000).select([0],['B_NDVI']));
img = img.addBands(img.select('B2').add(img.select('B3')).add(img.select('B3')).divide(3).select([0],['B_PAN']))
img = img.addBands(img.normalizedDifference(['B8', 'B_PAN']).multiply(10000).select([0],['B_PAN_ND']))
return img;
})
.select(BANDS)
/**
* getPeriods() is a utility for creating equally
* spaced dates given a beginning and ending year
*
* @param {Integer} begin
* @param {Integer} end
* @param {Integer} length
* @return {ee.List} dates
*/
function getPeriods(begin, end, length){
begin = new Date(begin)
end = new Date(end);
var dates = [];
while(begin.getTime() < end.getTime()) {
dates.push(ee.Date(begin));
begin = new Date(begin.setDate(begin.getDate() + length));
}
return ee.List(dates);
}
/**
* mosaicCollection() returns a uniform collection of
* mosaics over a list of periods
*
* @param {ee.ImageCollection} collection
* @param {ee.List} periods
* @return {ee.ImageCollection} collection
*/
function mosaicCollection(collection, periods) {
collection = ee.ImageCollection(periods.map(function(dt) {
// Select a subset of the collection based upon the period
var subset = collection.filterDate(dt, ee.Date(dt).advance(PERIOD_LENGTH, 'day')).median();
subset = subset.set('system:time_start',ee.Date(dt));
return subset;
}));
return collection;
}
// mosaic the periods
var periods = getPeriods(START, END, PERIOD_LENGTH);
collection = mosaicCollection(collection, periods);
Map.addLayer(collection,{}, 'collection',0);
// convert images to bands
var list = collection.toList(100);
var image = ee.Image(list.slice(1).iterate(function(a, b){return ee.Image(b).addBands(a);}, list.get(0)));
image = image.addBands(ee.Image.pixelCoordinates(ee.Projection("epsg:3857")).multiply(1).select([0,1],["B_X", "B_Y"]))
// image = image.focal_mean({
// radius: 1.5,
// kernelType: 'square',
// iterations: 1
// });
Map.addLayer(image, {}, 'image', 0);
var results = ee.Image(ee.List.sequence(THRESHOLD_START,THRESHOLD_END,THRESHOLD_STEP).iterate(function(threshold, image) {
threshold = ee.Number(threshold);
image = ee.Image(image);
var imageClustered = ee.apply("Test.Clustering.RegionGrow", {
"image": image.select("^(B).*$"),
"useCosine": USE_COSINE,
secondPass: true,
"threshold": threshold,
"maxObjectSize": MAX_OBJECT_SIZE,
});
var imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageClustered,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = ee.apply("Test.Clustering.SpatialConsistency", {
"image": imageConsistent,
"maxObjectSize": MAX_OBJECT_SIZE
})
imageConsistent = imageConsistent.select("^(B).*$").addBands(imageConsistent.select('clusters'))
return ee.Image(ee.Algorithms.If(image.bandNames().contains('clusters'), imageConsistent.addBands(image.select("^(cl).*$")), imageConsistent));
}, image));
// Visualize All Levels
var hierarchy = results.select("^(cl).*$").bandNames().getInfo();
for (var i = 0; i< hierarchy.length; i++) {
Map.addLayer(results.select(hierarchy[i]).randomVisualizer(),{},hierarchy[i],0);
}
// Map.addLayer(results.select("^(cl).*$"),{}, 'results',0);
// Export
var exportId = 'sgmnts_' + Date.now().toString() + '_' + serializedParameters;
Export.image.toAsset({
image:results.select("^(cl).*$").int64(),
assetId: exportId,
description: exportId,
region: geometry,
scale:10,
maxPixels: 1e13
});
// Kmeans
// var NUM_CLUSTERS = 10;
// var trainingFeatures = image.sample({
// region: geometry,
// scale:10,
// numPixels: 5e6
// });
// // cluster with minimal parameters
// var clusterer = ee.Clusterer.wKMeans({nClusters: NUM_CLUSTERS});
// clusterer = clusterer.train(trainingFeatures)
// var kmeans = image.cluster(clusterer)
// Map.addLayer(kmeans.select('cluster').randomVisualizer(), {}, 'kmeans');<file_sep>/Sentinel-2/sentinel-region-vectors.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var results = ee.Image("users/JustinPoehnelt/sgmnts_1465420832413_2015_8_01_2016_06_01_100_256_false_100_1800_200_B2B3B4B5B6B7B8B11B12B_NDVI");
/***** End of imports. If edited, may not auto-convert in the playground. *****/
var objects = results.select('clusters').reduceToVectors({
geometry: geometry,
scale:10,
tileScale: 4,
maxPixels: 1e13
});
Export.table.toDrive({
collection: objects,
description: "vect_"+exportId,
folder: 'gee',
fileNamePrefix: exportId
});
Map.addLayer(objects);<file_sep>/Array/create-diagonal-matrix.js
var y = ee.Array([[0],[1],[2],[3],[4],[5],[6],[7]]);
var I = ee.Array.identity(8);
var e = ee.Array([[1,0,0,0,0,0,0,0]]);
var t = y.matrixMultiply(y.transpose());
t = t.sqrt();
var diag = I.multiply(t);
<file_sep>/Reducer/separate-a-year-long-collection-into-two-halves.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var geometry = /* color: #d63000 */ee.Geometry.MultiPoint(
[[-122.1514892578125, 37.748322027789115],
[-121.3714599609375, 38.62049175671215]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
//Parameters
// b: background NDVI
// Ae: amplitude (Max NDVI - background)
// x:target DOY
// u: DOY of peak NDVI
// o:stdev (two stdev: one prior to peak, one after peak)
var delta = ee.Geometry.Rectangle(-122.1514892578125,37.748322027789115,-121.3714599609375,38.62049175671215);
// Mask coulds
var maskClouds = function(img) {
var cloudscore = ee.Algorithms.Landsat.simpleCloudScore(img).select('cloud');
return img.mask(cloudscore.lt(50));
};
// Add an NDVI band.
var addDOY = function(img){
var date = ee.Date(img.get('system:time_start'));
// Make an image out of the DOY.
var doy = ee.Image(ee.Date(img.get('system:time_start'))
.getRelative('day', 'year')
.short())
.rename('DOY').int();
var ndvi = img.normalizedDifference(['B5', 'B4']) // change when working with other Landsat data
.select([0], ['NDVI']).float();
// Add DOY and NDVI bands
return maskClouds(img).addBands(ndvi).addBands(doy);
};
//First step : find annual time series
var start = '2014-01-01';
var end = '2015-01-01';
var bstart = '2013-11-01'
var bend = '2014-03-01'
var imgs = ee.ImageCollection('LANDSAT/LC8_L1T_TOA')
.filterDate(start, end)
.filterBounds (delta)
.map(addDOY);
print (imgs)
//Background NDVI
var b = ee.ImageCollection('LANDSAT/LC8_L1T_8DAY_EVI')
.filterDate(start, end)
.filterBounds (delta)
.reduce(ee.Reducer.mean());
//Amplitude
var max = imgs.qualityMosaic('NDVI');
var Ae = max.select('NDVI').subtract(b.select('NDVI'));
//u (DOY of peak NDVI)
var u = max.select('DOY')
//Separate time series into two parts, one half before peak greenness and the second part after peak greenness
var beforePeak = imgs.map(function(image) {
return image.updateMask(image.select('DOY').lte(u))}).select('NDVI');
var beforeStDev = beforePeak.reduce(ee.Reducer.mean());
print(beforeStDev,'before')
Map.addLayer(beforeStDev)
var afterPeak = imgs.map(function(image) {
return image.updateMask(image.select('DOY').gt(u));
}).select('NDVI');
var AfterStDev = afterPeak.select('NDVI').reduce(ee.Reducer.std_dev());
Map.addLayer(AfterStDev)
<file_sep>/Sentinel-2/sentinel1.js
/**** Start of imports. If edited, may not auto-convert in the playground. ****/
var roi = /* color: #d63000 */ee.Geometry.Polygon(
[[[104.39967317142975, 8.648797299726574],
[104.97136816724105, 8.42750154669911],
[105.44386722890897, 8.433739470974832],
[106.66892316475673, 9.522314436594979],
[107.25187226402818, 10.336446225915548],
[106.80624398899499, 11.138468981755926],
[104.38860737239793, 10.944315053122876]]]);
/***** End of imports. If edited, may not auto-convert in the playground. *****/
// Load the Sentinel-1 ImageCollection.
var sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD');
// Filter VH, IW
var vh = sentinel1
// Filter to get images with VV and VH dual polarization.
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VH'))
// Filter to get images collected in interferometric wide swath mode.
.filter(ee.Filter.eq('instrumentMode', 'IW'))
// reduce to VH polarization
.select('VH')
// filter 10m resolution
.filter(ee.Filter.eq('resolution_meters', 10));
// Filter to orbitdirection Descending
var vhDescending = vh.filter(ee.Filter.eq('orbitProperties_pass', 'DESCENDING'));
// Filter time 2015
var vhDesc2015 = vhDescending.filterDate(ee.Date('2015-01-01'), ee.Date('2015-12-31'));
//The image collection spans the globe, or at least the parts that Sentinel-1 regularly covers.
// I am only interested in the Mekong Delta for now, so Iโll clip the image collection with a polygon
// of my Region-of-Interest
//
var roi2 = ee.Geometry.Polygon(
[[[-74.39967317142975, 2.648797299726574],
[-74.97136816724105, 2.42750154669911],
[-73.44386722890897, 2.433739470974832],
[-72.66892316475673, 9.522314436594979],
[-71.25187226402818, 10.336446225915548],
[-72.80624398899499, 11.138468981755926],
[-74.38860737239793, 10.944315053122876]]]);
// Filter to MKD roi
var s1_mkd = vhDesc2015.filterBounds(roi);
var s2_mkd = vhDesc2015.filterBounds(roi2);
var p90 = s1_mkd.reduce(ee.Reducer.percentile([90]));
var p10 = s1_mkd.reduce(ee.Reducer.percentile([10]));
var s1_mkd_perc_diff = p90.subtract(p10);
var p90n = s2_mkd.reduce(ee.Reducer.percentile([90]));
var p10n = s2_mkd.reduce(ee.Reducer.percentile([10]));
var s2_mkd_perc_diff = p90n.subtract(p10n);
//This type of calculation of features over a time-series is blazingly fast
//and it only takes seconds to visualize the results for this.
//Areas with a high amplitude are bright and areas with low amplitude are dark.
//Near the city of Rach Gia we can already see some structures from this amplitude image.
//Some (presumeably) forest and urban areas in dark color, some very bright areas,
//which might be rice fields or other agriculture.
Map.addLayer(s1_mkd_perc_diff, {min: [2], max: [17]}, 'p90-p10 2015', 1);
Map.addLayer(s2_mkd_perc_diff, {min: [2], max: [17]}, 'p90-p10 2015', 1);
//Following the initial idea, that agriculture has a higher backscatter amplitude
//than other land cover, Iโll mask all areas with a backscatter amplitude larger than 7.5 dB.
var amplitude_mask = s1_mkd_perc_diff.gt(7.5);
var amplitude_mask = amplitude_mask.updateMask(amplitude_mask);
Map.addLayer(amplitude_mask, {palette: 'FF0000'}, 'amplitude_mask', 1);
var amplitude_mask2 = s2_mkd_perc_diff.gt(7.5);
var amplitude_mask2 = amplitude_mask.updateMask(amplitude_mask);
Map.addLayer(amplitude_mask2, {palette: 'FF0000'}, 'amplitude_mask', 1);
|
9c29b49d829e55bbb300ebf519795a9e1a5d0105
|
[
"Markdown",
"JavaScript"
] | 32 |
Markdown
|
Jack-ee/ee-snippets
|
e201ad0346be71ccd3400c1d7184e1653e56b6c2
|
b485eddde77a341dcdbc88b3a642ab75ed4df37e
|
refs/heads/master
|
<file_sep>package com.test.game;
import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
public class TestMain {
public static void main(String[] args) {
User user =new User();
user.setName("qgl");
Gson gson = new Gson();
String path = "a.json";
try {
gson.toJson(user,new FileWriter(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>package com.test.game;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(value = ElementType.FIELD)
@Documented
public @interface NotIn {
}
|
a8f11a9fe387f3eb11a344deeb974ba40bd5bc9a
|
[
"Java"
] | 2 |
Java
|
qngolg/tdd-demo2
|
013965b042dba19020028290d49fd8a636d24852
|
7e814de44f55e93e1a7f41dcd5ceb260c13cbe00
|
refs/heads/master
|
<file_sep>package com.example.mailchimpapplication.ui.vm
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mailchimpapplication.data.SubRepository
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.utils.ScopedViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
class MemberViewModel @Inject constructor(private val subRepository: SubRepository) :
ScopedViewModel() {
private val memberLiveData = MutableLiveData<Member>()
val member: LiveData<Member>
get() = memberLiveData
fun getMember(memberId: String, memberListId: String) {
launch(Dispatchers.IO) {
memberLiveData.postValue(subRepository.getMember(memberId, memberListId))
}
}
fun updateMember(memberId: String, memberListId: String, member: Member) {
launch(Dispatchers.IO) {
subRepository.updateMember(memberListId, memberId, member)
}
}
}<file_sep>package com.example.mailchimpapplication.data.models
data class ListsResponse(val lists: List<MailChimpList>)
data class MailChimpList(val id: String, val name: String)
data class MembersResponse(val members: List<Member>)
data class MemberResponse(val member: Member)
data class Member(
val id: String,
var email_address: String,
val status: String,
val last_changed: String,
val list_id: String,
var merge_fields: MergeFields
)
data class MergeFields(
var FNAME: String,
var LNAME: String,
val ADDRESS: Address? = null,
val PHONE: String? = null,
val COMPANY: String? = null,
val CITY: String? = null,
val COUNTRY: String? = null,
val PHOTO: String? = null,
val BIRTHDAY: String? = null,
val LANGUAGE: String? = null
)
data class Address(
val addr1: String,
val addr2: String,
val city: String,
val state: String,
val zip: String,
val country: String
)<file_sep>package com.example.mailchimpapplication
import com.example.mailchimpapplication.di.DaggerInjector
import com.example.mailchimpapplication.di.NetModule
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
class MailChimpApplication : DaggerApplication() {
private val url = "https://us14.api.mailchimp.com"
override fun applicationInjector(): AndroidInjector<out DaggerApplication?>? {
return DaggerInjector.builder()
.application(this)
.netModule(
NetModule(url)
)
.build()
}
}<file_sep>package com.example.mailchimpapplication.di
import com.example.mailchimpapplication.data.SubRepository
import com.example.mailchimpapplication.data.SubService
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
class NetModule(private val mailChimpUrl: String) {
@Provides
@Singleton
fun providesSubRepository(subService: SubService) = SubRepository(subService)
@Provides
@Singleton
fun provideSubService(retrofit: Retrofit): SubService {
return retrofit.create(SubService::class.java)
}
@Singleton
@Provides
fun provideMailChimpRetrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit {
return Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(mailChimpUrl)
.build()
}
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
chain.proceed(
chain
.request()
.newBuilder()
.header(
AUTHORIZATION_HEADER_KEY,
AUTHORIZATION_PREFIX + "8ac1de26a49c4cca30ca8c0b62b8e68c-us14"
)
.build()
)
}
return builder.build()
}
@Provides
@Singleton
fun provideGsonBuilder(): GsonBuilder {
return GsonBuilder()
}
@Provides
@Singleton
fun provideGson(builder: GsonBuilder): Gson {
return builder.create()
}
companion object {
private const val AUTHORIZATION_PREFIX = "apikey "
private const val AUTHORIZATION_HEADER_KEY = "Authorization"
}
}
<file_sep>package com.example.mailchimpapplication.ui
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.ui.sublist.SubAdapter
class TitleItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.subList_title)
lateinit var titleText:TextView
@JvmField
protected var clickHandler: SubAdapter.SubListClickHandler? = null
init {
ButterKnife.bind(this, view)
}
fun bind(it: SubListItemUIModel.SubListTitleUiModel) {
titleText.text = it.title
}
}<file_sep>package com.example.mailchimpapplication.di
import com.example.mailchimpapplication.ui.MemberFragment
import com.example.mailchimpapplication.ui.di.MemberFragmentModule
import com.example.mailchimpapplication.ui.sublist.SubListFragment
import com.example.mailchimpapplication.ui.di.SubListModule
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class MainModule {
@FragmentScope
@ContributesAndroidInjector(modules = [SubListModule::class])
abstract fun contributeSubListFragment(): SubListFragment
@FragmentScope
@ContributesAndroidInjector(modules = [MemberFragmentModule::class])
abstract fun contributeMemberFragment(): MemberFragment
}<file_sep>package com.example.mailchimpapplication.ui.sublist
interface SubListAdapterType {
val subType: SubType
}
enum class SubType {
TITLE,
MEMBER
}<file_sep>package com.example.mailchimpapplication.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.sublist.SubListFragment
import dagger.android.support.DaggerAppCompatActivity
class MainActivity: DaggerAppCompatActivity(), SubListFragment.NavigationHandler {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
pushFragment(SubListFragment.newInstance())
}
private fun pushFragment(fragment: Fragment) {
if (fragment.isAdded) {
return
}
supportFragmentManager.popBackStackImmediate(
null,
FragmentManager.POP_BACK_STACK_INCLUSIVE
)
supportFragmentManager.beginTransaction()
.replace(R.id.activity_main_container, fragment)
.commit()
}
fun pushFragmentOnBackStack(fragment: Fragment) {
if (fragment.isAdded) {
return
}
supportFragmentManager
.beginTransaction()
.setCustomAnimations(
android.R.anim.fade_in,
android.R.anim.fade_out,
android.R.anim.fade_in,
android.R.anim.fade_out
)
.replace(R.id.activity_main_container, fragment)
.addToBackStack(null)
.commit()
}
override fun onMemberClick(member: Member) {
pushFragmentOnBackStack(MemberFragment.newInstance(member))
}
}
<file_sep>package com.example.mailchimpapplication.utils
import retrofit2.Response
import java.util.concurrent.CancellationException
suspend fun <T> safeCall(call: suspend () -> Response<T>): T? {
return try {
call.invoke().body()
} catch (e: Throwable) {
// error handling
if (e is CancellationException) { // allow coroutines to cancel
throw e
} else {
null
}
}
}<file_sep>package com.example.mailchimpapplication.di
import android.app.Application
import android.content.Context
import dagger.Binds
import dagger.Module
import javax.inject.Singleton
@Module(includes = [NetModule::class])
abstract class AppModule {
@Binds
@Singleton
abstract fun bindApplicationContext(application: Application): Context
}
<file_sep>package com.example.mailchimpapplication.ui.di
import android.app.Application
import androidx.lifecycle.ViewModelProviders
import com.example.mailchimpapplication.data.SubRepository
import com.example.mailchimpapplication.di.FragmentScope
import com.example.mailchimpapplication.ui.sublist.SubListFragment
import com.example.mailchimpapplication.ui.vm.SubListViewModel
import com.example.mailchimpapplication.ui.vm.SubListViewModelFactory
import dagger.Module
import dagger.Provides
@Module
class SubListModule {
@Provides
@FragmentScope
fun provideSubViewModelFactory(
application: Application,
subRepository: SubRepository
): SubListViewModelFactory {
return SubListViewModelFactory(application, subRepository)
}
@Provides
@FragmentScope
fun provideSubViewModel(
fragment: SubListFragment,
factory: SubListViewModelFactory
): SubListViewModel {
return ViewModelProviders.of(fragment, factory).get(SubListViewModel::class.java)
}
}<file_sep>package com.example.mailchimpapplication.ui.vm
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.mailchimpapplication.data.SubRepository
class SubListViewModelFactory(
application: Application,
private val subRepository: SubRepository
) : ViewModelProvider.AndroidViewModelFactory(application) {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return SubListViewModel(
subRepository
) as T
}
}<file_sep>package com.example.mailchimpapplication.ui
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.sublist.SubListAdapterType
import com.example.mailchimpapplication.ui.sublist.SubType
sealed class SubListItemUIModel {
data class SubListTitleUiModel(
val title: String?,
override val subType: SubType = SubType.TITLE
) :
SubListItemUIModel(),
SubListAdapterType
data class SubMemberItemUiModel(
val member: Member?,
val firstName: String?,
val lastName: String?,
val email: String,
val imageUrl: String?,
override val subType: SubType = SubType.MEMBER
) :
SubListItemUIModel(),
SubListAdapterType
}<file_sep>package com.example.mailchimpapplication.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.OnClick
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.vm.MemberViewModel
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import dagger.android.support.DaggerFragment
import javax.inject.Inject
class MemberFragment : DaggerFragment() {
@BindView(R.id.member_fragment_email)
lateinit var emailText: EditText
@BindView(R.id.member_fragment_name)
lateinit var nameText: TextView
@BindView(R.id.imageView)
lateinit var memberPhoto: ImageView
@Inject
lateinit var memberViewModel: MemberViewModel
var member: Member? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_member, container, false)
ButterKnife.bind(this, view)
return view
}
@OnClick(R.id.button)
fun saveMember() {
member?.let {
it.email_address = emailText.text.toString()
memberViewModel.updateMember(it.id, it.list_id, it)
}
//Will do for noq need handle errors later
Toast.makeText(activity, "Email has been saved", Toast.LENGTH_LONG).show()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val memberID = arguments?.getString(EXTRA_MEMBER_ID)
val listID = arguments?.getString(EXTRA_MEMBER_LIST_ID)
if (memberID != null && listID != null) {
memberViewModel.getMember(memberID, listID)
}
memberViewModel.member.observe(viewLifecycleOwner, Observer { setupView(it) })
}
private fun setupView(member: Member?) {
this.member = member
member?.let {
emailText.setText(member.email_address)
nameText.text = member.merge_fields.FNAME + " " + member.merge_fields.LNAME
val path = member.merge_fields.PHOTO
if (!path.isNullOrEmpty()) {
Picasso.get().load(path).fit().placeholder(R.mipmap.ic_launcher)
.into(memberPhoto, object : Callback {
override fun onSuccess() {
memberPhoto.contentDescription = member.id
}
override fun onError(exception: Exception) {
}
})
}
}
}
companion object {
const val EXTRA_MEMBER_ID = "member_id"
const val EXTRA_MEMBER_LIST_ID = "member_list_id"
@JvmStatic
fun newInstance(member: Member): MemberFragment {
return MemberFragment().apply {
arguments = Bundle().apply {
putSerializable(EXTRA_MEMBER_ID, member.id)
putSerializable(EXTRA_MEMBER_LIST_ID, member.list_id)
}
}
}
}
}
<file_sep>package com.example.mailchimpapplication.di
import com.example.mailchimpapplication.ui.MainActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
interface ActivityBindingModule {
@ActivityScope
@ContributesAndroidInjector(modules = [MainModule::class])
fun contributeMainActivityInjector(): MainActivity
}<file_sep>package com.example.mailchimpapplication.data
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.SubListItemUIModel
import com.example.mailchimpapplication.ui.sublist.SubListAdapterType
import com.example.mailchimpapplication.utils.safeCall
class SubRepository(private val subService: SubService) {
suspend fun getLists() = safeCall { subService.getLists() }?.lists
suspend fun getMembers(listId: String) = safeCall { subService.getListMembers(listId) }?.members
suspend fun getMember(memberId: String, listId: String) =
safeCall { subService.getMember(listId, memberId) }
suspend fun updateMember(listId: String, memberId: String, member: Member) =
safeCall { subService.updateMember(listId, memberId, member) }
suspend fun getUiList(): List<SubListAdapterType> {
val uiList: MutableList<SubListAdapterType> = mutableListOf()
val list = getLists()
list?.forEach {
uiList.add(
SubListItemUIModel.SubListTitleUiModel(it.name)
)
val members = getMembers(it.id)
members?.forEach { member ->
uiList.add(
SubListItemUIModel.SubMemberItemUiModel(
member,
member.merge_fields.FNAME,
member.merge_fields.LNAME,
member.email_address,
member.merge_fields.PHOTO
)
)
}
}
return uiList
}
}<file_sep>package com.example.mailchimpapplication.data
import com.example.mailchimpapplication.data.models.ListsResponse
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.data.models.MemberResponse
import com.example.mailchimpapplication.data.models.MembersResponse
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.PUT
import retrofit2.http.Path
interface SubService {
@GET("3.0/lists")
suspend fun getLists(): Response<ListsResponse>
@GET("3.0/lists/{list_id}/members")
suspend fun getListMembers(@Path("list_id") listId: String): Response<MembersResponse>
@GET("3.0/lists/{list_id}/members/{subscriber_hash}/")
suspend fun getMember(@Path("list_id") listId: String, @Path("subscriber_hash") subHash: String): Response<Member>
@PUT("3.0/lists/{list_id}/members/{subscriber_hash}/")
suspend fun updateMember(@Path("list_id") listId: String, @Path("subscriber_hash") subHash: String, @Body member: Member): Response<MemberResponse>
}<file_sep>package com.example.mailchimpapplication.ui.sublist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.vm.SubListViewModel
import dagger.android.support.DaggerFragment
import javax.inject.Inject
class SubListFragment : DaggerFragment() {
@Inject
lateinit var viewModel: SubListViewModel
@BindView(R.id.list)
lateinit var sublistRecyclerView: RecyclerView
var subAdapter: SubAdapter? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_sublist, container, false)
ButterKnife.bind(this, view)
setupSubsList()
viewModel.subList.observe(viewLifecycleOwner, Observer { displayList(it) })
return view
}
override fun onResume() {
super.onResume()
viewModel.setSubs()
}
private fun displayList(list: List<SubListAdapterType>) {
subAdapter?.update(list)
subAdapter?.notifyDataSetChanged()
}
interface NavigationHandler {
fun onMemberClick(member: Member)
}
private fun setupSubsList() {
subAdapter = activity?.let {
SubAdapter(
listOf()
)
}
subAdapter?.let { adapter ->
adapter.subListClickhandler = object :
SubAdapter.SubListClickHandler {
override fun onClickMember(member: Member) {
(activity as NavigationHandler).onMemberClick(
member
)
}
}
sublistRecyclerView.adapter = subAdapter
sublistRecyclerView.layoutManager = LinearLayoutManager(context)
}
}
companion object {
@JvmStatic
fun newInstance(): SubListFragment {
return SubListFragment()
}
}
}
<file_sep>package com.example.mailchimpapplication.ui.vm
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.mailchimpapplication.data.SubRepository
import com.example.mailchimpapplication.ui.sublist.SubListAdapterType
import com.example.mailchimpapplication.utils.ScopedViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
class SubListViewModel @Inject constructor(private val subRepository: SubRepository) :
ScopedViewModel() {
private val subsLiveData = MutableLiveData<List<SubListAdapterType>>()
val subList: LiveData<List<SubListAdapterType>>
get() = subsLiveData
fun setSubs() {
launch {
subsLiveData.postValue(subRepository.getUiList())
}
}
}<file_sep>package com.example.mailchimpapplication.di
import android.app.Application
import com.example.mailchimpapplication.MailChimpApplication
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Singleton
@Component(modules = [AndroidSupportInjectionModule::class, AppModule::class, NetModule::class, MainModule::class,ActivityBindingModule::class])
interface Injector : AndroidInjector<MailChimpApplication?> {
@Component.Builder
interface Builder {
fun build(): Injector
@BindsInstance
fun application(application: Application): Builder
fun netModule(netModule: NetModule): Builder
}
}
<file_sep>package com.example.mailchimpapplication.ui
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.sublist.SubAdapter
import com.squareup.picasso.Picasso
class MemberItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
@BindView(R.id.sublist_member_email)
lateinit var emailText: TextView
@BindView(R.id.sublist_member_name)
lateinit var nameText: TextView
@BindView(R.id.sublist_member_photo)
lateinit var subListMemberPhoto: ImageView
var member: Member? = null
@JvmField
protected var clickHandler: SubAdapter.SubListClickHandler? = null
init {
ButterKnife.bind(this, view)
val subListClickListener = View.OnClickListener {
member?.let {
clickHandler?.onClickMember(it)
}
}
itemView.setOnClickListener(subListClickListener)
}
fun setSubListClickHandler(handler: SubAdapter.SubListClickHandler) {
clickHandler = handler
}
fun bind(member: SubListItemUIModel.SubMemberItemUiModel) {
this.member = member.member
emailText.text = member.email
nameText.text = member.firstName + " " + member.lastName
val path = member.imageUrl
if (!path.isNullOrEmpty()) {
Picasso.get().load(path).fit().placeholder(R.mipmap.ic_launcher)
.into(subListMemberPhoto)
} else {
subListMemberPhoto.setImageResource(R.mipmap.ic_launcher)
}
}
}<file_sep>include ':app'
rootProject.name='MailChimpApplication'
<file_sep>package com.example.mailchimpapplication.ui.di
import android.app.Application
import androidx.lifecycle.ViewModelProviders
import com.example.mailchimpapplication.data.SubRepository
import com.example.mailchimpapplication.di.FragmentScope
import com.example.mailchimpapplication.ui.MemberFragment
import com.example.mailchimpapplication.ui.vm.MemberViewModel
import com.example.mailchimpapplication.ui.vm.MemberViewModelFactory
import dagger.Module
import dagger.Provides
@Module
class MemberFragmentModule {
@Provides
@FragmentScope
fun provideMemberViewModelFactory(
application: Application,
subRepository: SubRepository
): MemberViewModelFactory {
return MemberViewModelFactory(application, subRepository)
}
@Provides
@FragmentScope
fun provideMemberViewModel(
fragment: MemberFragment,
factory: MemberViewModelFactory
): MemberViewModel {
return ViewModelProviders.of(fragment, factory).get(MemberViewModel::class.java)
}
}<file_sep>package com.example.mailchimpapplication.ui.sublist
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.mailchimpapplication.R
import com.example.mailchimpapplication.data.models.Member
import com.example.mailchimpapplication.ui.MemberItemViewHolder
import com.example.mailchimpapplication.ui.SubListItemUIModel
import com.example.mailchimpapplication.ui.TitleItemViewHolder
class SubAdapter(private var subList: List<SubListAdapterType> = listOf()) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var subListClickhandler: SubListClickHandler? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view: View
return when (SubType.values()[viewType]) {
SubType.TITLE -> {
view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_subitem, parent, false)
TitleItemViewHolder(view)
}
SubType.MEMBER -> {
view = LayoutInflater.from(parent.context)
.inflate(R.layout.fragment_subitem_member, parent, false)
val viewHolder =
MemberItemViewHolder(view)
subListClickhandler?.let { viewHolder.setSubListClickHandler(it) }
viewHolder
}
}
}
override fun getItemViewType(position: Int) = subList[position].subType.ordinal
override fun getItemCount(): Int = subList.size
override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
when (SubType.values()[viewHolder.itemViewType]) {
SubType.TITLE -> {
(subList[position] as? SubListItemUIModel.SubListTitleUiModel)?.let {
(viewHolder as TitleItemViewHolder).bind(it)
}
}
SubType.MEMBER -> {
(subList[position] as? SubListItemUIModel.SubMemberItemUiModel)?.let {
(viewHolder as MemberItemViewHolder).bind(it)
}
}
}
}
fun update(newList: List<SubListAdapterType>) {
subList = newList
notifyDataSetChanged()
}
interface SubListClickHandler {
fun onClickMember(member: Member)
}
}
|
eb42bd5660084867136bd47363fd9bafdcd28abc
|
[
"Kotlin",
"Gradle"
] | 24 |
Kotlin
|
hughesmarcus/DemoApp
|
df9912e575364e2c22e3b66323eb1ebe9e1aa923
|
bfc1904782932d7b4ee1c294612f1440b7c80f51
|
refs/heads/master
|
<repo_name>yakhawkes/ddrating<file_sep>/imports/ui/Rater.jsx
import React from 'react';
import Mood from './Mood.jsx';
export default class Rater extends React.Component {
constructor(props) {
super(props);
this.fireSwisher = this.fireSwisher.bind(this);
this.choiceMade = this.choiceMade.bind(this);
this.state = {
swisherMoveToMood: '',
flipin: '',
flipout: '',
moodeSelected: false
};
}
fireSwisher(mood) {
this.setState({ swisherMoveToMood: `swisherMoveTo${mood}` });
}
choiceMade() {
this.setState({
flipin: 'flipin',
flipout: 'flipout',
moodeSelected: true
});
}
render() {
return (
<div className="rater-background">
<div className="rater-container">
<div className="floatleft rater-undercard" />
<div className="rater-card">
<div className={`question-wrapper ${this.state.flipout}`}>
<p className="rater-question">How did we do? Please rate your experience.</p>
<p className="rater-que">We're always looking to improve our customer experience.</p>
</div>
<div className={`thankyou-wrapper ${this.state.flipin}`}>
<p className="thankyou">Thank you.</p>
</div>
<div className="rater-wrapper">
<div className={`swisher ${this.state.swisherMoveToMood} floatleft`} />
<Mood
name="awful"
customerScore={0}
fireSwisher={this.fireSwisher}
choiceMade={this.choiceMade}
moodeSelected={this.state.moodeSelected}
/>
<Mood
name="bad"
customerScore={25}
fireSwisher={this.fireSwisher}
choiceMade={this.choiceMade}
moodeSelected={this.state.moodeSelected}
/>
<Mood
name="neutral"
customerScore={50}
fireSwisher={this.fireSwisher}
choiceMade={this.choiceMade}
moodeSelected={this.state.moodeSelected}
/>
<Mood
name="good"
customerScore={70}
fireSwisher={this.fireSwisher}
choiceMade={this.choiceMade}
moodeSelected={this.state.moodeSelected}
/>
<Mood
name="awesome"
customerScore={100}
fireSwisher={this.fireSwisher}
choiceMade={this.choiceMade}
moodeSelected={this.state.moodeSelected}
/>
</div>
</div>
</div>
</div>
);
}
}
<file_sep>/imports/ui/Mood.jsx
import React, { PropTypes } from 'react';
import { Ratings } from '../api/ratings.js';
export default class Mood extends React.Component {
constructor(props) {
super(props);
this.state = { selectedClassName: '', selected: false };
this.handleClick = this.handleClick.bind(this);
this.moodeSelected = '';
}
handleClick(event) {
event.preventDefault();
if (this.props.moodeSelected) return;
this.setState({ selectedClassName: 'selected', selected: true });
Ratings.insert({
score: this.props.customerScore
});
this.props.choiceMade();
this.props.fireSwisher(this.props.name);
this.moodeSelected = (
<div>
<div className="mood-selected">
<div className={`mood-${this.props.name}`} />
<div className="ticked" />
</div>
<div className="mood-selectpop" />
</div>);
}
render() {
return (
<a href="" onClick={this.handleClick} className="floatleft ">
<div className="cutout">
<div className={`mood ${this.state.selectedClassName}`} >
<div className={`mood-${this.props.name}`} />
</div>
{this.moodeSelected}
</div>
</a>
);
}
}
Mood.propTypes = {
name: PropTypes.string.isRequired,
customerScore: PropTypes.number.isRequired,
fireSwisher: PropTypes.func.isRequired,
choiceMade: PropTypes.func.isRequired,
moodeSelected: PropTypes.bool.isRequired
};
<file_sep>/imports/ui/Dashboard.jsx
import React from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import { Ratings } from '../api/ratings.js';
class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
mood: 'awesome',
moodColour: '',
score: 0
};
}
getScore(props) {
//This looks a really inefficient way to get a persentage from the server
return props.ratings.reduce((acc, rating) => { return acc + rating.score; }, 0) / props.ratings.length;
}
getMoodname(props) {
//This looks a really inefficient way to get a persentage from the server
const score = props.ratings.reduce((acc, rating) => { return acc + rating.score; }, 0) / props.ratings.length;
if (score > 0 && score < 20) {
return 'awful';
} else if (score >= 20 && score < 40) {
return 'bad';
} else if (score >= 40 && score < 60) {
return 'neutral';
} else if (score >= 60 && score < 80) {
return 'good';
} else if (score >= 80 && score < 100) {
return 'awesome';
} else {
return '';
}
}
render() {
this.getScore(this.props);
return (
<div className={`dashboard-background dashboard-moodbackground-${this.getMoodname(this.props)}`} >
<div className="dashboard-container">
<div className="dashboard-scorecontainer floatleft">
<p className="dashboard-score">{this.getScore(this.props).toFixed(1)}</p>
<p className="dashboard-scoreinfo">CUSTOMER SATISFACTION RATING</p>
</div>
<div className="dashboard-moodcontainer floatleft" >
<div className="dashboard-moodwrapper">
<div
className={`dashboard-moodbackground dashboard-moodbackground-${this.getMoodname(this.props)} floatleft`}
/>
<div className="mood" >
<div className={`mood-${this.getMoodname(this.props)}`} />
</div>
</div>
</div>
</div>
</div>
);
}
}
export default createContainer(() => {
return {
ratings: Ratings.find({}).fetch(),
};
}, Dashboard);
<file_sep>/client/Router.jsx
import React from 'react';
import { mount } from 'react-mounter';
import App from '../imports/ui/App.jsx';
import Rater from '../imports/ui/Rater.jsx';
import Dashboard from '../imports/ui/Dashboard.jsx';
FlowRouter.route('/', {
action() {
mount(App, { content: <Rater /> });
}
});
FlowRouter.route('/rating', {
action() {
mount(App, { content: <Rater /> });
}
});
FlowRouter.route('/dashboard', {
action() {
mount(App, { content: <Dashboard /> });
}
});
|
dba1be13f0c1fd19707bc18e0c54d66d49c7602a
|
[
"JavaScript"
] | 4 |
JavaScript
|
yakhawkes/ddrating
|
497506d0354e52840a1dbfd22809d8f3d90d85ce
|
55a14f750bcdcfb2116e21018adf83ac9098c85b
|
refs/heads/main
|
<file_sep>import telebot
from config import keys, TOKEN
from extencion import APIException, CryptoConverter
bot = telebot.TeleBot(TOKEN)
# ะัะฟะพะปะฝะตะฝะธั ะฟัะฝะบัะพะฒ 3, 4, 5 ะทะฐะดะฐะฝะธั
@bot.message_handler(commands=['start', 'help'])
def help(message: telebot.types.Message):
text = 'ะงัะพะฑั ะฝะฐัะฐัั ัะฐะฑะพัั ะฒะฒะตะดะธัะต ะบะพะผะผะฐะฝะดั ะฑะพัั ะฒ ัะปัะดะตััะตะผ ัะพัะผะฐัะต:\n<ะธะผั ะฒะฐะปััั, ัะตะฝั ะบะพัะพัะพะน ะฝะฐะดะพ ัะทะฝะฐัั> \
<ะธะผั ะฒะฐะปััั ะฒ ะบะพัะพัะพะน ะฝะฐะดะพ ัะทะฝะฐัั ัะตะฝั ะฟะตัะฒะพะน ะฒะฐะปััั> \
<ะบะพะปะธัะตััะฒะพ ะฟะตัะฒะพะน ะฒะฐะปััั>\n<ะฃะฒะธะดะธัั ัะฟะธัะพะบ ะฒัะตั
ะดะพัััะฟะฝัั
ะฒะฐะปัั:> /values\n <ะะฝััััะบัะธั ะฟะพ ะฟัะธะผะตะฝะตะฝะธั ะฑะพัะฐ /help ะธ /start'
bot.reply_to(message, text)
@bot.message_handler(commands=['values'])
def values(message: telebot.types.Message):
text = 'ะะพัััะฟะฝัะต ะฒะฐะปััั:'
for key in keys.keys():
text = '\n'.join((text, key, ))
bot.reply_to(message, text)
@bot.message_handler(content_types=['text',])
def convert(message: telebot.types.Message): # ะัะฝะบั 9 ะทะฐะดะฐะฝะธั
try:
values = message.text.split(' ')
if len(values) > 3: # ะะทะผะตะฝะธะป ััะปะพะฒะธะต ัะฐะบ ะบะฐะบ ััะปะพะฒะธะต ั ัะบัะธะฝะบะฐััะฐ ะฒัะฟะพะปะฝัะปะพัั ะฟะพััะพัะฝะฝะพ, ะบะพะด ะดะฐะปััะต ะฝะต ัะฐะฑะพัะฐะป
raise APIException('ะะพะปะธัะตััะฒะพ ะฟะฐัะฐะผะตััะพะฒ ะฝะต ัะพะพัะฒะตัััะฒัะตั ััะตะฑัะตะผะพะผั')
quote, base, amount = values
total_base = CryptoConverter.get_price(quote, base, amount)
except APIException as e:
bot.reply_to(message, f'ะัะธะฑะบะฐ ะฟะพะปัะทะพะฒะฐัะตะปั.\n{e}')
except Exception as e:
bot.reply_to(message, f'ะะต ัะดะฐะปะพัั ะพะฑัะฐะฑะพัะฐัั ะบะพะผะฐะฝะดั\n{e}')
else:
text = f'ะฆะตะฝะฐ {amount} {quote} ะฒ {base} - {total_base}'
bot.send_message(message.chat.id, text)
bot.polling()<file_sep>TOKEN = '<KEY>'
# ะขะพะบะตะฝ ัะฐั-ะฑะพัะฐ ั
ัะฐะฝะธััั ะฒ ะพัะดะตะปัะฝะพะผ ัะฐะนะปะต ัะพะณะปะฐัะฝะพ ะฟัะฝ.11 ะทะฐะดะฐะฝะธั
# ะกะปะพะฒะฐัั ั ะฒะฐะปััะฐะผะธ ัะพะณะปะฐัะฝะพ ะฟัะฝะบัั 1 ะทะฐะดะฐะฝะธั
keys = {'ะดะพะปะปะฐั': 'USD',
'ะตะฒัะพ': 'EUR',
'ััะฑะปั': 'RUB'
}
|
4ccadc372002bf434bd20d2a1e546dedd25f13ff
|
[
"Python"
] | 2 |
Python
|
Vitalii-Nekhrest/18.6
|
84e5bc455203bb6dbf2c5df03bb82cfcf3b05926
|
d2b27a650a219d0d1570db2afcebadd0f8925d67
|
refs/heads/master
|
<file_sep># parsing-XML-feed-google-shopping
Lo script legge il file XML di Google Shopping e restituisce in output il valore di alcuni attributi ed il contenuto di alcuni elementi testuali.
Eseguendo lo script otteniamo un output estratto dal file XML. Utilizzando la funzione simplexml_load_file carichiamo allโinterno di un oggetto SimpleXML il contenuto di un file passato come argomento. Lโargomento puรฒ essere sia un file che risiede sulla macchina locale come un file che risiede in remoto su un altro server.
Ho utilizzato questo script per stampare le immagini dei prodotti inclusi nel feed e verificare che rispettassero le norme di Google Shopping per evitarne la sospensione in fase di pubblicazione.
<file_sep><?php
$xml = simplexml_load_file("iltuofeedshopping.xml");
$ns = $xml->getNamespaces(true);
foreach($xml->channel->item as $item) {
$g = $item->children($ns["g"]);
printf(
"<ul><li><strong>SKU:</strong> %s - <strong>IMG:</strong> <img src='%s' height='80' width='80' /> - <strong>NOME PRODOTTO:</strong> %s - <strong>LINK:</strong> %s</li></ul>",
$g->id,
$g->image_link,
$item->title,
$item->link
);
}
?>
|
67231aa8b8925e66792638fdc5279e414044c05f
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
minosantoro/parsing-XML-feed-google-shopping
|
d41400602799d216d57931531105550f7570f437
|
f253fd66fb3c95556107d855ff02bec46789f14c
|
refs/heads/master
|
<file_sep>let object, sender, content, sendbutton, sent='true', turner = document.createElement('div'), rotation=20;
turner.style = 'width:10px;height:10px;background:blue;display:inline-block;float:right;position:relative;top:2px;'
let maketurn = async function(){
sendbutton.appendChild(turner)
await new Promise(resolve=>setTimeout(resolve,30))
turner.style.transform = `rotate(${rotation}deg)`
rotation += 5
if(sent == false){maketurn()}else{turner.remove()}
}
window.addEventListener('load', ()=>{
object = document.getElementById('cotitle')
sender = document.getElementById('coemail')
content=document.getElementById('cocontent')
sendbutton = document.getElementById('cosendnow')
sendbutton.addEventListener('click', async ()=>{
sent = false
maketurn()
Email.send({
Host : "smtp.gmail.com",
Username : "<EMAIL>",
Password : "<PASSWORD>",
To : '<EMAIL>',
From : sender.value,
Subject : object.value,
Body : content.value
}).then(
(message) => {alert(message);
sent = true}
);
})
})
|
112e730d62d8cf8db8656db46a2b2f9fb4207bc5
|
[
"JavaScript"
] | 1 |
JavaScript
|
DaCapo7/dacapo7.github.io
|
3dde19a34296fecbeef9ab78748017fc23899994
|
dbf00f22c61a76d637986eca909eefc585a965c0
|
refs/heads/master
|
<file_sep><?php
if (isset($_POST["submit"])) {
$user_name = $_POST["name"];
$enter_date = $_POST["date"];
$user_comment = $_POST["comment"];
//new post
// $new_post = ;
//colleting user data
$user_info = fopen("chat.txt", "a") or die("Unable to open file.");
$txt = $user_name . "--" . $enter_date . "--" . $user_comment . "\n";
$chat_info = explode("--", $txt);
fwrite($user_info, $txt);
fclose($user_info);
print_r($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<title>Chat</title>
</head>
<body>
<div class="container">
<form action="index.php" method="post" id="user_info">
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input name="name" type="text" class="form-control" id="exampleFormControlInput1" placeholder="Jonas">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Date</label>
<input name="date" type="text" class="form-control" id="exampleFormControlInput1" placeholder="2018-11-06">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Your comment</label>
<textarea name="comment" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" name="submit" class="btn btn-primary mb-2">Post comment</button>
</form>
<hr />
<div class="row">
<?php ?>
</div>
</div>
</body>
</html>
|
a34addc9c135d9f4bb4fdd63c5fc3f718f260c38
|
[
"PHP"
] | 1 |
PHP
|
Rimantas55/chat
|
b21be180fde201fca6a35bf60e50361a54fa3065
|
99e66c73cc0a4a4560c42c508e6f13b79dd5eaac
|
refs/heads/master
|
<repo_name>moults31/CPEN333<file_sep>/Lab2/src/integration.cpp
#include <iostream>
#include <random>
#include <thread>
#include <cmath>
#include <vector>
#include <chrono>
#define NUMSAMPLES 10000000
#define RADIUS 1.0
#define VOL RADIUS*RADIUS*RADIUS*4.0/3.0*3.14
#define DENSITY density2
using namespace std;
// three-dimensional point
struct pt_t
{
double x,y,z;
};
double density1(pt_t pt)
{
return exp(-1 * pow(abs(pt.x),2));
}
double density2(pt_t pt)
{
return abs(pt.x + pt.y + pt.z);
}
double density3(pt_t pt)
{
return pow(pt.x - 1, 2) + pow(pt.y - 2, 2) + pow(pt.z - 3, 2);
}
// virtual base class for functions
class Function
{
public:
Function() {};
virtual double operator()(pt_t pt)
{
return DENSITY(pt);
};
};
// computes x*fn(x,y,z)
class XFunction : public Function
{
Function& fn;
public:
XFunction(Function& fn) : fn(fn){};
double operator()(pt_t pt) {
return pt.x*fn(pt);
}
};
// computes y*fn(x,y,z)
class YFunction : public Function
{
Function& fn;
public:
YFunction(Function& fn) : fn(fn){};
double operator()(pt_t pt)
{
return pt.y*fn(pt);
}
};
// computes z*fn(x,y,z)
class ZFunction : public Function
{
Function& fn;
public:
ZFunction(Function& fn) : fn(fn){};
double operator()(pt_t pt)
{
return pt.z*fn(pt);
}
};
pt_t estimateC_ST(int nsamples);
pt_t estimateC_MT(int nsamples);
void computeMoment(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, pt_t pt, int idx);
void computeFns(vector<double> xrho, vector<double> yrho, vector<double> zrho, vector<double> rho, pt_t pt, int idx);
void sample(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, int idx, int nsamples);
bool isInSphere(pt_t pt);
pt_t centreOfMass(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, int n);
// Compute centre of mass of the sphere
pt_t estimateC_ST(int nsamples)
{
vector<double> xrho(NUMSAMPLES);
vector<double> yrho(NUMSAMPLES);
vector<double> zrho(NUMSAMPLES);
vector<double> rho(NUMSAMPLES);
sample(xrho, yrho, zrho, rho, 0, nsamples);
return centreOfMass(xrho, yrho, zrho, rho, nsamples);
}
// Compute centre of mass of the sphere using multiple threads
pt_t estimateC_MT(int nsamples)
{
vector<double> xrho(NUMSAMPLES);
vector<double> yrho(NUMSAMPLES);
vector<double> zrho(NUMSAMPLES);
vector<double> rho(NUMSAMPLES);
vector<thread> threads;
int nthreads = thread::hardware_concurrency();
int samplesHandled = 0;
int threadSamples = nsamples / nthreads;
// create nthreads threads and assign each of them an equal share of samples to handle
for(int i=0; i<nthreads-1; i++)
{
threads.push_back(thread(sample, ref(xrho), ref(yrho), ref(zrho), ref(rho), i, threadSamples));
samplesHandled += threadSamples;
}
// create threads for the extra samples that were the remainder in "nsamples / nthreads"
threads.push_back(thread(sample, ref(xrho), ref(yrho), ref(zrho), ref(rho),
nsamples-threadSamples-1, nsamples-threadSamples));
for (int i=0; i<nthreads; ++i) {
threads[i].join();
}
return centreOfMass(xrho, yrho, zrho, rho, nsamples);
}
// get random coords [x,y,z]. If they do not fall inside
// unit sphere, keep trying until they do.
// repeat this nsamples times starting at idx and incrementing each sample.
void sample(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, int idx, int nsamples)
{
static std::default_random_engine rnd(
std::chrono::system_clock::now().time_since_epoch().count());
static std::uniform_real_distribution<double> dist(-1.0, 1.0);
pt_t pt;
for(int i=0; idx+i<nsamples; i++)
{
do
{
pt.x = dist(rnd);
pt.y = dist(rnd);
pt.z = dist(rnd);
}while(!isInSphere(pt));
computeMoment(xrho, yrho, zrho, rho, pt, idx+i);
}
}
// compute the moment at this sample in [x,y,z] and store it in the vects
void computeMoment(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, pt_t pt, int idx)
{
Function fn;
rho[idx] = fn(pt);
XFunction xfn(fn);
xrho[idx] = xfn(pt);
YFunction yfn(fn);
yrho[idx] = yfn(pt);
ZFunction zfn(fn);
zrho[idx] = zfn(pt);
}
// Return true if point is within sphere of radius RADIUS, else return false
bool isInSphere(pt_t pt)
{
return sqrt(pt.x*pt.x + pt.y*pt.y + pt.z*pt.z) > RADIUS ? false : true;
}
// Calculate centre of mass given densities and moments
pt_t centreOfMass(vector<double>& xrho, vector<double>& yrho,
vector<double>& zrho, vector<double>& rho, int n)
{
double rhosum = 0, xsum = 0, ysum = 0, zsum = 0;
double rhoavg, xavg, yavg, zavg;
pt_t c;
for(int i=0; i<n; i++)
{
rhosum += rho[i];
xsum += xrho[i];
ysum += yrho[i];
zsum += zrho[i];
}
rhoavg = VOL*rhosum/n;
xavg = VOL*xsum/n;
yavg = VOL*ysum/n;
zavg = VOL*zsum/n;
c.x = xavg/rhoavg;
c.y = yavg/rhoavg;
c.z = zavg/rhoavg;
return c;
}
int main()
{
pt_t c;
// Estimate centre of mass using single threaded approach and time and report it
auto t1 = std::chrono::high_resolution_clock::now();
c = estimateC_ST(NUMSAMPLES);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = t2 - t1;
auto duration_ms_st = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
long ms = duration_ms_st.count();
cout << endl << "Centre of mass is located at:" << endl;
cout << "x: " << c.x << " y: " << c.y << " z: " << c.z << endl;
cout << "Found in " << ms << "ms using " << NUMSAMPLES << " samples and single threaded program" << endl << endl;
// Estimate centre of mass using multi threaded approach and time and report it
t1 = std::chrono::high_resolution_clock::now();
c = estimateC_MT(NUMSAMPLES);
t2 = std::chrono::high_resolution_clock::now();
duration = t2 - t1;
auto duration_ms_mt = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
ms = duration_ms_mt.count();
cout << "Centre of mass is located at:" << endl;
cout << "x: " << c.x << " y: " << c.y << " z: " << c.z << endl;
cout << "Found in " << ms << "ms using " << NUMSAMPLES << " samples and multi threaded program" << endl;
// Compute speedup and report it
double speedup = (double)duration_ms_st.count()/(double)duration_ms_mt.count();
cout << endl << "Speedup factor: " << speedup << endl;
return 0;
}
<file_sep>/Lab1/src/physics.h
#ifndef PHYSICS
#define PHYSICS
namespace physics
{
inline double compute_position(double x0, double v, double dt)
{
return v*dt + x0;
}
inline double compute_velocity(double v0, double a, double dt)
{
return a*dt + v0;
}
inline double compute_velocity(double x0, double t0, double x1, double t1)
{
return (x1 - x0)/(t1 - t0);
}
inline double compute_acceleration(double v0, double t0, double v1, double t1)
{
return (v1 - v0)/(t1 - t0);
}
inline double compute_acceleration(double f, double m)
{
return f/m;
}
}
#endif // PHYSICS
<file_sep>/Lab1/makefile
# car simulator project
bin/car_sim: bin/car_simulator.o
g++ -Wall bin/car_simulator.o -o bin/car_sim
bin/car_simulator.o: src/car_simulator.cpp
g++ -Wall -c src/car_simulator.cpp -o bin/car_simulator.o
# drag race project
bin/drag_race: bin/drag_race.o bin/Car.o
g++ -Wall bin/drag_race.o bin/Car.o -o bin/drag_race
bin/drag_race.o: src/drag_race.cpp
g++ -Wall -c src/drag_race.cpp -o bin/drag_race.o
# highway project
bin/highway: bin/highway.o bin/Car.o
g++ -Wall -std=c++11 bin/highway.o bin/Car.o -o bin/highway
bin/highway.o: src/highway.cpp
g++ -Wall -std=c++11 -c src/highway.cpp -o bin/highway.o
bin/Car.o: src/Car.cpp
g++ -Wall -std=c++11 -c src/Car.cpp -o bin/Car.o
<file_sep>/Lab1/src/drag_race.cpp
// OBJECT-ORIENTED CAR SIMULATOR
#include <iostream>
#include <string>
#include "State.h"
#include "Car.h"
#define QUARTERMILE 402.3
int main()
{
Car car1((std::string)"<NAME>", 1600, 790, 0.61);
Car car2((std::string)"<NAME>", 1450, 740, 0.58);
Car *leader = new Car((std::string)"<NAME>", 1600, 790, 0.61);
// Define time step size in seconds
double dt = 0.01;
// GO!!!!
car1.accelerate(true);
car2.accelerate(true);
do
{
if(car1.getState()->x <= QUARTERMILE) car1.drive(dt);
if(car1.getState()->x <= QUARTERMILE) car2.drive(dt);
// keep track of leader at each time step
*leader = car1.getState()->x > car2.getState()->x ? car1 : car2;
std::cout << car1.getModel() << " is at " << car1.getState()->x << std::endl;
std::cout << car2.getModel() << " is at " << car2.getState()->x << std::endl << std::endl;
} while(car2.getState()->x < QUARTERMILE || car1.getState()->x < QUARTERMILE);
// print out winner
std::cout << "Winner is " << leader->getModel() << " finishing in "
<< leader->getState()->t << " seconds" << std::endl;
return 0;
}
<file_sep>/Lab2/src/pi.cpp
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <math.h>
#include <random>
#define RADIUS 1.0
void pi_sampler(std::vector<bool>& hits, int idx);
double estimate_pi_multithread_naive(int nsamples);
void pi_hits(std::vector<int> &hits, int tidx, int nsamples);
double estimate_pi_multithread(int nsamples);
// estimates the value of pi single-threadedly
double estimate_pi(int nsamples) {
std::vector<bool> hits(nsamples);
double nhits = 0;
for(int i=0; i<nsamples; i++)
{
pi_sampler(hits, i);
if(hits[i]) nhits++;
}
double pi = nhits/nsamples;
return pi*4.0;
}
// generates a random sample and sets hits[idx]
// to true if within the unit circle
void pi_sampler(std::vector<bool>& hits, int idx) {
// single instance of random engine and distribution
static std::default_random_engine rnd(
std::chrono::system_clock::now().time_since_epoch().count());
static std::uniform_real_distribution<double> dist(-1.0, 1.0);
// get random [x,y]
double x = dist(rnd);
double y = dist(rnd);
// convert to polar (r only)
double r = sqrt(x*x + y*y);
// if pt fell upon circle set hits to true else not
if(r > RADIUS)
{
hits[idx] = false;
}
else
{
hits[idx] = true;
}
}
// naively uses multithreading to try to speed up computations
double estimate_pi_multithread_naive(int nsamples) {
// stores whether each sample falls within circle
std::vector<bool> hits(nsamples, false);
// create and store all threads
std::vector<std::thread> threads;
for (int i=0; i<nsamples; ++i) {
threads.push_back(std::thread(pi_sampler, std::ref(hits), i));
}
// wait for all threads to complete
for (int i=0; i<nsamples; ++i) {
threads[i].join();
}
// estimate our value of PI
double pi = 0;
for (int i=0; i<nsamples; ++i) {
if (hits[i]) {
pi = pi + 1;
}
}
pi = pi / nsamples*4;
return pi;
}
// Increments the number of pi hits
void pi_hits(std::vector<int> &hits, int tidx, int nsamples) {
// single instance of random engine and distribution
static std::default_random_engine rnd(
std::chrono::system_clock::now().time_since_epoch().count());
static std::uniform_real_distribution<double> dist(-1.0, 1.0);
for(int i=0; i<nsamples; i++)
{
// get random [x,y]
double x = dist(rnd);
double y = dist(rnd);
// get distance from centre using pythagorus
double r = sqrt(x*x + y*y);
// if pt fell upon circle increment hits for this thread
if(r <= RADIUS)
{
hits[tidx]++;
}
}
}
// divides work among threads intelligently
double estimate_pi_multithread(int nsamples) {
// number of available cores
int nthreads = std::thread::hardware_concurrency();
// hit counts
std::vector<int> hits(nthreads, 0);
// create and store threads
std::vector<std::thread> threads;
int msamples = 0; // samples accounted for
for (int i=0; i<nthreads-1; ++i) {
threads.push_back(
std::thread(pi_hits, std::ref(hits), i, nsamples/nthreads));
msamples += nsamples/nthreads;
}
// remaining samples
threads.push_back(
std::thread(pi_hits, std::ref(hits), nthreads-1, nsamples-msamples));
// wait for threads to finish
for (int i=0; i<nthreads; ++i) {
threads[i].join();
}
// estimate pi
double pi = 0;
for (int i=0; i<nthreads; ++i) {
pi += hits[i];
}
pi = pi/nsamples*4;
return pi;
}
int main(void) {
// Estimate pi using single threaded approach and time and report it
auto t1 = std::chrono::high_resolution_clock::now();
double pi = estimate_pi(100000000);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = t2 - t1;
auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
long ms = duration_ms.count();
std::cout << "Pi estimate (ST): " << pi << " (" << ms << "ms)" << std::endl;
// Estimate pi using naive multi threaded approach and time and report it
t1 = std::chrono::high_resolution_clock::now();
pi = estimate_pi_multithread_naive(1000);
t2 = std::chrono::high_resolution_clock::now();
duration = t2 - t1;
duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
ms = duration_ms.count();
std::cout << "Pi estimate (MT naive): " << pi << " (" << ms << "ms)" << std::endl;
// Estimate pi using intelligent multi threaded approach and time and report it
t1 = std::chrono::high_resolution_clock::now();
pi = estimate_pi_multithread(100000000);
t2 = std::chrono::high_resolution_clock::now();
duration = t2 - t1;
duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
ms = duration_ms.count();
std::cout << "Pi estimate (MT): " << pi << " (" << ms << "ms)" << std::endl;
return 0;
}
<file_sep>/Lab1/src/State.h
#ifndef STATE
#define STATE
#include <iostream>
class State
{
public:
// Properties
double x;
double v;
double a;
double t;
// Constructor
State() { x = v = a = t = 0; }
State(double pos, double vel, double acc, double time) :
x(pos), v(vel), a(acc), t(time) {};
// Methods
void set(double pos, double vel, double acc, double time);
};
// prints out a State class information
inline std::ostream& operator<<(std::ostream& os, State& state)
{
os << "t: " << state.t << ", x: " << state.x
<< ", v: " << state.v << ", a: " << state.a;
return os;
}
// sets properties of State
inline void State::set(double pos, double vel, double acc, double time)
{
x = pos;
v = vel;
a = acc;
t = time;
}
#endif //STATE
<file_sep>/Lab1/src/highway.cpp
#include <vector>
#include <string>
#include <iostream>
#include "Car.h"
#include "physics.h"
#include "State.h"
#define FLEETSIZE 100 // cars
#define SIMLENGTH 100 // seconds
#define MAXSPEED 27.8 // m/s
int main(void)
{
std::vector<Car *> cars;
// Add 100 cars to the fleet
for(int i=0; i<FLEETSIZE/4; i++)
{
cars.push_back(new Prius);
cars.push_back(new Tesla3);
cars.push_back(new Mazda3);
cars.push_back(new Herbie);
}
double dt = 1;
for(int t=0; t<SIMLENGTH; t++)
{
// Update car states
for (Car *car : cars)
{
if(car->getState()->v > MAXSPEED) car->accelerate(false);
else car->accelerate(true);
car->drive(dt);
std::cout << car->getModel() << " -- " << *(car->getState()) << car->getState()->v << std::endl;
}
}
// Print out car states and free their memory
for (Car *car : cars)
{
std::cout << car->getModel() << " is at " << car->getState()->x << std::endl;
delete car;
car = nullptr;
}
return 0;
}
<file_sep>/Lab2/src/quicksort.cpp
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <math.h>
#include <random>
#define _MAXTHREADS 10
// partitions elements low through high (inclusive)
// around a pivot and returns the pivot index
size_t partition(std::vector<int>& data, int low, int high)
{
int pivot = data[high];
int i = low-1;
int tmp;
for(size_t j = low; j < high; j++)
{
// If jth element <= pivot, do i++ and swap data @ i,j
if(data[j] <= pivot)
{
i++;
tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
// Place pivot at the upper end of the left partition
// by swapping it with the index just greater than i
tmp = data[high];
data[high] = data[i+1];
data[i+1] = tmp;
return i+1;
}
// sorts elements low through high (inclusive) using a single thread
void quicksort(std::vector<int>& data, int low, int high)
{
size_t pi;
if(low < high)
{
pi = partition(data, low, high);
quicksort(data, low, pi-1); // Up to partition
quicksort(data, pi+1, high); // Above partition
}
}
void thread_fn(int idx)
{
std::cout << "hellow thrad" << idx << std::endl;
}
// sorts elements low through high (inclusive) using multiple threads
void parallel_quicksort(std::vector<int>& data, int low, int high, int* numThreads, int MAXTHREADS)
{
if(low < high)
{
const size_t &pi = partition(data, low, high);
const size_t &lopi = pi - 1;
const size_t &hipi = pi + 1;
//std::cout << *numThreads << std::endl << std::endl;
if(*numThreads >= MAXTHREADS)
{
parallel_quicksort(data, low, lopi, numThreads, MAXTHREADS);
parallel_quicksort(data, hipi, high, numThreads, MAXTHREADS);
}
else
{
(*numThreads)++;
std::thread t1( parallel_quicksort,
std::ref(data),
low,
lopi,
std::ref(numThreads),
std::ref(MAXTHREADS)
);
(*numThreads)++;
std::thread t2( parallel_quicksort,
std::ref(data),
hipi,
high,
std::ref(numThreads),
std::ref(MAXTHREADS)
);
t1.join();
(*numThreads)--;
t2.join();
(*numThreads)--;
}
}
}
// Tests single threaded quicksort for accuracy
bool unitTest_quicksort()
{
std::vector <int> test {1, 5, 4, 3, 2};
std::vector <int> expected {1, 2, 3, 4, 5};
quicksort(test, 0, test.size()-1);
for(int i=0; i<test.size(); i++)
{
if(test[i] != expected[i])
{
std::cout << "Quicksort test failed" << std::endl;
return false;
}
}
std::cout << "Quicksort test passed" << std::endl;
return true;
}
// Tests multi threaded quicksort for accuracy
bool unitTest_parallel_quicksort()
{
std::vector <int> test {1, 5, 4, 3, 2};
std::vector <int> expected {1, 2, 3, 4, 5};
std::vector <std::thread> threads;
parallel_quicksort(test, 0, test.size()-1, 0, 4);
for(int i=0; i<test.size(); i++)
{
if(test[i] != expected[i])
{
std::cout << "Prll Quicksort test failed" << std::endl;
return false;
}
}
std::cout << "Prll Quicksort test passed" << std::endl;
return true;
}
int main()
{
// create two copies of random data
const int VECTOR_SIZE = 10000000;
std::vector<int> v1(VECTOR_SIZE, 0);
std::vector<std::thread> threads;
int MAXTHREADS = _MAXTHREADS;
// fill with random integers
for (int i=0; i<VECTOR_SIZE; ++i)
{
v1[i] = rand();
}
std::vector<int> v2 = v1; // copy all contents
// sort v1 using sequential algorithm and measure time taken
auto t1 = std::chrono::high_resolution_clock::now();
quicksort(v1, 0, v1.size()-1);
auto t2 = std::chrono::high_resolution_clock::now();
auto duration_seq = t2 - t1;
// cast duration of single threaded qsort to ms,
// and report it on stdout
auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration_seq);
long ms = duration_ms.count();
std::cout << "Quicksort took " << ms << " ms" << std::endl;
// report how many threads are supported on this hardware
unsigned int n = std::thread::hardware_concurrency();
std::cout << n << " concurrent threads are supported.\n";
// sort v2 using parallel algorithm and measure time taken
int *numThreads = new int;
t1 = std::chrono::high_resolution_clock::now();
parallel_quicksort(v2, 0, v2.size()-1, numThreads, MAXTHREADS);
t2 = std::chrono::high_resolution_clock::now();
auto duration_prll = t2 - t1;
delete numThreads;
// cast duration of single threaded qsort to ms,
// and report it on stdout
duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration_prll);
ms = duration_ms.count();
std::cout << "Prll quicksort took " << ms << " ms" << std::endl;
double speedup = (double)duration_seq.count()/(double)duration_prll.count();
std::cout << "num threads: " << MAXTHREADS << std::endl;
std::cout << "Speedup factor: " << speedup << std::endl << std::endl;
return 0;
}
<file_sep>/Lab1/src/Car.cpp
#include <iostream>
#include <stdlib.h>
#include <string>
#include "Car.h"
#include "physics.h"
#define RHO_AIR 1.225
// Return a string containing the model of the car
std::string Car::getModel(void)
{
return model;
}
// Return the mass of the car
double Car::getMass(void)
{
return mass;
}
// Set initial acceleration if on is true
void Car::accelerate(bool on)
{
accel_on = on;
}
// Update car's state after one time step
void Car::drive(double dt)
{
// Update drag force
double fd = 0.5*RHO_AIR*drag_area*state.v*state.v;
// Compute updated state (x,v,a,t)
double acc = accel_on ?
physics::compute_acceleration(engine_force - fd, mass) :
physics::compute_acceleration(-1 * fd, mass);
double vel = physics::compute_velocity(state.v, acc, dt);
double pos = physics::compute_position(state.x, vel, dt);
double time = state.t + dt;
// Store results in car's state member
state.set(pos, vel, acc, time);
}
// Return a pointer to the car's current state
State * Car::getState(void)
{
return &state;
}
// Drive but ignore air resistance
void Herbie::drive(double dt)
{
// Compute updated state (x,v,a,t)
double acc = physics::compute_acceleration(engine_force, mass);
double vel = physics::compute_velocity(state.v, acc, dt);
double pos = physics::compute_position(state.x, vel, dt);
double time = state.t + dt;
// Store results in car's state member
state.set(pos, vel, acc, time);
}
<file_sep>/Lab1/src/Car.h
#ifndef CAR
#define CAR
#include <string>
#include "State.h"
class Car
{
protected:
// Properties
std::string model;
double mass;
double engine_force;
double drag_area;
bool accel_on;
State state;
public:
// Constructor
Car(std::string argmodel, double argmass, double argengine_force, double argdrag_area) :
model(argmodel), mass(argmass),
engine_force(argengine_force), drag_area(argdrag_area) {};
virtual ~Car() {};
// Methods
std::string getModel(void);
double getMass(void);
void accelerate(bool on);
virtual void drive(double dt);
State * getState(void);
};
// Derived classes of Car
class Prius : public Car
{
public:
// Constructor
Prius() : Car((std::string)"<NAME>", 1450, 740, 0.58) {}
};
class Mazda3 : public Car
{
public:
// Constructor
Mazda3() : Car((std::string)"Mazda 3", 1600, 790, 0.61) {}
};
class Tesla3 : public Car
{
public:
// Constructor
Tesla3() : Car((std::string)"Tesla Model 3", 1400, 850, 0.5) {}
};
class Herbie : public Car
{
public:
// Constructor
Herbie() : Car((std::string)"Herbie", 1500, 750, 0.55) {};
void drive(double dt);
};
#endif
<file_sep>/Lab2/makefile
# quicksort project
bin/quicksort: bin/quicksort.o
g++ -Wall -std=c++11 bin/quicksort.o -o bin/quicksort
bin/quicksort.o: src/quicksort.cpp
g++ -Wall -std=c++11 -c src/quicksort.cpp -o bin/quicksort.o
# pi project
bin/pi: bin/pi.o
g++ -Wall -std=c++11 bin/pi.o -o bin/pi
bin/pi.o: src/pi.cpp
g++ -Wall -std=c++11 -c src/pi.cpp -o bin/pi.o
# integration project
bin/integration: bin/integration.o
g++ -Wall -std=c++11 bin/integration.o -o bin/integration
bin/integration.o: src/integration.cpp
g++ -Wall -std=c++11 -c src/integration.cpp -o bin/integration.o
|
9190bec27a50af1f3101f56adac5cf00ed472b80
|
[
"Makefile",
"C++"
] | 11 |
C++
|
moults31/CPEN333
|
e8cd584ad10a167e0af0c6d8f5973bb4134c38d6
|
22798fb224cafec18399b9738b4dde408c77c3fe
|
refs/heads/master
|
<file_sep>__author__ = 'Vijay'
import requests
import config
class Talk:
def __init__(self, webhook):
self.webhook = webhook
def push(self, title, text, redirectUrl):
pyload = {
'title': title,
'text': text,
'redirectUrl': redirectUrl
}
res = requests.post(url=self.webhook, json=pyload)
return res.json()
if __name__ == '__main__':
t = Talk(config.talk['webhook'])
t.push(title='test', text='testpush', redirectUrl='http://zhihu.com')<file_sep>__author__ = 'Vijay'
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
teambition = {
"client_id": "3e5f4ea0-c216-11e4-ac08-6bd9c5a2d72d",
"client_secret": "e61097d9-ca24-4a65-a353-dfe40f6eea9b",
"email": client['zhihu']['settings'].find_one({'key': 'tb_email'})['value'],
"password": client['zhihu']['settings'].find_one({'key': 'tb_password'})['value'],
"_tasklistId": "555c9abfb746efa51a89e8b1",
"_executorId": "54116bb57c6191897b163d00",
"token": client['zhihu']['settings'].find_one({'key': 'teambition_token'})['value'] or ""
}
talk = {
"webhook": client['zhihu']['settings'].find_one({'key': 'talk_webhook'})['value']
}
pushbullet = {
"pushs": client['zhihu']['pushes'].find()
}<file_sep>/**
* Created by Vijay on 15/5/31.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var SettingSchema = new Schema({
key: String,
value: String
});
module.exports = mongoose.model('Setting', SettingSchema);
<file_sep>__author__ = 'Vijay'
import requests
import config
class Pushbullet:
proxies = {
"http": "http://theironislands.f.getqujing.net:44758",
"https": "http://theironislands.f.getqujing.net:44758"
}
def __init__(self, token):
self.token = token
def push_note(self, title='', body=''):
url = 'https://api.pushbullet.com/v2/pushes'
headers = {
'Authorization': 'Bearer ' + self.token
}
payload = {
"type": "note",
"title": title,
"body": body
}
res = requests.post(url=url, headers=headers, json=payload, proxies=self.proxies)
return res.json()
if __name__ == '__main__':
pushs = config.pushbullet['pushs']
for push in pushs:
token = push['push_token']
pb = Pushbullet(token)
pb.push_note(title="VijayPush", body="TestPush")
<file_sep>/**
* Created by Vijay on 15/5/31.
*/
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
content: String,
createTime: Number,
_executorId: String,
_tasklistId: String,
follows: Number,
note: String,
url: String,
priority: Number
});
module.exports = mongoose.model('Task', TaskSchema);
<file_sep>__author__ = 'Vijay'
import requests
import config
class Teambition:
base_url = 'https://api.teambition.com'
def __init__(self, token=''):
if token == '' or not self.checkToken(token):
self.token = self.getTokenByPassword(email=config.teambition['email'], password=config.teambition['password'])
else:
self.token = token
def checkToken(self, token):
options = {
'method': 'get',
'url': 'https://api.teambition.com/api/applications/' + config.teambition['client_id'] + '/tokens/check',
'headers': {
'Authorization': 'OAuth2 ' + token
}
}
res = requests.request(**options)
return res.status_code == 200
def getTokenByPassword(self, email, password):
options = {
'method': 'post',
'url': 'https://account.teambition.com/oauth2/access_token',
'json': {
"client_id": config.teambition['client_id'],
"client_secret": config.teambition['client_secret'],
"code": "",
"grant_type": "password",
"email": email,
"password": <PASSWORD>
}
}
res = requests.request(**options)
token = res.json()['access_token']
config.teambition['token'] = token
config.client['zhihu']['settings'].update_one({'key': 'teambition_token'}, {'$set': {'value': token}}, upsert=True)
return token
def invokeGeneric(self, method, api_url, params={}):
url = self.base_url + api_url
headers = {
'Content-Type': 'application/json'
}
options = {
'method': method,
'url': url,
'params': {
'access_token': self.token
}
}
if method.lower() != 'get':
options['json'] = params
print(options)
res = requests.request(**options)
print(res.json())
return res.json()
def get(self, api_url, params={}):
return self.invokeGeneric('GET', api_url=api_url, params=params)
def post(self, api_url, params={}):
return self.invokeGeneric('POST', api_url=api_url, params=params)
def put(self, api_url, params={}):
return self.invokeGeneric('PUT', api_url=api_url, params=params)
def delete(self, api_url, params={}):
return self.invokeGeneric('DELETE', api_url=api_url, params=params)
class Task:
def __init__(self, _tasklistId, token=''):
self._tasklistId = _tasklistId
self.teambition = Teambition(token=token)
def find(self):
return self.teambition.get(api_url='/tasklists/'+ self._tasklistId + '/tasks')
def create(self, data):
data['_tasklistId'] = self._tasklistId
return self.teambition.post(api_url='/tasks', params=data)
def remove(self, _id):
return self.teambition.delete(api_url='/tasks/' + _id)
def update(self, _id, data):
return self.teambition.put(api_url='/tasks/' + _id, params=data)
if __name__ == '__main__':
token = '<KEY>Xq0HjObs007dca37c84cce4990bed4c826310a1d8c1fe63403dcb15f2ddde3be410e31f610a9cdefbba3da9ecf9bcd5faf515b6bdee58eaf8bad4eae18742fcd7a3fdfa9fcee4c052adc38a8c9754c8be12f2c213374ec0e4ed4be91b9a90821b86a99d9d90e41fcfc3c343650d11f7233432464'
tasklist = '5524aa31eda13690103c1713'
taskServer = Task(token=token, _tasklistId=tasklist)
tasks = taskServer.find()
for task in tasks:
_id = task['_id']
taskServer.update(_id=_id, data={'note':'test'})
<file_sep>/**
* Created by Vijay on 15/5/31.
*/
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/zhihu');
var Setting = require('../models/setting');
var Task = require('../models/task');
var Topic = require('../models/topic');
var Push = require('../models/push');
var moment = require('moment');
/* GET users listing. */
router.get('/settings', function(req, res, next) {
Setting.find(function(err, settings) {
if (err)
res.send(err);
res.json(settings);
});
});
router.put('/settings/:_id', function(req, res, next) {
Setting.findById(req.params._id, function(err, setting) {
if (err)
res.send(err);
setting.value = req.body.value;
setting.save(function(err, setting) {
if (err)
res.send(err);
res.json(setting);
});
});
});
router.get('/tasks', function(req, res, next) {
Task.find(function(err, tasks) {
if (err)
res.send(err);
res.json(tasks);
});
});
router.get('/taskscount', function(req, res, next) {
Task.find(function(err, tasks) {
if (err)
res.send(err);
var date = [];
for(i in tasks) {
date.push(tasks[i]['createTime']);
console.log(i)
console.log(moment(tasks[i]['createTime'], 'X').format('YYYY-MM-DD'))
}
date.sort();
var count = {};
var dateArray = [], countArray = [];
if(date.length){
for(var i = date[0], j = 0; i <= date[date.length - 1] || moment(i, 'X').format('YYYY-MM-DD') == moment(date[date.length - 1], 'X').format('YYYY-MM-DD') ;i += 24 * 60 * 60, j += 1) {
count[moment(i, 'X').format('YYYY-MM-DD')] = j;
dateArray.push(moment(i, 'X').format('YYYY-MM-DD'));
countArray.push(0);
console.log(i)
console.log(i + 24 * 60 * 6)
console.log(moment(i, 'X').format('YYYY-MM-DD'))
}
for(i in date){
countArray[count[moment(date[i], 'X').format('YYYY-MM-DD')]]++;
}
}
res.json({dateArray: dateArray, countArray: countArray});
});
});
router.get('/topics', function(req, res, next) {
Topic.find(function(err, topics) {
if (err)
res.send(err);
res.json(topics);
});
});
router.post('/topics', function(req, res, next) {
topic = new Topic();
topic.name = req.body.name;
topic.url = req.body.url;
topic.save(function(err, topic) {
if (err)
res.send(err);
res.json(topic);
})
});
router.put('/topics/:_id', function(req, res, next) {
Topic.findById(req.params._id, function(err, topic) {
if (err)
res.send(err);
topic.name = req.body.name;
topic.url = req.body.url;
topic.save(function(err, topic) {
if (err)
res.send(err);
res.json(topic);
});
});
});
router.delete('/topics/:_id', function(req, res, next) {
Topic.remove({
_id: req.params._id
}, function(err, topic) {
if (err)
res.send(err);
res.json(topic);
});
});
router.get('/pushs', function(req, res, next) {
Push.find(function(err, pushs) {
if (err)
res.send(err);
res.json(pushs);
});
});
router.post('/pushs', function(req, res, next) {
push = new Push();
push.name = req.body.name;
push.push_token = req.body.push_token;
push.save(function(err, push) {
if (err)
res.send(err);
res.json(push);
})
});
router.put('/pushs/:_id', function(req, res, next) {
Push.findById(req.params._id, function(err, push) {
if (err)
res.send(err);
push.name = req.body.name;
push.push_token = req.body.push_token;
push.save(function(err, push) {
if (err)
res.send(err);
res.json(push);
});
});
});
router.delete('/pushs/:_id', function(req, res, next) {
Push.remove({
_id: req.params._id
}, function(err, push) {
if (err)
res.send(err);
res.json(push);
});
});
module.exports = router;
<file_sep>__author__ = 'Vijay'
import requests
import config
import teambition
taskServer = teambition.Task(_tasklistId = config.teambition['_tasklistId'], token=config.teambition['token'])
tasks = taskServer.find()
for task in tasks:
taskServer.remove(_id=task['_id'])<file_sep>/**
* Created by Vijay on 15/5/31.
*/
$(document).ready(function() {
$.get('/api/settings').done(function(data){
for(i in data) {
var setting = data[i];
$('#' + setting['key']).val(setting['value']).attr('data-_id', setting['_id']);
$('#' + setting['key'] + '_save').attr('data-bind', setting['key']).click(function() {
var key = $(this).attr('data-bind');
var value = $('#' + key).val();
var _id = $('#' + key).attr('data-_id');
$.ajax({
method: 'PUT',
url: '/api/settings/' + _id,
data: {
key: key,
value: value
}
}).done(function() {
saveSuccess();
})
})
}
});
$.get('/api/topics').done(function(data){
for(i in data) {
var topic = data[i];
var html = '<tr> <td><input type="text" class="form-control"></td> <td><input type="text" class="form-control"></td> <td><button type="button" class="btn btn-info " onclick="saveTopic(this)">ไฟๅญ</button><button type="button" class="btn btn-danger " onclick="deleteTopic(this)">ๅ ้ค</button></td> </tr>';
var $element = $('#topic').append(html).find('tr:last-child');
$element.attr('data-_id', topic['_id']);
$element.find('td:first-child input').val(topic['name']);
$element.find('td:nth-child(2) input').val(topic['url']);
}
})
$.get('/api/pushs').done(function(data){
for(i in data) {
var push = data[i];
var html = '<tr> <td><input type="text" class="form-control"></td> <td><input type="text" class="form-control"></td> <td><button type="button" class="btn btn-info " onclick="savePush(this)">ไฟๅญ</button><button type="button" class="btn btn-danger " onclick="deletePush(this)">ๅ ้ค</button></td> </tr>';
var $element = $('#push').append(html).find('tr:last-child');
$element.attr('data-_id', push['_id']);
$element.find('td:first-child input').val(push['name']);
$element.find('td:nth-child(2) input').val(push['push_token']);
}
})
});
var saveSuccess = function() {
$('#alert').text('ไฟๅญๆๅ๏ผ').show();
setTimeout("$('#alert').hide()",2000);
}
var deleteSuccess = function() {
$('#alert').text('ๅ ้คๆๅ๏ผ').show();
setTimeout("$('#alert').hide()",2000);
}
var deleteTopic = function(element) {
var $topic = $(element).parent().parent();
$.ajax({
method: 'DELETE',
url: '/api/topics/' + $topic.attr('data-_id')
}).done(function(data) {
deleteSuccess();
})
$topic.remove();
}
var saveTopic = function(element) {
var $topic = $(element).parent().parent();
if($topic.attr('data-_id')) {
$.ajax({
method: 'PUT',
url: '/api/topics/' + $topic.attr('data-_id'),
data: {
name: $topic.find('td:first-child input').val(),
push_token: $topic.find('td:nth-child(2) input').val()
}
}).done(function(data) {
saveSuccess();
});
} else {
$.ajax({
method: 'POST',
url: '/api/topics/',
data: {
name: $topic.find('td:first-child input').val(),
push_token: $topic.find('td:nth-child(2) input').val()
}
}).done(function(data) {
$topic.find('td:last-child button:last-child').replaceWith('<button type="button" class="btn btn-danger " onclick="deleteTopic(this)">ๅ ้ค</button>');
saveSuccess();
});
}
}
var cancelTopic = function(element) {
var $topic = $(element).parent().parent();
$topic.remove();
}
var createTopic = function() {
var html = '<tr> <td><input type="text" class="form-control"></td> <td><input type="text" class="form-control"></td> <td><button type="button" class="btn btn-info " onclick="saveTopic(this)">ไฟๅญ</button><button type="button" class="btn btn-default " onclick="cancelTopic(this)">ๅๆถ</button></td> </tr>';
$('#topic').append(html);
}
var deletePush = function(element) {
var $push = $(element).parent().parent();
$.ajax({
method: 'DELETE',
url: '/api/pushs/' + $push.attr('data-_id')
}).done(function(data) {
deleteSuccess();
})
$push.remove();
}
var savePush = function(element) {
var $push = $(element).parent().parent();
if($push.attr('data-_id')) {
$.ajax({
method: 'PUT',
url: '/api/pushs/' + $push.attr('data-_id'),
data: {
name: $push.find('td:first-child input').val(),
push_token: $push.find('td:nth-child(2) input').val()
}
}).done(function(data) {
saveSuccess();
});
} else {
$.ajax({
method: 'POST',
url: '/api/pushs/',
data: {
name: $push.find('td:first-child input').val(),
push_token: $push.find('td:nth-child(2) input').val()
}
}).done(function(data) {
$push.find('td:last-child button:last-child').replaceWith('<button type="button" class="btn btn-danger " onclick="deletePush(this)">ๅ ้ค</button>');
saveSuccess();
});
}
}
var cancelPush = function(element) {
var $push = $(element).parent().parent();
$push.remove();
}
var createPush = function() {
var html = '<tr> <td><input type="text" class="form-control"></td> <td><input type="text" class="form-control"></td> <td><button type="button" class="btn btn-info " onclick="savePush(this)">ไฟๅญ</button><button type="button" class="btn btn-default " onclick="cancelPush(this)">ๅๆถ</button></td> </tr>';
$('#push').append(html);
}
<file_sep>__author__ = 'Vijay'
import requests
import config
import teambition
import talk
import pushbullet
import time
import ast
import html2text
def h2t(html):
h = html2text.HTML2Text()
h.ignore_images = True
h.body_width = 0
return h.handle(html)
print('run at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
taskServer = teambition.Task(_tasklistId = config.teambition['_tasklistId'], token=config.teambition['token'])
talkServer = talk.Talk(config.talk['webhook'])
def checkTask(url):
return config.client['zhihu']['tasks'].find_one({'url': url})
def warn(question):
url = question['url']
if not checkTask(url=url):
question['result']['description'] = h2t(question['result']['description'])
data = {
'content': question['result']['title'],
'note': question['result']['description'],
'_executorId': config.teambition['_executorId']
}
if question['result']['follows'] >= 100:
data['priority'] = 2
elif question['result']['follows'] >= 50:
data['priority'] = 1
else:
data['priority'] = 0
res = taskServer.create(data=data)
data['_id'] = res['_id']
data['url'] = url
data['createTime'] = time.time()
data['follows'] = question['result']['follows']
config.client['zhihu']['tasks'].insert(data)
talkServer.push(title=data['content'], text=data['note'], redirectUrl=data['url'])
pushs = config.pushbullet['pushs']
for push in pushs:
token = push['push_token']
pb = pushbullet.Pushbullet(token)
pb.push_note(title=data['content'], body=data['note'])
time_node = time.time() - 24 * 60 * 60
questions = config.client['resultdb']['zhihu'].find({'updatetime': { '$gt': time_node}})
for question in questions:
question['result'] = ast.literal_eval(question['result'])
if question['result']['follows'] > 50:
warn(question)
|
f589ddb2271598a533437cf2b55e9a39028d2af0
|
[
"JavaScript",
"Python"
] | 10 |
Python
|
zhangweijie-cn/zhihu-warning
|
7cdbd8eca652d493996c50d96763299d6af74be1
|
9db932f7d4c5ca914384e75c3cedb23578e2d888
|
refs/heads/master
|
<repo_name>nakozak/Microsoft_Prep<file_sep>/jsSandbox/jsSandbox/bin/Debug/AppX/js/main.js
๏ปฟ// For an introduction to the Blank template, see the following documentation:
// https://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var isFirstActivation = true;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.voiceCommand) {
// TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands,
// this is a good place to decide whether to populate an input field or choose a different initial view.
}
else if (args.detail.kind === activation.ActivationKind.launch) {
// A Launch activation happens when the user launches your app via the tile
// or invokes a toast notification by clicking or tapping on the body.
if (args.detail.arguments) {
// TODO: If the app supports toasts, use this value from the toast payload to determine where in the app
// to take the user in response to them invoking a toast notification.
}
else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
// TODO: This application had been suspended and was then terminated to reclaim memory.
// To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
// Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period.
}
}
if (!args.detail.prelaunchActivated) {
// TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization.
// In that case it would be suspended shortly thereafter.
// Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch
// should be done here (to avoid doing them in the prelaunch case).
// Alternatively, this work can be done in a resume or visibilitychanged handler.
}
if (isFirstActivation) {
// TODO: The app was activated and had not been running. Do general startup initialization here.
document.addEventListener("visibilitychange", onVisibilityChanged);
args.setPromise(WinJS.UI.processAll());
}
isFirstActivation = false;
};
function onVisibilityChanged(args) {
if (!document.hidden) {
// TODO: The app just became visible. This may be a good time to refresh the view.
}
}
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state that needs to persist across suspensions here.
// You might use the WinJS.Application.sessionState object, which is automatically saved and restored across suspension.
// If you need to complete an asynchronous operation before your application is suspended, call args.setPromise().
};
var b = false;
app.onready = function (e) {
// Arrays
//var fruit = ["apple", "orange", "banana","strawberry","cherry"];
//var vegetables = ["carrot", "broccoli","cauliflower"];
//fruit.push("pear");
//fruit.pop();
//fruit = fruit.concat(vegetables); // add fruit array to vegetable array ; immutable example since the function returns its value
//fruit = fruit.slice(0, 1); // Take a slice out of the array and returns it
//fruit.splice(1, 2,"melon","grape"); // changes the array contents ; mutable example
//select in c# is equivalent to map in js
//fruit = fruit.map(function (i) {
// return { fruitName: i };
//});
//fruit = fruit.filter(function (i) {
// return i[0] === "a";
//});
//log(fruit.sort());
//log(fruit.every(function (i) {
// //return i[0] === "a"; // false
// return i.length > 0; // true
//}));
//log(fruit.some(function (i) {
// return i[0] === "a"; // true
//}));
//fruit.forEach(function (i) {
//});
// Objects
//Object initializer syntax
//var dog = {
// breed: "<NAME>"
//};
//dog.breed = "<NAME>";
//dog.bark = function (log("woof"););
};
function log(msg) {
console.log(msg);
}
/*Methods*/
//log(f1("one", 2, 0.78, {}, []));
//function f1() {
// //debugger;
//}
//var ops = {
// // Add Method
// add: function addNumbers(n1, n2) {
// return n1 + n2;
// }
//}; // <---- ops ends here
//Example of runnning
//var x = ops.add(3, 5); // x == 8
//var y = ops.addNumbers(3, 5); // not valid!
/* Function Scope */
/************************************************
* Defining what is accessible in code and where
* encapsulation
* *********************************************/
/*Scope Example*/
/*
var x = 2000;
function someFunc() {
y = 12;
return y;
}
var z = x + y; // invalid use of y
var z = x + someFunc(); // z == 2012 */
//Functions in functions
//function outerFunction(n) {
// function innerFunction() {
// return n * n;
// }
// return innerFunction();
//}
//Example of running
// var x = outerFunction(4); // x == 16
// innerfunction cannot be called directly
//Module pattern
//var mod = (function () {
// var m = 2000, c = 0; d = 10; y = 2;
// return {
// getHiddenYear: function () {
// return m + c + d + y;
// }
// };
//}());
//var x = mod.getHiddenYear(); // x == 2012
//function add(n1, n2) {
// return n1 + n2;
//}
//function calc(n1, n2, processForCalc) {
// return processForCalc(n1, n2);
//}
//function executeMath() {
// setOutput(calc(4, 4, add));
//}
//DOM Selection
//ID
//var x = document.getElementById("anyID");
//or
//var x = document.querySelector("#anyID");
//Selectors
//var thing = document.querySelector("#anyID");
//var list = document.querySelectorAll(".item");]
function queryDOM() {
var x = document.getElementById("pic");
}
app.start();
})();
<file_sep>/README.md
# Microsoft_Prep
Cert Prep
|
22a57edccfceb39b7ad31e02bdd7e0e7cd80bdf6
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
nakozak/Microsoft_Prep
|
357cd0a942559a2d109ad4480865813e3899d865
|
55dae4dae5133e05b9786662eea7369ec3ba2cda
|
refs/heads/master
|
<file_sep>function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
var s = 0;
var x = document.getElementsByClassName("slides");
function openmodal() {
document.getElementById("modal").style.display = "block";
}
function closemodal() {
x[s].style.display = "none";
document.getElementById("modal").style.display = "none";
}
function currentslide(n){
document.getElementById("slideNo").innerHTML = n+"/"+x.length;
s = n - 1;
x[s].style.display = "block";
}
function changeslide(n) {
if (s+n >= x.length) {
alert("That's all folks!");
}
else if (s+n < 0) {
}
else{
x[s].style.display = "none";
s = s + n;
document.getElementById("slideNo").innerHTML = (s+1)+"/"+x.length;
x[s].style.display = "block";
}
}
<file_sep>Robotics & Automation Wing (RAW), SFIT
|
60844991e3922888e5cb0a197257d6b655e73255
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
aadityakhare/RAW-website
|
9e119ff5fec5d75a5b80c73cb7dc6731251e5ffe
|
06925f94821654d0e4ce8c8a53560cb0561c1614
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.