Downcast generic class

Question: I've got a generic class based on some type, and a child class which specifies that type. However, the Swift compiler doesn't seem to be able to downcast the parent class with the correct type to the child class.
I'm surprised because it seems like a legitimate need.
For example
class MyClass<T> {}

class ChildClass: MyClass<Double> {}

func test() {
  let instance = MyClass<Double>()
  let castedInstance: ChildClass = instance as! ChildClass
}

This code throws a runtime error: Could not cast value of type 'MyClass<Swift.Double>' (0x1f3e449f0) to 'ChildClass' (0x1024f58b0).
Is there any way to cast it the right way, or is it forbidden for some reason ? Anything I misunderstood ?
Comment: You can't cast to something that is not true; `instance` is _not_ a ChildClass so the cast fails. Do not lie to the compiler about what something is.
Comment: What is this "from a"? Can you please add an actual use case? I can't tell what you're asking.
Answer: It seems you have a misunderstanding of how inheritance works. You cannot convert the type of an object using type casting, whether that's up- or down casting.
You can only use downcasting when the object you are trying to cast is declared/stored as a more general type (a parent class for instance), but it might hold a more specialised instance (subclass). However, you are declaring a parent instance and then trying to downcast it to a subclass. That can never work, since the instance is of a different type.
Your example works if you declare a variable of the parent class type, but assign a child class instance to it.
func test() {
  let instance: MyClass<Double> = ChildClass()
  let castedInstance: ChildClass = instance as! ChildClass
}

Comment: @BigBro your update to the question doesn't really make sense. Why would you want to create a subclass instance from a parent class instance? Please provide a real use case, since with the current overly simplified example, this seems like an [XY problem](https://xyproblem.info). And probably best to ask a separate question with the real world example, since it seems to be different from the original question, which might still be useful for future readers in its current form.
Comment: I'm sorry I wasn't clear but I found the solution to what I was looking for. I'll remove my edit for future readers and approve your answer. My usage was to convert a `Matrix` to a `Vector`, which is a `Matrix` whenever a dot product created one.
Comment: I was indeed confused with how you can force cast types in `C++` asking the compiler to reinterpret the data in memory. Thanks for making that clear, I've edited my question
Answer: I'd say you misunderstand what casting is. Casting reveals to the compiler what something actually is. It does not change what that thing is.
So you cannot cast instance to ChildClass, for the simple reason that it is not in fact a ChildClass.
Comment: Makes sense :) I've edited my question accordingly

Downcast generic class


MeteorJs doesn't add data to collection - I'm stuck at point 8 of Intermediate Meteor Tutorial

Question: I was studying MeteorJs this days, but stuck at this point: Intermediate Meteor Tutorial #8 - Insert Permissions, Publishing & Meteor Toys.

errorClass {error: 404, reason: "Method '/recipes/insert' not found", details: undefined, message: "Method '/recipes/insert' not found [404]", errorType: "Meteor.Error"…}

I checked all the code. I tried to combine some ideas with "todos" tutorial. I even added insecure and autopublish packages - but error still appears.
How you can see on Screenshot in Mongol-panel there are Recipes collection. But when I type in mongo shell : show collections, it shows only "Users" collection.
I liked beginning of this tutorial and I hope, I can finish it , please help me to fix this error.
Comment: Do you have a method called `/recipes/insert`?
Comment: No, and how can method be called with this name? In this tutorial there is no methods , but i copied it from other , newer tutorial "todos" , and it did't work and i deleted it, and turn all like in current tutorial. In this code there are this for allowing publication :
`Recipes.allow({
    insert: function(userId, doc){
        return !!userId;
    }
})`
Also there are publish and subscribe for recipe .
Comment: Ah, I think `/recipes/insert` is a built-in Meteor method. Are you executing `const recipes = new Mongo.Collection('recipes')` on *both* the client and the server?
Comment: I think no. In this tutorial there are no "imports " like in "todos tutorial" , and I suppose, from those times (in 2015 it was posted), changed structure of project and now this code from video lessons doesn't work in new structure? And I haven't enough knowledge to fix this gap ....
Comment: Create `/lib/recipes.js` and just have the line `const recipes = new Mongo.Collection('recipes')` in it
Comment: it fires an error: Uncaught Error: There is already a collection named "recipes"
I tried to add to /lib/recipes.js  `import { Recipes } from '../client/collections/Recipes.js'; ` but app crashes : `Error: Cannot find module '../client/collections/Recipes.js'`
but I did in /client/collections/Recipes :
`export const Recipes = new Mongo.Collection("recipes");`
Answer: That is one way to do it, the other is
You add
this.Recipes = new Mongo.Collection('Recipes')

to a none client or server file.
This automatically lets you access the Recipes collection to the entire proyect.
Answer: I fixed this issue by moving client/collections/Recipe.js to import/ folder. I've added file /lib/recipes.js with one line of code:
import {Recipes} from '../import/Recipes.js'
And how I see, now all works. Clicking on Submit button adds entry to MongoDB.


How to get singleplayer universe up to speed when quests were advanced via multiplayer?

