Why does head change in this Linked List? - linked-list

Why does the head change here?
I thought assigning oddPointer to head would allow me to traverse through the list without changing head. This does not seem to be the case. When I log(head) it appears as 1->3->5, why is it not 1->2->3->4->5?
Is there a way to complete this without changing head?
// JavaScript
var oddEvenList = function (head) {
let oddList = new ListNode(-1);
let oddCopy = oddList;
let cnt = 0;
let oddPointer = head;
while (oddPointer) {
cnt++;
if (cnt % 2 !== 0) {
oddList.next = oddPointer; // -1,1,3,5
oddList = oddList.next;
}
oddPointer = oddPointer.next;
}
console.log(oddList);
console.log(oddCopy);
console.log(head);
console.log(oddPointer);
return -1;
}
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
let a1 = new ListNode(1);
let a2 = new ListNode(2);
let a3 = new ListNode(3);
let a4 = new ListNode(4);
let a5 = new ListNode(5)
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
console.log(oddEvenList(a1));

Related

NEAT - population number varies every generation

I'm trying to implement my own neat implementation and I can't get myself to understand how speciation works
I tried my best to follow the pesudocode I found in this paper (start of page 13)
but I'm think I'm doing it really wrong but I don't understand the right way to do it, here is my code
the sepciate function that splits the population into species:
function speciate(population, species=[]) {
let newSpecies = [...species];
for(const net of population) {
let placed = false;
for(const s of newSpecies) {
for(const member of s) {
if(sh(net, member)) {
s.push(net);
placed = true;
break;
}
}
if(placed) break;
}
if(!placed) {
newSpecies.push([net]);
}
}
return newSpecies;
}
the repopulation function that generates a new population using the number of offsprings:
function repopulate(popCount, species) {
let globalAvg = 0;
species.forEach(s => {
globalAvg += s.reduce((P, net) => P + net.genome.fitness, 0) / s.length;
});
let newPop = [];
for(const s of species) {
let N = popCount;
let sAvg = s.reduce((P, net) => P + net.genome.fitness, 0) / s.length;
let offspringCount = (sAvg / globalAvg) * N;
for(let i = 0; i < offspringCount; i++) {
let parent1 = wheelSelect(s);
let parent2 = wheelSelect(s);
let child = parent1.genome.crossover(parent2.genome);
child.mutateAddNeuron(0.01);
child.mutateAddConnection(0.01);
child.mutateWeight(0.01);
child.mutateEnabledToggle(0.01);
child.layerNeurons();
let net = new NeuralNetwork();
net.wireUsingGenome(child);
newPop.push(net);
}
}
return newPop;
}
the problem I'm facing is that the population number seems to change every new generation sometimes it goes up and sometimes down, so I'm gussing I'm calculating the offspring count wrong or my speciation isn't working correctly but I can't figure it out
any help is appreciated!

Highcharts Showing Uncaught TypeError: Cannot read properties of undefined (reading 'chart')

