text:
Q: error: new types may not be defined in a return type The above error is occurring on the line where I implement my constructor. I made a comment that points to that line. Any help greatly appreciated.
#include <vector>
#include <time.h>

class Stopwatch
{
    enum state {UNSTARTED, RUNNING, PAUSED, FINISHED};
    struct time
    {
        unsigned hours;
        unsigned minutes;
        unsigned seconds;
    };
    struct lap
    {
       unsigned n; // lap number
       time t; // lap time
       lap* next_ptr;
    };

    public:
    Stopwatch();
    ~Stopwatch();
    void right_button(); // corresponds to start/stop/pause
    void left_button();  // corresponds to lap/reset

    private:
    state cur_state;
    std::vector<lap> lapsvec;

}

Stopwatch::Stopwatch() // <--------- Here's where the compiler error is
{
    cur_state = UNSTARTED;
}

/* trivial destructor */
Stopwatch::~Stopwatch()
{
}

int main()
{
    return 0;
}

I reviewed C++ constructors to see if I could figure out the problem. No luck.

A: You need a ; after the class declaration. Since you don't have it, the class is not yet declared when the compiler reaches Stopwatch::Stopwatch(), thus complaining it's a new type.

A: You are declaring a class, which doesn't have a ; on the end:
 ...
    std::vector<lap> lapsvec;

};

That should fix it:


text:
Q: Why can't an excess of electrons or holes by themselves cause current flow? I am a beginner in electrical engineering. Often times (most cases actually), the underlying physics aren't really explained to us and we are just left to assume that it works "because it works." This is never enough for me in classes etc and I always end up doing a follow up of physics side of the spectrum.
My question is, you have a battery with excess electrons built up on the negative lead, and excess holes on the positive lead, why is it that in our universe then connecting a conductive compound (like.. copper) to just the negative lead does not produce current, or vice versa connecting the wire to just the positive lead.
After all, if we move a magnet passed a conductor, there is a tiny induced current. How can the magnet do this, but an excess of electrons or electron holes repelling each other cannot?

A: Physicist Plug
You may want to consider becoming a Physicist, especially if the ambiguity of engineering classes bother you. :)
Electrons and Holes Need Holes or Electrons to Flow to!
Excess electrons or holes do not cause current to flow because those excess electrons (or holes) need someplace to go to. If the electrons/holes don't "see" any places to go to, you don't get current. You need a path for the electrons and holes to flow. (This path also has to be energetically allowable, that is: the electrons need to have enough energy to follow that path. That's why batteries don't randomly spark and arc.)
Batteries Use Entropy to Make a Potential Difference
It just so happens that many batteries use entropy to keep the holes at one end and the electrons at the other. This trick is complicated, and something you should ask the Chemistry Stack Exchange, or at least in a different question here. Entropy keeps the holes and electrons apart, despite the fact that they would electrically come together.
Additionally, batteries also work by allowing ions (not electrons or holes) to flow from one end of the battery to the other. This allows the electrons to flow through the rest of the circuit instead of having them discharge like capacitors. Once again, this is where chemistry and physics meet, and you should try the chemistry stack exchange for more information.
The Conclusion
Since electrons/holes need holes/electrons to flow to, you're safe touching one end of a battery, but in trouble if you hold both ends. If you're holding only one end of the battery, the holes/electrons don't "see" anywhere to go, so they don't go. If you connect the circuit, the holes and electrons "see" each other at opposite ends of the circuits and then flow through it to meet up. You could also get current if you brought something with a lot of holes or electrons near the appropriate end, although it would likely be in the form of a sudden static discharge instead of the smooth flow from a battery.
Maxwell's Equations, Magnets, and Induced Currents
Finally, if you take a look at Maxwell's equations, you'll find an equation with a term that relies on a change in magnetic fields to produce current. More specifically, it's those last two which explain the relations between magnetic fields and electric fields. Since you're starting your career as an electrical engineer, you may want to wait until you have a good grasp of vector calculus before tackling those.

A: If you connect a piece of wire to just one terminal of a battery, the whole wire tends to gain the same potential as that of the terminal it is connected to, this requires an instantaneous current and is achieved very quickly.
The need of connecting the wire to both terminal, is that the internal chemical mechanism of the battery maintains a potential difference across the wire, thus the wire never reaches a desired potential and continues to try to reach it by flowing current.
The moving magnet also provides a stable potential difference between 2 points on a conductor which just by transference of electrons isn't diminished or nullified, because it is controlled by the moving action of the magnet.
Whereas, the excess/lack of electrons, provide a potential differece only till redistribution takes place and whole conductor gets to the same potential.

A: An excess of electrons can cause a current flow.
Imagine two spheres of metal.  One is neutrally charged, but the other is negatively charged with an excess of electrons.  Connect a wire between them, and what happens?  The charge re-distributes itself so that the charge on both spheres is equal.  As this is happening, a brief current of electrons is flowing through the wire, but it stops as soon as the charge is equal.

My question is, you have a battery with excess electrons built up on the negative lead, and excess holes on the positive lead, why is it that in our universe then connecting a conductive compound (like.. copper) to just the negative lead does not produce current

It does produce a current.  It's just very small, because the voltage of the battery and capacitance of the wire are very small, and it's very brief, because there's no path for the current to flow continuously, so after the charge has equalized there's no more current.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL self-referencing ID and selects I have a MySQL table here Starcraft2brackets:
http://i.stack.imgur.com/welPq.png (re-edited so I could edit again, sorry first editor)
uId => reference to a user
id => the index
opponent => reference to id in this table, -2 is considered a bye.
What I am trying to do, is come up with a sql statement that will select a username based upon the uId of a row, as well as select the username of their opponent. The most constructive one I have come up with so far was
SELECT u1.username, if(sc2a.opponent = -2, "Bye", u2.username) as username
FROM Starcraft2brackets AS sc2a
LEFT JOIN users AS u1 ON u1.id = sc2a.uId
LEFT JOIN Starcraft2brackets AS sc2b ON sc2a.opponent = sc2b.id
LEFT JOIN users AS u2 ON sc2b.uId = u2.id

This did give me the correct usernames, however it gave duplicate entries, like so..
http://i.imgur.com/znbAi.png
SELECT u1.username, IF( sc2a.opponent = -2,  "Bye", u2.username ) AS username
FROM Starcraft2brackets AS sc2a
LEFT JOIN users AS u1 ON u1.id = sc2a.uId
LEFT JOIN Starcraft2brackets AS sc2b ON sc2a.opponent = sc2b.id
LEFT JOIN users AS u2 ON sc2b.uId = u2.id
WHERE u1.username < u2.username
OR sc2a.opponent = -2

This gave me the result set I was looking for exactly. Thanks for the help stackoverflow.com.

A: Try this:
SELECT u1.username, if(u1.oppponent = -2, "Bye", u2.username) as username
FROM users AS u1
left join users AS u2 on u1.opponent = u2.id
join Starcraft2brackets AS sc2a on u1.id = sc2a.uId
where u1.uid = ?;


text:
Q: How to load JSON file with date to Google Charts I can't plot data with google charts because of json format data is not properly fitted. I can't figure out how manipulate the data for get the expected format. The data come from a csv file.
I applied file_get_contents() from php, and returns:
[{"Fecha3":1566259200000,"Precio":30.0},
 {"Fecha3":1566345600000,"Precio":6.0},
 {"Fecha3":1566432000000,"Precio":4.0},
 {"Fecha3":1566518400000,"Precio":44.0},
 {"Fecha3":1566777600000,"Precio":80.0},
 {"Fecha3":1566864000000,"Precio":2.0}
]

(shorted for explanation)
So I convert Unix date to the format that Google Charts needs.
When I applied the php code below, the output from getjson.php file is:
{"new Date(2019, 08, 20)":30,
 "new Date(2019, 08, 21)":6,
 "new Date(2019, 08, 22)":4,
 "new Date(2019, 08, 23)":44,
 "new Date(2019, 08, 26)":80,
 "new Date(2019, 08, 27)":2
}

(shorted for explanation)
getjson.php
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
$result = [];
$i = 0;

// Loop to convert the unix date and sort the data
foreach($arr as $item) {
    $uses1 = $item['Fecha3']/1000;
    $uses2 = $item['Precio'];
    $fecha->setTimestamp($uses1);
    $datevar = "new Date(" .$fecha->format('Y, m, d') . ")";
    // I think months have to be months - 1
    $result[$datevar] = $uses2;
    $i++;
}

$jsonTable = json_encode($result);
echo $jsonTable;
?>

Then, I load the file is inside the javascript code:
var jsonData = $.ajax({
     url: "getjson.php",
     dataType: "json",
     async: false
}).responseText;

var data = new google.visualization.DataTable(jsonData);

data.addColumn('date', 'Fecha');
data.addColumn('number', 'Number');

var options = {
    [...]
    hAxis: {   // I put fixed dates for testing
      viewWindow: {
        min: new Date(2019, 0, 1),
        max: new Date(2019, 11, 31)
    },
    [...]

Graph is shown but data isn't.

Javascript console.log(jsonData) shows:

I've read here that format should be:
{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}

But I don't know how to transform on that way!
Possible solutions I tried but I failed:

*

*Convert csv original file to a json style as mentioned above.

*Add javascript code below var jsonData to manipulate it.
I've seen in others examples, different solutions:
data.addRows([
[new Date(2019, 1, 1), 0.2],    [new Date(2019, 2, 1), 0.8],
[new Date(2019, 3, 1), 0.4],    [new Date(2019, 4, 1), 0.4],
]);

I also tried but I never achieve to plot data.
I would appreciate any advice or snippet code.
Really thanks for time and consideration!
:-)

A: the solution you found will work, but does require additional processing on the client.
to pass a real date to google, the json format you found must be used.
it is basically the same date string, without the new keyword.
you can find the reference here --> dates and times using the date string representation
{
  "cols": [
        {"label":"Date","type":"date"},
        {"label":"Charge","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Date(2019, 7, 20)"},{"v":20}]},
        {"c":[{"v":"Date(2019, 7, 21)"},{"v":21}]},
        {"c":[{"v":"Date(2019, 7, 22)"},{"v":22}]},
      ]
}

and yes, the month needs to be reduced by one...
here is an example of the php you could use (not tested)
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);

// create data table, with columns
$table = [];
$table['cols'] = [
    ['label' => 'Date', 'type' => 'date'],
    ['label' => 'Charge', 'type' => 'number']
];

// Loop to convert the unix date and sort the data
$rows = [];
foreach($arr as $item) {
    $uses1 = $item['Fecha3']/1000;
    $uses2 = $item['Precio'];
    $fecha->setTimestamp($uses1);

    // month does have to be - 1
    $datevar = "Date(".$fecha->format('Y').", ".((int) $fecha->format('m') - 1).", ".$fecha->format('d').")";

    // create rows
    $result = [];
    $result[] = ['v' => (string) $datevar];
    $result[] = ['v' => (float) $uses2];
    $rows[] = ['c' => $result];
}