Question: I can't be the first to be in this situation: I started my single player world and before I made any progress in the quests, I joined a friend's world and completed some of the quests there, unlocking the FTL drive and navigation and Ark stores.
Now, back in my own singleplayer universe, my ship's FTL drive is working and I can view navigation but can't actually go anywhere. I had to reactivate the Ark gateway on my planet in order to get there, but all the stores are boarded up as if I hadn't completed the quests. (The quest log is up to date with what I completed on my multiplayer world: the Floran scanner quest.)
Does anyone know how I can unlock the stores since I can't redo the quests?
Answer: Okay I figured it outvia a community post.
This may be helpful to total beginners. You can enable admin mode by pressing Enter to open the chat window and then typing /admin. Then to set the shops back you use command /setuniverseflag outpost_mission1 (basically this tells the world that you've finished the scanner quest which unlocks the shops). The link has several other admin commands to fix the world up.


Changing out the Range power cord

Question: My Range cord 3 prong is only 14 years old and in excellent condition.
However, we are getting a new range and they insist we get a new (over priced) 3 prong for our new range. I do not like this as I believe it is just another scam to make money. THE CORD WE HAVE IS FINE i DO BELIEVE SOMETHING IS VERY FISHY HERE. House built before 1979 FYI.
Comment: no neutral but with ground". Don't know yet. But please, don't get all upset about the cord. An appliance cord is typically $15 - $40 depending on brand, length, type. I am sure that is a *tiny* fraction of the total cost of the range.
Comment: Welcome to [diy.se]! If you'll spend a moment taking the [tour], you'll note that this is a _Question_ and Answer forum, not a place to post a rant. Please feel free to [edit] your post to actually ask a question and I'm sure you'll get some good answers. As it stands, this isn't a Question, so it will likely get closed.
Comment: The only reason to change the cord is if it is damaged or the new range is higher power rating and the cord is too small.  There is one problem that is you are using an old type NEMA 10(two hots and neutral, no ground) circuit which is unsafe to you.  This is highly recommended to be changed to a four wire circuit with ground.  If your range uses ground and no neutral you are good with three wire.  NEMA 10 plugs have three flat prongs(bad), If using ground two flat prongs and a round one.
Comment: Unfortunately, I got a call (have to do some work sometimes) and didn't finish posting my Answer before the question was closed due to needing more details (which is correct). A 3-prong connection **usually** means "hot/hot/neutral" and no ground. Which is **DANGEROUS**. So before going any farther we need to find out whether the **new** range uses neutral or not. **Make/model # of new range, please.** Then I can provide a complete answer (or find a duplicate for it) which will either be "Take the time now to replace the 3 with 4" or "Hardwire" or "Replace 3 with no ground with instead 3 with
Answer: There's a few reasons appliance stores do this. They don't want to accept liability for the condition of your old cord. Ranges are often twenty years old or older when they are replaced. They don't want to show up and find out that the cord on your range is cracked, or melted, or was poorly connected and burned, or really that there is anything wrong with it. They don't want to show up and find out you don't have a cord. So by default they suggest a new cord.
Is it strictly needed? No. It may be required if you want to use their installation services though, so if you want them to do the install, you're buying a new cord. If you are doing your own installation and the current cord is in good condition, you can reuse it.

Changing out the Range power cord


How to write a Switch statement for unit conversion using Javascript

Question: Switch statement for unit conversion using Javascript.
Comment: unit is undefined set it to 0 or 1 initially
Comment: You need to get the value from the input field first. You also need to attach a listener to something so it runs in response to input, rather than on document load.
Answer: You tried to use "unit" as js variable which is already part of loaded document, need to correct your code as below,

<!DOCTYPE html>

<input id="units" type="number" placeholder="Feet" value="1"/>

Again, need to write separate function to load values from input field to screen. it could be event based like keypressed, mouse or simple button.
Answer: Below are some issues in your code:

unassigned variable valNum
output was given in case 1:
syntax error in switch-case.

function calc() {
  var unit = parseInt(document.getElementById("unit").value, 10) || -1;
  var feet = parseInt(document.getElementById("feet").value, 10) || 0;
  var result = 0;
  switch (unit) {
    case 0:
      result = 'Result is: ' + (feet / 3.2808);
      break;
    case 1:
      result = 'Result is: ' + (feet / 0.0022046);
      break;
    default:
      result = 'Unit ##.##';
      break;
  }
  document.getElementById("demo").innerHTML = result;
}

Unit ##.##

<input placeholder="Unit" oninput='calc()' id='unit' />
<input placeholder="Feet" oninput='calc()' id='feet' />


Javascript Prototype Programming

Question: I'm trying to include some namespace into my Javascript API.
Here's what I have so far:
if (!Sample || Sample == "undefined")
    var Sample = {};

Sample.SomeApi = {};

Sample.SomeApi.prototype = {
    SomeMethod: function() {
        alert('some api');
    }
};

What's going on here?
When I'm calling Sample.SomeApi.SomeMethod(); // it won't work as it will complain:
Uncaught TypeError: Object #<Object> has no method 'SomeMethod'
(anonymous function)Course:43
onclick

Comment: Good point, alternatively, he can do `Sample == undefined` but then again the whole undefined is unnecessary, that's what `!Sample` is testing for anyway.
Comment: Side note: you want `undefined` or `typeof Sample === 'undefined'` not `"undefined"`.
Comment: Well, `Sample == "undefined"` is not going to test if it is undefined, it is going to test whether `Sample` equals the string "undefined."
Answer: I think you meant __proto__ not prototype, like so:
if (!Sample || Sample == "undefined")
    var Sample = {};

Sample.SomeApi = {};

Sample.SomeApi.__proto__ = {
    SomeMethod: function() {
        alert('some api');
    }
};

Sample.SomeApi.SomeMethod();

You can test it out in this jsFiddle: http://jsfiddle.net/luisperezphd/xtyyf/
But why not just this:
if (!Sample || Sample == "undefined")
    var Sample = {};

Sample.SomeApi = {
    SomeMethod: function() {
        alert('some api');
    }
};

Sample.SomeApi.SomeMethod();

It's much cleaner.
And there is the jsFiddle for that: http://jsfiddle.net/luisperezphd/HUuMQ/
Comment: I'm not so sure about that. That would mean that you assign SomeMethod to the prototype of {}?
Comment: Using `__proto__` works because objects do not have a `prototype`, functions do. However `__proto__` is not standard and won't work across browsers, that is what [`getPrototypeOf`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/GetPrototypeOf) is for. But the second method really is much cleaner.
Answer: You have to create a constructor for Sample.SomeApi not assign an empty object:
if(typeof Sample == 'undefined')
    Sample = {};

Sample.SomeApi = function() {
};

Sample.SomeApi.prototype = {
    someMethod : function() {
            alert('some api');
    }
}

new Sample.SomeApi().someMethod();

Comment: how would you make it call it like this: Sample.SomeApi.someMethod(); instead of Sample.SomeApi().someMethod(); ?
Comment: Well you don't need to use the prototype if your API is only a single object. just use `Sample.SomeApi = {
    SomeMethod: function() {
        alert('some api');
    }
);`
Answer: Try this
if(typeof Sample == 'undefined')
        var Sample ={}
    Sample.SomeApi = function(a)
    {
        this.a =a;
    }

Sample.SomeApi.prototype.SomeMethod = function() {
        alert('some api');
    }
    var d = new Sample.SomeApi(1);
    d.SomeMethod();

Hope this helps you
Go through this link here

Javascript Prototype Programming


How do I control the display order of traces in plotly.js?

Question: I have a large number of trace lines being displayed.  50-200 typically.  I am comparing historical data to simulated data.  I want to highlight a single simulated traceline by selection via a different color.  All of this works fine.
However, the trace line being shown is sometimes hidden by the large number of other lines.  Is there a way to force the specified trace to be drawn on top of the others, aside from redrawing the entire plot and adding that line last?  Some sort of z-index equivalent or "bring to front" mechanism?
Comment: Unfortunately not as far as I know, plotly draws SVG images which don't have a z-index (http://stackoverflow.com/questions/482115/with-javascript-can-i-change-the-z-index-layer-of-an-svg-g-element/482147#482147). Your approach of adding the line last seems to best in absence of alternatives.
Comment: Thanks.  Yeah, as of now that seems like the only viable approach.  Good point on the SVG factor.  I might explore a little more in SVG draw order, but I suspect you're right.
Answer: Perhaps this useful to other Plotly users as well. The snippet pushed trace 7 to the foreground using Plotly's react function.

var foreground = 7; //trace which is pushed to the foreground

//generate some random data
var trace1 = {
  x: [1, 2, 3, 4],
  y: [1, 2, 0.5, 1.5],
  type: 'lines',
  name: 'trace 0',
  line: {
width: 2
  }
};

var data = [trace1];
var i = 0;
var j = 0;
for (i = 1; i < 10; i += 1) {
  var trace = {
x: [],
y: [],
type: 'lines',
name: 'trace ' + i,
'line': {
  'width': 2
}
  };
  for (j = 0; j < trace1.x.length; j += 1) {
trace.x.push(trace1.x[j])
trace.y.push(trace1.y[j] + Math.random())
  }
  data.push(trace);
}

var buttonForeground = document.getElementById("foreground");
var buttonReset = document.getElementById("reset");

var div = document.getElementById('myDiv');
Plotly.newPlot(div, data);

buttonReset.disabled = true;
buttonForeground.onclick = function() {
  var temp = data[foreground];
  data[foreground] = data[data.length - 1];
  data[data.length - 1] = temp;
  data[data.length - 1]['line']['width'] = 5;
  Plotly.react(div, data);

  switchButtons();
};

document.getElementById("reset").onclick = function() {
  var temp = data[data.length - 1];
  data[data.length - 1] = data[foreground];
  data[foreground] = temp;
  data[foreground]['line']['width'] = 2;
  Plotly.react(div, data, {});

  switchButtons();
};

function switchButtons() {
  buttonForeground.disabled = !buttonForeground.disabled;
  buttonReset.disabled = !buttonReset.disabled;
}

<button type="button" id='foreground'>Foreground</button>
<button type="button" id='reset'>Reset</button>
Comment: Interesting solution, however this changes the order of plots in the legend.
Comment: @Mark: Thanks for noticing! Plotly's function seem to have gotten an update, I modified the answer to have it working with latest version.
Comment: The script has an error when clicking on Foreground button.
Answer: I had the top trace at the end of the data array, but it was still not appearing at the top.
Turns out, it was of a different type than the rest, and plotly seems to prioritise scattergl over the default type. So when I changed the type of all my objects in data to scattergl finally plotly respected the order in the data array.
Example before:
const data = [];

data.push({
  x: [0, 1, ...],
  y: [43, 100, ...],
  ids: ["first", "second", ...],
  type: "scattergl",
  mode: "markers",
  marker: {opacity: 1, color: "green", size: 8},
  showlegend: false,
  name: "",
});

// Highlight quake
data.push({
  x: [10],
  y: [55],
  ids: ["selected"],
  mode: "markers",
  marker: {opacity: 1, color: "green", size: 8},
  showlegend: false,
  name: "",
});

After fixing:
// Highlight quake
data.push({
  x: [10],
  y: [55],
  ids: ["selected"],
  type: "scattergl", // <---- add this
  mode: "markers",
  marker: {opacity: 1, color: "green", size: 8},
  showlegend: false,
  name: "",
});


Can I add framing to build a room under my basement staircase?

Question: I have space under the basement staircase that I want to make a proper room with door. On one side I have a concrete block wall, so there is no issue there and I can put a door in the front. But on the other side I cannot put drywall because existing studs are not aligned and metal post supporting the beam is outside the stud.
So can I solve this by adding additional studs on either side to the existing studs (sister stud)and the put a drywall on it? Or any other ideas?
Answer: You can frame as you like to provide a surface for drywall. Use pressure-treated lumber when in contact with concrete. It's common practice to do so to surround steel posts, plumbing, etc.
If you have more specific questions, please update your post.
Comment: Citation is probably needed, for the pressure treated part of this answer. Some localities prohibit its use indoors, as well as requiring no more than a simple vapor barrier, at the point of contact. My basement, that was finished with untreated wood in the early 80's, and then subsequently ripped out, 20 years later, only had a painted floor; no signs of rot anywhere, except maybe for a few rusty nails. The permeability of the concrete is the problem, that leads to water related issues; pressure treated wood may be rot resistant to a point, but is by no means water resistant.
Comment: Since there's obviously PT lumber on the bottom plates now, it's a safe bet that this is appropriate in this case. Point taken in general.
Comment: As far as building the room I agree since it is not a load bearing wall.+


Dyed and Sealed concrete - do I wax on a "sacrificial layer" to protect sealant?

Question: Just removed old carpet and had the concrete dyed and sealed in our family room.      Before allowing anyone in there or moving furniture back in, I am vacillating between adding a "sacrificial" layer of wax (though I'd prefer not to glossy up the floors any further) or just plan to seal them again in a year or so if I am noticing scuffing?   I bought Lundmark All Wax (I can return) and would run out to home depot to get a appropriate mop head if needed.
I have read up some on how to clean the floors but also always happy for suggestions.
(I have two small dogs who weigh less than 18 pounds with small regularly maintained claws.)
Comment: What does the person who did the concrete stain work recommend for protecting the newly-stained surface?
Comment: Very minimal commentary from the concrete guys - "not a bad idea" (when asking the same question in this post) and "home depot or ace has wax" (when asking for a wax recommendation for low shine/good for the concrete seal) so I was curious if others had commentary since the contractor was less than inspiring.
Comment: I'm surprised they didn't have recommendations, as I'd think they'd want the job to last and look good for a long time, so you'd recommend them to others.
Answer: There are so-called "low gloss" concrete floor waxes available. The manufacturer of this example product describes is as a "matte finish".
It is recommended to seal the concrete floor to protect it from picking up stains and protecting against scuffing and scratching so you seem to be on the right track.
Comment: Yes, the "acrylic wax" products such as this were what came to mind immediately - they are called wax but are more of a finish that can be easily renewed or removed without taking off the finish below if needed for complete renewal. They are commonly seen in commercial settings. The only one I can think of that actively markets (though I can't say I've seen an ad for it in decades...) to home use is all about its shine, while matte products are commonly available. In either case, not actually slippery wax as one assumes "floor wax" to be if thinking about real wax.
Comment: Maybe talk to a commercial janitorial supply company in your town and see if they have products they'd recommend to protect the floor with a low sheen.


filesystem with invalid superblock checksum error on ubuntu 18.04 boot

Question: I recently installed Ubuntu 18.04LTS with windows 10 and after I boot into Windows, Ubuntu boot failed with fsck.ext4: Superblock checksum does not match superblock while trying to open /dev/sda8 and it dropped to initframe terminal. I tried to repair it with fsck , but it doesn't work. However I can boot into Windows again. How to boot into Ubuntu again?
Answer: I had the same issue. That problem came from Ex2fsd versions below than v0.68 which installed on Windows. Upgrade the Extfsd and run following command on initframe terminal. fsck.ext4 -p -b 884736 -B 4096 /dev/sda8 and reboot. That worked for me.
Comment: Thanks this worked for me and now I could reboot the Ubuntu.


DependencyObject Array C# to VB.NET

Question: I have a DependencyObject in C# that is used in an array.  Example shown below:
private KeywordTag[] tags = new KeywordTag[] {
    new KeywordTag { Tag = "test", IncidenceCount = 2076 },
    new KeywordTag { Tag = "oi", IncidenceCount = 2052 },
    new KeywordTag { Tag = "hmm", IncidenceCount = 1887 },
    new KeywordTag { Tag = "grr", IncidenceCount = 1414 },
    new KeywordTag { Tag = "thanks", IncidenceCount = 1166 }}

How would I convert this code to VB.NET?
Thanks!
Answer: dummy's response was almost right, VB.Net's syntax has a "WITH" after the constructors.
Private tags() As KeywordTag = { _
    New KeywordTag() WITH {.Tag = test", .IncidentCount = 2076}, _
    New KeywordTag() WITH {.Tag = "oi", .IncidentCount = 2052}, _
    New KeywordTag() WITH {.Tag = "hmm", .IncidentCount = 1887}, _
    New KeywordTag() WITH {.Tag = "grr", .IncidentCount = 1414}, _
    New KeywordTag() WITH {.Tag = "thanks", .IncidentCount = 1166} _
    }

Comment: I bet there is not blank before "Tag". But this look better the mine, so i deleted it.
Answer: Something like:
Private tags() As KeywordTag = { New KeywordTag { Tag = "test", IncidenceCount = 2076 }, New KeywordTag { Tag = "oi", IncidenceCount = 2052 }, New KeywordTag { Tag = "hmm", IncidenceCount = 1887 }, New KeywordTag { Tag = "grr", IncidenceCount = 1414 }, New KeywordTag { Tag = "thanks", IncidenceCount = 1166 }}

DependencyObject Array C# to VB.NET


Plone 5 custom content types missing in portal navigation

Question: When adding dexterity content types to my Plone 5.3 instance, they do not show up in the portal navigation.
I tried ttw and with a custom product.
The catalog is up-to-date. I forced rebuilding with no success.
The behaviors added to the type are:
<property name="behaviors">
  <element value="plone.dublincore"/>
  <element value="plone.namefromtitle"/>
  <element value="plone.allowdiscussion"/>
  <element value="plone.excludefromnavigation"/>
  <element value="plone.shortname"/>
  <element value="plone.constraintypes"/>
  <element value="plone.relateditems"/>
  <element value="plone.nextprevioustoggle"/>
 </property>

How can I make the custom types show up in the portal navigation?
Answer: Layer 8 error.
After fiddling around with other settings, I remembered that this is actually an option. Under <PORTAL_URL>/@@navigation-controlpanel, one can select the content types that appear in the portal navigation.


Save a reference to a particular selector

Question: Ok, what I am after is quite simple.
I have click handler for multiple radio group sets. Inside the handler I am passing some parameters to a functions parameters references are relative to the group set but their path are the same. So I basically have:
$(document).ready(function(){
    $("input[name='radioGroup1']").click(function(){
        updateWalletInfo(
            $(this).val(),
            $(this).parent().parent().find(".cSec .f_class a").text(),
            $(this).parent().parent().parent().find(".cSec .flight-time").text(),
            $(this).parent().parent().parent().find(".cSec .city").text(),
        );
    });

    $("input[name='radioGroup2']").click(function(){
        updateWalletInfo(
            $(this).val(),
            $(this).parent().parent().find(".cSec .f_class a").text(),
            $(this).parent().parent().parent().find(".cSec .flight-time").text(),
            $(this).parent().parent().parent().find(".cSec .city").text(),
        );
    });
});

What I want to do is to save reference to particular item under $(document).ready() so if I change the path I wouldn't have to change it in each handler. Like what I am after is like:
   $(document).ready(function(){
        var value = $(this).val();
        var f_class = $(this).parent().parent().find(".cSec .f_class a").text();
        var f_time =$(this).parent().parent().parent().find(".cSec .flight-time").text();
        var f_city = $(this).parent().parent().parent().find(".cSec .city").text();

        $("input[name='radioGroup1']").click(function(){
            updateWalletInfo(value,f_class,f_time,f_city);
        });

        $("input[name='radioGroup2']").click(function(){
            updateWalletInfo(value,f_class,f_time,f_city);
        });
    });

I know the this operator will not work there, but I thought that makes my point more clear. I am even happy if I could only remove the redundancy for .parent().parent().find(".cSec .????").text() bit.
Answer: You can replace parent().parent(). with closest()..
Also pass a reference to the jQuery element to the updateWalletInfo function and get all the values inside that function, rather than passing all values. Something like
$(document).ready(function(){
    $("input[name='radioGroup1']").click(function(){
        updateWalletInfo($(this));
    });

    $("input[name='radioGroup2']").click(function(){
        updateWalletInfo($(this));
        );
    });

    function updateWalletInfo(elem)
    {
        var value = elem.val();
        var f_class = elem.closest("selector").find(".cSec .f_class a").text();
        var f_time = elem.closest("selector").find(".cSec .flight-time").text();
        var f_city = elem.closest("selector").find(".cSec .city").text();
    }
});

If you are taking all the values from the same parent element then you can take
var parentElem = elem.closest("selector");
var f_class = parentElem.find(".cSec .f_class a").text();
var f_time = parentElem.find(".cSec .flight-time").text();
var f_city = parentElem.find(".cSec .city").text();

Comment: Thanks rahul, I will give it a go tomorrow, but just a quick Q: Is "selector" should be written literally or do I have to figure which selector it is? Cheers
Comment: "selector" is just a placeholder.
Comment: You have to identify the selector.
Answer: You could register an impromptu jQuery plugin function.
$.fn.registerMyClick = function() {
  $(this).each(function() {
    var $this = $(this);
    $this.click(function() {
      updateWalletInfo(
        $this.val(),
        $this.parent().parent().find(".cSec .f_class a").text(),
        $this.parent().parent().parent().find(".cSec .flight-time").text(),
        $this.parent().parent().parent().find(".cSec .city").text(),
      );
    });
  });

  return this;
}

Depending on your HTML, it could also be simplified as:
$.fn.registerMyClick = function() {
  $(this).each(function() {
    var $this = $(this);
    $this.click(function() {
      $parent = $this.closest('.cSec');
      updateWalletInfo(
        $this.val(),
        $(".f_class a", $parent).text(),
        $(".flight-time, $parent").text(),
        $(".city", $parent).text(),
      );
    });
  });

  return this;
}

Then you use it like this:
$("input[name='radioGroup1']").registerMyClick();
$("input[name='radioGroup2']").registerMyClick();


PassportJS deserializeUser never called

Question: I've got Passport setup to authenticate users stored in mongodb. Seems to work fine: authentication succeeds/fails appropriately and session variables get set. However, getting Passport to check for a session is failing. Something seems to be quite wrong in that the console.log statements I've added to the deserializeUser callback never see the light of day. I assume my problem is related to deserializeUser never being called. Anyone able to diagnose my misstep?
// Passport configuration
passport.serializeUser(function(user, cb){ cb(null, user.id) });
passport.deserializeUser(function(uid, cb){
  console.log("Trying to deserialize user: "+uid);
  User.findById(uid, function(err, user){
    cb(err, user);
  });
});
// auth strategy function
passport.use(new LocalStrategy({usernameField: 'email'},
  function(email, pass, done){
    User.findOne({email: email}, function (err, user) {
      if (err)
        return done(err);
      if (!user)
        return done(null, false, {message: "Couldn't find user"});
      var crypted = bcrypt.hashSync(pass, user.salt);
      if(user.hashpass != crypted)
        return done(null, false, {message: "Bad password"});
      return done(null, user);
    });
  }
));

passport.CreateSession =  function (req, res, next) {
  passport.authenticate('local', function(err, user, info){
    if(err || !user)
      return res.json({status: "Failure: "+err});
    req.logIn(user, function (err){
      if(err)
        return res.json({status: "Failure: "+err});
      return res.json({status: "Authenticated"});
    });
  })(req, res, next);
};

with the following in app.js:
app.post('/session', passport.CreateSession); // restify better
app.del('/session', passport.DestroySession);
app.get('/images', passport.CheckSession, routes.images);

Answer: For anyone else who is having this issue, take a look at this:
app.use(session({
    secret: 'something',
    cookie: {
        secure: true
    }}));

If you have cookie.secure set to true and you're NOT using SSL (i.e. https protocol) then the cookie with the session id is not returned to the browser and everything fails silently. Removing this flag resolved the problem for me - it took hours to realise this!
Comment: Dave, is session here "express-session"? can you make that clear.
Comment: This was the issue for me, and it took 2 work days to find this answer...
Thanks!
Comment: Thank you very much. Same thing for me. Serialize user was being called, but never deserialize. No cookies present in the browser, and nothing in req.session.passport. Flipping this flag seemed to help. Even though locally it was working, on my prod instance which is running on Heroku and using their free SSL, it didn't want to set the secure cookie.
Answer: If you are using the authenticate callback when you authenticate with passport you need to log the user in manually. It will not be called for you.
passport.authenticate('local', function (err, user) {
    req.logIn(user, function (err) { // <-- Log user in
       return res.redirect('/');
    });
})(req, res);

Comment: You might want to recheck that, if you are doing auth manually it will not be called.
Comment: From passport's docs: `Note: passport.authenticate() middleware invokes req.login() automatically. This function is primarily used when users sign up, during which req.login() can be invoked to automatically log in the newly registered user.`
Comment: How does it relate to *deserializeUser never being called* issue?
Comment: In the passport docs about the custom callback in `authenticate`: `The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.`
Comment: `console.log(err.message)` after `req.logIn(user, function (err) {` show: `Failed to serialize user into session` ?
Answer: Have you use()'d passport.session() middleware?  Like in this example:
https://github.com/jaredhanson/passport-local/blob/v1.0.0/examples/login/app.js#L91
That's what restores the session and calls deserializeUser, so it sounds like that may be missing.
Comment: Also, `passport.session()` should be below/after the `app.use(session…`
Comment: Jared - I'm using express.cookieParser(), express.session({secret: 'somethingsecret'}), and passport.session()... anything else I'm missing? Did try it with node 0.6.0 and no joy. If that session setup looks proper and you don't see anything else, I'll post a gist later on this evening. Thanks so much for your help - the node community really benefits from folks like yourself aiding users.
Comment: Jared - thanks for helping out. Yep, I've got  app.use(passport.session()); in app.js
Comment: This is node 0.8.0, express 2.5.10, and the latest passport, btw.
Comment: Hmm, and I'm assuming you have your sessions properly set up and persisted too?  If so, I don't see anything obvious.  Here's my suggestion: 1. Try running under node 0.6.x, to see if there's an incompatibility somewhere with 0.8.  2. Post a runnable, copy-n-paste gist, and I'll run it and see what I can find.
Comment: Gist is here: https://gist.github.com/3030629 ...I didn't include the user model in the gist, but it's a straightforward mongo document with a bcrypted password and email field. The execution gets nowhere near it, so I didn't think it was critical - if you disagree, let me know and I'll update.
Comment: I'm not having any troubles with your gist.  `deserializeUser` gets called and the `CheckSession` function `next()`s as expected.  Are you using cluster or load balancing?  That could cause a request to bounce to a different server, and you'll need to switch to something besides the MemoryStore for sessions (see connect-redis).
Comment: Other than that, I'm out of ideas.  Can you run the example in passport-local?  If that works, I'd start stripping things down until you isolate the point that is going wrong.  Let me know what you discover.
Comment: Jared, no cluser, no load balancer, and the passport-local example works perfectly. Very strange. I'll continue to poke around, and if I find something, I'll let you know.
Comment: Fixed it. Seems that my version of Mongoose won't allow me to access document fields from the strategy definition without using .get() ...not sure how that didn't throw an error somewhere, but that seems to get me up and running. +1 for looking into it!
Answer: Okay, this took me almost 3 days to solve, which seems to be a simple fix, at least in my case. I had to place:
app.use(require('cookie-parser'));

and
app.use(require('express-session')({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));

BEFORE calling:
app.use(passport.initialize());
app.use(passport.session());

Note: These snippets are not my actual code, I have taken it from GitHub, but that is the gist of it.
Answer: Today I faced the same issue, and in my case the cause was how the client side makes the API calls. And the following approach helped me to overcome the problem:
const doFetch(url, method = 'GET', body) {
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  headers.append('Accept', 'application/json');
  headers.append('Cache', 'no-cache');
  const params = {
    method, headers,
    credentials: 'include' // The cookie must be sent!
  }
  if(body) {
    params.body = body;
  }
  return fetch(url, params);
}

After this, deserializeUser began to be called properly.
Comment: This put me on the correct solution, in my case, using Axios, I had to make my call with `axios.get(route, {withCredentials: true})`
Answer: In my case it was because I had this code:
app.get("/auth/google/callback",
    passport.authenticate("google", {
        failureRedirect: "/admin/login/?error",
    }),
    (req, res) => {
        return res.redirect("/admin/");
    },
);

Apparently in this case req.login() will not be called (which calls deserialize). I changed it to this and it worked:
app.get("/auth/google/callback",
    passport.authenticate("google", {
        successRedirect: "/admin/",
        failureRedirect: "/admin/login/?error",
    })
);

Comment: i tried this and it didn't work but then i made a bunch of random changes and it still didn't work and then i tried this again and it worked... computer science moment i guess
Answer: I fought the same problem the entire day. I had a custom callback set up to do authorizations (like at the bottom of http://passportjs.org/guide/authenticate/). It looks like Passport preprocesses all request objects before they even hit the other middleware (based on some logging statements I wrote). As part of that preprocessing, it places the deserialized user information into the request.user object. Unfortunately, the default behavior of passport.authenticate ('local', callback) seems to be to ignore any session or cookie data, and instead assume that the username and PW are being sent in the request object. What I did to fix this was to first check the request.user object, and if it existed, it meant that Passport had done its preprocessing and then I could call login directly. Here is my authorization function, which I use in place of passport.authenticate('local'):
function doAuth(request, response, next)
{

if (request.user) {
    request.logIn(request.user, function (err) {
        if (err) {
            console.log(err);
            response.status(500).json({message:
                    "Login failed. Auth worked. Nonsense"});
            return;
        }
        console.log("doAuth: Everything worked.");
        next();
    });
    return;
}

passport.authenticate('local', function(err, user, info) {
    if (err) {
        response.status(500).json({message: "Boo Passport!"});
        return; //go no further
        //until I figure out what errors can get thrown
    }
    if (user === false) {
        console.log("Authentication failed. Here is my error:");
        console.log(err);
        console.log("Here is my info:");
        console.log(info);
        response.status(500).json({message: "Authentication failed."});
        return;
    }
    request.logIn(user, function(err) {
        if (err) {
        console.log("Login failed. This is the error message:");
        console.log(err);
        response.status(500).json({message:"Login failed."});
            return;
        }
        console.log("doAuth: Everything worked. I don't believe it.");

        next();
    });
})(request, response, next);

 }

Comment: Your explanation helped me a lot thanks! I have not applied your solution but you pointed out the problem though :D
Answer: In Heroku, all requests come into the application as plain http, but with the X-Forwarded-Proto header to know whether the original request was http or https.
That causes express to see non-ssl traffic and so it refuses to set a secure cookie when running on Heroku. You have to tell express to trust the information in that header by setting 'trust proxy'.
app.set('trust proxy', 1);

right before
app.use(session...

might work for you if you're having trouble with this on Heroku specifically. If your cookies/session are messed up then that could be why deserialize is not being called.
Answer: in my case, I've placed
app.use(cookieSession({
  maxAge : 60*60*1000,
  keys : [key.cookieSession.key1]
}));

above
app.use(passport.initialize());
app.use(passport.session());

and it worked.
Answer: I faced this issue while using JamStack architecture (client-side rendering instead of server-side) and none of the existing answers were useful.
Backend (localhost:4000)
The most important part is the CORS setup:
const cors = require("cors");
const corsOptions = {
  origin: "http://localhost:3000",
  credentials: true, // ! important
  methods: ["GET", "POST"],
};
app.use(cors(corsOptions));

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

const sessionMiddleware = session({
  secret: process.env.SESSION_SECRET || "random-secret",
  resave: false,
  saveUninitialized: true,
});
// ! order of middlewares below is important
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());

Dealing with login:
router.post("/login", (req, res, next) => {
  passport.authenticate("local", (err, user, info) => {
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.status(401).send(info);
    }
    req.login(user, (err) => { // ! important
      if (err) {
        return res.status(500).json({ error: "Login failed." });
      }
      res.status(200).send();
    });
  })(req, res, next);
});

The req.login() part is essential.
The above route will authenticate a user. If successfully verified, Passport will call the serializeUser function. When the session is authenticated, Passport will call the deserializeUser function and the req.user property is then set. (https://www.passportjs.org/concepts/authentication/sessions/)
For the sake of completeness, here's my passport setup:
passport.use(
  new LocalStrategy(
    {
      // https://stackoverflow.com/questions/34511021/passport-js-missing-credentials
      usernameField: "email",
      passwordField: "password",
    },
    async (email, password, done) => {
      console.log(email, password);

      try {
        const user = await User.findOne({ email });
        if (!user) {
          return done(null, false, { error: "Email does not exist." });
        }
        console.log("User valid");

        const match = await bcrypt.compare(password, user.password);

        if (!match) {
          console.log("Passwords invalid");
          // passwords do not match!
          return done(null, false, { error: "Invalid password." });
        }
        console.log("Passwords valid");
        return done(null, user);
      } catch (err) {
        return done(err);
      }
    }
  )
);

passport.serializeUser((user, done) => {
  console.log(`serializeUser: ${user}`);

  done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
  console.log(`deserializeUser: ${id}`);

  try {
    const user = await User.findById(id);
    console.log(user);

    done(null, user);
  } catch (err) {
    done(err);
  }
});

Frontend (localhost:3000)
On the login page of my frontend, I had to include credentials: "include" when making a POST request to the API:
      const response = await fetch(`${BACKEND_URL}/auth/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include", // ! important
        body: JSON.stringify(values),
      });

Each time the frontend communicates with the backend via the API, I had to include credentials: "include" in my request. For example, on another page of my frontend which is only available to authenticated users, I made a GET request as follows:
        const response = await fetch(`${BACKEND_URL}/canvas`, {
          method: "GET",
          credentials: "include",
        });

Now, the session is preserved across requests and passport.deserializeUser is called.
Answer: make sure the line of code app.use(express.static(path.join(__dirname, 'public'))); stays below the app.use(require('express-session')
Comment: Why? This order doesn't matter for the issue - `deserializeUser` is not called either. Also, you get DB query on EVERY assets request. Are you sure you need to query session for your every `styles.css`?
Answer: I open the google chrome with web-security or open incognite mode, it's working for me
web-security for linux /usr/bin/google-chrome-stable
--disable-web-security --user-data-dir=/home/jossnaz/.config/google-chrome/

Answer: passport.serializeUser(
    function(user, done){
        done(null, user.id);
});

passport.deserializeUser(
    function(id, done){
        User.findById(id, function(err, user){
            if(err){
                done(err);
            }
            done(null, user);
        });
});

**> try this one**

PassportJS deserializeUser never called


Environmentalists are annoying me, how can I silence them?

Question: I haven't been very environment-friendly and now the environmentalists are on my heels. My reputation with them is very low, especially because I cut some trees and dug for gold.
What's the best way to get back on their good side?
I tried recycling and putting up some gardens, but that doesn't really seem to be enough to make them like me again.
Are there any tricks to make environmentalists happy while still making a profit with the earth's natural resources?
Comment: Make out with a tree.
Comment: Optional tasks are good for this.
Comment: This question is off topic. This forum is for gaming... :D
Comment: It's a universal problem I think. ;)
Answer: If all else fails, you can always just perform the Outlaw Faction edict and get rid of them entirely.  You just need a little preparation in advance with some secret police and a sizable army to quell any possible rebellion.
Comment: This solution may not be 'optimal,' but really, its the most thoroughly *Tropico* answer available.
Comment: Hm, tempting... \*evil laugh\*
Comment: Yeah, upvote for getting into the spirit of Tropico!
Comment: +1 for answering the question - that definitely counts as 'silencing' them!
Answer: Planting trees, building botanical gardens and issuing anti-pollution edicts helps.
Make sure all your applicable industries have pollution-reducing options enabled; build a garbage dump somewhere out of sight of the city but within operating reach, and have it recycle and use high temperature burners.
Praise the environmentalists during your speeches - it's a +10 bonus that doesn't cost you anything.
Try not to bulldoze areas of high natural beauty for industry sites.
Keep an eye out for subtasks from their faction; they may not always be things you /want/ to do, but it's worth hearing them out to see what they want.
EDIT: Can't remember why I forgot to add this originally, but shacks cause lots of pollution. Make sure everyone has somewhere at least halfway decent to live.
Comment: How far is the "operating reach" of the garbage dump? Can I place it outside of the red (polluted) area and it still has effect?
Comment: The range of a garbage dump is pretty huge; you can check it directly in the overlays, and it's not affected by road networks. It's under Island Conditions, and there's an option to see Landfill Coverage. Since the Environmentalists complain about "insufficient landfill coverage," it's useful to see when you have a far-flung mine or farm that isn't covered.
Comment: Yes. I don't recall the actual range offhand, but I think road accessibility probably has an effect on it as well (speaking of which; make sure your road network is up to scratch. All cars pollute, but traffic jams and gridlocks mean lots of cars in the same area, *causing pollution without actually getting anywhere*
Answer: Here are some things to try.

Make sure you have enough recycling, a large city may need several dumps.  There is an overlay that shows garbage coverage.
Pass some of the environmentally friendly edicts like Pollution control and Anti-Litter ordinance.
Watch for optional tasks that can boost your faction rep quickly.
Take a look at the faction leader and see what else he is interested in.  If you can make him generally happy, it will improve your relationship with the faction overall.  If all else fails, you can always try bribing him.
Don't worry about them.  You don't need to please all the factions all the time.  If they start performing eco-protests, just make some of them disappear and they should be scared off.


Where can I put holes in my yard?

Question: I bought string lights and I plan to put them in my small indoor/outdoor yard (I am not sure whether it is indoor or outdoor).
I used a strong magnet (see picture) to detect where have metal behind the paint, but I find many spots. I guess that they are plates for connection. I cannot drill through those areas where have metal plate.
My question is where I can drill holes to mount eye screws?
Thanks

https://ibb.co/jzXwYt1
https://ibb.co/W3ykkxF
https://ibb.co/dQ7ccVH
https://ibb.co/SP2dw2K
Comment: I'm confused. You mention a yard (which may be inside our outside, somehow), but show photos of a wall and a light device. Are you asking about drilling through the _wall_? What plates are you talking about? How is your home constructed? Please revise your question to clarify.
Comment: A small light string shouldn't need to be screwed into studs.  Small screws or nail-on clips that only penetrate the outer layer should be fine.  I feel like what you are trying to do is unclear.
Comment: I believe that you want to attach lights to the exterior wall and which might or might not be under cover. I see in your picture the exterior of the building with an overhang that protects the wall from weather. It looks to me like you have stucco and my understanding is that stucco is applied over a wire mesh which would be why your magnet seems to hold in most places. I believe that your question is more along the lines of: how do I find the studs? Is this accurate?
Answer: I don't use magnets, or stud finders set to 'metal', ever. I use drill bits. If there's protection plates, the drill bit will tell you that.
I think you're finding screw heads. Disclaimer : I live in EMT land, so there's generally no concern beyond hitting a PVC pipe or low voltage comm.
If you have to push really hard, don't; relocate. Patching and painting my be required after all is said and done. That's why it sucks trying to hang something that won't cover your booboos. And why 'new construction' people won't touch rehab jobs that begin and end with 'unforeseen circumstances'. This is your can of worms; open it up:
You're going to have to do some recon... with a drill bit. Bite the bullet and start making holes. And use your intuition: It's an outside wall so it's unlikely there's any plumbing. And way up there would be a strange place for an electrical run, but anything's possible. - Henry Jones says: "I don't know. WE'LL FIND OUT!"
Comment: ... it could be an i-beam. Cut the tips off of drywall anchors and use shorter screws, if you have to.
Comment: "EMT land"  Emergency Medical Technician land?
Comment: @Steve Wellens Electrical metallic tubing, protecting any dangerous line-voltage wires.
Comment: "EMT land" is obvious to those who understand electrical work, but is totally meaningless to the OP who seems quite confused.

Where can I put holes in my yard?


filtering contents of radgridview

Question: i have a problem with filtering th contents of my radgridview.
here's my code
private void Filter_Click(object sender, System.Windows.RoutedEventArgs e)
{
    FilterDescriptor filter = new FilterDescriptor("Name", FilterOperator.Contains, (RadGridView1.SelectedItem as Person).Name);
    RadGridView1.FilterDescriptors.Add(filter);
}
it only filters the "Name" column. i want it to filter the data based on the value of the cell clicked... i have to get the column name of the cell clicked and replace it to "Name" in my code...
can anyone help me with this?
Answer: here's the code to filter:

FilterDescriptor filter = new FilterDescriptor(RadGridView1.CurrentCell.Column.UniqueName, FilterOperator.IsEqualTo, RadGridView1.CurrentCell.Value);
RadGridView1.FilterDescriptors.Add(filter);

here's the code to remove filter:

RadGridView1.FilterDescriptors.Clear();

RadGridView1 is the name of the radgridview.

filtering contents of radgridview


How to let shell sh known ksh's environment variable

Question: system: AIX6
default shell is ksh
in ~/.profile, set the env var MFE_HOME:
MFE_HOME=/home/mfe/MFE
then exec some shell scripts, "sh xxx.sh", which will judge $MFE_HOME exists or not,
and it finds not.
-----> how to let it find ~/.profile 's env var $MFE_HOME?
Answer: You need to export the environment variable so that it is inherited/available to sub shells.  Add export MFE_HOME in your .profile.


How to calculate the size of the scale transform applied control

Question: How to calculate increased width and height of the scale transform applied control in WPF?
Answer: public static Rect GetAbsolutePlacement(this FrameworkElement visual)
{
    Point topLeft = visual.PointToScreen(new Point(0, 0));
    var bottomRight = visual.PointToScreen(new Point(visual.ActualWidth, visual.ActualHeight));

    var bounds = Rect.Empty;
    bounds.Union(topLeft);
    bounds.Union(bottomRight);

    return bounds;
}

Answer: You can use the ActualHeight and ActualWidth properties. These return the true values of the controls, not the values you have requested. Though this is the value after the control has been rendered.
If you want to know what the height and width will be then you could apply your transformation to the request sizes, but these might not match what the actual values will be.
The MSDN has more information.

There is a difference between the properties of Height and Width and ActualHeight and ActualWidth. For example, the ActualHeight property is a calculated value based on other height inputs and the layout system. The value is set by the layout system itself, based on an actual rendering pass, and may therefore lag slightly behind the set value of properties, such as Height, that are the basis of the input change.
Because ActualHeight is a calculated value, you should be aware that there could be multiple or incremental reported changes to it as a result of various operations by the layout system. The layout system may be calculating required measure space for child elements, constraints by the parent element, and so on.


How to expose SCSS variables from a gem into a rails project with a single `@import`

Question: I have a rails project and a gem. The rails project has .scss files that require variables from the gem:
Rails Project
application.scss:
@import "gem-styles.scss";
@import "my-scss-file-that-needs-access-to-variables.scss"

my-scss-file-that-needs-access-to-variables.scss:
color: $primary-color;

Gem
in gem-styles.scss:
@import "common/variables";

in common/_variables.scss:
$primary-color: #00d9ff;

Doing this, I get the error: Undefined variable: "$primary-color".
I can include common/variables in my-scss-file-that-needs-access-to-variables.scss to fix the issue:
@import "common/variables";
but I don't find that solution DRY enough. I would have to import common/variables into every .scss file that requires them. I would prefer to be able to only import one .scss file from the gem which contains all of the variables that I need exposed in my parent application, as well as the rest of the styles from gem-styles.scss.
Answer: you can just paste this @import "common/variables"; into your application.scss only once.
@import "common/variables";
@import "gem-styles.scss";
@import "my-scss-file-that-needs-access-to-variables.scss"

like this
Comment: but then I'm still importing two `.scss` files, I would like to only import one, is this possible?


CRM 2011 Merging records using dialog

Question: Morning guys. I will try to be as short as possible.
We are using CRM 2011 on premises. Currently the way data flow works is that we have two systems (system X and System Y). System X have all customer information regarding purchase and System Y have all the information regarding customer's subscription choice. (news letter etc)
We bring these two database together and merge it in to one and then using thirdparty service, push it in to the CRM. (we process these data that's de-dups rows, checks for data quality etc)
PROBLEM start when the third type of data gets entered in by customer service. This guys uses Outlook to push data in to CRM (this are the only data that goes directly in to CRM)
This last method creates lots of duplicates and makes it imposible to use this data for better customer service and reporting.
Few important info: over 99% of data (in form of cases) entered in to CRM by customer service are of customers who already exist in CRM (These are the data that came from System X and System Y). The existing data have all the details (email, postal address etc..) but duplicate data that is entered by Customer service only have basic info like Firstname, Lastname and Email address.
what is the best solution to 1. merge these datas? and 2. Avoid duplicates when entered by customer services? I tried using dialog but it's asking end user (in customer service) to manually pick details they want to keep from each row. Some time these rows are more then 2-3.
I am sorry for making it so long but this issue seems to not going away. I am not looking for full on solution from you guys but any tips, link or if you have tried some thing like this before.
Many thanks for your time.
Answer: Have you looked at duplicate detection rules?
E.g. CRM Duplicate Detection Part 1: Configure Settings and Create Rules
Comment: So what will happen if Duplicate Detection finds a duplicate value? At the moment, evry entry from customer service is creating duplicate record. 1. Will it ask end user to merge records 2. will it delete one of them (if so which one) and 3. can I define how to merge records automatically. Thanks for your help buddy :)
Comment: It will inform the user they are about to create a duplicate and ask them what they want to do. You can also have jobs running in the background which find existing duplicates. Its eaiser for you to try it out than for me to explain it.
Comment: Agree, it's always easy to try it. Thanks James. I will look in to it. One of the reason we are getting these duplicates is because end users who are entering these data are, let me honest, don't care. Giving them choice on which data to keep might be a terrible idea. What I am struggling to understand is that when they raise case, WHY it's creating duplicates. In other words, trying to find out prevention then fix. Hey ho, I will have to just flag these data for now as potential duplicates so they don't get included in marketing list etc...Thanks for your help :)

CRM 2011 Merging records using dialog


Sine and Cosine Expansion Problem

Question: We know:
$$\sin{x} = x - \frac{x^3}{3!} + \frac{x^3}{5!}-\dotsb$$
 and so on. Also,
$$\cos{x} = 1 - \frac{x^2}{2!} +\frac{x^4}{4!}-\dotsb$$
and so on.
With the help of these expansions we need to prove that $\sin^2 x+\cos^2 x=1$ .
I tried generalizing $\sin{x}$ as
$$\sum (-1)^n\frac{x^{2n+1}}{(2n+1)!}$$
and $\cos{x}$ as
$$\sum (-1)^n\frac{x^{2n}}{(2n)!},$$
 then squaring and adding. But it didn't get through.
Please help!
Answer: I think the easiest way to see it is to notice that $e^{ix}=\cos(x)+i\sin(x)$ which is easily verified by writing down the Taylor expansion of both sides. Then
$$\sin^2(x)+\cos^2(x)=e^{ix}e^{-ix}=1$$
If you want to verify $f(y)=e^{y}e^{-y}=1$, here's how: first show $\frac{d}{dx}e^y=e^y$ from the Taylor series. Then show $f'(y)=f(y)-f(y)=0$ by the chain rule. Conclude $f(y)$ is a constant, and plug in $y=0$ to get $f(y)=1$.
Comment: Since we are using the series based approach it is much easier to show that the series $g(z) = 1 + z + \dfrac{z^{2}}{2!} + \dfrac{z^{3}}{3!} + \cdots$ satisfies the property $g(z_{1} + z_{2}) = g(z_{1})g(z_{2})$ by directly multiplying the series and using binomial theorem. This easily gives $g(z)g(-z) = g(0) = 1$.

Sine and Cosine Expansion Problem


Can pixels on the image plane be mapped to world space coordinates?

Question: I'm trying to learn the fundamentals of 3d computer graphics by writing a toy framework in WebGL.
I'm currently working on mouse based camera controls. There are plenty of good resources in the ACM SIGGRAPH library to be found, but there are some aspects of this area that I can't find answers to.
A lot of orbit controls simply use the origin as the pivot point, but other implementations can orbit around any arbitrary point in a scene and the camera stays 'still'. I'm trying to implement the latter.
It seems that a good way to do this would be to simply get the cross product of the two vectors made by the pivot point and 3d coords of the corresponding pixels on the image plane, but I can't anything like this approach anywhere which leads me to believe I've misunderstood some fundamental aspect of image projection/image planes.
Is the image plane an abstract construct that doesn't really have 3d coords or can pixels in the image plane actually be mapped to world coords?
Comment: "other implementations can orbit around any arbitrary point in a scene and the camera stays 'still'." - please elaborate.
Comment: Imagine several objects in a scene and all those objects are placed around the origin. The camera looks at the origin (which is in the center of the image plane). Normally, the camera orbits the origin (which is also the pivot point), but by picking a different pivot point, the camera remains looking at the origin, but all the objects rotate around the pivot point.
Comment: So you want a collection of objects revolving around some point in space?
Comment: Amongst other things, yes. But I want to experiment with this stuff to help me understand. I guess what I'm really after is a way to determine the vector from a pixel on the image plane to any point in the scene and to know if that's even possible.
Comment: A collection of objects rotating around another object, can be done through hierarchical transformations. In your case `T_pivot * R_pivot * T_model * pos`. Transforming screen-space coords to world coords is an entirely different problem. There are many articles on this, here's one that includes it: https://mynameismjp.wordpress.com/2010/09/05/position-from-depth-3/
Answer: What you are asking about is 'mouse picking'. If a user clicks a pixel on the screen how can you get corresponding world space coordinates of an object being clicked on.
Imagine a ray from that pixel, through the view volume all the way to the far plane. That ray is a set of all possible points the user is clicking on. So we want to perform ray/poly ntersections with every object in the scene, and return the first intersect.
To transform the pixel into world space, you first have to turn your x,y point in screen space into NDC coordinates (-1 to 1) use -1 for your Z component and 1 for W to create a 4 float component vector and then multiply that vector by the inverse projection and then inverse view matrices.
There are many examples of this process if you want to see code, but this is the basic process.
Now we have a ray from the camera/eye position into the scene, we want to do intersection tests with our objects. There are many ways of achieving this, take your pick.
Hope this helps, good luck!
Comment: Aha! That's exactly what I needed to hear. I had a feeling the -1 z plane of the NDC cube would be the screen, but I couldn't confirm it. Thanks


Spring MVC binding request parameters

Question: I wrote a spring-mvc controller method to get an array of values in the request parameter.The method looks like below
/**
 Trying to get the value for request param foo which passes multiple values

**/
@RequestMapping(method=RequestMethod.GET)
public void performActionXX(HttpServletRequest request,
                        HttpServletResponse response,
                        @RequestParam("foo") String[] foo) {

......
......

}

The above method works fine when the request url is in below format
...?foo=1234&foo=0987&foo=5674.

However when the request url is in below format the server returns 400 error
...?foo[0]=1234&foo[1]=0987&foo[2]=5674

Any idea how to fix the method to cater to the second format request url?
Comment: why do you want to do it this way ? "foo[0]=1234&foo[1]=0987&foo[2]=5674" and not the other way? any special reason?
Comment: I don't have the control over the request url
Answer: This is not possible with @RequestParam. What you can do is implement and register your own HandlerMethodArgumentResolver to perform to resolve request parameters like
...?foo[0]=1234&foo[1]=0987&foo[2]=5674

into an array. You can always checkout the code of RequestParamMethodArgumentResolver to see how Spring does it.
Note that I recommend you change how the client creates the URL.
The server is supposed to define an API and the client is meant to follow it, that's why we have the 400 Bad Request status code.
Answer: I resolved this issue using the request.getParameterMap().Below is code.
Map<String,String> parameterMap=  request.getParameterMap();
    for(String key :parameterMap.keySet()){
        if(key.startsWith("nameEntry")){
            nameEntryLst.add(request.getParameter(key));
        }
    }

Spring MVC binding request parameters


Reading serial data from Arduino fails

Question: I have written a program for Arduino that reads some analog signals and sends them to the computer when it receives a command from the master computer. I wondered why this didn't work on the computer it was intended to run on. On my own computer it runs fine.
I uploaded a simple test code in the Arduino.
<code>void setup() {
    Serial.begin(9600);
}

void loop() {
    if(Serial.available()) {
        Serial.println(Serial.read());
    }
}
</code>
This doesn't run on the second computer either. When I use Arduino serial monitor for transfering data, I see the RX led blink but not the TX. With the computer it's working on, I can see both of the leds flash. Arduino receives the data on both computers, but the second computer doesn't receive Arduino's responses. What might be wrong?
Edit. I forgot the Arduino hooked up to the problematic PC for a few minutes and tried it again. Then it worked! It seems like it needed some time to warm up. Why's that?
Answer: Sometimes it can take a second for the Arduino and computer to establish the Serial handshake, especially at 9600 baud. I'm glad you got it working!
Comment: The time it takes is probably closer to 40 seconds.
Comment: @MikkoP it behaviour is always? I am trying to connect the Arduino and my application and something it takes a lot of time. I am talking about 1 minute, do you find a solution to reduce this time or it is only resolved by the software and hardware of the machine?
Comment: @Robert Unfortunately I wasn't able to get it working any faster. Haven't played with it for over a year now though, could be there's a fix for that or something.

Reading serial data from Arduino fails


How can I scale textviews using shared element transitions?

Question: I am able to get TextViews to transition perfectly between two activities using ActivityOptions.makeSceneTransitionAnimation. However I want to make the text scale up as it transitions. I can see the material design example scaling up the text "Alphonso Engelking" in the contact card transition.
I've tried setting the scale attributes on the destination TextView and using the changeTransform shared element transitions, but it doesn't scale and the text ends up being truncated as it transitions.
How can I scale TextViews using shared element transition?
Answer: Edit:
As pointed out by Kiryl Tkach in the comments below, there is a better solution described in this Google I/O talk.

You can create a custom transition that animates a TextView's text size as follows:
public class TextSizeTransition extends Transition {
    private static final String PROPNAME_TEXT_SIZE = "alexjlockwood:transition:textsize";
    private static final String[] TRANSITION_PROPERTIES = { PROPNAME_TEXT_SIZE };

    private static final Property<TextView, Float> TEXT_SIZE_PROPERTY =
            new Property<TextView, Float>(Float.class, "textSize") {
                @Override
                public Float get(TextView textView) {
                    return textView.getTextSize();
                }

                @Override
                public void set(TextView textView, Float textSizePixels) {
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizePixels);
                }
            };

    public TextSizeTransition() {
    }

    public TextSizeTransition(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public String[] getTransitionProperties() {
        return TRANSITION_PROPERTIES;
    }

    @Override
    public void captureStartValues(TransitionValues transitionValues) {
        captureValues(transitionValues);
    }

    @Override
    public void captureEndValues(TransitionValues transitionValues) {
        captureValues(transitionValues);
    }

    private void captureValues(TransitionValues transitionValues) {
        if (transitionValues.view instanceof TextView) {
            TextView textView = (TextView) transitionValues.view;
            transitionValues.values.put(PROPNAME_TEXT_SIZE, textView.getTextSize());
        }
    }

    @Override
    public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
                                   TransitionValues endValues) {
        if (startValues == null || endValues == null) {
            return null;
        }

        Float startSize = (Float) startValues.values.get(PROPNAME_TEXT_SIZE);
        Float endSize = (Float) endValues.values.get(PROPNAME_TEXT_SIZE);
        if (startSize == null || endSize == null ||
            startSize.floatValue() == endSize.floatValue()) {
            return null;
        }

        TextView view = (TextView) endValues.view;
        view.setTextSize(TypedValue.COMPLEX_UNIT_PX, startSize);
        return ObjectAnimator.ofFloat(view, TEXT_SIZE_PROPERTY, startSize, endSize);
    }
}