I've had this HighCharts spider chart working fine for a while now, but we upgraded to the latest HighCharts code and I noticed that the mouseovers are no longer working. My PHP code looks like this:
// Create a new Highchart
$chart = new Highchart();
$chart->includeExtraScripts();
$chart->chart->renderTo = "control_maturity_spider_chart";
$chart->chart->polar = true;
$chart->chart->type = "line";
$chart->chart->width = 1000;
$chart->chart->height = 1000;
$chart->title->text = "Current vs Desired Maturity by Control Family";
$chart->title->x = -80;
$chart->pane->size = "80%";
$chart->xAxis->categories = $categories;
$chart->xAxis->tickmarkPlacement = "on";
$chart->xAxis->lineWidth = 0;
$chart->yAxis->gridLineInterpolation = "polygon";
$chart->yAxis->lineWidth = 0;
$chart->yAxis->min = 0;
$chart->yAxis->max = 5;
$chart->yAxis->tickInterval = 1;
$chart->tooltip->shared = true;
$chart->tooltip->pointFormat = '<span style="color:{series.color}">{series.name}: <b>{point.y}</b><br/>';
$chart->legend->align = "center";
$chart->legend->verticalAlign = "top";
$chart->legend->layout = "vertical";
// Draw the Current Maturity series
$chart->series[0]->name = $escaper->escapeHtml($lang['CurrentControlMaturity']);
$chart->series[0]->data = empty($categories_current_maturity_average) ? [] : $categories_current_maturity_average;
$chart->series[0]->pointPlacement = "on";
// Draw the Desired Maturity series
$chart->series[1]->name = $escaper->escapeHtml($lang['DesiredControlMaturity']);
$chart->series[1]->data = empty($categories_desired_maturity_average) ? [] : $categories_desired_maturity_average;
$chart->series[1]->pointPlacement = "on";
$chart->credits->enabled = false;
echo "<figure class=\"highcharts-figure\">\n";
echo " <div id=\"control_maturity_spider_chart\"></div>\n";
echo "</figure>\n";
echo "<script type=\"text/javascript\">";
echo $chart->render("control_maturity_spider_chart");
echo "</script>\n";
The actual chart renders just fine, but if you mouse over it, you just get this message in the javascript console over and over again:
HighCharts Error Message
If we comment out these two lines of code, the mouseover works:
$chart->tooltip->shared = true;
$chart->tooltip->pointFormat = '<span style="color:{series.color}">{series.name}: <b>{point.y}</b><br/>';
Any thoughts on what we are doing wrong here, or what changed, would be greatly appreciated. Thank you.
this is the bug which you can track here: https://github.com/highcharts/highcharts/issues/17472
As a temporary workaround, add the following wrap function to your code:
(function(H) {
const isObject = H.isObject;
H.Pointer.prototype.findNearestKDPoint = function(series, shared, e) {
var chart = this.chart;
var hoverPoint = chart.hoverPoint;
var tooltip = chart.tooltip;
if (hoverPoint &&
tooltip &&
tooltip.isStickyOnContact()) {
return hoverPoint;
}
var closest;
/** #private */
function sort(p1, p2) {
var isCloserX = p1.distX - p2.distX,
isCloser = p1.dist - p2.dist,
isAbove = ((p2.series.group && p2.series.group.zIndex) -
(p1.series.group && p1.series.group.zIndex));
var result;
// We have two points which are not in the same place on xAxis
// and shared tooltip:
if (isCloserX !== 0 && shared) { // #5721
result = isCloserX;
// Points are not exactly in the same place on x/yAxis:
} else if (isCloser !== 0) {
result = isCloser;
// The same xAxis and yAxis position, sort by z-index:
} else if (isAbove !== 0) {
result = isAbove;
// The same zIndex, sort by array index:
} else {
result =
p1.series.index > p2.series.index ?
-1 :
1;
}
return result;
}
series.forEach(function(s) {
var noSharedTooltip = s.noSharedTooltip && shared,
compareX = (!noSharedTooltip &&
s.options.findNearestPointBy.indexOf('y') < 0),
point = s.searchPoint.call(s.polar, e, compareX);
if ( // Check that we actually found a point on the series.
isObject(point, true) && point.series &&
// Use the new point if it is closer.
(!isObject(closest, true) ||
(sort(closest, point) > 0))) {
closest = point;
}
});
return closest;
};
}(Highcharts))
Demo:
https://jsfiddle.net/BlackLabel/8b2mhqf0/

How to update List View Model in Asp.net MVC