$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
?>

then on the client side, you only need to pass the json to the data table constructor.
var data = new google.visualization.DataTable(jsonData);

you don't need to add columns or rows...
google.charts.load('current', {
  packages: ['corechart']
}).then(function () {

  $.ajax({
    url: 'getjson2.php',
    dataType: 'json'
  }).done(function (jsonData) {

    var data = new google.visualization.DataTable(jsonData);

    var options = {
      hAxis: {
        viewWindow: {
          min: new Date(2019, 0, 1),
          max: new Date(2019, 11, 31)
        }
      }
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart'));

    chart.draw(data, options);

  });
});

note: async: false on ajax has been deprecated and should no longer be used.
use the done callback instead (see above snippet).

A: I've just found a solution!!!
Data has to be presented like:

[{"Fecha":"2019, 08, 20","Precio":30},{"Fecha":"2019, 08, 21","Precio":6},{"Fecha":"2019, 08, 22","Precio":4},{"Fecha":"2019, 08, 23","Precio":44},{"Fecha":"2019, 08, 26","Precio":80},{"Fecha":"2019, 08, 27","Precio":2},{"Fecha":"2019, 09, 09","Precio":48},{"Fecha":"2019, 09, 10","Precio":2}]

It is done by getjson.php file:
<?php
$fecha = new DateTime();
$strJsonFileContents = file_get_contents("datos_nego2.json");
$arr = json_decode($strJsonFileContents, true);
$result = [];
$i = 0;

foreach($arr as $item) { //foreach element in $arr
    $uses1 = $item['Fecha3']/1000; //etc
    $uses2 = $item['Precio'];
    $fecha->setTimestamp($uses1);
    $datevar = $fecha->format('Y, m, d');
    $result[$i]['Fecha'] = $datevar;
    $result[$i]['Precio'] = $uses2;
    $i++;
}

$jsonTable = json_encode($result);
echo $jsonTable;
//echo $strJsonFileContents;

?>

Then, in the javascript code:
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

      var jsonData = $.ajax({
          url: "getjson2.php",
          dataType: "json",
          async: false
          }).responseText;
      var array_datos = JSON.parse(jsonData)
      var longitud_array = array_datos.length;

      var data = new google.visualization.DataTable();
      data.addColumn('date', 'Date');
      data.addColumn('number', 'Charge');

      for (var i = 0; i < longitud_array; i++) {
          console.log(array_datos[i]);
          data.addRow([
          new Date(array_datos[i].Fecha),
          parseFloat(array_datos[i].Precio),
        ]);
      }


text:
Q: When hovering over text, change the text and background image I am new to coding and wrapping my head around utilization of JavaScript it still hard for me.
My problem is that I have like a navigation menu, those  have one word in them. I want that when I hover over navigation menu background of the entire site changes corresponding to the navigation menu item I hovered over, and the navigation item changes it's content from one word to more words.
I tried searching on Google, YouTube and here on stackoverflow of course. I managed to get working code but it feels like a mess and bad practice and I wasn't able to implement good answers to my code or they were using ES5 JavaScript which differentiates from ES6 a lot.
Here are the things I tried:
1 . First thing i tried is to create a function with if statements. Didn't quite work. Probably because of my low understanding of JS.

*I tried then to addEventListener to every navigation menu item individually. And that works, but it's a mess. Just blocks of copy / pasted code.

*I tried then to create a function again and have onmouseover = "function()" inside of HTML but didn't work either.

*Then I tried to do it over CSS but my inexperience started to show again it seems. I wasn't able to succeed in it with :before and :after either.
I have some example code here.

  NAV1
  NAV2
  NAV3
  NAV4

A: Alright figured it out! Took me whole day but I got it!
First of, on JSfiddle where it says JavaScript + No-Library (pure JS) you need to press on the arrow on the side and for LOAD TYPE choose no wrap - bottom of body.
Second, if you have code which has an error which is represented by red color by JSfiddle your whole directory (JavaScript directory in my case) won't run. Error in my code was that I just commented all the code I didn't need at the bottom with /* but didn't close it since I thought it wasn't important.
Third, the solution itself:

// changed whole thing, which was my point. Reduced code from ~50 lines to two functions in 16 lines

// onHover function has a property of i which corresponds to numbers in html on onmouseover and out

// created arrays with IDs, what text and image should be after hovering
// i will correspond to numbers in html which in turn correspond to numbers in arrays

function onHover(i) {
  const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
  const strings = ["MY NAV 1 LONGER", "MY NAV 2 LONGER", "MY NAV 3 LONGER", "MY NAV 4 LONGER"];
  const bckgUrls = ["url('https://picsum.photos/id/2/300/200", "url('https://picsum.photos/id/3/300/200')", "url('https://picsum.photos/id/4/300/200')", "url('https://picsum.photos/id/5/300/200')"];
  var idvar = document.getElementById(array[i]);
  idvar.innerHTML = `${strings[i]}`;
 document.getElementById("bckgimg").style.backgroundImage = `${bckgUrls[i]}`;
 }

// when hovering out from text do same like onHover just the reverse
// return values of navigation menu and background image to original

function outHover(i) {
  const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
  const strings = ["NAV1", "NAV2", "NAV3", "NAV4"];
  var idvar = document.getElementById(array[i]);
  idvar.innerHTML = `${strings[i]}`;
 document.getElementById("bckgimg").style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
 }
#bckgimg{
    background-image: url('https://picsum.photos/id/1/300/200');
    overflow: hidden;
    background-position: center center;
    background-size: cover;
    height: 300px;
}

a {
  color: white;
  text-decoration: none;
}

  NAV1

  NAV2

  NAV3

  NAV4


text:
Q: Link to Magento Admin section in email template Every time a customer makes a new order I need to send an email to the Administrator with the link to the ADMIN order detail section to access directly. For example:
http://www.mydomain.com.ar/index.php/admin/sales_order/view/order_id/19/key/72977b31f74180d25ba185a1cfe86d5a/
How can I achieve this?
Thanks you very much for any help

A: Bcc in the admin email in System > configuration > Sales emails > Orders etc

A: ...
use Magento\Backend\Model\UrlInterface;

...

    private UrlInterface $url;
...
    public function __construct(
        ...
        UrlInterface $url
    ) {
        ...
        $this->url = $url;
    }
...
        $url = $this->url->getUrl('sales_order/view', ['order_id' => $order->getId()])
...


text:
Q: Sharepoint 2010 Foundation Forms authentication I've followed through this(http://goo.gl/1LTX) guide to setup FBA in SP 2010, but I get an error...
Note: I have enable WCF error messages
Cannot get Membership Provider with name wss_fba. The membership provider for this process was not properly configured. You must configure the membership provider in the .config file for every SharePoint process.
Any ideas?
I've checked the config and the default for membership and roles is correct as I have setup in IIS 7.
<membership defaultProvider="wss_fba" />
<roleManager defaultProvider="wss_roles" />

A: You need to add your own membership provider to the web.config file of the SecurityTokenServiceApplication. You can do that either by hand (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebServices\SecurityToken) or by IIS manager (open up SharePoint Web Services and modify the providers in the SecurityTokenServiceApplication webapp).


text:
Q: datetime value in database I updated the datetime to the datebase. It's 5/2/2012. But when I want to show this value from that database into a textbox it will show me : 05/02/2012.
Please help me to solve this problem. I want to show it's value into the textbox like the format has been updated : 5/2/2010
Thanks in advance

A: If you have the data as a DateTime object, then you can format its output using its ToString(string) overload with the format string "d/M/yyyy" or any other format as described here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

A: SELECT CAST(DATEPART(MM,GETDATE()) AS VARCHAR(2))+'/'
+CAST(DATEPART(DD,GETDATE()) AS VARCHAR(2))+'/'
+CAST(DATEPART(YYYY,GETDATE()) AS VARCHAR(4))

A: Try this :
Textbox1.Text=datevalue.ToString("MM/dd/yyyy");

A: Try this ToString("d/M/yyyy") to give desired format.
If you can show me your code then I can help you more.

A: You can use ToString("MM/dd/yyyy") while assigning the value.
If your textbox is Textbox1 and your date value is stored in DateTime object datevalue then you should do it like this.
Textbox1.Text=datevalue.ToString("MM/dd/yyyy");

A: When you store this data into sql server as datetime type then the original format is lost.  However, if you want to show the data without leading 0's then you can do this for your textbox.
mytextbox.Text = dt.Month.ToString().TrimStart('0') + "/" + dt.Day.ToString().TrimStart('0') + "/" + dt.Year.ToString()

A: It's generally poor practice to go mucking with your data with a complex query or pre-format the data before reaching your application as you lose flexibility with the results.
The data coming from SQL is properly formatted as a generic DateTime stamp - allow the application to massage it for display purposes, as @Chris-Sinclair suggests with the link to examples.
The best aproach, if using WPF, is to allow the UI element to format the text as it sees fit, that way the content of your class instances remains unmodified. It's still a DateTime object so you can do DateTime "math" or other manupiations without losing the full value.
Here is an example from elegantcode.com where the WPF UI element determines it's format:
<TextBlock Text="{Binding Date, StringFormat={}{0:MM/dd/yyyy hh:mm tt}}" />

For your speficif purpose the correct line would read
<TextBlock Text="{Binding Date, StringFormat={}{0:M/d/yyyy hh:mm tt}}" />

A: For doing that the best way is saving datetime into the database as a string. then after retrieving the string I can convert that to datetime. and it will show the correct format.


text:
Q: Can openID and facebook connect be used to get user email address? Bonus question: Anybody knows how to do it using ruby-openid gem?
Thanks!

A: It is possible with both, but with some limitations. OpenID provider needs to support either simple registration or attribute exchange. For example Yahoo supports sreg and Google supports AX. Yahoo will send email only to verified websites. Google asks for user's premission before sharing email with openid relying party, if user declines login will fail.
To get user's email from Facebook your application should first ask for extended permissions (see http://developers.facebook.com/docs/authentication/permissions and http://developers.facebook.com/blog/post/355).
This is pretty common question, so you should be able to google up ton of info on this subject.

A: No, I don't think so.
And any attempts to do so (without the user's permission) would certainly be considered malicious and unethical.


text:
Q: Google sheets - Optimisation of function to create notes in a range (very slow) I have a script to create Notes on cells based on their value, but the process is very slow and my sheet has 15000 rows. Is it possible to reduce the delay by optimizing the script ?
PS : I use spreadsheet with french parameters.
function InsertCellsNotes(){

  var plage = SpreadsheetApp.getActiveSpreadsheet().getSelection().getActiveRange();
  var Notes = plage.getValues();
  var NB_lines = Notes.length;

  for (var i=1; i<NB_lines+1; i++){  // ajouter +1 !
    var myCell = plage.getCell(i, 1);
    var cellValue = Notes[i-1];

    if (cellValue == "#N/A" || ""){   }
    else {  myCell.setNote(cellValue); }
 }
}

An example of the sheet : https://docs.google.com/spreadsheets/d/1lu7dEoyO2NDHV4phXeh8DAAkbBuQG5EQWwMA6SJDP1A/edit?usp=sharing

A: Explanation:
Two tricks:

*

*Avoid unnecessary api calls when possible. You are iteratively using methods that interact with the spreadsheet file and that causes extreme delays. Read best practices.

*When you use null as an argument for setNote, no note is set. We can take advantage of this and construct an array by using the map method. Namely, if the value is #N/A or blank "", assign null to the element, otherwise take the value of the cell:
var notes = rng.getValues().flat().map(v=>[v=="#N/A" || ""?null:v]);
This will allow you to get rid of the for loops but also create an array that can directly be used in the setNotes function: rng.setNotes(notes);
Solution - active range:
Select (with your mouse) a particular range and insert notes (depending on the condition):
function InsertCellsNotes(){
   var rng = SpreadsheetApp.getActiveRange();
   var notes = rng.getValues().flat().map(v=>[v=="#N/A" || ""?null:v]);
   rng.setNotes(notes);
}

Solution - predefined range:
This is a more static approach. You define a particular sheet "Sheet1" and for all the cells in column B (until the last row with content of the sheet) you insert notes (depending on the condition):
function InsertCellsNotes(){
   var plage = SpreadsheetApp.getActive().getSheetByName("Sheet1");
   var rng = plage.getRange(1,2,plage.getLastRow(),1);
   var notes = rng.getValues().flat().map(v=>[v=="#N/A" || ""?null:v]);
   rng.setNotes(notes);
}


text:
Q: How to enable copy and paste for OSX menu extra I am writing a menu extra in Swift that brings up a window for the user to enter some data. It would be handy to have the copy an paste keyboard shortcuts for this window.
I have added an edit submenu to my menu extra so that I and defined the keyboard shortcuts. I have linked them to methods in my controller, but when type the shortcut command such as command-v, it does not call the associated method.
How should I go about enabling the shortcuts for the menu extra?

A: I don't know if this is the right way to do it, but I managed to get it working based on the approach in this post:
Cocoa Keyboard Shortcuts in Dialog without an Edit Menu
I created a similar MyApplication class and also linked the copy, paste etc actions of first responder to my menus.
I had some trouble getting the syntax right for the latest swift. Here is the code I used:
import Cocoa

class MyApplication: NSApplication {
    override func sendEvent(event: NSEvent) {
        if event.type == NSEventType.KeyDown {

            if ((event.modifierFlags.rawValue) & (NSEventModifierFlags.CommandKeyMask.rawValue) > 0) {
                switch event.charactersIgnoringModifiers!.lowercaseString {
                case "x":
                    if NSApp.sendAction(Selector("cut:"), to:nil, from:self) { return }
                case "c":
                    if NSApp.sendAction(Selector("copy:"), to:nil, from:self) { return }
                case "v":
                    if NSApp.sendAction(Selector("paste:"), to:nil, from:self) { return }
                case "z":
                    if NSApp.sendAction(Selector("undo:"), to:nil, from:self) { return }
                case "a":
                    if NSApp.sendAction(Selector("selectAll:"), to:nil, from:self) { return }
                default:
                    break
                }
            }
        }
        return super.sendEvent(event)
    }
}


text:
Q: android resource specifiers - avoiding image duplication I am making a game for android which uses a large number of images.
I have a set of images that I would like to use for 480x800 ish resolutions (i.e. large devices or normal hdpi/xhdpi devices). Another set of images I should like to use for normal mdpi, normal ldpi and small devices of any dpi.
My problem is this. I could copy the images into many different folders which would give me the desired functionality. However, this would make my .apk too large. I could also create resource aliases using xml. However, with the amount of images, I'm looking at having to create hundreds of xml files manually.
Any ideas on how to accomplish the following more conveniently? I noticed they have introduced new resource specifiers that would solve my problem in API level 13, but I need this to work on android 2.1+

A: There are resource specifiers in android 2.1+ they were just changed to handle different parameters that better suited android becoming both a tablet and phone platform.
The old specifiers were drawable-hdpi, drawable-mdpi, and drawable-ldpi.
drawable-xhdpi was added to support larger screen sizes in Android 2.2.


text:
Q: Dynamic Gradle compile dependencies for different buildConfigFields In my project, I'm using different configurations based on different buildConfigFields, and for some of them I don't use certain dependencies.
So I don't want to have certain dependencies in specific configs, depending on the buildConfigFields.
How can I do something similar to the following?
dependencies {
    if (buildConfigField("String", "WHICH_MESSAGE_ENABLED") == "VALUE") {
        compile "xxx.yyy.zz:1.0"
    } else {
        provided "xxx.yyy.zz:1.0"
    }
}

A: You can use the following in defaultConfig:
def mBuildConfigFields

android {
    defaultConfig {
        mBuildConfigFields = buildConfigFields
    }
}

dependencies {
    if (localBuildConfigFields.get("KEY").value == "VALUE") {
        compile "xxx.yyy.zz:1.0"
    } else {
        provided "xxx.yyy.zz:1.0"
    }
}

Hope this helps.


text:
Q: statistics metrics I'm using a confusion matrix and the metrics that we can derived from that (sensitivity, specificity etc).
I've calculated the False Negative Rate (FN/TN+FN) and I'm in a big discussion with my colleague who thinks that the FN/(TN+FN+TP+FP) is more relevant and representative.
I couldn't find this formula in the literature.
Is it something wrong? Could that lead to fallacy? Any argument against or for it?
Thank you for your help!

A: The False Negative Rate is FN/(FN+TP) and not FN/(TN+FN) which is the complement of the False Omission Rate.
Your colleague's formula is just the number of false negatives divided by the total number of observations. The confusion matrix itself seems more meaningful. What does representative mean here?
When it comes to fallacies, you can come up with something to make a metric look better than it actually is. Just get a data set with almost no positives or no negatives and check the formulas.
The relevance of your metric depends on the problem at hand, e.g. FNR interpreted as "no virus" when you actually do have the virus. It might be helpful to understand the underlying cost distributions with respect to misclassifications as well.


text:
Q: How do I invoke a MethodCall with another MethodCall on the first MethodCall's first argument? I am attempting to implement this:
@Override // java.util.Function
public Object apply(final ThingWithParameters thing) {
  return bozo(thing.getParameters());
}
private Object bozo(final Object[] parameters) {
  // Use magic ByteBuddy stuff to "spread" the parameters out
  return this.object.baz(parameter0, parameter1); // ...where these are the first two parameters in the array
}

I've tried:
builder = builder
  .defineMethod("bozo" ...)
  .implement(MethodCall.invoke(bazDescription)
             .onField(thisObjectFieldDescription)
             .withArgumentArrayElements(0, 2))

  .implement(parameterizedTypeFunctionThingWithParametersObject) // Function<ThingWithParameters, Object>
  .intercept(MethodCall.invoke(bozoDescription) // implement apply(ThingWithParameters thing): call bozo()...
             .withMethodCall(MethodCall.invoke(getParametersMethodDescription) // ...with the result of invoking getParameters()...
                             .onArgument(0))); // ...on thing (except see below)

…but this does not work.  The error message is deeply weird and leads me to believe that argument 0 is not referring to thing, but to something else entirely (maybe the receiver type somehow?).  Here is a snippet from the stack:
java.lang.IllegalStateException: Cannot invoke public java.lang.Object[] com.foo.ThingWithParameters.getParameters() on java.util.function.Function<? super V, ? extends com.foo.ThingWithParameters>
    at net.bytebuddy.implementation.MethodCall$TargetHandler$ForMethodParameter$Resolved.toStackManipulation(MethodCall.java:2530)
    at net.bytebuddy.implementation.MethodCall$Appender.toStackManipulation(MethodCall.java:3548)
    at net.bytebuddy.implementation.MethodCall$ArgumentLoader$ForMethodCall.toStackManipulation(MethodCall.java:1687)
    at net.bytebuddy.implementation.MethodCall$Appender.toStackManipulation(MethodCall.java:3545)
    at net.bytebuddy.implementation.MethodCall$Appender.apply(MethodCall.java:3509)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyCode(TypeWriter.java:708)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:693)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:600)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:5660)
    at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:2166)
    at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:232)

Note that while my proxy class does in fact implement Function, it actually implements Function<ThingWithParameters, Object>.  And, I never define V.  I'm assuming ByteBuddy does this internally somewhere.
What is the recipe I should be using?

A: The Function class defines multiple methods, some of them as default methods. Byte Buddy will attempt to implement all those methods by your Implementation where it works for the apply method but fails for others. Therefore, rather define an explicit matcher to indicate the method you'd like to implement.


text:
Q: Why is the notification area showing no internet access when there is no connection with any network either Wired/Wireless Usually when I power on the laptop near the notification tray for the Internet access it will generally show a small red colour cross.This turns Ethernet if I plug an Ethernet cable or turns into WiFi if there is a WiFi connection connected.
[Update]:-
This is what as expected when the windows boots(WiFi is off,No Ethernet connection etc)

This is what when the connection is established to WiFi.

But since few days it is showing a No internet access.I don't have any internet connection to either a WiFi or the Ethernet cable.
When I try to connect using the WiFi hotspot it is able to connect to the Android device but instead gives a limited connection.
[Update]:-
This is how it shows in the notification area when the Windows boots on my laptop and when I point the icon it says no internet access by default.( even when WiFi is turned ON,no Ethernet connection)

What is your question?
Why is the notification not showing the default red cross sign on the network notification as it should when I don't have any connection either through the LAN/WiFi
What do you want to happen?
Why can't the notification icon for the Network show the default red coloured cross when not connected and show the simple WiFi when connected to a WiFi network
Software specifications:-
Windows 7 Ultimate 64 bit
Hardware specifications:-(as seen from the device manager)
Broadcoam virtual wireless Adapter
Dell Wireless 1701 802.11 b/g/n
Microsoft Virtual WiFi  Miniport adapter
Realtek PCIC FE Family controller
Virtual Host only Ethernet Adapter

Things tried:-
As per the above mentioned post i have tried the route command in the
  cmd prompt and it gave the following
route ADD 3ffe::/32 3ffe::1 route CHANGE 157.0.0.0 MASK 255.0.0.0
  157.55.80.5 METRIC 2 IF 2 route DELETE 157.0.0.0 route DELETE ffe::/32
I have spoken with the technical team of the manufacturer and he says
  me that i need to do a clean format(Format only the C:\ drive)
  [Update]:-
  Have done the complete System Anti-virus scan and no viruses,worms
  were detected.The system is running clean

A: Try uninstalling and re installing your networking drivers or rolling them back, connect to a AP then flush your dns, cmd; "ipconfig/flusdns" I believe then do a ipconfig/release and ipconfig/renew in cmd as well, reset the access point as well (AP).

A: I had a similar thing a few years ago, the quickest fix for me was to open up device manager from your Windows Control Panel, then under the "Network Adapters" section right click and uninstall the LAN/WIFI adapters (just make sure you DON'T tick the delete drivers during the uninstall process).  After the adapters have been removed click the "Action" menu and then "Scan for Hardware Changes", Windows should then automatically pick-up the adapters and reinstall them using the existing drivers.  This process tends to reset any customisations or corrupt configuration affecting how the adapters operate.


text:
Q: jQuery 18n plugin I've got a jQuery i18n plugin init:
jQuery.i18n.properties({
    name : 'appsConstants',
    path : '/gadgets/',
    mode : 'both',
    language : 'en'
});

How to take out the language variable into browser line like a parameter?

A: You have several options here:

*

*Read the language from the URL path or an URL query parameter by parsing window.location

*Set the language in a cookie

*Generate your init Javascript dynamically on the server and set the language there (storing it in the session on the server).

A: This article from Scott Hanselman talks about globalization (cultures/locale)
http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx
I've used that for making my jQuery aware of the users culture (for use with a datepicker amongst others) I also downloaded the i18n jQuery plugin and registered that.
I went with the "Slightly Less Cheesy - Meta Tag" solution for "detecting" locale and registered a
<meta name="accept-language" content="en-US">

in the head section, then I could utilize that tag in my jQuery to figure out what locale/language to use.
The article is slightly outdated so some of the javascript needs an update here and there as an example Globalization.js has changed from $.global. to Globalize.
Bits and pieces like that you need to update to get it all working.


text:
Q: PHP reload issue I have the following php script:
<?php

$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];
$submit = $_REQUEST['submit'];
$to = "torayevagajan@gmail.com";

if(isset($submit))
{

    function isValidEmail($email)
    {
        return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
    }

    if(!empty($name) && !empty($email) && !empty($message) && isValidEmail($email))
    {
        $text = "From: ".$email."
Name: ".$name."
".$message;
        if(mail($to, $subject, $text) && !empty($submit)){
            echo "";
            }
        else{
            echo "";
            }
    }elseif(empty($name) || empty($email) || empty($message))
    {
        echo "";
    }else echo "";

    unset($submit);
}
?>

I have the following problem, after submitting details to contact php, whenever I want to refresh page, it tries again and again send mail, I mean it tries to run script, even I unset($submit); how can fix this?

A: The solution to this problem is called Post Redirect Get
You can look for a sample code solution here  :
Simple Post-Redirect-Get code example

A: 1) You shouldn't use $_REQUEST as it opens some security issues for your application. Use $_POST instead.
2) Why do you need to refresh the contact page? An alternative is to have a separate script for processing the form submission and then redirect back to the original contact page upon completion.

A: Dude refresh means send the request again which will consist the varaiables also to be resent..
That's why many websites use such caution to not refresh after submit...
But there is a solution for that..
Redirect the script to the same page after you send the mail..
header('Location: http://www.example.com/contact.php');

That way it will resend the page request to the same page but this time with no variables..
Or send them to another page after successful send of mail..

A: When you refresh the page, the browser resends the POST data from your form. Unsetting $submit does not do you any good, as it is being set again every time you execute the script. While I'm not sure what your goal is with refreshing the page, you would have to write code to refresh the page after script has been done. (Unless you want to use sessions to detect if that form has been submitted.)
Anyway, this would work to refresh. Note that you cannot have any output (even whitespace) before the headers.
<?php header('Refresh: 0'); ?>

You would of course have to have this when $submit is set, and not otherwise.

A: you unset the var $submit, but not the $_REQUEST['submit'].
so on every reload you set $submit again with the data still stored in the $_REQUEST Array :)


text:
Q: CSS opera problem with  tag
CSS:
select {
float:left;
background:url(../images/bg_search_sml.png) top left repeat-x;
border:none;
width:200px;
font:15px Arial, Helvetica, sans-serif;
letter-spacing:-1px;
padding:7px 0 10px;
}

option {
height:auto;
outline:none;
border:none;
}

Why only opera and IE6 has problems with this  tag. What i must do in opera and IE6 that  tag will work like in IE7,8 or FF. Code forr CSS is up.
regards

A: Styling form elements consistently with pure CSS across every browser is more or less impossible. The reason is that, to some degree, elements like form controls and scrollbars are considered part of the operating system (Windows, OS X, etc.) interface. After that, the way they look is further determined by each individual browser. Each browser then allows only some aspects of some form controls to be manipulated with CSS. They do not implement this in a standard way across each browser.
As jcubic mentioned in a comment, you can use JavaScript (like Dojo Toolkit does) to create custom form elements. However, you need to be aware that with <select> elements, this is usually accomplished by replacing the <select> with a text <input>. Then JavaScript is used to add functionality that attempts to mimic a real <select>. While this sounds fine in theory, the functionality never fully matches a real <select> and tends to create usability concerns because these custom elements don't quite behave the way users expect a <select> to work.
The best advice you'll ever get is just find a way to incorporate the default form control appearance into your design.


text:
Q: With Gravity Forms Product Add-ons + Woocommerce, is possible to create an add to cart link? Here's the scenario:
I have a product using gravity forms product add-ons with prepopulated fields in the URL.
Example: website.com/product/book/?title=BookTitle&price=9.99
When a user clicks the link, the fields are prepopulated into the product so when the user clicks the add to cart button on the product page, the details are injected into the product and displayed on the cart & checkout pages. This part works well.
Is it possible to create an add-to-cart link that includes the URL parameters?
Example: website.com/cart/?add-to-cart=20762&title=BookTitle&price=9.99
I know this probably doesn't work like this, but ideally, I want a simple add to cart button that adds the product to the cart and also includes the URL parameter information.


text: Q: How do I prevent branch merge for bitbucket or github in a specific time range? for example, I don't want any merge happen in Friday. Are there any rules to apply these mandatory restrictions rather than manual judgment?


text:
Q: HttpContext.Current.User.Principal vs WindowsIdentity.GetCurrent() What's the difference in an asp.NET environment with Windows Authentication and Identity Impersonation turned on, between HttpContext.Current.User.Principal and WindowsIdentity.GetCurrent()?

A: According to this forum on WindowsIdentity.GetCurrent().Name vs. User.Identity.Name:

*

*User.Identity.Name represents the identity passed from IIS.

*WindowsIdentity.GetCurrent().Name is the identity under which the thread is running.

Depending on your app's authentication settings in IIS, they will return different values:
| Anonymous | Impersonate | User.Identity.Name | WindowsIndentiy.GetCurrent()  |
|-----------|-------------|--------------------|-------------------------------|
| Yes       | True        | Empty String       | IUSR_<machineName>            |
| Yes       | False       | Empty String       | NT Authority\Network Service  |
| No        | True        | domain\user        | domain\user                   |
| No        | False       | domain\user        | NT Authority\Network Service  |

Legend:

*

*Where domain\user will show up as:

*

*domain\user for Active Directory

*machineName\userName for local account

*Where NT Authority\Network Service will show up as:

*

*NT Authority\Network Service for Windows Server or ASP.NET

*machineName\ASPNET_WP for Windows XP


text:
Q: Sort and parse multi level of JSON with recursion It's my first time when I am trying to use recursion in javascript and I need some help to understand it.
I have this JSON with multi levels of "subcategories"
    var STORE_CATEGORIES = [{
        "Id":"1",
        "Name":"One Parent",
        "Sort":"0",
        "Subcategories":[
            "Id":"1",
            "Name":"One Subcategory",
            "Sort":"0",
            "Subcategories":[{
                "Id":"1",
                "Name":"One SubSubcategory",
                "Sort":"0",
                "Subcategories":[{
                     .....
                }]
            }]
        ]},
        "Id":"2",
        "Name":"Two Parent",
        "Sort":"1",
        ....
    ]}

and this is my script until now:
function sortJSON(json, output, prop, asc){
    json = json.sort(function(a, b){
        if(asc){
            return (a[prop] > b[prop]) ? 1 : ((a[prop]  a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
        }
    });
    showJsonResults(json, output);
}
function showJsonResults(json, output){
    var parent = output;
    var list = $('
').appendTo(parent);
    var html = '';
    for (var i = 0; i < json.length; i++) {
        var result = json[i];
        html += '
'+result.Name+'';
        if(result.Subcategories){
            html += '
';
            for (key in result.Subcategories) {
                var sub = result.Subcategories[key];
                html += '
'+sub.Name+'';
                html += '
';
            }
            html += '
';
        }
        html += '
';
    }
    list.append(html);
}

Function to call:
sortJSON(STORE_CATEGORIES, $('.categories div'), 'Sort', true);

Now I am getting only categories + subcategories, but there are more subcategories of subcategories.
How can I use recursion here?
Thanks.

A: You need to alter your functions slightly:
    function sortJSON(json, output, prop, asc){
        json = json.sort(function(a, b){
            if(asc){
                return (a[prop] > b[prop]) ? 1 : ((a[prop]  a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            }
        });
        var parent = output;
        var list = $('
').appendTo(parent);
        var html = showJsonResults(json);
        list.append(html);
    }
function showJsonResults(json) {
   var html = '';
   $.each(json, function(i, result) {
     html += '
' + result.Name + '';
     if (result.Subcategories.length) { //if you have subcategories call the function again
       console.log(result.Subcategories[0].Name);
       html += '
' + showJsonResults(result.Subcategories) + '
';
     }

     html += '
';
   });
   return html
 }
}

demo:https://jsfiddle.net/neLbgp4r/1/


text:
Q: I want to learn javascript I want to learn javascript soon and I would like to ask for your opinion about the online sites where I could start: Udemy, Pluralsight, Codecademy ...
Which one is better? I attended a training in Angular on Pluralsight and I can say that I like it but I would like to try something new if it is worth it.

A: I used PluralSight and I can say it was worth it. In my opinion, it only matters when you think you will succeed in learning. I recommend Udemy because you can purchase a Javascript course that you will have at your disposal all your life.
If you use Pluralsight you have to pay a monthly fee, but you have access to all the courses.


text:
Q: How do I change IE8 settings for terminal (rdp) users in Windows Server 2003 I have a terminal server (Windows 2003) serving 10-15 users. I have a list of internet/intranet secure sites configured in administrator account for which security level is set to low.  However when a remote user logins in to a session, the settings for IE are set to default in the profile and wouldn't let the user change them.  How can I make changes to IE8 for these users and make them effective for all the RDP users?

A: I would use Group policy and the ADM templates from the IE8 deployment kit.
http://technet.microsoft.com/en-us/library/cc985341.aspx
http://technet.microsoft.com/en-us/library/cc985351.aspx


text:
Q: Наложение background только на текст Есть текст. На него надо наложить background так, чтобы он был только на тексте. То есть все, что не текст, было прозрачным. Думаю через svg сделать наложение картинки на текст, но не знаю, как сделать все прозрачным, кроме букв. Сложность в том, что на каждой букве должны быть не разные картинки, а одна цельная

A:

svg {
  width: 6em;
  height: 1.5em;
  font: 900 500%/1.2 'Arial Black', sans-serif;
}

text {
  fill: url(#sea);
}
<svg>
  <defs>
    <pattern id="sea" patternUnits="userSpaceOnUse" width="544" height="340" >
      <image xlink:href="http://i01.i.aliimg.com/wsphoto/v0/32244527293/F0050-24inch-x38-inch-Underwater-World-Coral-Sharks-Turtle-Moray-Eel-Fish-Poster-on-Waterproof-Canvas.jpg" width="544" height="340" />
    </pattern>
  </defs>
  <text y="1.2em">Ваш текст!!!</text>
</svg>

A: Обратите внимание на проблему кроссбраузерности.

* {
  margin: 0;
  padding: 0;
}

div {
  font: 900 normal 450%/100vh sans-serif;
  text-transform: uppercase;
  text-align: center;
  background-image: url("https://i.stack.imgur.com/zN1F6.jpg");
  background-size: cover;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

Lorem ipsum


text:
Q: ASP.net Imitate Slow Connection Speed Our web application is meant to be run on remote locations with very slow internet speed. We are considering various factors to reduce application overheads. This question is only related to see how our application would work on slow bandwidth.
We are still on development, we would like to be able to browse our web application on speed around 32kbps and 128 kbps on an internet browser, preferably firefox.
Is this possible with firefox to browse a website with max "x" speed?

A: I develop primarily in Firefox, so I use the following plugin to simulate low bandwidth situations:
http://www.uselessapplications.com/en/Application/FirefoxThrottle.aspx

A: If you're using Firefox and have permissions to install plugins, you could use Firefox Throttle
There are other programs out there where you basically set up a local proxy, send all your connection through it, and have it slow your connection down.
UPDATE
Finally found the old program we used to use: Netlimiter


text:
Q: vector subscript out of range C++ (substring) So I'm having this problem with substrings and converting them into integers. This will probably be an easy-fix but I'm not managing to find the answer.
So I receive this string "12-12-2012" and i want to split it, convert into integers and call the modifications methods like this:
string d = (data.substr(0,data.find("-")));
setDia(atoi(d.c_str()));

But it gives me the error mentioned in the title when I try to comvert into an integer.
EDIT:
Turns out that the string doesn't actually contain a '-' but this is really confusing since the string in the parameter results from this : to_char(s.diaInicio,'dd-mm-yyyy')
More information: I used the debugger and it's making the split correctly since the value that atoi receives is 12 (the first split). But I don't know why the VS can't convert into an integer even though the string passed is "12".

A: This code is not save in the sense that it fails when data does not contain a -.
Try this:
std::size_t p = data.find("-");
if(p == std::string::npos) {
    // ERROR no - in string!
}
else {
    std::string d = data.substr(0,p);
    setDia(atoi(d.c_str()));
}

A: Please duplicate the problem with a very simple program.  If what you say is correct, then the following program should also fail (taken from Danvil's example, and without calling the unknown (to us) setDia() function):
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
   string data = "12-12-2012";
   std::size_t p = data.find("-");
   if(p == std::string::npos) {
    // ERROR no - in string!
   }
   else {
       std::string d = data.substr(0,p);
       atoi(d.c_str());
    }
}


text:
Q: Parse.com filtering Push Notification as "multi server" first I apologize for my poor English. I'm just approaching to Parse.com and I'm developing a "multi-server" application that allows me to send notifications filtered by "server".
I tried two solutions but both have some issue all connected to the fact that when i start my Application i don't know which "server" the user will choose.
Idea 1 - Real Multi Server

*

*I create manually n Parse.com servers, totally separated each other

*I store all my servers keys in objects like [Name, AppID, clientKey]

*My application lists the name attribute

*The user choose his server

*I start new Activity in which onCreate() I initialize Parse like:
String appID = getAppID();
String cKey = getKey();
Parse.initialize(this, appID, cKey);
ParseInstallation.getCurrentInstallation().saveInBackground();

*(If he want to change server i simply clean my App data and re-initialize Parse with the new keys)

*Everything works fine until I try to send a Push Notification when the the app is closed (not active and not in background) when I have a NullPointerException due to initialization of Parse not yet called.

Idea 2 - Simulated Multi Server

*

*I create manually ONE Parse.com server

*All tables have a new Column like (just as example) uniqueIdServer

*I initialize Parse in Application like:
public class MyApplication extends Application {
@Override
public void onCreate() {
    Parse.initialize(this, "ThisTimeIHaveJustOneAppIDIt'sEasy", "SameHere");
    ParseInstallation.getCurrentInstallation().saveInBackground();
    super.onCreate();
}}

*I display my old list but this time is just [name, uniqueID]

*The user choose his "server"

*Now i can easy filter my data with my new column and i have no problem when my app is closed because Parse will call his initializer by his own

*But i don't know how i can filter Push Notification just for some uniqueId

*I tried using channels and than sending Push only at that channel:
    List<String> channels = new ArrayList<>();
channels.add(getUniqueID());
ParseInstallation install = ParseInstallation.getCurrentInstallation();
install.put("channels", channels);
install.saveEventually();

*But is always the same, i dont know at "Application time" what my user will choose so my getUniqueID() will bind "null" or similar and even worse i don't know how can i change channel (atm i can only if i uninstall my app)
Really thanks at all, any help will be really appreciated.

A: Using your idea 2, installations can be given custom attributes and queried exactly as any other objects.  Moreover, pushes can be made with an installation query.  See "advanced targeting" in the docs.
Minimally, you can say something like this:
var query = new Parse.Query(Parse.Installation);
query.equalTo('uniqueIdServer', 'serverId123');

var data = { alert: "Ciao users of serverId123!" }

Parse.Push.send({ where: query, data: data }).then(function() {
    // this code runs after the push has been sent to APN
}, function(error) {
    // this code runs in case of an error
});


text:
Q: general update pattern D3 - repainting unchanged nodes I am making a d3 chart based off of time series data. I would like to plot moving averages based off a time window specified by the user in real time.
All lines will share the same dataset.
I am implementing the general update pattern (I believe), however, when I change the dataset, the update doesn't occur unless I call my update function explicitly.  This works, however, a node is created for each element in the array (creating a new DOM element over the old one) as opposed to just adding the updated element. I feel I am misunderstanding something fundamental about D3, or perhaps about javascript itself.  Here is a minimal working example of my code:
In brief, my chart has a setInterval method that adds to the dataset and updates all the lines on the chart. Each line shares the chart data, but will transform the data in different ways.
window.onload = function() {
  let mychart = chart( '#chart' );
  let props1 = {
    'className': 'line-1',
    'Color': 'red',
    'y': function( d ) { return d + 25; }
  }

  let line1 = line( mychart, props1 );

  mychart.addPlot( line1 );
  mychart.stream();
}

//need to find best way to share data across all indicators
var chart = function(svg_id) {
  let data = [ 0, 1, 2, 3, 4, 5];
  let plots = [];
  let svg = ( function(  ) {
    return d3.select( svg_id + '-container' ).append( 'svg' )
      .attr( 'height', 500 )
      .attr( 'width', 1000 )
      .attr( 'id', svg_id.replace('#', '' ))
  })();

  let xscale = d3.scaleLinear()
                  .domain( [0, 100] )
                  .range( [10, 990] )

  let addPlot = function( plot ) {
    plots.push( plot );
  }

  let stream = function() {
    setInterval( function() {
      data.push( Math.random(0, 1) * 100);
      for( var i = 0; i < plots.length; i++ ) {
        plots[i].update();
      }
    }, 1000);
  }
  return {
    'svg': svg,
    'xscale': xscale,
    'data': data,
    'addPlot': addPlot,
    'stream': stream,
  }

}

var line = function( chart, props ) {
  let data = chart.data;
  let xscale = chart.xscale;
  let svg = chart.svg;

  let buildLine = d3.line()
    .x( function(d, i ) { return xscale( i ) + i*1; })
    .y( function(d) { return props.y( d ); })

  let update = function() {
    let line = svg.selectAll( props.className ).data( data );

    line.enter()
      .append( 'path' )
      .attr( 'stroke', props.Color )
      .attr( 'stroke-width', 2 )
      .attr( 'class', props.className )
      .attr( 'fill', 'none' )
      .merge( line )
        .attr( 'd', buildLine( data ))

    line.exit().remove();
  }

  return {
    'update': update,
  }
}

I found plenty online about nodes not being added, but nothing about d3 repainting on every iteration, and adding nodes every iteration. Thank you.

A: I'm not sure, but perhaps you can take a look at this: Key functions
As second argument of .data( data ) you can provide a function which uniquely identifies your data points. Like .data( data, function(d) { return d.someUniqueId; })
D3 can use this key to update DOM elements instead of regenerating them, as I understand it correctly from Mike Bostock's post.

A: I solved this using this tutorial on d3 paths https://www.dashingd3js.com/svg-paths-and-d3js . Key point is selectAll is not appropriate for paths since a line is only one 'path' element, therefore append is all that is necessary. I am removing the line using jquery, so still a bit hacky as I'm sure D3 has a way to do this. But here is an updated  init and update functions.
  let init = function() {
    svg.append( 'path' )
      .attr( 'd', buildLine( data ))
      .attr( 'stroke', props.Color )
      .attr( 'stroke-width', 2 )
      .attr( 'class', props.className )
      .attr( 'fill', 'none' )

  }

  let update = function( newdata ) {
    data.push( newdata );
    $( '.' + props.className ).remove();
    init();


text:
Q: QTextEdit crash on appending text I am developing an application which run scripts and display scripts results in a "Shell Window". This window contains a QTextEdit where all script output is appended.
The script may append data to two QTextStream: out and err.
To let the QTextStream use the QTextEdit as an output I used the TextEditIODevice class (source below).
The script is run in a separated thread in the VirtualMachine class (source not provided).
My problem is that the program randomly crash while appending data to the QTextEdit.
Here is a screen shoot of the crash:

Does someone already had this problem ? Do you know how to solve it ?
Thanks for your help solving this !

TextEditIODevice
Header file
class TextEditIODevice : public QIODevice
{
    Q_OBJECT

public:
    TextEditIODevice(QTextEdit * qTextEdit, QColor color, QObject * parent);

    virtual ~TextEditIODevice();

protected:
    qint64 readData(char *data, qint64 maxlen);

    qint64 writeData(const char *data, qint64 len);

private:
    /**
     * @brief Pointer to QTextEdit
     */
    QPointer<QTextEdit> textEdit;

    /**
     * @brief Text color
     */
    QColor color;

    /**
     * @brief Shared pointer to QTextEdit associated mutex
     */
    QSharedPointer<QMutex> mutex;

    /**
     * @brief Storage for QTextEdit associated mutexes
     */
    static QMap<QPointer<QTextEdit>, QSharedPointer<QMutex>> mutexes;
};