Since changing the TextView's text size will cause its layout bounds to change during the course of the animation, getting the transition to work properly will take a little more effort than simply throwing a ChangeBounds transition into the same TransitionSet. What you will need to do instead is manually measure/layout the view in its end state in a SharedElementCallback.
I've published an example project on GitHub that illustrates the concept (note that the project defines two Gradle product flavors... one uses Activity Transitions and the other uses Fragment Transitions).
Comment: @Ted It is possible to reference the custom transition above in your XML files because it overrides the `TextSizeTransition(Context, AttributeSet)` constructor. For example, you could reference the custom transition above like this: ``
Comment: Nice solution using the `SharedElementCallback` feature. Something useful to add is that if your shared element is actually a ViewGroup and your TextView is centered inside it, you have to re-layout the TextView in `SharedElementCallback.onSharedElementStart` in addition to `SharedElementCallback.onSharedElementEnd`. See @AlexLockwood's `EnterSharedElementCallback` example.
Comment: Don't think that this code is correct because of the thrashing font cache. It is told [here](https://youtu.be/4L4fLrWDvAU?t=17m31s). This code will create a lot of cache with font size like 15.025 or 17.356, which will be never used in the future. The right way to do this is to swap text with drawable and after animation swap it back. Everything is told in [this](https://youtu.be/4L4fLrWDvAU) video.
Comment: Hey, so could you elaborate on what "properly" means? I asked a SO question (see below), regarding an animation that isnt looking good. Is it not advicable to define animations in XML, but do it the hard way in code?
http://stackoverflow.com/questions/27123561/animation-between-activities-and-shared-views-glitchy-hack-at-the-ends-of-anima#comment42872658_27123561
Comment: @Ted I answered your stack overflow question with a bit more detail on why your code doesn't work.
Comment: Thanks for the input, I will try to figure out what you mean, as I am currently not entirely clear on that =)
Comment: @Ted I linked to a sample project on GitHub in my answer... you can always start with that. :)
Comment: I did. I only see a bunch of files that seems to be unrelated to each other?
Comment: @Ted Did you run the application? Not sure what you mean by "they seem unrelated to each other", but the example text size transition in the project works for me when I run it.
Comment: If I go the URL, I see activity_main.xml, TransitionActivity.java, and other files listed, no way to download complete project, I see no transition xml files, there is some Python script...?
Comment: @Ted You can download the project using `git clone https://github.com/alexjlockwood/custom-lollipop-transitions`. Then import it into Android Studio.
Comment: @AlexLockwood Thanks for this! The only issue I have is that if the target `TextView` is not centered, the text jumps at the end. (you can reproduce by setting the `layout_gravity` of `end_scene`'s `TextView` to `left|center`
Comment: -> edit: I am messing around with `text.layout` in `OnSharedElementEnd`. That seems to be working
Comment: My TextView is flickering / blinking while transitioning. Specifically the last word is flickering. weird. :(
Comment: Figured it out. You need to exclude the textviews from changeBounds Transition. Then there is no flickering. yay.
Comment: Could you please take a look at [my post](http://stackoverflow.com/questions/42041926/detect-textsize-of-textviews-both-in-start-scene-and-end-scene-in-custom-transit). Your blog and answers in SO help me a lot.
Comment: @KirylTkach I updated the post to suggest your solution, as I agree it is the better option.
Comment: If you're using a container view to transition your animations in, you can
1) add TextSizeTransition class to your project
2) reference it in your transition xml file (example: https://github.com/googlesamples/android-unsplash/blob/master/app/src/main/res/transition/shared_main_detail.xml)
3) `scene = getSceneForLayout(...)` and use with `scene.transition(activity, R.transition.your_transition_file_that_mimics_the_linked_example_in_2), object : TransitionListenerAdapter() {})`
3) you might have to re-import some classes in TextSizeTransition if you already migrated to androidx
Answer: I used solution from Alex Lockwood and simplified the use (it's only for TextSize of a TextView), I hope this will help:
public class Activity2 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity2);

        EnterSharedElementTextSizeHandler handler = new EnterSharedElementTextSizeHandler(this);

        handler.addTextViewSizeResource((TextView) findViewById(R.id.timer),
                R.dimen.small_text_size, R.dimen.large_text_size);
    }
}