Hi I am facing issue in update records in MVC. I have created one list view model and in that i want to update some of the records but i am getting error. Please help me.
Here is my code:
public async Task<bool> AddPurchase(PurchaseOrderViewModel objModel, List<TableViewModel> tableListDto)
{
using (var txn = context.Database.BeginTransaction())
{
bool success = true;
try
{
PurchaseOrder purchase1 = new PurchaseOrder();
purchase1.LoginID = objModel.LoginID;
purchase1.SupplierID = objModel.SupplierID;
purchase1.SupplierName = objModel.SupplierName;
purchase1.LocationID = objModel.LocationID;
purchase1.Notes = objModel.Notes;
purchase1.Currency = objModel.Currency;
purchase1.TotalQuantity = objModel.TotalQuantity;
purchase1.TotalAmount = objModel.TotalAmount;
purchase1.TotalVolume = objModel.TotalVolume;
purchase1.TotalWeight = objModel.TotalWeight;
purchase1.TotalLandedCost = Convert.ToDecimal(objModel.TotalCost);
purchase1.TotalOtherCost = objModel.TotalOtherCost;
purchase1.Date_Of_Purchase = objModel.Date_Of_Purchase;
purchase1.Due_Date = objModel.Due_Date;
purchase1.Date_Arrived = objModel.Date_Arrived;
purchase1.Date_Departed = objModel.Date_Departed;
purchase1.CreatedBy = objModel.LoginID;
purchase1.CreatedOn = objModel.CreatedOn;
purchase1.UpdatedBy = objModel.LoginID;
purchase1.UpdatedOn = objModel.UpdatedOn;
purchase1.Status = StatusConstant.Active;
context.PurchaseOrders.Add(purchase1);
await context.SaveChangesAsync();
success = true;
int latest = purchase1.PurchaseID;
PO_Landed_Cost cost = new PO_Landed_Cost();
cost.LoginID = objModel.LoginID;
cost.PurchaseID = latest;
cost.Packaging_Costs = objModel.Packaging_Cost;
cost.Packaging_Costs_Date_Paid = objModel.Packaging_Costs_Date_Paid;
cost.Inspection_Costs = objModel.Inspection_Cost;
cost.Inspection_Costs_Date_Paid = objModel.Inspection_Costs_Date_Paid;
cost.Freight_And_Duty_Tax = objModel.Freight_Cost;
cost.Freight_And_Duty_Tax_Date_Paid = objModel.Freight_And_Duty_Tax_Date_Paid;
cost.Other_Costs = objModel.Other_Cost;
cost.Total_Landed_Cost = objModel.TotalOtherCost;
context.PO_Landed_Costs.Add(cost);
context.SaveChanges();
OrderDetail order = new OrderDetail();
PO_Landed_Cost_Spread spread1 = new PO_Landed_Cost_Spread();
List<DataDisplayViewModel> data = new List<DataDisplayViewModel>();
if (tableListDto != null)
{
foreach (var item in tableListDto)
{
//First we take all the basic things
var a = Convert.ToDecimal(item.Qty); //Quantity
var b = Convert.ToDecimal(purchase1.TotalQuantity); //Total Quantity
var e = Convert.ToDecimal(objModel.TotalOtherCost); //TotalOtherCost
var g = Convert.ToDecimal(item.Price); //Price
var j = Convert.ToDecimal(item.Volume); //Volume
var l = Convert.ToDecimal(item.Weight); //Weight
var c = Math.Round(Convert.ToDecimal((a / b) * 100), 2); //Total Percent(Quantity)
var f = Math.Round(Convert.ToDecimal(((c * e) / a) / 100), 2); // Quantity Unit Price(Indirect Cost)
var h = Math.Round(Convert.ToDecimal(f + g), 2); //Landed Cost Unit Price (Quantity)
var i = Math.Round(Convert.ToDecimal(h * a), 2); //New Total (Quantity)
var k = Math.Round(Convert.ToDecimal(a * j), 2); //Total Volume
var m = Math.Round(Convert.ToDecimal(a * l), 2); //Total Weight
DataDisplayViewModel datalist = new DataDisplayViewModel();
datalist.LoginID = objModel.LoginID;
datalist.PurchaseID = latest;
datalist.Stock_ID = item.Pid;
datalist.Stock_Name = item.ProductName;
datalist.Quantity = Convert.ToInt32(item.Qty);
datalist.Price = Convert.ToDecimal(item.Price);
datalist.Amount = Convert.ToDecimal(item.Amount);
datalist.Volume = Convert.ToInt32(item.Volume);
datalist.Total_Volume = Convert.ToInt32(k);
datalist.Weight = Convert.ToInt32(item.Weight);
datalist.Total_Weight = Convert.ToInt32(m);
datalist.Total_Percent = Convert.ToString(c);
datalist.Indirect_Cost_UnitPrice = Convert.ToString(f);
datalist.Landed_Cost_UnitPrice = Convert.ToString(h);
datalist.New_Amount = i;
data.Add(datalist);
}
var totalweight = data.Where(x => x.PurchaseID == latest).Select(x => x.Total_Weight).Sum();
var totalvolume = data.Where(x => x.PurchaseID == latest).Select(x => x.Total_Volume).Sum();
foreach (var item in tableListDto)
{
var z = Convert.ToInt32(item.Price);
var a = Convert.ToInt32(item.Qty); //Qty
var l = Convert.ToDecimal(item.Weight); //Weight
var j = Convert.ToDecimal(item.Volume); //Volume
var d = Math.Round(Convert.ToDecimal(((a * l) / totalweight) * 100), 2); //Total Percent Of Weight
var e = Convert.ToInt32(objModel.TotalOtherCost); //Total Other Cost
var f = Math.Round(Convert.ToDecimal(((d * e) / a) / 100), 2);
var h = Convert.ToDecimal(a + f); // Landed Cost Unit Price Of Weight
var i = Convert.ToString(h * a); // New Total Of Weight
var m = (a * j / totalvolume) * 100; //Total Percent Of Volume
var o = Math.Round(Convert.ToDecimal(((m * e) / a) / 100), 2); //Unit Price Of Volume
var q = Math.Round(Convert.ToDecimal(z + o), 2); // Landed Cost Unit Price Of Volume
var r = Convert.ToInt32(q * a); //New Total Of Volume
data.Where(x => x.PurchaseID == latest).FirstOrDefault();
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Indirect_Cost_WeightUnitPrice = Convert.ToString(f);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Landed_Cost_WeightUnitPrice = Convert.ToString(h);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().New_WeightAmount = Convert.ToDecimal(i);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Total_Percent_Volume = Convert.ToString(m);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Indirect_Cost_VolumeUnitPrice = Convert.ToString(o);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Landed_Cost_VolumeUnitPrice = Convert.ToString(q);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().New_VolumeAmount = Convert.ToDecimal(r);
context.Entry(data).State = EntityState.Added;
context.SaveChanges();
}
foreach (var item in data)
{
order.LoginID = objModel.LoginID;
order.PurchaseID = item.PurchaseID;
order.Stock_ID = item.Stock_ID;
order.Quantity = item.Quantity;
order.Price = item.Price;
order.Amount = item.Amount;
order.CreatedBy = objModel.LoginID;
order.CreatedOn = objModel.CreatedOn;
order.UpdatedBy = objModel.LoginID;
order.UpdatedOn = objModel.UpdatedOn;
order.Status = StatusConstant.Active;
order.Stock_Name = item.Stock_Name;
order.Volume = item.Volume;
order.Total_Volume = item.Total_Volume;
order.Weight = item.Weight;
order.Total_Weight = item.Total_Weight;
context.OrderDetails.Add(order);
context.SaveChanges();
spread1.PurchaseID = item.PurchaseID;
spread1.OrderID = order.OrderID;
spread1.LoginID = item.LoginID;
spread1.Total_Percent = item.Total_Percent;
spread1.Indirect_Cost_UnitPrice = item.Indirect_Cost_UnitPrice;
spread1.Landed_Cost_UnitPrice = item.Landed_Cost_UnitPrice;
spread1.New_Amount = item.New_Amount;
spread1.Total_Percent_Volume = item.Total_Percent_Volume;
spread1.Indirect_Cost_VolumeUnitPrice = item.Indirect_Cost_VolumeUnitPrice;
spread1.Landed_Cost_VolumeUnitPrice = item.Landed_Cost_VolumeUnitPrice;
spread1.New_VolumeAmount = item.New_VolumeAmount;
spread1.Total_Percent_Weight = item.Total_Percent_Weight;
spread1.Indirect_Cost_WeightUnitPrice = item.Indirect_Cost_WeightUnitPrice;
spread1.Landed_Cost_WeightUnitPrice = item.Landed_Cost_WeightUnitPrice;
spread1.New_WeightAmount = item.New_WeightAmount;
context.PO_Landed_Cost_Spreads.Add(spread1);
context.SaveChanges();
}
}
else
{
order.LoginID = objModel.LoginID;
order.PurchaseID = latest;
order.CreatedBy = objModel.LoginID;
order.CreatedOn = objModel.CreatedOn;
order.UpdatedBy = objModel.LoginID;
order.UpdatedOn = objModel.UpdatedOn;
order.Status = StatusConstant.Active;
context.OrderDetails.Add(order);
context.SaveChanges();
PO_Landed_Cost_Spread spread = new PO_Landed_Cost_Spread();
spread.LoginID = objModel.LoginID;
spread.PurchaseID = latest;
spread.OrderID = order.OrderID;
context.PO_Landed_Cost_Spreads.Add(spread);
context.SaveChanges();
}
txn.Commit();
}
catch (Exception ex)
{
txn.Dispose();
success = false;
}
return success;
};
}
In this code i want to update records when first i need to find some values and then i need to update in the list view model and then i need to update in the table. But i am unable to do that. Please help me in this.