Source file
QMap<QPointer<QTextEdit>, QSharedPointer<QMutex>> TextEditIODevice::mutexes;

TextEditIODevice::TextEditIODevice(QTextEdit * qTextEdit, QColor color, QObject * parent) :
    QIODevice(parent),
    textEdit(qTextEdit),
    color(color)
{
    open(QIODevice::WriteOnly | QIODevice::Text);

    qRegisterMetaType<QTextCharFormat>("QTextCharFormat");
    qRegisterMetaType<QTextBlock>("QTextBlock");
    qRegisterMetaType<QTextCursor>("QTextCursor");

    if(mutexes.contains(textEdit))
    {
        qDebug() << QString("[%1] Reuse previously created mutex").arg(textEdit->objectName());
        mutex = mutexes[textEdit];
    }
    else
    {
        qDebug() << QString("[%1] Create mutex").arg(textEdit->objectName());
        mutex = QSharedPointer<QMutex>(new QMutex());
        mutexes.insert(textEdit, mutex);
    }
}

TextEditIODevice::~TextEditIODevice()
{
}

qint64 TextEditIODevice::readData(char *data, qint64 maxlen)
{
    Q_UNUSED(data);
    Q_UNUSED(maxlen);
    return 0;
}

qint64 TextEditIODevice::writeData(const char *data, qint64 len)
{
    if(textEdit)
    {
        qDebug() << QString("[%1] Wait for lock").arg(textEdit->objectName());
        mutex->lock();
        qDebug() << QString("[%1] Append text : %2").arg(textEdit->objectName()).arg(data);
        const QColor lastColor = textEdit->textColor();
        textEdit->setTextColor(color);
        textEdit->append(QString(data));
        textEdit->setTextColor(lastColor);
        qDebug() << QString("[%1] Unlock mutex").arg(textEdit->objectName());
        mutex->unlock();
    }

    return len;
}