and the class EnterSharedElementTextSizeHandler:
public class EnterSharedElementTextSizeHandler extends SharedElementCallback {

    private final TransitionSet mTransitionSet;
    private final Activity mActivity;

    public Map<TextView, Pair<Integer, Integer>> textViewList = new HashMap<>();

    public EnterSharedElementTextSizeHandler(Activity activity) {

        mActivity = activity;

        Transition transitionWindow = activity.getWindow().getSharedElementEnterTransition();

        if (!(transitionWindow instanceof TransitionSet)) {
            mTransitionSet = new TransitionSet();
            mTransitionSet.addTransition(transitionWindow);
        } else {
            mTransitionSet = (TransitionSet) transitionWindow;
        }

        activity.setEnterSharedElementCallback(this);

    }

    public void addTextViewSizeResource(TextView tv, int sizeBegin, int sizeEnd) {

        Resources res = mActivity.getResources();
        addTextView(tv,
                res.getDimensionPixelSize(sizeBegin),
                res.getDimensionPixelSize(sizeEnd));
    }

    public void addTextView(TextView tv, int sizeBegin, int sizeEnd) {

        Transition textSize = new TextSizeTransition();
        textSize.addTarget(tv.getId());
        textSize.addTarget(tv.getText().toString());
        mTransitionSet.addTransition(textSize);

        textViewList.put(tv, new Pair<>(sizeBegin, sizeEnd));
    }

