Refresh Text within Swift UI after 1st run - xcode

I am racking my brain trying to get this code working, I am just starting out on SwiftUI and haven't found a solution. I have a math equation that adds the variables and accepts the answer input from the user. My issue is once the answer is correct, how can i get the variables numbers1 & numbers2 to refresh and grab new numbers and give another math problem?
import SwiftUI
import Foundation
struct ContentView: View {
#State private var answer = ""
#State private var number1 = ""
#State private var number2 = ""
#State private var messageText = ""
#State private var keyboardHeight: CGFloat = 0.0
var numbers1 : Int = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
var numbers2 : Int = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
var questionNumber = 0
var value = 0.00
var body: some View {
VStack {
ForEach((1...10).reversed(), id: \.self) {_ in
Text(self.number2)
}
Text("\(numbers1)")
.font(.largeTitle)
.padding()
Text("\(numbers2)")
.font(.largeTitle)
.padding()
TextField("answer", text: self.$answer)
.padding(/*#START_MENU_TOKEN#*/.all/*#END_MENU_TOKEN#*/)
.font(/*#START_MENU_TOKEN#*/.largeTitle/*#END_MENU_TOKEN#*/)
//.keyboardType(.numberPad)
Button(action: {
var addition: Int {
let addition = self.numbers1 + self.numbers2
return addition
}
print("submit button pressed")
print(addition)
if (self.answer == String(addition)) {
print("Answer is Correct!")
}
else {
print("Answer is Incorrect")
}
self.answer = ""
}) {
Text("Submit")
.font(.largeTitle)
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(40)
}
// .padding()
.actionSheet(isPresented: /*#START_MENU_TOKEN#*/ /*#PLACEHOLDER=Is Presented#*/.constant(false)/*#END_MENU_TOKEN#*/) {
ActionSheet(title: Text(/*#START_MENU_TOKEN#*/ /*#PLACEHOLDER=Title#*/"Action Sheet"/*#END_MENU_TOKEN#*/))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
```
enter code here

what you can do is this:
declare
#State var numbers1 : Int = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
#State var numbers2 : Int = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
and
if (self.answer == String(addition)) {
print("Answer is Correct!")
self.numbers1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
self.numbers2 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].randomElement()!
}
or some variation of this, like storing the array in a var.

Related

How can I determine if a point is hidden on a 3D Scatterplot (Plotly.js)?

I'm using Plotly.js to draw a 3-D scatter plot . On zoom , I want to check which points are visible . Can this be done on svg level ? or any plotly expert ?
Snippet:
var myPlot = document.getElementById("myDiv");
var trace = {
x: [1, 7, 2, 4,1],
y: [12, 9, 15, 12,2],
z: [1, 2, 4, 8,4],
// x: [1,2],
//y: [12,15],
//z: [1, 4],
mode: 'markers' ,
type: 'scatter3d' ,
marker: {size:5 }
}
var data = [trace];
var layout = {
margin: {
l: 0,
r: 0,
b: 0,
t: 0} ,
//title: {text: 'ReOptim8 Scatter Plot'},
scene: {
yaxis:{title: 'X-axis'},
xaxis:{title: 'y-axis'},
zaxis:{title: 'z-axis'},
camera: {eye: {x:1.25, y:1.25, z:1.25}}
}
};
var config = {
displayModebar : true,
displaylogo: false,
responsive: true
};
Plotly.plot( myPlot, data, layout, config );
Code pen link below :
https://codepen.io/aniwar/pen/wLOzZv

multi-line chart animation code modify google charts

I found the code from here:
On load Google LineChart animation
google.load('visualization', '1', { packages: ['corechart'], callback: function() {
var data = new google.visualization.DataTable();
data.addRows(5);
data.addColumn('string', '');
data.addColumn('number', 'Sales');
data.addRows(5);
data.setValue(0, 0, 'Jan');
data.setValue(1, 0, 'Feb');
data.setValue(2, 0, 'Mar');
data.setValue(3, 0, 'Apr');
data.setValue(4, 0, 'May');
var options = {
title: 'Sales by months for 2013 year', curveType: 'function',
"vAxis": { "minValue": "0", "maxValue": 6 }, "hAxis": { "slantedTextAngle": "45", "slantedText": "true" }, "legend": { "position": "top" }, "pointSize": "5",
animation: { duration: 250 }
};
var chart = new google.visualization.LineChart(document.getElementById('test'));
var index = 0;
var chartData = [ 5, 1, 4, 2, 3 ]
var drawChart = function() {
console.log('drawChart index ' + index);
if (index < chartData.length) {
data.setValue(index, 1, chartData[index++]);
chart.draw(data, options);
}
}
google.visualization.events.addListener(chart, 'animationfinish', drawChart);
chart.draw(data, options);
drawChart();
}});
If I want to create multi-line, how to modify this code? Thanks!
I'm not a javascript programmer and not familiar with OOP
The author is OneMoreVladimir, but I don't have the access to comment under his post.
google.load('visualization', '1', {
packages: ['corechart'],
callback: function() {
var data = new google.visualization.DataTable();
data.addRows(5);
data.addColumn('string', '');
data.addColumn('number', 'Sales');
data.addColumn('number', 'Sales2');
data.addRows(5);
data.setValue(0, 0, 'Jan');
data.setValue(1, 0, 'Feb');
data.setValue(2, 0, 'Mar');
data.setValue(3, 0, 'Apr');
data.setValue(4, 0, 'May');
var options = {
title: 'Sales by months for 2013 year',
curveType: 'function',
"vAxis": {
"minValue": "0",
"maxValue": 8
},
"hAxis": {
"slantedTextAngle": "45",
"slantedText": "true"
},
"legend": {
"position": "top"
},
"pointSize": "5",
animation: {
duration: 600
}
};
var chart = new google.visualization.LineChart(document.getElementById('test'));
var index = 0;
var chartData = [5, 1, 4, 2, 3]
var drawChart = function() {
console.log('drawChart index ' + index);
if (index < chartData.length) {
data.setValue(index, 1, chartData[index++]);
chart.draw(data, options);
}
}
var index1 = 0;
var chartData1 = [1, 3, 4, 6, 5]
var drawChart1 = function() {
console.log('drawChart1 index1 ' + index1);
if (index1 < chartData1.length) {
data.setValue(index1, 2, chartData1[index1++]);
chart.draw(data, options);
}
}
google.visualization.events.addListener(chart, 'animationfinish', drawChart);
google.visualization.events.addListener(chart, 'animationfinish', drawChart1);
chart.draw(data, options);
drawChart();
drawChart1();
}
});
I figure out! Here is the code.
But another question, the code pass the http://jsfiddle.net and run very well, but when I copy paste it into the HTML why it doesn't work? Did I miss something?

SVG animation / TweenMax / Reverse animation

Here is the animation which is running with yoyo = true meaning the animation goes one way and then do the "reverse" animation.
I would like to be able to play the animation in mode reverse without having the yoyo mode.
In other words, I would like to have the second part (the reverse one)
https://codepen.io/chrisgannon/pen/greVXG
var xmlns = "http://www.w3.org/2000/svg",
xlinkns = "http://www.w3.org/1999/xlink",
select = function(s) {
return document.querySelector(s);
},
selectAll = function(s) {
return document.querySelectorAll(s);
}
TweenMax.set('svg', {
visibility: 'visible',
transformOrigin:'50% 50%',
scale:1
})
var mainTl = new TimelineMax({repeat:-1, yoyo:true, repeatDelay:2});
var skySunTl = new TimelineMax({paused:true});
skySunTl.fromTo('#lower', 10, {
stopColor:'#020111'
},{
stopColor:'#CD82A0',
ease:Linear.easeNone
})
.fromTo('#upper', 10, {
stopColor:'#1F1F2B'
},{
stopColor:'#4B4A6A',
ease:Linear.easeNone
},'-=10')
.to('#lower', 10, {
stopColor:'#95DFFF',
ease:Linear.easeNone
})
.to('#upper', 10, {
stopColor:'#94DFFF',
ease:Linear.easeNone
},'-=10')
.to('#lower', 10, {
stopColor:'#f9b681',
ease:Linear.easeNone
})
.to('#upper', 10, {
stopColor:'#eb4a78',
ease:Linear.easeNone
},'-=10')
.fromTo('#sun', 10, {
fill:'#B30200'
},
{
fill:'#EC8323',
ease:Linear.easeNone
},'-=30')
.to('#sun', 10, {
fill:'#FFF',
ease:Linear.easeNone
},'-=20')
.to('#sun', 10, {
fill:'#fefdeb',
ease:Linear.easeNone
},'-=10')
.fromTo('#sun', 15, {
attr:{
cy:410,
r:105
}},{
attr:{
cy:0,
r:90
},
ease:Power1.easeInOut
},'-=30')
.to('#sun', 14, {
attr:{
cy:300,
r:105
},
ease:Sine.easeInOut
},'-=13')
.from('#mainCircleMask circle', 30, {
attr:{
r:500
},
ease:Power1.easeInOut
},'-=30')
var waterTl = new TimelineMax({paused:true});
waterTl.fromTo('#waterCircle', 30, {
fill:'#020111'
},{
fill:'#5DB3C6',
ease:Linear.easeNone
})
.fromTo('#waterRipple', 30, {
fill:'#020111'
},{
fill:'#A5DCE4',
ease:Linear.easeNone
},'-=30')
.fromTo('body', 30, {
backgroundColor:'#020111'
},{
backgroundColor:'#FFF',
ease:Linear.easeNone
},'-=30')
var skySunTween = TweenMax.to(skySunTl, 10, {
time:skySunTl.duration(),
ease:Power2.easeInOut
})
var waterTween= TweenMax.to(waterTl, 10, {
time:waterTl.duration(),
ease:Power2.easeInOut
})
mainTl.add(skySunTween, 0);
mainTl.add(waterTween, 0);
mainTl.timeScale(4);
mainTl.play(0)
//ScrubGSAPTimeline(mainTl)
//tl.timeScale(30)
Thank you
This should do the trick, using a mix of reversed:true in your TimelineMax() constructor. And also using progress(0.5) when you chain your timelines/tweens:
https://codepen.io/jonathan/pen/dNxgVK
I changed this:
var mainTl = new TimelineMax({
repeat:1,
yoyo:true,
repeatDelay:2
});
To this using reversed:true
var mainTl = new TimelineMax({
reversed:true
});
reversed is found in the TimelineMax Docs:
reversed ( value:Boolean ) : *
Gets or sets the animation's reversed state which indicates whether or
not the animation should be played backwards.
And i changed this
mainTl.add(skySunTween, 0);
mainTl.add(waterTween, 0);
mainTl.timeScale(4);
mainTl.play();
To this and added progress(0.5), which represents half way through the timeline
mainTl.add(skySunTween, 0);
mainTl.add(waterTween, 0);
mainTl.timeScale(4);
mainTL.progress(0.5); // added GSAP progress() method
mainTl.play();
.progress( value:Number, suppressEvents:Boolean ) : *
[override] Gets or sets the timeline's progress which is a value
between 0 and 1 indicating the position of the virtual playhead
(excluding repeats) where 0 is at the beginning, 0.5 is halfway
complete, and 1 is complete.
Resources:
progress(): https://greensock.com/docs/#/HTML5/GSAP/TimelineMax/progress/
TimelineMax: https://greensock.com/docs/#/HTML5/GSAP/TimelineMax/

amCharts with intra-day data not showing properly

The problem is what you see in the chart: http://www.fanta-trade.eu/chart.php?tipo=f&code=1450018272
The chart is not showing correctly the data according with the date.
The code probably might be here:
var categoryAxesSettings = new AmCharts.CategoryAxesSettings();
Full code:
AmCharts.ready( function() {
createStockChart();
} );
var chartData = [];
chartData.push({ date: new Date(2015, 11, 15, 13, 59, 0, 0), value: 203.84, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 13, 36, 0, 0), value: 203.86, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 12, 59, 0, 0), value: 203.86, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 12, 37, 0, 0), value: 203.81, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 12, 11, 0, 0), value: 203.8, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 11, 34, 0, 0), value: 203.79, volume: 1 });
chartData.push({ date: new Date(2015, 11, 15, 4, 47, 0, 0), value: 203.68, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 21, 41, 0, 0), value: 202.64, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 18, 16, 0, 0), value: 199.73, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 17, 52, 0, 0), value: 197.94, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 17, 22, 0, 0), value: 199.83, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 13, 11, 0, 0), value: 198.56, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 8, 54, 0, 0), value: 198.56, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 8, 0, 0, 0), value: 198.56, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 2, 11, 0, 0), value: 198.56, volume: 1 });
chartData.push({ date: new Date(2015, 11, 14, 1, 13, 0, 0), value: 198.56, volume: 1 });
var chart;
function createStockChart() {
chart = new AmCharts.AmStockChart();
// DATASETS //////////////////////////////////////////
var dataSet = new AmCharts.DataSet();
dataSet.color = "#000000";
dataSet.fieldMappings = [{
fromField: "value",
toField: "value"
}, {
fromField: "volume",
toField: "volume"
}];
dataSet.dataProvider = chartData;
dataSet.categoryField = "date";
// set data sets to the chart
chart.dataSets = [dataSet];
// PANELS ///////////////////////////////////////////
// first stock panel
var stockPanel1 = new AmCharts.StockPanel();
stockPanel1.showCategoryAxis = false;
stockPanel1.title = "Price";
stockPanel1.percentHeight = 70;
// graph of first stock panel
var graph1 = new AmCharts.StockGraph();
graph1.valueField = "value";
graph1.type = "smoothedLine";
graph1.bullet = "round";
graph1.lineThickness = 2;
graph1.bulletBorderColor = "#FFFFFF";
graph1.bulletBorderAlpha = 1;
graph1.bulletBorderThickness = 3;
stockPanel1.addStockGraph(graph1);
// create stock legend
var stockLegend1 = new AmCharts.StockLegend();
stockLegend1.valueTextRegular = " ";
stockLegend1.markerType = "none";
stockPanel1.stockLegend = stockLegend1;
// second stock panel
var stockPanel2 = new AmCharts.StockPanel();
stockPanel2.title = "Volume";
stockPanel2.percentHeight = 30;
var graph2 = new AmCharts.StockGraph();
graph2.valueField = "volume";
graph2.type = "column";
graph2.fillAlphas = 1;
stockPanel2.addStockGraph(graph2);
// set panels to the chart
chart.panels = [stockPanel1];
// OTHER SETTINGS ////////////////////////////////////
var scrollbarSettings = new AmCharts.ChartScrollbarSettings();
scrollbarSettings.graph = graph1;
chart.chartScrollbarSettings = scrollbarSettings;
var cursorSettings = new AmCharts.ChartCursorSettings();
cursorSettings.valueBalloonsEnabled = true;
cursorSettings.graphBulletSize = 1;
chart.chartCursorSettings = cursorSettings;
var categoryAxesSettings = new AmCharts.CategoryAxesSettings();
categoryAxesSettings.minPeriod="mm";
chart.categoryAxesSettings = categoryAxesSettings;
// PERIOD SELECTOR ///////////////////////////////////
var periodSelector = new AmCharts.PeriodSelector();
periodSelector.periods = [{
period: "DD",
count: 10,
label: "10 days"
}, {
period: "MM",
count: 1,
selected: true,
label: "1 month"
}, {
period: "YYYY",
count: 1,
label: "1 year"
}, {
period: "YTD",
label: "YTD"
}, {
period: "MAX",
label: "MAX"
}];
chart.periodSelector = periodSelector;
var panelsSettings = new AmCharts.PanelsSettings();
panelsSettings.marginRight = 16;
panelsSettings.marginLeft = 16;
panelsSettings.usePrefixes = true;
chart.panelsSettings = panelsSettings;
dataSet.stockEvents = [];
chart.write('chartdiv');
}
The issue is very simple, actually.
Data in amCharts must come in ascending order. While you have it in descending, which creates all kinds of anomalies.
To fix simply add your data points in ascending order. For example use unshift() instead of push().
Or simply reverse() the result array:
chartData.reverse();
Here's the same chart with reversed data:
http://codepen.io/team/amcharts/pen/5d2891ce1710ce06dae34bebc2db8644

How to render jquery jqplot 3 year stacked line graph with a date axis render

I would like to be able to use jqplot to stack 3 different years of data on top of each other to compare the data accordingly. The only way to do it that I have found is to "hack" the dates of each result series to use the same year as a base date.
This is not exactly ideal and was wondering if anyone had found a better fix?
I am using C# and javascript to do this for 2 years of data.
In C#
I perform 2 queries to the database getting year1 data and year2 data.
I loop through year2 data setting the year to be the same as year1
I push this data to the client in two arrays. If there is no data for one of the years I set the array to null. Sending an empty array makes jqplot display an empty graph.
I push the two labels for example 2011 and 2010.
On the client
I create an array of data.
If the year array is not null I push it to the array.
I display the charts. I thought I might need to create an array for holding the labels, but jqplot doesn't display the labels when there is no corresponding chart. If you are doing it for three years you will need to have a seperate array for labels.
Here is my C# code:
protected void btnShowGraph_Click(object sender, EventArgs e)
{
SomeRatingSummary SearchCriteria = GetSearchCriteria();
var year1Results = SearchCriteria.ExecuteFind();
string year1Label = SearchCriteria.YearTypeCode;
StringBuilder year1 = getJavaScriptArrayFromRatingsData(year1Results);
int year1int = int.Parse(year1Label);
SearchCriteria.YearTypeCode = (year1int - 1).ToString();
var year2Results = SearchCriteria.ExecuteFind();
year2Results.ToList().ForEach(a => a.FirstSeasonRating = DateTime.Parse(a.FirstSeasonRating).AddYears(1).ToShortDateString());
var year2Label = SearchCriteria.YearTypeCode;
StringBuilder year2 = getJavaScriptArrayFromRatingsData(year2Results);
string script = " jQuery(document).ready(function () {{drawChart('{0}','{1}',{2},{3});}});";
string filledScript = String.Format(script, year1Label, year2Label, year1, year2);
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "callChart", filledScript, true);
}
private static StringBuilder getJavaScriptArrayFromRatingsData(SubSonicList<SomeRatingSummary> results)
{
var firstYear = results.OrderBy(srs => srs.FirstSeasonRating).GroupBy(a => a.FirstSeasonRating).Select(g => new { value = g.Key, count = g.Count() });
string prefix = "[";
StringBuilder year1 = new StringBuilder(prefix);
firstYear.ToList().ForEach(a => year1.AppendFormat("['{0}', {1}],", a.value, a.count));
if (year1.Length > prefix.Length)
{
year1.Length = year1.Length - 1;
year1.Append("]");
}
else
{
year1.Length = 0;
year1.Append("null");
}
return year1;
}
Here is my JavaScript code:
function drawChart(year1Label, year2Label, year1Data, year2Data) {
//these are two sample charts.
//var line1 = [['2008-09-30 4:00PM', 1], ['2008-8-30 4:00PM', 3], ['2008-11-30 4:00PM', 5], ['2008-12-30 4:00PM', 7], ['2009-01-30 4:00PM', 9]];
//var line2 = [['2008-09-31 4:00PM', 5], ['2008-10-20 4:00PM', 2], ['2008-11-15 4:00PM', 4], ['2008-12-16 4:00PM', 9], ['2009-01-29 4:00PM', 8]];
var chartData = [year1Data];
if (year2Data != null) {
chartData.push(year2Data);
}
var plot1 = jQuery.jqplot('chart1', chartData, {
grid: {
//background:'#f0ffff',
background: '#F0F8FF',
gridLineColor: '#dfdfdf',
borderWidth: 1.5
},
title: 'Ratings by Day',
axes: { xaxis: {
renderer: jQuery.jqplot.DateAxisRenderer,
rendererOptions: { tickRenderer: jQuery.jqplot.CanvasAxisTickRenderer },
tickInterval: '2 month',
tickOptions: { formatString: '%b' }
}
},
legend: { show: true, location: 'e', showSwatch: true },
seriesDefaults: { showMarker: false, lineWidth: 1.5, markerOptions: { style: 'square'} },
series: [{ label: year1Label }, { label: year2Label}]
});
};

Resources