text:
Q: How to use font awesome in a fxml project (javafx) I want to use font font awesome in my project but I have no idea how to use font awesome in my project.
I had found some example but they can't be use in fxml.
font awesome javafx
I need help how to use it in my project using fxml
Thank you.

A: I think this is what you need ControlFX that include font awesome support.
see the javadoc for more info (But I tested it one day and it works fine)

A: I ported the Android-Iconics library, developed by Mike Penz, to FX. Updates will follow soon (docs, as well)..
The showcase.jar will give you an overview of the icons.
Usage (Java 1.8 required):
FxIconicsLabel labelTextDefault =
                (FxIconicsLabel) new FxIconicsLabel.Builder(FxFontGoogleMaterial.Icons.gmd_folder_special)
                        .size(24)
                        .text("Right (default)")
                        .color(MaterialColor.ORANGE_500)
                        .build();

(or see DialogPlayGround.java)
FxIconics on GitHub

A: If you use SceneBuilder try this.

*

*First, download
'fontawesomefx'.

*Second, import jar to SceneBuilder using SceneBuilder's Jar/FXML Manager.

*Third, Library search for FontAwesomeIconView, GlyphCheckBox, MaterialDesignIconView, MaterialIconView, or WeatherIconView
Sample FXML:
<?xml version="1.0" encoding="UTF-8"?>