    @Override
    public void onSharedElementStart(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {

        for (View v : sharedElements) {

            if (!textViewList.containsKey(v)) {
                continue;
            }

            ((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_PX, textViewList.get(v).first);
        }
    }

    @Override
    public void onSharedElementEnd(List<String> sharedElementNames, List<View> sharedElements, List<View> sharedElementSnapshots) {
        for (View v : sharedElements) {

            if (!textViewList.containsKey(v)) {
                continue;
            }

            TextView textView = (TextView) v;

            // Record the TextView's old width/height.
            int oldWidth = textView.getMeasuredWidth();
            int oldHeight = textView.getMeasuredHeight();

            // Setup the TextView's end values.
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textViewList.get(v).second);

            // Re-measure the TextView (since the text size has changed).
            int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            textView.measure(widthSpec, heightSpec);

            // Record the TextView's new width/height.
            int newWidth = textView.getMeasuredWidth();
            int newHeight = textView.getMeasuredHeight();

            // Layout the TextView in the center of its container, accounting for its new width/height.
            int widthDiff = newWidth - oldWidth;
            int heightDiff = newHeight - oldHeight;
            textView.layout(textView.getLeft() - widthDiff / 2, textView.getTop() - heightDiff / 2,
                    textView.getRight() + widthDiff / 2, textView.getBottom() + heightDiff / 2);
        }
    }
}

Comment: you forgot about `mTransitionSet .setOrdering(TransitionSet.ORDERING_TOGETHER)`
Answer: This was covered in one of the Google I/O 2016 talks. The source for the transition which you can copy into your code is found here. If your IDE complains the addTarget(TextView.class); requires API 21, just remove the constructor and add the target either dynamically or in your xml.
i.e. (note this is in Kotlin)
val textResizeTransition = TextResize().addTarget(view.findViewById(R.id.text_view))

Answer: If you look at how ChangeBounds works, it operates on the left/right/top/bottom properties of the view.
What I expect is that you'll need to use the same text size across the two activities, and use the scaleX and scaleY properties in your launched activity to modify the text size as needed. Then, use a combination of ChangeBounds and ChangeTransform in your TransitionSet.
Comment: @klmprt I thought an even simpler solution would be to create a custom `TextSizeTransition` like [**this**](https://gist.github.com/alexjlockwood/578c87f65b905ededfe7)... I still haven't been able to get it to work the way I want it, but do you think something like this is on the right track? I feel like modifying the view's scale properties is a hacky way to achieve this effect when you can just modify the text size...
Comment: Yep looks like the textview bounds is animating correctly. However the actual text isn't scaling!
Comment: Great, that's what we'd expect. Now try to set the scale property in the destination activity and use both ChangeBounds and ChangeTransform together in a TransitionSet (e.g. TransitionSet.addTransition().addTransition())
Comment: The more I experiment with custom transitions, the more I think that some custom transitions simply refuse to work when used with shared element transitions... :/
Comment: @AlexLockwood `TextSizeTransition` looks good to me; you may need to use it in conjunction with ChangeBounds though. What wasn't working for you?
Comment: @klmprt I'll write up a short sample project demonstrating the problem tonight. I really want to figure out how to write custom transitions myself, but the only way I can ever get them to work is by modifying the shared views somehow in `SharedElementCallback#onSharedElementStart()` and even then it just feels so hacky.
Comment: @AlexLockwood Depending on what you're modifying, that's probably okay. The onSharedElementStart and onSharedElementEnd callbacks are there for you to 'set the scene' as needed -- ultimately the framework can't do all the work for you.
Answer: My solutions for the TransitionAnimation, not quite on the topic but close, perhaps with modifications or just someone come in handy.
package com.example.android.basictransition

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder.ofFloat
import android.content.Context
import android.transition.Transition
import android.transition.TransitionValues
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup

class ScaleTransition : Transition {

    companion object {

        private const val LAYOUT_WIDTH = "ScaleTransition:layout_width"
        private const val LAYOUT_HEIGHT = "ScaleTransition:layout_height"
        private const val POSITION_X = "ScaleTransition:position_x"
        private const val POSITION_Y = "ScaleTransition:position_y"
        private const val SCALE_X = "ScaleTransition:scale_x"
        private const val SCALE_Y = "ScaleTransition:scale_y"

        private val PROPERTIES = arrayOf(
                LAYOUT_WIDTH,
                LAYOUT_HEIGHT,
                POSITION_X,
                POSITION_Y,
                SCALE_X,
                SCALE_Y
        )
    }

    constructor() : super()

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    override fun getTransitionProperties(): Array<String> {
        return PROPERTIES
    }

    override fun captureStartValues(transitionValues: TransitionValues) {
        captureValues(transitionValues)
    }

    override fun captureEndValues(transitionValues: TransitionValues) {
        resetValues(transitionValues.view)
        captureValues(transitionValues)
    }

    private fun captureValues(transitionValues: TransitionValues) = with(transitionValues.view) {
        transitionValues.values[LAYOUT_WIDTH] = width.toFloat()
        transitionValues.values[LAYOUT_HEIGHT] = height.toFloat()
        transitionValues.values[POSITION_X] = x
        transitionValues.values[POSITION_Y] = y
        transitionValues.values[SCALE_X] = scaleX
        transitionValues.values[SCALE_Y] = scaleY
    }

    private fun resetValues(view: View) = with(view) {
        translationX = 0f
        translationY = 0f
        scaleX = 1f
        scaleY = 1f
    }

    override fun createAnimator(
            sceneRoot: ViewGroup,
            start: TransitionValues?,
            end: TransitionValues?
    ): Animator? {
        if (start == null || end == null) {
            return null
        }

        val startWidth = start.values[LAYOUT_WIDTH] as Float
        val endWidth = end.values[LAYOUT_WIDTH] as Float
        val startHeight = start.values[LAYOUT_HEIGHT] as Float
        val endHeight = end.values[LAYOUT_HEIGHT] as Float

        val startX = start.values[POSITION_X] as Float
        val endX = end.values[POSITION_X] as Float
        val startY = start.values[POSITION_Y] as Float
        val endY = end.values[POSITION_Y] as Float

        val startScaleX = start.values[SCALE_X] as Float
        val startScaleY = start.values[SCALE_Y] as Float

        end.view.translationX = (startX - endX) - (endWidth - startWidth) / 2
        end.view.translationY = (startY - endY) - (endHeight - startHeight) / 2

        end.view.scaleX = (startWidth / endWidth) * startScaleX
        end.view.scaleY = (startHeight / endHeight) * startScaleY

        return ObjectAnimator.ofPropertyValuesHolder(end.view,
                ofFloat(View.TRANSLATION_X, 0f),
                ofFloat(View.TRANSLATION_Y, 0f),
                ofFloat(View.SCALE_X, 1f),
                ofFloat(View.SCALE_Y, 1f)).apply {
            addListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    resetValues(start.view)
                    resetValues(end.view)
                }
            })
        }
    }
}