Google Sheets script hangs on getDataRange or getRange

I have a google spreadsheet that allows me to keep track of costs and item amounts. I wrote a script to update these values; however, today it just hangs on getRange or getDataRange, even while debugging. This was working fine yesterday.
<code>function onOpen() {
var menuEntries = [{name: "Update P0", functionName: "UpdateP0"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu("PI Utils", menuEntries);
}
function showMsg(data, title, timeout) {
if (typeof title == 'undefined') title = "";
if (typeof timeout == 'undefined') timeout = 5;
SpreadsheetApp.getActiveSpreadsheet().toast(data, title, timeout);
}
function UpdateP0() {
showMsg("Updating...", "", -1);
var piSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('PI (Set1)');
piSheet.activate();
//SpreadsheetApp.flush();
var numPlanets = 5;
try {
var dRange = piSheet.getRange('A1:F55'); // will not execute pass this line
} catch (e) {
throw (e);
return;
}
for (var p = 1, prGroup = 1; p <= numPlanets; p++, prGroup += 11) {
var cell1, cell2, v1, v2;
// update extraction amounts
for (var r = 0; r < 3; r++) {
cell1 = dRange.getCell(prGroup + 2 + r, 3);
cell2 = dRange.getCell(prGroup + 2 + r, 4);
v1 = cell1.getValue().toString();
v2 = cell2.getValue().toString();
v1 = (v1.length == 0) ? parseFloat(0.0) : parseFloat(v1);
v2 = (v2.length == 0) ? parseFloat(0.0) : parseFloat(v2);
v2 += v1;
cell1.setValue(0);
cell2.setValue(v2);
}
// update production costs
for (var c = 2; c <= 5; c++) {
cell1 = dRange.getCell(prGroup + 9, c);
cell2 = dRange.getCell(prGroup + 8, c);
v1 = cell1.getValue().toString();
v2 = cell2.getValue().toString();
v1 = (v1.length == 0) ? parseFloat(0.0) : parseFloat(v1);
v2 = (v2.length == 0) ? parseFloat(0.0) : parseFloat(v2);
v2 += v1;
cell1.setValue(0);
cell2.setValue(v2);
}
}
SpreadsheetApp.flush();
showMsg("Completed.", "", 5);
}</code>
What I did to fix this issue (or maybe it's a coincidence) is to create a new sheet, with an adjusted name, and then cut & paste everything from the old sheet to the new one, and then finally delete the old sheet. Running the function worked on the new sheet.

Autocomplete on phone - AS3

I've made an autocomplete that work very well in the swf file.
very simple, when the user write the first letter, a suggestion is made with words.
I've published my project for IOS.
When I'm trying it on the Iphone, nothing is suggested when I'm typing the first letter.
I have to write the first letter and then clicked on "enter" in order to display the suggestions...
I don't want the users to "validate" in order to have the suggestion but simply by typing a letter.
Do you know what could be the problem ? Anyone can help me ?
Weirdly, I've tried on an Android device, and it's working perfectly well ! (like my swf).
Here is my code :
urlLoader.load(new URLRequest("test.txt"));
urlLoader.addEventListener(Event.COMPLETE, loadComplete);
inputField.addEventListener(KeyboardEvent.KEY_UP, suggest);
function loadComplete(e:Event):void
{
suggestions = e.target.data.split(",");
}
function suggest(e:KeyboardEvent):void
{
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
for (var j:int = 0; j < suggestions.length; j++)
{
if (suggestions[j].indexOf(inputField.text.toLowerCase()) == 0)
{
var term:TextField = new TextField();
term.width = 300;
term.height = 20;
term.x = 70;
term.y = (20 * suggested.length) + 314;
term.border = true;
term.borderColor = 0x353535;
term.background = true;
term.backgroundColor = 0xFF9900;
term.textColor = 0x4C311D;
term.defaultTextFormat = format;
term.addEventListener(MouseEvent.MOUSE_UP, useWord);
term.addEventListener(MouseEvent.MOUSE_OVER, hover);
term.addEventListener(MouseEvent.MOUSE_OUT, out);
term.addEventListener(MouseEvent.CLICK, tellMe);
addChild(term);
textfields.push(term);
suggested.push(suggestions[j]);
term.text = suggestions[j];
}
}
if (inputField.length == 0)
{
suggested = [];
for (var k:int = 0; k < textfields.length; k++)
{
removeChild(textfields[k]);
}
textfields = [];
}
if(e.keyCode == Keyboard.DOWN && currentSelection < textfields.length-1)
{
currentSelection++;
textfields[currentSelection].textColor = 0x4C311D;
}
if(e.keyCode == Keyboard.UP && currentSelection > 0)
{
currentSelection--;
textfields[currentSelection].textColor = 0x4C311D;
}
if(e.keyCode == Keyboard.ENTER)
{
inputField.text = textfields[currentSelection].text;
suggested = [];
for (var l:int = 0; l < textfields.length; l++)
{
removeChild(textfields[l]);
}
textfields = [];
currentSelection = 0;
}
}
function useWord(e:MouseEvent):void
{
inputField.text = e.target.text;
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
}
Thank you
EDIT
Here's my new code with Stagetext
var myTextField:StageText = new StageText();
var stageTextInitOptions:StageTextInitOptions;
var urlLoader:URLLoader = new URLLoader();
var suggestions:Array = new Array();
var suggested:Array = new Array();
var textfields:Array = new Array();
var format:TextFormat = new TextFormat();
var currentSelection:int = -1;
var searchChannel:SoundChannel = new SoundChannel();
myTextField.returnKeyLabel = ReturnKeyLabel.SEARCH;
myTextField.addEventListener(KeyboardEvent.KEY_UP, suggest);
stageTextInitOptions = new StageTextInitOptions(false);
myTextField = new StageText(stageTextInitOptions);
myTextField.softKeyboardType = SoftKeyboardType.DEFAULT;
myTextField.returnKeyLabel = ReturnKeyLabel.DONE;
myTextField.autoCorrect = true;
myTextField.fontSize = 20;
myTextField.color = 0x000000;
myTextField.fontWeight = "bold";
myTextField.stage = this.stage;
myTextField.viewPort = new Rectangle(25, 108, stage.stageWidth-40, 28);
urlLoader.load(new URLRequest("Sports2.txt"));
urlLoader.addEventListener(Event.COMPLETE, loadComplete);
myTextField.addEventListener(KeyboardEvent.KEY_UP, suggest);
KeyboardEvent.KEY_UP, KeyboardEvent.KEY_DOWN, TextEvent.TEXT_INPUT doesn't really works at iOS. KeyboardEvent.KEY_DOWN is dispatching only on some keys. I saw only key "Enter".

Resources