<?import de.jensd.fx.glyphs.control.GlyphCheckBox?>
<?import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView?>
<?import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView?>
<?import de.jensd.fx.glyphs.materialicons.MaterialIconView?>
<?import de.jensd.fx.glyphs.weathericons.WeatherIconView?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.StackPane?>
<?import javafx.scene.layout.VBox?>

<StackPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <VBox maxHeight="-Infinity" maxWidth="-Infinity">
         <children>
            <Label text="FontAwesomeIconView">
               <graphic>
                  <FontAwesomeIconView />
               </graphic>
            </Label>
            <Label text="GlyphCheckBox">
               <graphic>
                  <GlyphCheckBox />
               </graphic>
            </Label>
            <Label text="MaterialDesignIconView">
               <graphic>
                  <MaterialDesignIconView />
               </graphic>
            </Label>
            <Label text="MaterialIconView">
               <graphic>
                  <MaterialIconView />
               </graphic>
            </Label>
            <Label text="WeatherIconView">
               <graphic>
                  <WeatherIconView />
               </graphic>
            </Label>
         </children>
      </VBox>
   </children>
</StackPane>

Don't forget to add these jars to your project's classpath!

A: As said by @Sedrick you can use fontawesomefx library and use it in FXML as follows:
Note: JavaFX 8 and FontAwesomeFx v8.9
dashboard.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane xmlns="http://javafx.com/javafx/8.0.121"
    xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="com.example.DashboardController"
    prefHeight="760" prefWidth="1080">

    <Button text="Close" AnchorPane.topAnchor="0" AnchorPane.leftAnchor="0">
        <graphic>
            <FontAwesomeIconView glyphName="CLOSE" glyphSize="24"/>
        </graphic>
    </Button>