Error: socket hang up with Node.js, Mongo DB & load-balancer

Question: I am developing an REST-API that is running via a load-balancer with a database in MongoDB.
The API works when not using the load-balancer, but when implemented i do not get a response in Postman/Insomia when posting a GET request to the database - on the index ("/") route there in no problem getting a response back though.
But as the title shows, it get this error when canceling the request in PostMan, if like the connection could not be established.
This is the full error:

Error: socket hang up
    at connResetException (internal/errors.js:628:14)
    at TLSSocket.socketCloseListener (_http_client.js:449:25)
    at TLSSocket.emit (events.js:412:35)
    at net.js:675:12
    at TCP.done (_tls_wrap.js:563:7) {
  code: 'ECONNRESET'
}

This is my load-balancer
const https = require ("https");
const httpProxy = require("http-proxy");
const seaport = require("seaport");
const express = require("express");
const fs = require("fs");
const HOST = 'localhost';
const path = require("path")

const PORT = 8080;

const connect = seaport.connect('localhost', 9090);

let i = - 1;

  const certificate = {
    key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
    cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
    secure: false
};

let proxy = httpProxy.createProxyServer({secure: false});

let server = https.createServer(certificate, function(req, res) {

    let addresses = connect.query('server');
    if (!addresses.length) {
        res.end('Server failed');
};

i = (i + 1) % addresses.length;
let host = addresses[i].host.split(":").reverse()[0];
let port = addresses[i].port;
proxy.web(req, res, { target: 'https://' + host + ':' + port });
});