</AnchorPane>

In scene builder looks like below:

A: I achieved using FA Icons by adapting Jens Deters's approach.
His routines target dynamic gui composition opposing fxml's declarative way. Nevertheless, his AwesomeIcon enumeration (which maps FA comprehensible names with unicode characters) suited perfectly to my intents.
It should start by statically load the font in main/app class:
public class App extends Application {
    static {
        Font.loadFont(App.class.getResource("/font/fontawesome-webfont.ttf").toExternalForm(), 10);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        URL resource = getClass().getResource("/fxml/app.fxml");
        primaryStage.setScene(new Scene((Parent) FXMLLoader.load(resource), 500, 500));
        primaryStage.setTitle("FontAwesomeFX demo");
        primaryStage.show();
    }

    public static void main(String... args){
        launch(args);
    }
}

One can not use unicode characters in fxml (as needed to specify FA Icons), but can dynamic set attributes with such values. Hence having the above mentioned enumeration (AwesomeIcon), the job was done:

*

*The import:
<?import de.jensd.fx.fontawesome.AwesomeIcon?>

*The node:
<Label styleClass="awesome"
       style="-fx-font-family: FontAwesome; -fx-font-size: 16.0;">
    <text><AwesomeIcon fx:constant="FILE"/></text>
</Label>

I end up implementing an Icon Widget/Control/Component for resuming the amount of code with two properties:

*

*value: FA Icon Name;

*size: styleable attribute for style -fx-font-size on label.

New code (same effect):
<Icon value="FILE" size="16"/>

The code for that control can be found here. You can also find an working example as it includes the font and testing code.

A: You can use fontawesomefx library by using .jar file in Scene Builder
and you can browse all available icons with  Fontawesome-fx Glyph browser


text:
Q: Catch android's back button press event when showint a dialog/spinner's list? I need to capture the event when my app is showing a dialog and i press the device's back button.
Well it is not definetly a dialog. It is a dropdown list for my spinner.
I tryed:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK)
    {

    Toast myToast = Toast.makeText(getApplicationContext(), "back putton pressed", 1);
    myToast.show();

    }

    // Call super code so we dont limit default interaction
    super.onKeyDown(keyCode, event);

    return true;
}

Not worked.
I also tryed:
public void onBackPressed()
{

    Toast myToast = Toast.makeText(getApplicationContext(), "back putton pressed", 1);
    myToast.show();

}

I even tryed this with overriding.
So none of the above sollutions are worked for me. I found both of these on stackoverflow but for some reason they are not working for me.
Of course they work when there is now dialog showing, but when do... they are not run.
Any ideas ?
So my

A: Try
 if (keyCode == KeyEvent.KEYCODE_BACK)
{

    Toast myToast = Toast.makeText(getApplicationContext(), "back putton pressed", 1);
   myToast.show();
    return true;
}

A: A general way to detect if a dialog has been canceled (back button pressed) is to implement OnCancelListener, not really sure if it works on spinners though!

A: see this
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Handle the back button
        if(keyCode == KeyEvent.KEYCODE_BACK) {
            //write your code...
        }
    }

A: try this...
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {

        Toast myToast = Toast.makeText(getApplicationContext(), "back putton pressed", 1);
        myToast.show();
   new Handler().postDelayed(new Runnable{
    public void run(){
              finish();
        }
    }, 1000);
        }
    else{
        // Call super code so we dont limit default interaction
        super.onKeyDown(keyCode, event);
    }

        return true;
    }

A: try to use dismiss listener. a dialog can be dismissed by pressing a button or back key and using this listener you can know if user has pressed a button or back key (you can listen for onClick listener on your dialog to catch dialog's button' click).


text:
Q: How to Generate Random Binary Numbers in C++? I am trying to implement  fuction to generate random binary numbers, using the following :
srand(time(NULL));
int S = rand() % 2;//continuous random variable between 0 and 1

and then :
 rand()%2;

is continuously called 2^20 times ...
however im not getting proper random numbers.. any suggestions for improvement ?
Is there a data type for binary numbers or eqv.? (instead of declaring an integer)
Also, the only implementation of the seed of srand that i've seen is time(NULL) OR time(0) , is there a way to manipulate the seed to get better random numbers ?

A: Binary numbers are just numbers in a different base. There is no issue if you just generate integers (base 10) and then, when outputting, convert them to binary.
Check this question for more info on converting an integer into a "binary" string:
C++ - Decimal to binary converting


text: Q: terminal not working properly in Qt I am having a Qt application which run on bootup of RPI. I am using system to run start the other application. Where I start the application from terminal(for testing purpose) the system command works properly but on boot up the system command doesn't works. I could not figure out whats wrong ......


text:
Q: AWS API gateway average downtime per year per region? Our team is trying to see if we should use the managed AWS API gateway over IDC Kong for API Gateway.
So I am looking for some concrete statistics for AWS managed service (In particular, AWS API Gateway).
But the total downtime per year region statistics is surprisingly difficult to find from the AWS official website.
I looked at the SLA agreement (https://aws.amazon.com/api-gateway/sla/) that seems to guarantee up to 95% availability - that is totally out of the question. 18 days per year we might as well just go out of the business. And they only reimburse the credit used - not the total losses incurred due to the downtime.
There is also service health dashboard that shows current health and status history. But I need something way better than that - pie chart for total downtime in minutes during 2019, 2018, 2017 in each regions.

I found this stats "Modernize your Microsoft Applications on AWS" but again its not specific enough - it combines all services and regions.
Why are these stats so difficult to find? I am sure this is one of the more important metrics for choosing the service?
Many thanks in advance

A: That SLA document says the SLA is 99.95%, not your stated 95%.

AWS will use commercially reasonable efforts to make API Gateway available with a Monthly Uptime Percentage of at least 99.95% for each AWS region.

The 95% is only mentioned in the table that shows how much credit you get back if they breach the SLA.

Anyway, things break and services go down. But not all at the same time.
Your API GW may break (on its own or due to your actions), but perhaps not all API GWs at once. Availability Zone may go down but perhaps not all AZs at the same time. Yes sometimes even some Region goes down but other Regions are fine.
If your service is super critical and you can't afford an outage make it highly-available through geo-redundancy. That means deploy the same API in different regions, perhaps one region in US, one in EU and one in Asia-Pacific.
AWS provides a lot of tools to do that, from unified deployment through CloudFormation templates, through DynamoDB Global tables, to latency based routing with Route53. And more.
Single instance / API GW uptime / etc doesn't matter if your deployment is HA.
Hope that helps :)


text:
Q: Filtering based on PropertyInfo Name I am trying to modify the code below:
public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators, List<string> inTreatmentCohort)
{
    var type = typeof(T);
    var props = type.GetProperties();

    //Setup expression constants
    var param = Expression.Parameter(type, "x");
    var doublequote = Expression.Constant("\"");
    var doublequoteescape = Expression.Constant("\"\"");
    var comma = Expression.Constant(",");

    //Convert all properties to strings, escape and enclose in double quotes
    var propq = (from prop in props
        let tostringcall = Expression.Call(Expression.Property(param, prop),
            prop.ReflectedType.GetMethod("ToString", new Type[0]))
        let replacecall = Expression.Call(tostringcall,
            typeof(string).GetMethod("Replace", new[] {typeof(string), typeof(string)}), doublequote,
            doublequoteescape)
        select Expression.Call(
            typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
            doublequote, replacecall, doublequote)
    ).ToArray();

    var concatLine = propq[0];
    for (var i = 1; i < propq.Length; i++)
        concatLine =
            Expression.Call(
                typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
                concatLine, comma, propq[i]);

    var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
    var header = string.Join(",", props.Select(p => p.Name).ToArray());

    return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
}

I need to filter based on the two lists (keyIndicators and inTreatmentCohort) which contain the suffix and prefix of the PropertyInfo Name field contained in the list being converted to CSV.
I tried adding a where keyIndicators.Contains(prop.Name) essentially simulating an IN statement this returns null.
I also tried putting the propq query in a foreach loop this brought the correct data but all the column names shown rather than just the column names that are selected in the keyIndicators or inTreatmentCohort list.
How do I modify this code to only return a csv that contains the columns in the two filtering lists rather than all the columns in list being converted?

Revised to include new linq queries
Have revised the code that I previously provided the Contains is now working as intended, these changes can be seen below:
public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators,
    List<string> inTreatmentCohorts)
    {
        var type = typeof(T);
        var props = type.GetProperties();

        //Setup expression constants
        var param = Expression.Parameter(type, "x");
        var doublequote = Expression.Constant("\"");
        var doublequoteescape = Expression.Constant("\"\"");
        var comma = Expression.Constant(",");
        MethodCallExpression[] propq = { };
        var propqList = new List<MethodCallExpression>();

        //Convert all properties to strings, escape and enclose in double quotes

        foreach (var keyIndicator in keyIndicators)
        {
            if (keyIndicator != "Pend" && keyIndicator != "Area" && keyIndicator != "DrugGroup" &&
                keyIndicator != "Gender") continue;
            propq = (from prop in props
                let tostringcall = Expression.Call(Expression.Property(param, prop),
                    prop.ReflectedType.GetMethod("ToString", new Type[0]))
                let replacecall = Expression.Call(tostringcall,
                    typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }), doublequote,
                    doublequoteescape)
                where prop.Name.Contains(keyIndicator)
                select Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    doublequote, replacecall, doublequote)
            ).ToArray();

            propqList.AddRange(propq);
        }

        foreach (var keyIndicator in keyIndicators)
        {
            foreach (var inTreatmentCohort in inTreatmentCohorts)
            {
                propq = (from prop in props
                         let tostringcall = Expression.Call(Expression.Property(param, prop),
                             prop.ReflectedType.GetMethod("ToString", new Type[0]))
                         let replacecall = Expression.Call(tostringcall,
                             typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }),
                             doublequote,
                             doublequoteescape)
                         where prop.Name.Contains(inTreatmentCohort) && prop.Name.Contains(keyIndicator)
                         select Expression.Call(
                             typeof(string).GetMethod("Concat",
                                 new[] { typeof(string), typeof(string), typeof(string) }),
                             doublequote, replacecall, doublequote)
                ).ToArray();
            }

            propqList.AddRange(propq);
        }

        propq = propqList.ToArray();

        var concatLine = propq[0];
        for (var i = 1; i < propq.Length; i++)
            concatLine =
                Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    concatLine, comma, propq[i]);

        var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
        var header = string.Join(",", props.Select(p => p.Name).ToArray());

        return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
    }

I need to rewrite the LINQ query for var header so that only columns selected in propq are shown when the csv is generated.

A: After making some revisions I managed to get the Contains to work in conjunction with a couple of foreach loops for processing the two filter lists.
the complete code is shown below:
public static string ToCsv<T>(this IEnumerable<T> list, List<string> keyIndicators,
    List<string> inTreatmentCohorts)
    {
        var type = typeof(T);
        var props = type.GetProperties();

        //Setup expression constants
        var param = Expression.Parameter(type, "x");
        var doublequote = Expression.Constant("\"");
        var doublequoteescape = Expression.Constant("\"\"");
        var comma = Expression.Constant(",");
        MethodCallExpression[] propq = { };
        var propqList = new List<MethodCallExpression>();
        var columnNames = new List<string>();

        //Convert all properties to strings, escape and enclose in double quotes

        foreach (var keyIndicator in keyIndicators)
        {
            foreach (var inTreatmentCohort in inTreatmentCohorts)
            {
                propq = (from prop in props
                    let tostringcall = Expression.Call(Expression.Property(param, prop),
                        prop.ReflectedType.GetMethod("ToString", new Type[0]))
                    let replacecall = Expression.Call(tostringcall,
                        typeof(string).GetMethod("Replace", new[] {typeof(string), typeof(string)}), doublequote,
                        doublequoteescape)
                    where prop.Name.Contains(keyIndicator) && prop.Name.Contains(inTreatmentCohort)
                    select Expression.Call(
                        typeof(string).GetMethod("Concat", new[] {typeof(string), typeof(string), typeof(string)}),
                        doublequote, replacecall, doublequote)
                ).ToArray();

                var columnNameQuery = (from prop in props
                    where prop.Name.Contains(keyIndicator) && prop.Name.Contains(inTreatmentCohort)
                    select prop.Name);

                columnNames.AddRange(columnNameQuery);

                propqList.AddRange(propq);
            }
        }

        propq = propqList.ToArray();

        var concatLine = propq[0];
        for (var i = 1; i < propq.Length; i++)
            concatLine =
                Expression.Call(
                    typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string), typeof(string) }),
                    concatLine, comma, propq[i]);

        var method = Expression.Lambda<Func<T, string>>(concatLine, param).Compile();
        var header = string.Join(",", columnNames.ToArray());

        return header + Environment.NewLine + string.Join(Environment.NewLine, list.Select(method).ToArray());
    }

The column names that I want to be included in the CSV are added to a columnNames list and are then added to the header variable so the the columns and the data match up in the CSV.

A: Try following :
            string[] columnNames = { "A", "B", "C", "D" };
            string[] filteredColumns = { "A", "C", "D" };

            string[] csv = {
                               "1,2,3,4",
                               "11,12,13,14",
                               "21,22,23,24",
                               "31,32,33,34"
                           };

            int[] indexes = columnNames.Select((x, i) => new { x = x, i = i }).Where(x => filteredColumns.Contains(x.x)).Select(x => x.i).ToArray();

            var results = csv.Select(x => x.Split(new char[] { ',' }).Where((y, i) => indexes.Contains(i)).ToArray()).ToArray();


text:
Q: asp.net core 3 routing In my Asp.net core 3 project I am using some controler to access from js code to do some stuff and also using Razor pages at the same time.
at the configure service section :
    services.AddControllersWithViews();
    services.AddRazorPages();

I added both RazorPages and MVC controller with view.
And at then configure section
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

        });

Added above codes.
When I try to access to controller I am getting 404. I also tried to add just services.AddControllers();
need help please.
Edit : controller code
public class DashboardsController : BaseController, IDashboardsController
{
    [HttpGet]
     public async Task<JsonResult> GetAssetCategorySummaryAsync(){
        -------
    }
}

A: Your url should be localhost:9011/Dashboards/GetAssetCategorySummary.
You could modify the Startup.cs like below to allow using the whole action name:
public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(options =>
        {
            options.SuppressAsyncSuffixInActionNames = false;
        });
        services.AddControllersWithViews();
        services.AddRazorPages();
    }

It is a known issue on github,you could refer to here.

A: I can recommend my solution.
In Startup
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

Create your CUSTOM base controller like that.
    [Route("api/[controller]/[action]/{id?}")]
    [ApiController]
    public class CustomBaseController : ControllerBase
    {
    }

And use CustomBaseController
 public class TestController : CustomBaseController
    {
        public IActionResult Test()
        {
            return Ok($"Test {DateTime.UtcNow}");
        }
    }