server.listen(PORT, function() {
 console.log('loadbalancer listens on'+ ":" + PORT)
});

And this is my app.js

const express = require("express");
const app = express();
const morgan = require("morgan")
const bodyParser = require("body-parser")
const https = require('https');
const fs = require('fs');
const seaport = require('seaport');
const path = require('path');
const mongoose = require("mongoose");

//Database
const db = require('./database/db');
const { MongooseDocument } = require('mongoose');

//Routes
const clientRoute = require ("./api/routes/client")
const reservationsRoute = require ("./api/routes/reservations")

app.use('/client', clientRoute);
app.use('/reservations', reservationsRoute);

//index route
app.use('/', (req, res) =>{
    res.send('Welcome to the app');
});

//Error handling 1
app.use((req, res, next) => {
    const error = new Error("Not found" + " ");
        error.status = 400;
            next(error);
        })
//Error handling 2
app.use((error, req, res, next) => {
        res.status(error.status || 500);
            res.json({
        error: {
             message:("Error 2" + " - " + error.message )
        }
      });
    });

//Create server with the https key and certificate
const sslServer = https.createServer({
    key: fs.readFileSync(path.join(__dirname, 'cert', 'key.pem')),
    cert: fs.readFileSync(path.join(__dirname, 'cert', 'cert.pem')),
}, app);