Rout` api/Test/test


text:
Q: Finding a horizontal asymptote of a function with ln I have this function
\begin{align}
  \ f (x) &= (x-1)\cdot \ln\left(\frac{\ x-1}{x}\right) \\\\
\end{align}
and I need to find it's asymptotes. I know there is a vertical asymptote at $x=0$, because of the denominator in the fraction inside $\ln$. But I have a problem with finding the horizontal asymptote. I graphed it and I know it is at $y=-1$, but I don't know how to prove it. How to solve the limit of this function as $x \to \infty$ or $x \to -\infty$?.

A: $$\lim_{x\to\infty}(x-1)\log\left(\frac{x-1}x\right)=\lim_{x\to\infty}\frac{\log\left(\frac{x-1}x\right)}{\frac1x}\stackrel{l'Hos.}=\lim_{x\to\infty}\frac{\frac1{x(x-1)}}{-\frac1{x^2}}=-\lim_{x\to\infty}\frac x{x-1}=-1$$
Check now the limit when $\;x\to-\infty\;$ ...It is very similar.

A: For horizontal asymptotes you have to make $x \rightarrow \infty$ and $x \rightarrow -\infty$ and $f$ must goes to some constant.
$$\lim_{x \rightarrow \infty} (x-1)\ln \left(1-\frac{1}{x}\right)=\lim_{x \rightarrow \infty}\frac{\ln \left(1-\frac{1}{x}\right)}{\frac{1}{x-1}}$$
By L'Hopital:
$$\lim_{x \rightarrow \infty}\frac{\frac{1}{x^2}\frac{x}{x-1}}{-\frac{1}{(x-1)^2}}=\lim_{x \rightarrow \infty}\frac{\frac{1}{x(x-1)}}{-\frac{1}{(x-1)^2}}=\lim_{x \rightarrow \infty}-\frac{x-1}{x}=-1$$

A:
I know there is a vertical asymptote at $x=0$, because of the denominator in the fraction inside $\ln$.

Careful: the reason is that $f(x) \to \pm\infty$ as $x \to 0$, verifying this is a little more subtle than just observing the denominator $x$. Recall that $\ln x$ has a vertical asymptote at $x=0$ as well (and there is no denominator!), while your function does not have one where the logarithm's argument becomes $0$ (namely in $x=1$). You can/should check all this by calculating the corresponding limits.

But I have a problem with finding the horizontal asymptote. I graphed it and I know it is at $y=-1$, but I don't know how to prove it. How to solve the limit of this function as $x \to \infty$ or $x \to -\infty$?.

Use l'Hôpital's rule:
$$\lim_{x \to +\infty}\left((x-1)\ln \left(\tfrac{x-1}{x}\right)\right)=\lim_{x \rightarrow \infty}\frac{\ln \left(\tfrac{x-1}{x}\right)}{\tfrac{1}{x-1}}=\lim_{x \rightarrow \infty}\tfrac{\left(\ln \left(\tfrac{x-1}{x}\right)\right)'}{\left(\frac{1}{x-1}\right)'} =\ldots=\lim_{x \rightarrow \infty}\frac{1-x}{x}=-1$$
I omitted the calculation of the derivatives; you can do this and simplify.
The limit at $-\infty$ is similar.


text:
Q: How to change Wallpapers Programmatically? Can I change the Installed wallpapers by their Package names?
For example:
String packageName = "com.wallpaper.livewallpaper";

start(packageName);

A: Changing Live Wallpaper Programmatically in Android is not possible cause of the System Security Issues.


text:
Q: Parse a group of JSON arrays I have some json data in this format
    var dataJSON = '[["a","b","0","1"],["c","d","3","4"],["e","f","5","6"],["g","h","7","8"],["i","j","9","10"]]';
document.getElementById("description").innerHTML=dataJSON;

and html:

Ho to target just the first value in each array, so the result can be "a - c - e - g - i"
*Edited

A: Use JSON.parse with map:
const first = JSON.parse(dataJSON).map(([e]) => e);

To join that into a string separated by hyphens and spaces:
const str = first.join(" - ");

A: you have to parse the string to json object and loop through the array and get the first element of the array element
var dataJSON = '[["a","b","0","1"],["c","d","3","4"],["e","f","5","6"],["g","h","7","8"],["i","j","9","10"]]';

var result = [];

JSON.parse(dataJSON).forEach(function(d){
  result.push(d[0]);
});

console.log(result.join(' - ');

A: Code example.
var dataJSON = '[["a","b","0","1"],["c","d","3","4"],["e","f","5","6"],["g","h","7","8"],["i","j","9","10"]]';

console.log(JSON.parse(dataJSON).map(item => item[0]));

// ["a", "c", "e", "g", "i"]


text:
Q: How to make Divs to use 100% height between horizontal nav and footer i have been searching for this and have tried every solution given on this page, but for some reason i haven't found why the given solutions doesn't work on my project.
i need the left_wrapper and right_wrapper to use 100% of height, and also need the footer to be always at bottom.
here is my code:

Code jsdfiddle.net

HTML
<!DOCTYPE html>

Inicio

cosa2

cosa3

&Aacuterea 51

pendejadas a la izquierda

A Helena.

de que se ven rüinas y pedazos.

Y la dura ocasión de tanto daño

mientras vencido Paris muere ardiendo

del griego vencedor duerme en los brazos.

Lope de Vega.

Aquí

CSS
html {
margin: 0;
padding: 0;
height: 100%;
}
body {
font-family: sans-serif;
background-color: #ccc;
margin: 0;
font-size: 0.9em;
height: 100%;
}
.global_wrapper {
width: 90%;
background-color: transparent;
margin: 0 auto;
min-height: 100%;
position: relative;
}
header {
width: 100%;
height: 100px;
margin: 0 auto;
background-color:orange;
}
header img.logo {
float: left;
max-height: 50px;
max-width: 140px;
margin-top: 25px;
margin-left: 25px;
}
nav.menuhorizontal {
width:100%;
margin: 0 auto;
height: auto;
color: #e1e1e1;
border: 0;
background: #0061a7;
text-align: center;
vertical-align: middle;
line-height: 190%;
}
nav.menuhorizontal li {
list-style: none;
display: inline;
}
nav.menuhorizontal a.item1 {
text-decoration: none;
color: #e1e1e1;
padding-left: 7px;
padding-right: 7px;
border-color:silver;
}
nav.menuhorizontal a.item1:hover {
background: #e1e1e1;
color:#0061a7;
padding: 7px;
border-top-left-radius: 7px;
border-top-right-radius: 7px;
-webkit-transition: background-color .30s ease-in-out;
-moz-transition: background-color .30s ease-in-out;
-o-transition: background-color .30s ease-in-out;
transition: background-color .30s ease-in-out;
}
.content_wrapper {
width: 100%;
margin: auto;
padding-bottom: 100px;
overflow: hidden;
}
.left_column {
display: block;
width: 25%;
float: left;
background-color:#de9e47;
padding: 1.7%;
box-sizing: border-box;
}
.right_wrapper {
display: block;
width:75%;
float: left;
background-color: #e1e1e1;
padding: 1.7%;
box-sizing: border-box;
height: 100%;
}
footer {
clear:both;
width: 100%;
height: 100px;
margin: 0 auto;
background-color:orange;
text-align: center;
bottom: 0;
left: 0;
padding: 2%;
box-sizing: border-box;
position: absolute;
}

A: you have to make come changes in css ...like left_column  position:absolute and its parent position:relative. and right_wrapper float:right thats it, and you will get what you are trying to achieve..

html {
    margin: 0;
    padding: 0;
    height: 100%;
}
body {
    font-family: sans-serif;
    background-color: #ccc;
    margin: 0;
    font-size: 0.9em;
    height: 100%;
}
.global_wrapper {
    width: 90%;
    background-color: transparent;
    margin: 0 auto;
    min-height: 100%;
    position: relative;
}
header {
    width: 100%;
    height: 100px;
    margin: 0 auto;
    background-color:orange;
}
header img.logo {
    float: left;
    max-height: 50px;
    max-width: 140px;
    margin-top: 25px;
    margin-left: 25px;
}
nav.menuhorizontal {
    width:100%;
    margin: 0 auto;
    height: auto;
    color: #e1e1e1;
    border: 0;
    background: #0061a7;
    text-align: center;
    vertical-align: middle;
    line-height: 190%;
}
nav.menuhorizontal li {
    list-style: none;
    display: inline;
}
nav.menuhorizontal a.item1 {
    text-decoration: none;
    color: #e1e1e1;
    padding-left: 7px;
    padding-right: 7px;
    border-color:silver;
}
nav.menuhorizontal a.item1:hover {
    background: #e1e1e1;
    color:#0061a7;
    padding: 7px;
    border-top-left-radius: 7px;
    border-top-right-radius: 7px;
    -webkit-transition: background-color .30s ease-in-out;
    -moz-transition: background-color .30s ease-in-out;
    -o-transition: background-color .30s ease-in-out;
    transition: background-color .30s ease-in-out;
}
.content_wrapper {
    width: 100%;
    margin: auto;
    padding-bottom: 100px;
    overflow: hidden;
    position:relative;
}
.left_column {
    display: block;
    width: 25%;
    float: left;
    background-color:#de9e47;
    padding: 1.7%;
    box-sizing: border-box;
    position:absolute;
    height:100%;
}
.right_wrapper {
    display: block;
    width:75%;
    float: right;
    background-color: #e1e1e1;
    padding: 1.7%;
    box-sizing: border-box;
    height: 100%;
}
footer {
    clear:both;
    width: 100%;
    height: 100px;
    margin: 0 auto;
    background-color:orange;
    text-align: center;
    bottom: 0;
    left: 0;
    padding: 2%;
    box-sizing: border-box;
    position: absolute;
}

Inicio

cosa2

cosa3

&Aacuterea 51

pendejadas a la izquierda

A Helena.

de que se ven rüinas y pedazos.

Y la dura ocasión de tanto daño

mientras vencido Paris muere ardiendo

del griego vencedor duerme en los brazos.

Lope de Vega.

    Aquí

A: change this..and also mention the height for .left_column
css
.content_wrapper {
width: 100%;
overflow: scroll;
position: absolute;
height: 49%;/*increase it as you need*/
}

do ask if you find it difficult to understand

A: why cant u try to achieve this with jquery??
Script
$(document).ready(function () {
    changeHeight();
    window.resize();
    $(window).resize(function () {
        changeHeight();
    });
});
$(document).change(function () {
    changeHeight();
});

function changeHeight() {
    $(".left_column, .right_wrapper").css({
        "height": "100%"
    });
    var headerHeight = $("header").height();
    var navHeight = $(".menuhorizontal").height();
    var footerHeight = $("footer").height();
    var bodyHeight = $('body').height();
    var wrapperHeight = (bodyHeight - (headerHeight - navHeight - footerHeight));
    console.log(wrapperHeight);
    $(".content_wrapper, .left_colulmn, .right_wrapper").height(wrapperHeight);
}

Fiddle Demo


text:
Q: Distinguish router path in Angular Angular routing:
{
    path: ':id',
    loadChildren: () => import('./test/test.module').then(m => m.TestModule)
  },
  {
    path: '**',
    component: AnyComponent
  },

There is any mechanism for distinguish routing path, which are was provided from url, f.e.
I. If the User provide/enter in browser url -> http://example.com/10
- will be calling below routing

path: '**',
    component: AnyComponent

II. If in component, we are using the router navigate:
 this.router.navigate([`${this.someData.id}]);

 will be calling:

path: ':id',
loadChildren: () => import('./test/test.module').then(m => m.TestModule)

So I would like to select/control which component will be loading, according to how the proper url will be provided (By User or By Code)

A: AFAIK, using the code based approach leverages the same mechanism as the user-entered route. So I don't think that there is a built-in way to distinguish them.
Alternate ideas:

*

*Use different routes. For example: http:/example.com/10 and http://example.com/id/10 so that they can be captured and processed differently.

*Pass data to the route using something like shown here: Pass data in Angular router dynamically

A: this should be done on the component and you should not be doing wild card routing on the root route.  this will cause you state issue on the angular router.
so what you should do is create a root component also called a parent in your lazy loaded route then call the child from there.
IE number/:id.
NOT :id - if you do this - this will create many problems for yourself because all routes will be caught by the :id route which in effect is the exact same as the catchall route **. the causation would be no matter what route the users takes unless its strong typed and placed before this route - every single route would go there so if someone went too contacts as an example it would be caught by the same route that you want the number 10 to go to.
the angular router is incredibly powerful is you use it properly - but I think for you its a logic thing, you need to reshape your routes so that they can be maintained.
in terms of the getting the end of the url from the route.  I've provided an example for you.
constructor(router: Router){}

ngOnInit(){ const routeName =
this.router.url.split('/').pop();
if(routerName==='10'){
do something here
}
}

https://angular.io/guide/router