//Middleware
app.use(morgan("dev"));
app.use(bodyParser.json());

const seaportObject = seaport.connect('localhost', 9090);

//Start listening
let port = seaportObject.register('server');

sslServer.listen(port, () => {
    db.mongoConnection()
    .then(
        console.log('Localserver listens on: ' + port)
    )
    .catch(err =>{
        console.log(err)
        res.status(500).json({
            error:err,
            message: "
It went wrong here "
        })
    });
});

My Database folder

const mongoose = require('mongoose');

let connection;

const mongoConnection = async () => {
    if (!connection) {
        connection =
        await mongoose.connect("removed",
       () => console.log("Mongo is up and running")),{
        useNewUrlParser: true,
        useCreateIndex: true,
        useUnifiedTopology: true
       }
    }
    return connection;
}

module.exports = {
    mongoConnection: mongoConnection
};

I am stuck on this subject, please share some guidance
Answer: A solution has been found - the problem was that the database never connected


What does the green diamond beneath the character mean?

Question:
Sometimes they are lit, sometimes they aren't.  What does that represent?
Comment: As a guess, does it mean that they have their ultimate ready?
Answer: It's an indicator whether or not their ultimate is up.
If the gem is blue, it indicates that the ultimate is off cooldown, but they don't currently have the mana to cast it (credit to @Decency)
League of Legends has something similar.
Comment: If the gem is blue it indicates that they have their ultimate off cooldown but don't presently have the mana to cast it.
Comment: What if the gem is blue? As I've seen Clockwerk's being blue before.
Comment: "Apparently I need another sentence so I don't get this automatically converted to a comment, but that's really all there is to it." Woah wait what?!
Comment: @Mana Yeah. Before it just wouldn't let you post if the algorithm thought you didn't meet the guidelines. Now it posts it *as a comment*. Check the deleted comments on the OP.
Comment: Wait, I can see deleted comments?! What?!
Comment: @Mana *Now* who's the terrible mod? Arda, of course. >.>
Comment: wow that's nifty, I'll have to pay more attention to it now.


acts_as_taggable runs queries on every request

Question: I have a User.rb model that includes the line:
acts_as_taggable_on :industries, :uxes

[The 'uxes' term contains UX preferences belonging to the user, such as whether they dismissed a certain help box.]
What I've noticed is the following queries are loading at the top of every request involving a @user:
User Load (1.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 354 LIMIT 1
ActsAsTaggableOn::Tag Load (0.4ms)  SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.id = `taggings`.tag_id WHERE ((`taggings`.taggable_id = 354) AND (`taggings`.taggable_type = 'User')) AND (taggings.context = 'uxes' AND taggings.tagger_id IS NULL)
AREL (0.3ms)  UPDATE `users` SET `last_request_at` = '2012-09-17 09:44:24', `perishable_token` = 'un5eK7SHDNzTegt7GPUk', `updated_at` = '2012-09-17 09:44:24' WHERE `users`.`id` = 354
ActsAsTaggableOn::Tag Load (0.3ms)  SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.id = `taggings`.tag_id WHERE ((`taggings`.taggable_id = 354) AND (`taggings`.taggable_type = 'User')) AND (taggings.context = 'uxes' AND taggings.tagger_id IS NULL)
ActsAsTaggableOn::Tagging Load (0.4ms)  SELECT `taggings`.* FROM `taggings` WHERE `taggings`.`tagger_type` IS NULL AND `taggings`.`tagger_id` IS NULL AND `taggings`.`context` = 'uxes' AND `taggings`.`tag_id` IN (NULL) AND (`taggings`.taggable_id = 354 AND `taggings`.taggable_type = 'User')

These queries are adding time to every pageload on which a user is loaded (i.e. 90%+ of all pageloads). Why is acts_as_taggable forcing these queries to occur, and how can I stop it from loading them unless necessary?
Answer: The  ActsAsTaggableOn gem allegedly supports caching your tag lists directly
in your model, see also this question. To enable caching for tag lists, simply add a cached_tag_list column to your table, because the caching methods look for a column called "cached_#{context}_list"
on the acts_as_taggable record table. Not sure if this works, though.


python, psycopg2, and bound parameters

Question: I have this guy:
query = 'DELETE FROM boyd.%s WHERE teamid = %s AND id = %s AND year = %s' % (statstype, '%s', '%s', '%s')
self.executequery(query, values[0:3])

Which strikes me as ugly. The first %s is actually supplied by the variable, the other three are bound variables: do I really need to go % (statstype, '%s', '%s', '%s')? Is there a more... pythonic approach here?
Answer: If you use double %% signs, one % will still remain after string interpolation:
query = 'DELETE FROM boyd.%s WHERE teamid = %%s AND id = %%s AND year = %%s' % (statstype)
self.executequery(query, values[0:3])

python, psycopg2, and bound parameters