text:
Q: Why is my app hanging on localhost? I have recently built an MVC (well, more like a VC app) app in NodeJS and Express. Everything was working fine until I installed express-validator and pasted the middleware in the app file. Afterwards, localhost began hanging, with a GET / - - ms - - message in the console. I started a new app, reinstalled the modules, and copied and pasted the code. I still had the same issue, so I removed the express-validator middleware. Nothing changed.
 App.js (entry point):
var config = require('./server/configure');
var express = require('express');
var app = express();
var app = config(app);
app.set('port', process.env.port || 3300);
app.set('views', __dirname + '/views');
app.listen(app.get('port'), function(req, res){
    console.log('Server up: http://localhost:' + app.get('port'));
});

The routes file (/server/routes.js)
var express = require('express');
    home = require('../controllers/home');
module.exports = function(app) {
    router = express.Router();
    router.get('/', home.home);
    app.use(router);
};

The configure module (/server/configure.js)
var path = require('path'),
    routes = require('./routes'),
    ejs = require('ejs'),
    express = require('express'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    morgan = require('morgan'),
    methodOverride = require('method-override'),
    errorHandler = require('errorhandler');
module.exports = function(app) {
  app.use(morgan('dev'));
  app.use(bodyParser.json);
  app.use(bodyParser.urlencoded({extended:false}));
  app.use(bodyParser({
    uploadDir: path.join(__dirname, 'public/upload/temp')
  }));
  app.use(methodOverride());
  app.use(cookieParser('secret value'));
  routes(app);
  app.use('/public/', express.static(path.join(__dirname, '../public')));
  if ('development' === app.get('env')) {
    app.use(errorHandler());
  }
  app.set('view engine', 'ejs');
  return(app);
};

The home controller (/controllers/home.js):
module.exports = {
    home: function(req, res) {
        res.render('home');
    }
};

The Package file (package.json):
{
  "name": "krementcookdev",
  "version": "1.0.0",
  "description": "the krementcook web application",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Isaac Krementsov",
  "license": "ISC",
  "dependencies": {
    "body-parser": "*",
    "cookie-parser": "*",
    "ejs": "*",
    "errorhandler": "*",
    "express": "*",
    "express-handlebars": "*",
    "express-validator": "*",
    "method-override": "*",
    "morgan": "*",
    "path": "*"
  },
  "devDependencies": {}
}

Of course, I have a view file (home.ejs) in the /views directory. If you need to see it, let me know and I will add it to the post. Please do not close this a being a duplicate; I have checked similar problems and they mostly regard simple apps without routers or anything like that. I tried the solutions offered that applied to me, but none were relevant or productive.
Update: I did have specific versions in the package file, but I still had the same issue.

A: Try to use specific version (latest) of individual package in dependencies. for more detail Refer - https://docs.npmjs.com/files/package.json


text:
Q: Security Patches for Ubuntu 16 after 9 Months I have installed Ubuntu 16 on my machine. I have come to know that after 9 months security patches will not be available.
Please let me know how can I get support after 9 months. Is there any way I could purchase the support?
Regards,
Jatinder

A: What do you mean?  16.04 is an LTS release.  This means that you'll get full support and updates for 5 years.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Linked list Pointer I am learning C and I've come up with a conceptual question about pointers.
Here is a simple code to push (add to the beginning) an int to a linked list in C.
The following code works:
#include <stdio.h>
#include <stdlib.h>

typedef struct node {
  int val;
  struct node *next;
} node_t;

void push(node_t **head, int val) {
  // head is a pointer to the pointer of the first node_t
  node_t *new_node; // new pointer to a node
  new_node = (node_t *)malloc(sizeof(node_t));

  new_node->val = val;
  new_node->next = *head;
  *head = new_node;
}

int main() {
  // creating the first node
  node_t *head;
  head = (node_t *)malloc(sizeof(node_t));
  head->val = 2;
  head->next = NULL;

  // pushing a value
  push(&head, 1); // the '&' is important

  return 0;
}

As you notice, we have to pass &head as a parameter. So I though changing the function so I could pass head instead. Here's the modified function :
void push(node_t *head, int val) {
  node_t **p_head;
  p_head = &head; // p_head is a pointer to the pointer of the first node_t

  node_t *new_node; // pointer to a new node
  new_node = (node_t *)malloc(sizeof(node_t));

  new_node->val = val;
  new_node->next = *p_head;
  *p_head = new_node;
}

Why does this version won't work ?
Thanks in advance.

A: You should be able to pass along the structure's pointer for the creation of another structure in a linked list.  I would suggest looking at the linked list structure in a slightly different way.
Usually, in the creation of a linked list, whenever a new list item (aka structure in your case) is created, the "next node structure" pointer is set to null and the previous linked list member has its "next node structure" pointer updated to the pointer of the newly created structure.  Making some revisions to your program I store some additional information in your structure and produce a linked list of ten members.  Following is the revised code.
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    int val;
    struct node *previous;  /* Added this to use with the passed node pointer */
    struct node *next;
} node_t;

node_t * push(node_t *nd, int val)   /* Return the pointer of the newly created node */
{
    node_t *new_node; // New pointer to a node
    new_node = (node_t *)malloc(sizeof(node_t));
    new_node->val = val;
    new_node->previous = nd;
    new_node->next = NULL;

    return new_node;
}

int main()
{
    node_t *work;  // Pointer work variable for building a linked list of nodes

    node_t *head;
    head = (node_t *)malloc(sizeof(node_t));
    head->val = 2;   /* This value will get adjusted to provide unique values */
    head->previous = NULL;

    // Create a set of ten nodes.

    work = head;

    for (int i = 0; i < 10; i++)
    {
        work->next = push(work, (2 * i + i + 12));
        work = work->next; /* Links this node to the newly created node. */
    }

    // Now travel down the chain and print out the pertinent statistics of the nodes.

    work = head;

    while (1)
    {
        printf("This node's values are: this->%p value->%d previous->%p next->%p.\n", work, work->val, work->previous, work->next);
        if (work->next == NULL)  /* We have reached the end of the list */
            break;
        work = work->next;
    }

    return 0;
}

When I ran this program, I received the following output on my terminal.
This node's values are: this->0x55bfd6edc2a0 value->2 previous->(nil) next->0x55bfd6edc2c0.
This node's values are: this->0x55bfd6edc2c0 value->12 previous->0x55bfd6edc2a0 next->0x55bfd6edc2e0.
This node's values are: this->0x55bfd6edc2e0 value->15 previous->0x55bfd6edc2c0 next->0x55bfd6edc300.
This node's values are: this->0x55bfd6edc300 value->18 previous->0x55bfd6edc2e0 next->0x55bfd6edc320.
This node's values are: this->0x55bfd6edc320 value->21 previous->0x55bfd6edc300 next->0x55bfd6edc340.
This node's values are: this->0x55bfd6edc340 value->24 previous->0x55bfd6edc320 next->0x55bfd6edc360.
This node's values are: this->0x55bfd6edc360 value->27 previous->0x55bfd6edc340 next->0x55bfd6edc380.
This node's values are: this->0x55bfd6edc380 value->30 previous->0x55bfd6edc360 next->0x55bfd6edc3a0.
This node's values are: this->0x55bfd6edc3a0 value->33 previous->0x55bfd6edc380 next->0x55bfd6edc3c0.
This node's values are: this->0x55bfd6edc3c0 value->36 previous->0x55bfd6edc3a0 next->0x55bfd6edc3e0.
This node's values are: this->0x55bfd6edc3e0 value->39 previous->0x55bfd6edc3c0 next->(nil).

Hopefully, this might give you some food for thought on pointer usage as it pertains to linked lists.  Also, since the program is using "malloc" it usually is a good idea to have some cleanup in the program to make sure the memory is freed up (e.g. use the "free()" function).
Hope that helps.
Regards.


text:
Q: Pagination of a particular action Can anyone help this is about pagination
(i have an action ) in controller
 def foo
 end

now , i want to paginate that actions outcome( suppose those are products )
and my view is foo.html.erb

A: You can use will_paginate gem.
Add
gem 'will_paginate', '~> 3.0'

to your Gemfile.
Run bundle install.
In your controller:
def foo
  @products = Product.your_custom_scope.paginate(page: params[:page])
end

Lastly, add <%= will_paginate @products %> in your view in place where you want pagination links to be displayed.

A: You can use kaminari gem 'kaminari' for pagination.
You can get the git document here
Your action in the controller will be like this
def foo
  @products = Product.order('name ASC').page params[:page]
end

the paginate helper method
<%= paginate @users %>

This would output several pagination links such as « First ‹ Prev ... 2 3 4 5 6 7 8 9 10 ... Next › Last »


text:
Q: add key and value from different collections into dictionary I have two array with string values, and one dictionary, im trying to add values from array1 as key and values from array2 as value in dictionary.
what is best practice in this case?
i have tried following
foreach(var i in array1)
{
    foreach(var t in array2)
    dictionary.add(i.value, t.value)
}

A: Well you could do (in .NET 4):
var dictionary = array1.Zip(array2, (key, value) => new { key, value })
                       .ToDictionary(pair => pair.key, pair => pair.value);

That basically zips together the two arrays, so you end up with a sequence of pairs. You then call the ToDictionary extension method, extracting the key and value from each pair.
Alternatively, you could do it the old-fashioned way:
var dictionary = new Dictionary<string, string>();
for (int i = 0; i < array1.Length; i++)
{
    dictionary[array1[i]] = array2[i]; // Or use Add
}

In both cases you should make sure the arrays are the same length, of course.

A: You could use the .Zip extension method:
var array1 = new[] { "key1", "key2", "key3" };
var array2 = new[] { "value1", "value2", "value3" };
if (array1.Length != array2.Length)
{
   throw new Exception("The two arrays must have same lengts");
}
Dictionary<string, string> dic = array1
    .Zip(array2, (x, y) => new { Key = x, Value = y })
    .ToDictionary(x => x.Key, x => x.Value);

A: are the 2 arrays having equal length? if they are
a simple loop will do the trick,
for(int i = 0; i<array1.length();i++)
{
  dict.put(array1[i],array2[i]);
}

A: another linq approach
var dictionary = new Dictionary<string, string>();
foreach (var pair in array1.Zip(array2, (a, b) => new KeyValuePair<string, string>(a, b)))
    ((ICollection<KeyValuePair<string, string>>)dictionary).Add(pair);

EDIT
More readable:
var dictionary = new Dictionary<string, string>();
var collection = (ICollection<KeyValuePair<string, string>>)dictionary;
var pairs = array1.Zip(array2, (a, b) => new KeyValuePair<string, string>(a, b));

foreach (var pair in pairs)
    collection.Add(pair);


text:
Q: Formatting issue for View UPDATE:::
Sorry everyone I have been clearer.  This is supposed to be for the "format my view" feature in the Sharepoint Online custom list.  I'm trying to make the entire row change color based on the "assigned?" column. I know i can do it for the column only but I want the whole row to highlight.  When I try several guides, nothing happens.
This is one of the guides that I used but it didn't change the view.
https://support.office.com/en-us/article/formatting-list-views-f737fb8b-afb7-45b9-b9b5-4505d4427dd1

I'm sure that this code is written correctly but it's not doing anything. A coworker of mine is helping me with the JSON but neither of us can figure out why it isn't working on Sharepoint Online.

Here is the code.
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
    "elmType": "div",
    "txtContent": "@Assigned?",
    "style":
    {
        "color": "#fff",
        "padding-left": "14px",
        "background-color":
        {
            "operator": "?",
            "operands": [
            {
                "operator": "==",
                "operands": ["@Assigned?", "Not Released Yet"]
            }, "#2ECC71",
            {
                "operator": "?",
                "operands": [
                {
                    "operator": "==",
                    "operands": ["@Assigned?", "Needs Reassignment"]
                }, "#E74C3C",
                {
                    "operator": "?",
                    "operands": [
                    {
                        "operator": "==",
                        "operands": ["@Assigned?", "Needs Assignment"]
                    }, "#F1C40F",
                    {
                        "operator": "?",
                        "operands": [
                        {
                            "operator": "==",
                            "operands": ["@Assigned?", "Assigned"]
                        }, "#FFFFF", ""]
                    }]
                }]
            }]
        }
    }
}

A: What does "@Assigned?" represent in your code? Is it the name of current column? If so, pleace use "@currentField" instead of "@Assigned?".
{
    "$schema": "https://developer.microsoft.com/json-schemas/sp/view-formatting.schema.json",
    "elmType": "div",
    "txtContent": "@currentField",
    "style":
    {
        "color": "#fff",
        "padding-left": "14px",
        "background-color":
        {
            "operator": "?",
            "operands": [
            {
                "operator": "==",
                "operands": ["@currentField", "Not Released Yet"]
            }, "#2ECC71",
            {
                "operator": "?",
                "operands": [
                {
                    "operator": "==",
                    "operands": ["@currentField", "Needs Reassignment"]
                }, "#E74C3C",
                {
                    "operator": "?",
                    "operands": [
                    {
                        "operator": "==",
                        "operands": ["@currentField", "Needs Assignment"]
                    }, "#F1C40F",
                    {
                        "operator": "?",
                        "operands": [
                        {
                            "operator": "==",
                            "operands": ["@currentField", "Assigned"]
                        }, "#FFFFF", ""]
                    }]
                }]
            }]
        }
    }
}

Test result:

A: I have the impression that you have misled, there is two errors appearing here:
The first is "txtContent": "@Assigned?" should be "txtContent": "@currentField"
The second you are trying to format a row in a column formatting section ? even if you correct the first error it will format only the column you are working on, but for the whole row please check this article:
https://aslamsumayya.wordpress.com/2015/04/10/changing-colors-in-sharepoint-list-rows-conditional-formatting-in-sharepoint-2013online/
I hope this will enlighten you something,
Best wishes for you.


text:
Q: saving date in mongodb using python I have a field, 'date' that I take from a document.
The field date has a value like this: "01.01.2014".
I'm saving this field into a mongo database like this:
"date" : "01.01.2014",

If I split those parameters I have:
year ='2014'
month ='01'
day ='01'

I want to save this field in proper type like datetime so how can I store it using those parameters?

A: Use module datetime
your date object to be saved in mongoDB would be
myDateObject = datetime.datetime(year,month,day, 0 , 0)

use myDateObject to store as a value for date key in mongoDB.
Here year, month and day are expected to be integer.
As in your question, you can also use the date field to convert it to python datetime. Assuming date is in mm.dd.yyyy format, the code to convert date into datetime object is,
>>> datetime.datetime.strptime(date,"%m.%d.%Y")
datetime.datetime(2014, 1, 1, 0, 0)


text:
Q: Redirect from /index.html, /index.php and /index to root kitten :)
How to make at the same time a redirect from /index.html, /index.php and / index to root?
I tried this code
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index\.html
RewriteRule ^(.*)index.html$ /$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index$ /$1 [R=301,L]

but with this code administrative panel MODX ceases to work normally

A: You can simply use a Redirect
Redirect /index /

This will redirect /index/anyPath to root.


text:
Q: como consumir webservice en azure Yo desde mi VM en azure puedo consumir de manera local un webservice sin problemas.
Ahora cuando lo quiero consumir con soapUI no llego:
desde linea de comando, con un wget me da este error:
$ wget http://xx.xx.xx.xx:8080/WSService/WSService?wsdl
--2018-04-23 17:54:46--  http://xx.xx.xx.xx:8080/WSService/WSService?wsdl
Conectando con xx.xx.xx.xx:8080... falló: Conexión rehusada.

me estara faltando alguna regla en el firewall?
el puerto 8080 esta abierto

Un detalle que note ahora es que llego al jboss en ese puerto pero no tengo permisos para por ejemplo entrar al manager así que si me falta algo que no se que seria...
la vm es un centos con jboss eap7
$ telnet xx.xx.xx.xx 8080
Trying xx.xx.xx.xx...
telnet: connect to address xx.xx.xx.xx: Connection refused

A: Hace un tiempo me sucedió algo similiar y en mi caso se resolvió reiniciando la instancia de la VM.
Desconozco si añadir/actualizar las reglas de NSG sobre la marcha no afecta a las instancias en ejecución de manera inmediata (o que tome mucho tiempo de sincronización).


text:
Q: Python: Write JSON dictionary values to a JSON file I am attempting to:

*

*Load data from a JSON list of dictionaries

*Write the values of a specific key from each dictionary to a file

Yet, when I attempt to dump the key pairs to the new .json file, it only prints the very last dictionary key pair. Anyone know how to loop through each dictionary and append the key pair? I have tried a few methods but I can't seem to figure out what i'm missing and where.
Here is my code:
with open(join(dirname(__file__),'text.json')) as tone_json:
    python_obj = json.load(tone_json)       #read file object into string
    my_list = python_obj["data"]            #assign list name to string

for dictionary in my_list:                  #loop through dictionaries in list
    for key,value in dictionary.items():    #loop through key pairs in dictionaries
        if key == "text":
            with open('comments.json', 'w') as f:
                json.dump("{}: {}".format(key,value), f)    #write key pair objects as json formatted stream to json file
                f.write('\n')

A sample of my JSON file:
{
    "data": [
    {
        "text": "apple",
        "created_time": "2017-12-23",
        "comment_count": 154,
        "like_count": 856,
        "id": "1015595299xxxxx"
    },
    {
        "text": "orange",
        "created_time": "2017-12-04",
        "comment_count": 13,
        "like_count": 437,
        "id": "10155952xxxxx"
    },
    {
        "text": "grapes",
        "created_time": "2017-12-04",
        "comment_count": 12,
        "like_count": 163,
        "id": "1015595299xxxxx"
    }
    ]
}

My current output:
"text: grapes"

But, I want to loop through every dictionary and eventually print only the values from each "text" key.
Expected Output:
"text: apple"
"text: orange"
"text: grapes"

Any hints will help! Thanks!

A: You have opened file in w mode, you need to open it into a (append mode)
from docs:
1. 'w' for only writing (an existing file with the same name will be erased)
2. 'a' opens the file for appending; any data written to the file is automatically added to the end
Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> import json
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> for d in my_list:
...     for key, value in d.items():
...             if key == "text":
...                     with open('comments.json', 'a') as f:  # Append mode here
...                             json.dump("{}: {}".format(key,value), f)
...                             f.write('\n')
...

Contents of comments.json,
"text: apple"
"text: orange"
"text: grapes"

File modes in Python,
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)

A: If I did understand you correctly, this should do what you want:
with open('comments.json', 'a') as f:
    json.dump("{}: {}".format(key,value), f)    #write key pair objects as json formatted stream to json file
    f.write('\n')

Just change 'w' to 'a' so you don't overwrite but append to the file


text:
Q: Database design where % of rows have unused attributes/columns Is there a theory/practice that promotes a design by analysing the usage of attributes of a table, such that given a threshold of unused columns over a percentage of rows would suggest that the attributes do not actually belong that that table, but instead in a relationship?
example:
users
| id | name  | completed_sign_up |
| 1  | Bob   | null |
| 2  | Sarah | false |
| 3  | Penny | true |

The above false and nil cases are the same, so instead one could say completed_sign_up is not a property of users, but instead should be a join table on it, eg:
sign_ups
| id | user_id |
| 10 | 3

A: The question of 'when should nulls be used?' is touchy. See this post as an example. I haven't heard of a principle that is based on the percentage of null values. How would the threshold be decided?
To avoid nulls completely, I also thought of the same 'join table' solution you did: for every nullable column, convert it to a one-to-zero-or-one lookup table. I use that pattern occasionally in practice.


text:
Q: Using variables outside the function this is probebly a silly question but I don't know where else to ask this.
I need to call on $conn in the functions below, but if I try to turn it into a global it doesn't work. If someone can explain to me how to use an outside variable inside a function I'd be very grateful.
Here's my little piece of code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
 //Maak connectie met database
 $host = "localhost";
 $username = "i266161_studie";
 $password = "studie";
 $dbnaam = "test";
 $fout = "Error: Failed to open database";

 $conn = mysqli_connect($host, $username, $password, $dbnaam)
 or die ("Connection failed: ".mysqli_connect_error());

function insert_once($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Henk", 17, "Eindhoven")';
mysqli_query($conn,$query);
}

function insert_twice($conn){
$query = 'INSERT INTO gebruikers (naam, leeftijd, woonplaats)
VALUES ("Bert", 21, "Helmond"), ("Ruud", 32, "Helmond")';
mysqli_query($conn,$query);
}
insert_twice();

?>

A: don't use globals unless you REALLY have to! don't forget to pass your $conn parameter to your functions e.g.
change this:
insert_twice();

to this:
insert_twice($conn);

I'd suggest adding some error handling to your mysql_query() calls too, you should not assume that these are always successful

A: I personally would try 1) to create a connection class that has a static connection (basically a global without being a global) that allows you to create instances both inside and outside of functions. Also, if you make it a singleton, you can reuse the same connection without anymore resources 2) Make one function that can handle more than one insert. Below is just an example, use or don't use it, but it will give you a simple example, by no means is it complete, so use at your own risk:
interface.Database.php
interface   Database
    {
        public  static  function SetConnection($host,$username,$password,$dbnaam);
    }

class.MySQLConn.php
class   MySQLConn implements Database
    {
        protected   static  $host;
        protected   static  $username;
        protected   static  $password;
        protected   static  $dbnaam;

        public      static $connect;

        private function __construct()
            {
            }

        public  static  function SetConnection($host = "localhost",$username = "i266161_studie",$password = "studie",$dbnaam = "test")
            {
                self::$host     =   $host;
                self::$username =   $username;
                self::$password =   $password;
                self::$dbnaam   =   $dbnaam;
                self::$connect  =   (!isset(self::$connect))? self::Initialize() : self::$connect;
            }

        private static  function Initialize()
            {
                return new mysqli(self::$host, self::$username, self::$password, self::$dbnaam);
            }
    }

function.insert_into.php
// Make your insert a bit more robust
// Should be built out to accommodate preparing and binding
// This will handle one or multiple row insert
function insert_to($settings = false)
    {
        $con    =   MySQLConn::$connect;

        $table  =   (isset($settings['table']))? $settings['table']:"gebruikers";
        $cols   =   (isset($settings['cols']) && is_array($settings['cols']))? "(`".implode("`,`",$settings['cols'])."`)":false;

if($cols == false)
    return false;

if(is_array($settings['vals']) && !empty($settings['vals'])) {
        foreach($settings['vals'] as $values) {
                $sql[]  =   "('".implode("','",$values)."')";
            }

        return $con->query("INSERT INTO {$table} {$cols} VALUES ".implode(",",$sql));

    }
}

index.php
// Include assets
include_once('interface.Database.php');
include_once('class.MySQLConn.php');
include_once('function.insert_into.php');

// Create instance and initialize connection
MySQLConn::SetConnection();

// create settings (you could get them from posts)
// You have to sanitize user input or as mentioned bind/prepare values
$query["cols"]      =   array("naam","leeftijd","woonplaats");
$query["table"]     =   "gebruikers";
$query["vals"][]    =   array("Henk", 17, "Eindhoven");
$query["vals"][]    =   array("Ruud", 32, "Helmond");

insert_into($query);


text:
Q: PyObjC - NSTableView with checkboxes mapping to Python throws class is not key value coding-compliant I am building a Mac application using PyObjC. In Interface Builder I have a NSTableView. The Columns are filled with NSTextFieldCells and NSButtonCells.
I fill it with data using an array controller that itself is filled through a Python list of dicts. Instead of "Python dicts" I have also tried NSMutableDictionary. The keys representing NSTextFieldCells are filled with strings and the NSButtonCells with Booleans. For the latter I have also tried: 1/0, "Yes"/"No", and NSNumber.numberWithBool_ .
The stream of data from Python to the GUI works without a problem.
My problem is, that whenever I click on a checkbox it throws me:
(from bound object <NSTableColumn: 0x1067a52f0> identifier: (null)): [<__NSDictionaryI 0x10a604ed0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key checkb.

How can I get the states of the checkboxes back into my Python code?


text:
Q: Logging to Azure from on-premise site I have a .net application not hosted in Azure. I would love to be able to read it's log and traces from a centralized place. I thought immediately of Azure Blob Storage as a good place to do so.
When inside Azure, I am familiar with enabling logging in .cscfg file:
Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString.

But in that case, the application is NOT in Azure.
Is it possible ?... i mean without going against best practices...
If yes, how to do so ?
If no, any other centralized logging and tracing system that you would recommend ?

A: Not storing logs in Azure, but we host our applications in Azure and store our logs in Logentries.com - great free tier, excellent analytics and works from localhost/Azure/any other location with internet you can imagine.

A: I think it shouldn't be difficult to achieve this with AZ-Copy tool. It is resumable and resilient, IHMO with the right switches and as a scheduled task it can be a very robust solution for your purposes.
Going further into detail, I have the idea that it should be feasible to make use of that old-fashined 'archive' file attribute to keep track of what is pending to being uploaded, and with a simple command line delete what has already been uploaded.

Furthermore, in one hand, with SQL PolyBase one can afterwards make queries to the Azure Storage uploaded files as if they were on a Sql Table, or on the other hand, point Azure PowerBI to prepare a dashboard if necessary.
(In fact, I plan to do it myself when I have a bit of time for testing, I'll update this answer with my findings.)


text:
Q: Failure Could not find file ...App.g.i.cs I'd like to stop this error appearing in the Intellisense section in the Output window in Visual Studio:
[Failure] Could not find file 'C:\code\CatApp\obj\x86\Debug\App.g.i.cs'.
I've cleared obj and bin folders, upgraded to the latest version of Visual Studio 2017,cleared all nuget packages and checked my project out from SVN again.
I get the same problem if I create a new UWP project. (Every time I create a new UWP project, I have to get the Nuget package Microsoft.NETCore.UniversalWindowsPlatform separately. I'm wondering if the two problems could be related.)
My target and min version are 16299.


text:
Q: Why and how can arrange do the same as a combination of mutate, arrange and select in one line? This question arose by working on this The R dplyr function arrange(ymd(col)) is not working
We have this data frame:
df <- structure(list(record_id = 1:5, group = c("A", "B", "C", "D",
"E"), date_start = c("Apr-22", "Aug-21", "Jan-22", "Feb-22",
"Dec-21")), class = "data.frame", row.names = c(NA, -5L))

  record_id group date_start
1         1     A     Apr-22
2         2     B     Aug-21
3         3     C     Jan-22
4         4     D     Feb-22
5         5     E     Dec-21

We would like to sort date_start:
My first approach: worked
library(dplyr)
library(lubridate)
df %>%
  mutate(date_start1 = myd(paste0(date_start,"-01"))) %>%
  arrange(date_start1) %>%
  select(-date_start1)

  record_id group date_start
1         2     B     Aug-21
2         5     E     Dec-21
3         3     C     Jan-22
4         4     D     Feb-22
5         1     A     Apr-22

Then I tried this and it also worked
library(dplyr)
library(lubridate)
df %>%
  arrange(date_start1 = myd(paste0(date_start,"-01")))

  record_id group date_start
1         2     B     Aug-21
2         5     E     Dec-21
3         3     C     Jan-22
4         4     D     Feb-22
5         1     A     Apr-22

I would like to understand how one arrange can do the same as a combination of mutate, arrange and select

A: What the code is not doing
The output of arrange() is perhaps surprising because you think it is doing the following:
Everything to the right of the = is just a function to create a vector.
time_col <- df$date_start %>%
  paste0(.,"-01") %>%
  myd() %>%
  print()
#> [1] "2022-04-01" "2021-08-01" "2022-01-01" "2022-02-01" "2021-12-01"

The = of course is assignment to a new column :
  df <- df %>%
  mutate(date_start1 = time_col) %>%
    print()
#>   record_id group date_start date_start1
#> 1         1     A     Apr-22  2022-04-01
#> 2         2     B     Aug-21  2021-08-01
#> 3         3     C     Jan-22  2022-01-01
#> 4         4     D     Feb-22  2022-02-01
#> 5         5     E     Dec-21  2021-12-01

You're then sorting on that variable:
  df %>% arrange(date_start1)
#>   record_id group date_start date_start1
#> 1         2     B     Aug-21  2021-08-01
#> 2         5     E     Dec-21  2021-12-01
#> 3         3     C     Jan-22  2022-01-01
#> 4         4     D     Feb-22  2022-02-01
#> 5         1     A     Apr-22  2022-04-01

What the code is doing
If you look at the output, the code is not actually doing what is shown previously and then removing a column. It is missing the new column date_start1 without us even needing to remove it manually:
  df %>%
    arrange(date_start1 = myd(paste0(date_start,"-01")))
#>   record_id group date_start
#> 1         2     B     Aug-21
#> 2         5     E     Dec-21
#> 3         3     C     Jan-22
#> 4         4     D     Feb-22
#> 5         1     A     Apr-22

The key then is to understand that you are not creating a new variable that is added to the data.frame, sorting on it, then removing it. Rather, you are passing a set of values (one per row) on which to sort.
Why this is possible
This is permitted because you can pass any arbitrary vector that may (not) be a function of the variables in the data. As noted in the documentation for arrange(), the second argument is:

 Variables, or functions of variables. Use desc() to sort a variable in descending order.

All you are doing is passing a function of variables! This is why you can also do:
  df %>%
    arrange(1:nrow(df) + record_id)
  #>   record_id group date_start
  #> 1         1     A     Apr-22
  #> 2         2     B     Aug-21
  #> 3         3     C     Jan-22
  #> 4         4     D     Feb-22
  #> 5         5     E     Dec-21


text:
Q: Relating volume elements and metrics. Does a volume element + uniform structure induce a metric? AFAIK a metric uniquely determines the volume element up to to sign since the volume element since a metric will determine the length of supplied vectors and angle between them, but I do not see a way to derive a metric from the volume element. The volume form must heavily constrain the the set of compatible metrics though. So is there a nice statement of what the volume element tells you about a metric that is compatible with it?
If you have a volume element what is the least additional information you need to be able to derive a metric?
EDIT:
Is the minimum additional information uniform structure?
A volume element gives us a kind of notion of local scale but much weaker than a metric. We can can measure a volume, but we can't tell if it looks like a sphere, a pancake or string (that is the essence of @Rhys's answer). To get a metric we need to be able to tell that a volume is "spherical", or to compare distances without assigning an actual value to them, since if we can do that then we can use use the the volume to determine the radius of a hypershere in the limit of small volumes. So the last part of my question is really asking how to do that without implicitly specifying a metric. I believe that uniform structure does this. It specifies a set of entourages that are binary relations saying that points are within some unspecified distance from each other. An entourage determines a ball of that size around each point. To induce a metric, the uniform structure needs to be compatible with the volume element by assigning the same volume to all the balls induced by the same entourage in the limit of small spheres (delta epsilonics required to make this formal). The condition will not hold for macroscopic spheres if the uniform structure is inducing a curved geometry. There must also be some conditions for the uniform structure to be compatible with the manifold structure.
Does this make sense?

A: The volume form tells you very little about the metric.  Let $V$ be an $n$-dimensional vector space, with volume form $v_1\wedge \ldots \wedge v_n$, where $\{v_1,\ldots,v_n\}$ are linearly independent elements of $V$ (any volume form can be written this way).  Now define a metric by the condition that this be an orthonormal set; this metric gives you the above volume form.  But it's far from unique, as there are many choices of $n$ vectors which give the same volume form.
The same story should apply on some small enough patch of a Riemannian manifold.


text:
Q: How to exclude rows from an aggregate based on the rest of the rows in the aggregate I've tried to simplify this a little without removing any pertinent information, so here goes...
I am trying to rewrite a view which currently aggregates data, but based on the aggregate of some of the data it may or may not include other data. For example:
;WITH CTE_ExtraFees AS
(
    SELECT AccountID, SUM(Amount) AS TotalAmount
    FROM AccountFees
    WHERE
        FeeType = 'EXTRA' AND
        AccountType = 'P'
    GROUP BY
        AccountID
)
SELECT
    AccountID,
    CASE
        WHEN SUM(F.Amount) > 0 THEN SUM(F.Amount) - XF.TotalAmount
        ELSE SUM(F.Amount)
    END AS FeeAmount
FROM
    AccountFees F
LEFT OUTER JOIN CTE_ExtraFees XF ON XF.AccountID = F.AccountID
GROUP BY
    F.AccountID,
    XF.TotalAmount

There's quite a bit more logic on which extra fees are excluded, but I've worked all of that out and the above is the last sticking point for me. I now have something similar to this:
SELECT
    AccountID,
    SUM(Amount) AS FeeAmount
FROM
    AccountFees
WHERE
    (
        FeeType <> 'EXTRA' OR
        AccountType <> 'P'
    )
GROUP BY
    AccountID

The problem of course is that when the SUM(Fees) <= 0 I still end up excluding the extra fees.
I'd like to avoid having multiple aggregates performed for performance reasons, so I was hoping to do this all in one aggregation, but I can't seem to come up with anything to accomplish the same logic.
Thanks for any help or suggestions that you can give!

A: SELECT
      AccountID
    , FeeAmount =
        CASE WHEN SUM(Amount) > 0
            THEN SUM(Amount) - SUM(CASE WHEN FeeType = 'EXTRA' AND AccountType = 'P' THEN Amount ELSE 0 END)
            ELSE SUM(Amount)
        END
FROM dbo.AccountFees
GROUP BY AccountID

A: How about
SELECT
    AccountID,
    SUM(
        CASE WHEN FeeType = 'EXTRA' AND AccountType = 'P'
            THEN -1 * Amount
            ELSE Amount
        END
    ) AS FeeAmount
FROM AccountFees
GROUP BY AccountID

I think they key part that you may have been missing on this problem is the fact that you can run a Sum function on a case statement, which is used both in my answer and in Devart's answer (which, by the way, I feel more comprehensively encompasses the logic of the original query). The case statement will fire on a row-by-row basis and then provide its results to the sum function, which results in a conditional sum function.


text:
Q: RegExp match in Swift I use a code from Swift extract regex matches
func matchesForRegexInText(regex: String!, text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

I try match this pattern (sample pattern) "^([a-z]+).*?(\d+)$"
And if I use it for string "abc.....123" I get as result this full string...
But I want to get array of strings ["abc", "123"]

A: You have to get the subranges of the captured groups – the expressions of the regex within the parentheses respectively – with rangeAtIndex() of the first match.
Since the range of the full string is at index 0, start the loop at index 1.
func matchesForRegexInText(regex: String, text: String) -> [String] {
  var result = [String]()
  do {
    let regex = try NSRegularExpression(pattern: regex, options: [])
    let nsString = text as NSString
    if let match = regex.firstMatchInString(text, options: [], range: NSMakeRange(0, nsString.length)) {
      for i in 1..<match.numberOfRanges {
        result.append(nsString.substringWithRange(match.rangeAtIndex(i)))
      }
    }
  } catch let error as NSError {
    print("invalid regex: \(error.localizedDescription)")
  }
  return result
}

PS: Not everything in Swift needs a ? or !. The exclamation marks in the parameter strings are meaningless as none of them is actually considered as optional.


text:
Q: PHP PDO Update SQL Syntax Error I am new to PDO and I'm trying to build my own CRUDS application. I already created CRD but I'm getting stuck with Updating user information. It seems that I have a problem with my syntax, but I thoroughly checked the documentation and I can't figure out what is wrong with the code. It's passing me this error:
ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Doe, email=johndoe@gmail.com, location=New York City WHERE id=1' at line 1
Here is my code:
include('database.inc.php');

if (isset($_POST['submit'])) {

$id = $_POST['userId']; // 1
$name = $_POST['employee_name']; // John Doe
$email = $_POST['email']; // johndoe@gmail.com
$location = $_POST['location']; // New York City

    try {

     $query = "UPDATE users SET employee_name=$name, email=$email, location=$location WHERE id=$id";
     $statement = $conn->prepare($query);
     $statement->execute();

     header('Location: ../index.php');

     } catch(PDOException $e) {

    echo 'ERROR: ' .$e->getMessage();

     }

}

A: The problem with your code is that you didn't put quotes around the string values in the SQL. But you should use parametrized queries, not substitute variables into the SQL. This solves the quoting problem, and also prevents SQL injection.
$query = "UPDATE users SET employee_name=:name, email=:email, location=:location WHERE id=:id";
$statement = $conn->prepare($query);
$statement->execute(array(':name' => $name,
                          ':email' => $email,
                          ':location' => $location,
                          ':id' => $id));

A: Try surrounding the variables in the statement with single quotes ( ' )
$query = "UPDATE users SET employee_name='$name', email='$email',
location='$location' WHERE id='$id'";


text:
Q: How to display Dash Home by keyboard shortcut I wish to press Super (or any other key combination) and start typing to launch programs. How do I do it?
Thanks

A: super key is the default key for "dash home".
By the way, press super key and hold it, and it will show you all keyboard shortcuts.

A: Super is the key you press to access Dash Home.
    The Super key is equivalent to the windows logo key or the ⌘ (command) key.
In Ubuntu, it's just another name for the windows logo key.

You can always change mapping of such keys. In Ubuntu 12.04 you can do so from
System Settings -> Keyboard Layout -> options -> Alt/Win key behavior.

A: Super key is the default key for opening dashboard.
You can find more help from this link
or otherwise you can use Compiz Configuration Settings Manager for changing keys
install compizconfig-settings-manager
sudo apt-get install compizconfig-settings-manager

After that open dash and type ccsm, then go to unity plugin option

Change key from here.


text:
Q: Is there any ojAlgo solver for when the condition number is large and the matrix is symmetric and indefinite? I use ojAlgo to solve a system of linear equations.
In one case I get a RecoverableCondition exception. Probably because matrix is ill-conditioned, the condition number is about 1e15.
I use ojAlgo to solve it as seen in the code below. It usually works, but not in this case.
Is there any other solver I could use for a symmetric indefinite (ill-conditioned) matrix?
The present failing size is 18x18 but later 1000x1000 might be needed. Since its part of a iterative algorithm the accuracy is not super important.
         SolverTask<Double> equationSolver = SolverTask.PRIMITIVE.make(KKT, rhs.negate());
         MatrixStore<Double> deltaX = null;
         try {
            deltaX = equationSolver.solve(KKT, rhs.negate());
         } catch (RecoverableCondition ex) {
            int i = 0;
         }

I tried to reproduce this in a self contained example but failed, because there it works. Maybe I do not get exactly the same matrix down to the last bit.

A: In your case, that method would use a Cholesky decomposition as the solver.
If here's a problem then try to pick another decomposition by instantiating a suitable alternative directly. An SVD can usually handle anything, but that would be very expensive. Perhaps QR can be ok.
QR<Double> qr = QR.PRIMITIVE.make(templateBody);
qr.decompose(body);
qr.getSolution(rhs,x);

This way you can reuse the decomposition instance as well as the solution vector x.
Another alternative is to precondition the body/KKT matrix. Perhaps add a small diagonal - just enough to make the Cholesky decomposition solvable.
if (!cholesky.isSolvable()) {
    // Fix that
}

Or perhaps try something in the org.ojalgo.matrix.task.iterative package.


text:
Q: UiViewController - Pop doesn't pop I'm displaying UIControllerView subclass when a button is pressed from a another UIViewController like this:
- (IBAction)openNextLevelViewController
{
    NSLog(@"openNextlevelViewController");

    [self.navigationController pushViewController:nextLevelViewController animated:YES];

}

And the app will return from that view on a button push which trigger this method:
-(IBAction) returnToStart {

    NSLog(@"returnToStart method called");
    [self.navigationController popViewControllerAnimated:YES];

}

The problem is that the displayed view not getting destroyed/deallocated on the pop. As a result, when it gets pushed, it's not executing the viewDidLoad, which initiates some variables. This may be causing a related problem where, the second time through, when the user presses the return button, the "pop" no longer causes a return to the previous controller.
What's the best way to deal with this? I could move the initialization code to the "willAppear" method, but it seems as if that could be called almost randomly.

A: Well, its not getting released because nextLevelViewController is still being retained somewhere else. Most likely in your nextLevelViewController variable.
- (IBAction)openNextLevelViewController
{
    NSLog(@"openNextlevelViewController");
    // assuming you have nib already set up
    UIViewController *nextLevelViewController = [[NextLevelViewController alloc] init];
    // RETAIN COUNT = 1

    // navigationController retains your controller
    [self.navigationController pushViewController:nextLevelViewController animated:YES];
    // RETAIN COUNT = 2

    // Don't need it any more let navigation controller handle it.
    [nextLevelViewController release]
    // RETAIN COUNT = 1 (by NavigationController)
}

Further On
-(IBAction) returnToStart {
    [self.navigationController popViewControllerAnimated:YES];
    // RETAIN COUNT = 0, dealloc will be called on your viewController, make sure to release all your retained objects.
}

Now when your controller gets popped, it SHOULD get released (shouldn't have been retained anywhere else). And next time you call openNExtLevelViewController, it'll be initializing a new instance of your viewController anyway.
I'm a fan of releasing viewController when it is no longer needed (displayed), instead of holding it in memory. Let navigationController and TabBarController handle viewControllers whenever possible.


text:
Q: Consider the system $\dot{x}=(x-2y)(x^2-1), \dot{y}=(3x+y)(x^2-1)$ Consider the system
$$\dot{x}=(x-2y)(x^2-1), \dot{y}=(3x+y)(x^2-1)$$
Determine the stability property of the system equilibria. If an equilibrium is asymptotically stable, give an estimate of its attractiveness basin. (For $(0,0)$ use the Liaponouv $V(x,y)=3x^2+2y^2$ function)
I have already tried to solve this problem and I get to that $(0,0)$ is a balance point but I do not know how to find the others, is there only this balance point? I already found the attractiveness basin of $(0,0)$, but I need to know the other points of balance.

A: (x, y) is an "equilibrium point" (your "balance point" though it seems strange that you would ask about "system equilibria" without using the phrase "equilibrium point") if and only if $x'= (x- 2y)(x^2- 1)= 0$ and $y'= (3x+ y)(x^2- 1)= 0$.  That will clearly be true if $x^2- 1= 0$.  That is, if x= 1 or -1 with y anything.  Every point along the lines x= 1 and x= -1 is an equilibrium point.  If $x^2- 1\ne 0$, we must have both x- 2y= 0 and 3x+ y= 0 and, of course, the only (x, y) that satisfies those is (0, 0).  That is, the equilibrium points are (0, 0), (1, y) for all y, and (-1, y) for all y.

A: Your equations are $x˙=(x−2y)(x^2−1)$, $y˙=(3x+y)(x^2−1)$.  The equilibrium points are, as others have said, points where x'= 0 and y'= 0.  That is, $(x- 2y)(x^2- 1)$, $(3x+ y)(x^2- 1)= 0$.  First, if x= 1 or x= -1, y can be anything so every point on the line x= 1 or on the line x= -1 is an equilibrium point.  If $x^2- 1$ is not 0, then we must have x- 2y= 0 and 3x+ y= 0.  From the second equation, y= -3x so the first equation becomes x- 2(-3x)= 7x= 0, y= 0 and then x= 0.  (0, 0) is also an equilibrium point.  Whether that equilibrium point is "stable" or "unstable" depends on what happens close to (0, 0) so we can linearize the equations.  That is, if x is close to 0, $x^2$ is a lot closer- we can drop it and $y^2$.  The "linearized" equations are x'= x- 2y and y'= 3x+ y.  Differentiating again, x''= 1- 2y'= 1- 2(3x+ y)= 1- 6x+ 2y.  From the first equation 2y= x- x' so x''= 1- 6x+ x- x' or x''+ x'+ 5x= 1.  Solve that to find the trajectories and then use the original equation to see if solution move along those trajectories toward or away from (0, 0).


text:
Q: How can I allow user to download or view a PDF online that I am hosting in my static folder? I have a modal that stores the file_name, file_link, is_active and an uploaded on field. I can add the PDF via the admin site but I am trying to allow the users the ability to download the PDF or view the PDF on a new tab from the front end webpage that I created.
Currently, the view that I created is getting the information for each PDF so that I can display the name, link, etc. If I put the {{ pdf.file_link }} into an  it doesn't do anything.
I would really appreciate getting some assistance on this so that I can stope spinning my wheels. Thank you in advance!+
EDIT:
Models:
class HelpfulPDF(models.Model):
    file_name = models.CharField(max_length=256)
    file_link = models.FileField(upload_to='pdfs')

    uploaded_on = models.DateField(auto_now=True)

    is_active = models.BooleanField(default=True)

    def __str__(self):
        return "{} - {}".format(self.id, self.file_name)

View:
As you can see in the view, I am only getting the date from the model. I am not doing anything special with the actual PDF yet. That is the question.
@login_required()
    def help_center_view(request):
    data = dict()
    data['userprofile'] = request.user.userProfile
    data['get_pdfs'] = HelpfulPDF.objects.filter(is_active=True)

    return render(request, 'help_center.html', data.items())

Template:
{% extends 'base.html' %}

{% load staticfiles %}

{% block content %}

            Please look at the below PDF's. (You can view   in browser or download to your computer)

    {% if get_pdfs %}
        {% for each_pdf in get_pdfs %}

                {% if each_pdf.file_name %}

{{ each_pdf.file_name }}

                {% else %}

Helpful PDF

                {% endif %}

                    <button class="btn-primary btn-sm">Download PDF</button>
                    <button class="btn-primary btn-sm">View PDF Online</button>

        {% endfor %}
    {% else %}

There are no PDF's to display at this time.

    {% endif %}

{% endblock %}

A: If your link to the pdf file works (try going to it in your browser and see what happens), then it should be possible to do the equivalent of this in your template:

Add the target="_blank" attribute to have it open in another tab.
You can add a download attribute to the anchor element if you want it to download on click.
The browser should handle opening or downloading the PDF automatically.  If not, then either your link is not valid (the most likely cause) or (much less likely because you'd probably know it) your server is sending the wrong content-type header in the response (which you can inspect from the browser dev console in the Network tab on Chrome).

A: You can create a view to proxy the PDF files and return specific headers, see the following answer: How to show a PDF file in a Django view


text:
Q: How can I alter this code to accept a slug as well as an ID? This code is from the codex.
/* ==  If In Parent Category... ==============================*/

if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}

I use it in the theme like this:
if ( post_is_in_descendant_category( 11 ) ) ...
It only accepts the post ID (11), however, and I'd like it to accept the slug. Is there a way to alter this code somehow to accept the slug?

A: The Codex essentially explains how to do this:

if ( $category_to_check = get_term_by( 'name', 'fruit', 'category' ))
   post_is_in_descendant_category($category_to_check->term_id);

https://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category

Putting it all together in your function you would have:
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
    function post_is_in_descendant_category( $cats, $_post = null ) {
        foreach ( (array) $cats as $cat ) {
            if (!absint($cat)) {
//            $cat = get_category_by_slug($cat); // option one
              $cat = get_term_by('slug',$cat,'category'); // option two
//            $cat = get_term_by('name',$cat,'category'); // option three; by category name, not slug, as in the Codex
              if(!$cat) return false;
              $cat = $cat->term_id;
            }
            // get_term_children() accepts integer ID only
            $descendants = get_term_children( (int) $cat, 'category' );
            if ( $descendants && in_category( $descendants, $_post ) )
                return true;
        }
        return false;
    }
}


text:
Q: How to switch from blank activity to tabbed activity without doing major changes to code? I have made an app that is well tested and complete. It is currently using blank activity. I now want to add multiple screens so I decided to switch to a tabbed activity. I tried simple copy pasting code at necessary places in the fragment from old mainActivity but I got runtime errors. I can definitely fix them but it will take a lot of time (fixing and re-testing). Is there any other workaround. Like by converting previous activity view and pass to fragment without changing(a bit is fine) MainActivity.class . I simply don't have enough time to do major changes. Even a hint will be enough.

A: For making it a "Tabbed" Activity you must go through these steps:

*Add a viewpager as root to your activity layout

*Setup an adapter for the viewpager

*Move your code from you main activity to a fragment(s)
That's it after that your activity will be converted into a tabbed activity. It might seem a lot to do at first but once you get through it you will realise viewpager is one of the most basic element in android development.
Here are some helpful links to know more about viewpager.
 codepath guide
 Official docs
http://blog.appliedinformaticsinc.com/android-viewpager-a-quick-guide/
If you want to just save yourself the pain of reading and understanding viewpager(which I do not recommend), Android Studio lets you create a TabbedActivity. Either initialise a new project or create a new Tabbed Activity in your project and copy paste your code from blank activity to tabbed activity.
In case you decide to make a new Activity in your current project, don't forget to change the Launcher Activity in Android Manifest.


text:
Q: Does duplex patch fiber optic cable (LC-LC) need termination box/splicing? The duplex fiber optic cable (LC-LC) I am talking about looks like this

I am trying to run an outdoor cable about 120m and was informed that I need to have splicing and a termination box. But based on this picture it seems I can just have this kind of connector which is 120m long and plug into a SFP module on both end?

A: Well, you could - provided you can find one long enough and appropriate for outdoor usage. The outdoor cables must sustain weather conditions, especially UV radiation coming from the Sun - they are usually black, as the jacket colors usually are meaningful (e.g. the patchcord from your photo is apparently some multimode).


text:
Q: Creating a linked list, templated Stack I am trying to compile the code my instructor has given us (had to retype it, but I can't find any typos) and it will not compile. We will be using this code for later assignments so I want to make it work before we get there.
It should simply make a linked-list based stack. I understand how the code works, and I have done templates before, but I can't figure out why it won't compile.
First Stack.h
#ifndef STACK_H
#define STACK_H
//Stack definition file
//Stack.h

template<class ItemType>
struct NodeType<ItemType>; //Line 9

template<class ItemType>
class StackType {
public:
    StackType();
    ~StackType();
    void MakeEmpty();
    void Push(ItemType);
    void Pop(ItemType &);
    bool IsEmpty() const;
    bool IsFull() const;
    ItemType Top();

private:
    NodeType* topPtr;
};

template<class ItemType>
struct NodeType<ItemType> {
    int info;
    NodeType<ItemType>* next;
}; //Line 34

#include "Stack.cpp"

#endif

Stack.cpp
//Stack implemenation
#include <iostream>

template<class ItemType>
StackType<ItemType>::StackType() { //Line 5
    topPtr=NULL;
}

template <class ItemType>
StackType<ItemType>::~StackType() { //Line 11
    MakeEmpty();
}

template <class ItemType>
void StackType<ItemType>::MakeEmpty() {
    NodeType<ItemType>* tempPtr;

    while (topPtr != NULL) {
        tempPtr = topPtr;
        topPtr = topPtr->next;
        delete tempPtr;
    }
}

template <class ItemType>
void StackType<ItemType>::Pop(ItemType & item) {

    NodeType<ItemType>* tempPtr;
    item = topPtr->info;
    tempPtr = topPtr;
    topPtr = topPtr->next;
    delete tempPtr;
}

template<class ItemType>
void StackType<ItemType>::Push(ItemType item) {
    NodeType<ItemType>* location;
    location = new NodeType<ItemType>;
    location->info = newItem;
    location->next = topPtr;
    topPtr = location;
}

template <class ItemType>
bool StackType<ItemType>::IsEmpty() const {
    return (topPtr=NULL);
}

template <class ItemType>
bool StackType<ItemType>::IsFull() const {
    return (false);
}

template<class ItemType>
ItemType StackType<ItemType>::Top() {
        return topPtr->info;
}

and main.cpp
#include <iostream>
#include "Stack.h"
using namespace std;

int main () {

    int whatever;
    StackType<int> s;
    s.Push(10);
    s.Push(1);
    s.Pop(whatever);
    return 0;

}

The errors I get are

c:\users\geldhart\dropbox\cs210\stack\stack.h(9):
    error C2143: syntax error : missing ';' before '<'
  c:\users\geldhart\dropbox\cs210\stack\stack.h(9):
    error C2059: syntax error : '<'
  c:\users\geldhart\dropbox\cs210\stack\stack.h(34):
    error C2753: 'NodeType' : partial specialization cannot match argument list for primary template
   Stack.cpp
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(5):
    error C2143: syntax error : missing ';' before '<'
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(5):
    error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(5):
    error C2988: unrecognizable template declaration/definition
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(5):
    error C2059: syntax error : '<'
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(11):
    error C2588: '::~StackType' : illegal global destructor
  c:\users\geldhart\dropbox\cs210\stack\stack.cpp(11):
    fatal error C1903: unable to recover from previous error(s); stopping compilation

A: This syntax
template<class ItemType>
struct NodeType<ItemType>; //Line 9

would possibly be for partially specializing some existing NodeType.
To (forward) declare the type, you just need
template<class ItemType>
struct NodeType;


text:
Q: Image saves to server but doesn't appear in browser when using header() I've set up jCrop so that users on my site can crop and save (download) images. I'm near the end now however I've hit a wall. I've got the code set up (see below) and when I comment out the header() line everything works as intended, the cropped image is saved to the server and I can download it from there.
The problem is that when I include the header and broken image is returned and I'm really not sure why. If anyone could help I would be most grateful
<?php
//$_POST['src'] = http://example.com/example.jpg
$image_url = $_POST['src'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $image_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

$targ_w = $_POST['w']; $targ_h = $_POST['h'];

$image = imagecreatefromstring( $data );
$dst_r = imagecreatetruecolor( $targ_w, $targ_h );

if ( !$image )
    exit( 'No valid image' );

$path = '/home/hostname/public_html/'.time().'-image.jpg';

imagecopyresampled( $dst_r, $image, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h'] );

//header( 'Content-Type: image/jpeg' );

imagejpeg( $dst_r, $path, 100 );

imagedestroy( $dst_r );
//unlink( $path );
exit;
?>

Currently as the code stands the image is saved in the root of the site. If I uncomment the unlink() the image is deleted from the directory (which is intended). If I uncomment the header() line then a page is returned containing a broken image with the src matching the page url.
Thank you.

A: Like the documentation specifies, the second argument of imagejpeg should be NULL if you want to output the image directly.
Try changing imagejpeg( $dst_r, $path, 100 ); to imagejpeg( $dst_r, NULL, 100 );.
Edit: this also saves you from using unlink, since no file is made.


text:
Q: How to delete entries/relationships in SugarCRM Web Service SugarCRM Web Service API provide only methods for Set and Get entries/relationships.
How can I do delete/remove entries and their relationships with entries in other related modules?
Is the  Web Service API designed only for Get and Set?

A: You can set the 'deleted' flag to '1' as one of the fields in the 'name_value_list' in the set_entry/set_entries call and it will mark a record deleted.
http://gist.github.com/4019840
For relationships, you can use set_relationship/set_relationships and pass the argument '1' for the 7th argument to that call will delete the relationships instead of add them.
http://gist.github.com/4019851


text:
Q: Starting an application when starting Apache Server Is there a way to start a Java application when launching Apache Server? I need to generate a report of the server's statistics, periodically, with a separate application.

A: On Windows: Create a batch file; which will start both Apache and Tomcat services one after another. See below:
sc start MyService


text:
Q: Can't write to S3 when using AWS Batch Container I'm trying to run a very simple script that writes to S3 from an AWS batch job.
When I run the container locally on my machine, I can write to the S3 bucket (the credentials are stored in the container...which I know is not advised, but in this case is simply to test). However, when I start a batch job with this same container, I cannot seem to write to s3.
The batch job will succeed, but the S3 bucket doesn't show the file that should have been written.
The command I give the batch job is below
python3 -c \
'import boto3; s3=boto3.resource("s3"); f=open("test.txt", "w");
f.write("works"); f.close();
s3.Object(<bucket>, "test.txt").upload_file("test.txt")'


text:
Q: Can't license ArcGIS Pro from an evaluation I have the evaluation version of ArcMap 10.3 and it is working well. However, I was trying to run the associated ArcGIS Pro 1.4 but it won't allow me in. It keeps asking me for my ESRI account details and whenever I put it, it pops out an error notification that I cannot use it as an individual. Please, I need assistance on this.

A: I've just installed ArcMap & ArcGIS Pro trials. These two links will give you some background info:
https://pro.arcgis.com/en/pro-app/get-started/install-and-sign-in-to-arcgis-pro.htm
https://pro.arcgis.com/en/pro-app/get-started/licensing-arcgis-pro.htm
You should have been prompted to create a new ESRI account with your trial. Using these account details, log into My ESRI and authorise access to ArcGIS Pro.


text:
Q: Restore Photos/Videos Back to iPhone Camera Roll If you connect the iPhone to Windows, it comes up in the Computer as a digital camera and lets you Copy/Move photos/videos easily from there, you don't need to use Photos on the Mac.
If, after connecting like above, you move (not copy) all the photos and videos to a folder on the PC, they will obviously disappear from the Camera Roll in iPhone.
Is it possible to restore the photos and videos back to the Camera Roll?
I have accidentally moved (instead of copying) lots of photos and videos from my iPhone to a folder Windows 7. It slipped my mind that there were a few slow-mo videos which will not play without iPhone/iMovie.
Also, when photos are viewed on iPhone, it displays the location name in the title, which I cannot have once I have moved photos to the computer. In the JPG metadata I only see the Latitude and Longitude saved there.
Thus I prefer to undo this mistake and take photos/videos back to iPhone, is there a way?

A: I finally resolved this by using iTunes Sync to add photos to an album in iPhone. It is only slightly different as my photos went back to a separate album, not Camera Roll but that's okay. I noticed that the location name was restored and since it syncs Videos too, I'm sure slow-mo videos would work the way they should.
Also, latest Quicktime player on Mac plays slow-mo videos just like the iPhone.

A: I'm not familiar with Windows but it seems that this may work. If you have the iCloud Control Panel installed you should navigate to your Pictures folder and open the Photo Stream folder. In here you can paste your photos into the Uploads folder and they will automatically sync to your iPhone. Videos cannot be synced through this method, however they can be added using the Photos tab in iTunes.
Source


text:
Q: GWT: Get current time as a float since long isn't supported I am making a GWT game using LibGDX and it relies on using the current time to compare differences between the server state and the client state.
I am currently using longs that I get using System.currentTimeMillis() but GWT doesn't support this.
Is there a way to get the current time as a float in seconds (not milliseconds), since float is supported in JavaScript?
Thanks.

A: I found that using long only doesn't work when serializing with Reflections using JSON.
The solution is to replace all longs with doubles in all objects that are being serialized.
So yes, you can use System.currentTimeMillis().


text:
Q: storing variables in dictionary and descending order sorting In my code how can i store and sort in descendinng order in a dictionary.
I wanted to store Item as key, and Mutual_information as value and store them in a descending order based on the Mutual_information numerical value, in a dictionary.
My coding, which contains variables item and Mutual_information:
for item in lines:
    specificy = c[item]
    try:
        MI1= specificy/float(specificx)
        MI2= MI1*specificx
        M13= specificx*specificx
        Mutual_Information = MI1* math.log(MI1/float(MI2))
        print item, Mutual_Information #to be stored in descendin
    except ZeroDivisionError:
        print "divide by zero"

A: As I mentioned in a comment dicts are unordered so this will get all the items in a list then sort in reverse order and create an OrderedDict from those sorted elements:
from collections import OrderedDict
from operator import itemgetter

# store all key,value pairings to sort later
items = []
for item in lines:
    specificy = c[item]
    try:
        MI1= specificy/float(specificx)
        MI2= MI1*specificx
        M13= specificx*specificx
        Mutual_Information = MI1* math.log(MI1/float(MI2))
        # add tuple of key/value to items
        items.append((item,Mutual_Information))
    except ZeroDivisionError:
        print "divide by zero"

# create OrderedDict from sorted items, sorting by the second element
d = OrderedDict(sorted(items,key=itemgetter(1),reverse=True))

An example using a list of tuples:
from collections import OrderedDict

items = [(1, 3), (4, 7), (2, 4), (6, 10)]
from operator import itemgetter

d = OrderedDict(sorted(items, key=itemgetter(1), reverse=True))
print(d)
OrderedDict([(6, 10), (4, 7), (2, 4), (1, 3)])


text:
Q: SQLAlchemy и Python3 - как превратить выборку с повторяющимися значениями в таблицу Задача наверняка типовая, но я что-то не могу найти инфу.
Мы каждый день получаем информацию и записываем ее в базу данных, допустим примерно так:
id  параметр    дата      значение
1 | Параметр1 | 1 января | 100 ед.
2 | Параметр2 | 1 января | 200 ед.
3 | Параметр1 | 2 января | 101 ед.
4 | Параметр2 | 2 января | 201 ед.
5 | Параметр1 | 3 января | 102 ед.
6 | Параметр2 | 3 января | 202 ед.
7 | Параметр1 | 4 января | 103 ед.
8 | Параметр2 | 4 января | 203 ед.

Как на Python и SQLAlchemy принципиально правильно реализовать выгрузку, чтобы вывести в каком-то view вот такую таблицу:
параметр    | 1 января | 2 января | 3 января | 4 января
Параметр 1  | 100 ед   | 101 ед   | 102 ед   | 103 ед
Параметр 2  | 200 ед   | 201 ед   | 202 ед   | 203 ед

A: В данном случае удобно будет воспользоваться модулем Pandas:
import pandas as pd
from sqlalchemy import create_engine

conn = create_engine(db_connection_string)

df = pd.read_sql('SELECT * FROM tab_name', conn)

получим DataFrame:
In [118]: df
Out[118]:
   id   параметр      дата значение
0   1  Параметр1  1 января  100 ед.
1   2  Параметр2  1 января  200 ед.
2   3  Параметр1  2 января  101 ед.
3   4  Параметр2  2 января  201 ед.
4   5  Параметр1  3 января  102 ед.
5   6  Параметр2  3 января  202 ед.
6   7  Параметр1  4 января  103 ед.
7   8  Параметр2  4 января  203 ед.

теперь можно построить PIVOT:
In [119]: res = df.pivot(index='параметр', columns='дата', values='значение')

In [120]: res
Out[120]:
дата      1 января 2 января 3 января 4 января
параметр
Параметр1  100 ед.  101 ед.  102 ед.  103 ед.
Параметр2  200 ед.  201 ед.  202 ед.  203 ед.

его можно выгрузить в отдельную таблицу:
res.to_sql('new_table_name', conn, index=False, if_exists='replace')


text:
Q: include('form.php') throw error 404 I am writing page-contact.php for a WordPress website contact page. Where I insert form.php through the following code snippet
<?php
include ('form.php');

But running over the localhost, throw a 404 error. While accessing form.php in browser work fine as expected.
<form id="contact" action="<?php htmlspecialchars($_SERVER["PHP_SELF"]) ?>" method="post">
 // some code here
</form>

This is the inside the form.php

A: You can use the absolute path (due to your example this example assumes your form.php is in the same directory. Otherwise you´d need to adjust the path):
include __DIR__ . DIRECTORY_SEPARATOR . 'form.php';

In the form.php, you have $_SERVER['PHP_SELF'] . I think due to security issues it would be better to use
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>" >


text:
Q: PayPal and item_name Can I see what was entered in the item_name field (by the customer) in my PayPal account? I know that I can see it if I use IPN but I don't want to use it.

A: Yes. If you go to History under My Account for a business acount, you can view the list of transactions sorted and filter by date ranges. From here if you select details for a rowitem/transaction you can see the values of most of the parameters sent with the transaction, including item_name. Even though I think on the transaction datails page its shown as Item Title.


text:
Q: How to combine numerical and symbolic variables in MatLab I've been trying to calculate and plot trajectories for orbital motion, but got stuck with the variable types.
All input variables are of double type, as well as the desired output. As a consequence, variables of orbital system (the ones with "_orb" in the names) are of double type.
Here's the script. The diffficulties start from "Velocity corrections" part, in which I want to calculate minimum for a function of velocity change:
function trajectory_final (x0, y0 , z0, vx0, vy0, vz0, q0, q1, q2, q3)

o = 0.00114;
xk = 0;
yk = -150;
zk = 150;
double t;
%% Coordinate system transition:
x0_orb = (1 - 2*q2*q2 - 2*q3*q3)*x0 + 2*(q1*q2 + q0*q3)*y0 + 2*(q1*q3 - q0*q2)*z0;
y0_orb = 2*(q1*q2 - q0*q3)*x0 + (1 - 2*q1*q1 - 2*q3*q3)*y0 + 2*(q2*q3 + q0*q1)*z0;
z0_orb = 2*(q1*q3 + q0*q2)*x0 + 2*(q2*q3 - q0*q1)*y0 + (1 - 2*q1*q1 - 2*q2*q2)*z0;

vx0_orb = (1 - 2*q2*q2 - 2*q3*q3)*vx0 + 2*(q1*q2 + q0*q3)*vy0 + 2*(q1*q3 - q0*q2)*vz0;
vy0_orb = 2*(q1*q2 - q0*q3)*vx0 + (1 - 2*q1*q1 - 2*q3*q3)*vy0 + 2*(q2*q3 + q0*q1)*vz0;
vz0_orb = 2*(q1*q3 + q0*q2)*vx0 + 2*(q2*q3 - q0*q1)*vy0 + (1 - 2*q1*q1 - 2*q2*q2)*vz0;
%% Velocity corrections:

vx1 = sym('(xk - x0_orb - (6*o*t - 6*sin(o*t))*y0_orb - (-2*cos(o*t)/o + 2/o)*((-3*cos(o*t) + 4)*y0_orb - yk))/(4*sin(o*t)/o - 3*t - (2*cos(o*t)/o - 2/o)*(2*cos(o*t)/o - 2/o))');
vy1 = sym('(-3*cos(o*t) + 4)*y0_orb + (2*cos(o*t)/o - 2/o)*vx1 - yk');
vz1 = sym('(zk - (cos(o*t))*z0_orb)/(sin(o*t)/o)');

dvx = vx1 - vx0_orb;
dvy = vy1 - vy0_orb;
dvz = vz1 - vz0_orb;

total = sqrt((dvx)^2 + (dvy)^2 + (dvz)^2);
D = diff(total);
D_math = matlabFunction(D);
root = fzero(D_math, 600);

However, several problems occur:
1) If I run it as is now, variables in vx1, vy1 and vz1 are not replaced with their values assigned at launch, resulting in "Not enough input arguments" for fzero.
2) If I make vx1, vy1 and vz1 numerical, the error "Undefined function or variable t" appears;
3) If I make vx1, vy1 and vz1 numerical AND assign boundaries for t, then I cannot find root for D_math function on the desired interval.
Could you please tell me what is the best way to handle this problem?


text:
Q: letter dictionary for javascript lzw compression, "only-use-these-chars"-string Good day to all of you readers and helpers,
i want to make use of a javascript function i recently found, its LZW compressing a string.
function lzw_encode(s) {
    var dict = {};
    var data = (s + "").split("");
    var out = [];
    var currChar;
    var phrase = data[0];
    var code = 256;
    for (var i=1; i<data.length; i++) {
        currChar=data[i];
        if (dict[phrase + currChar] != null) {
            phrase += currChar;
        }
        else {
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            dict[phrase + currChar] = code;
            code++;
            phrase=currChar;
        }
    }
    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
    for (var i=0; i<out.length; i++) {
        out[i] = String.fromCharCode(out[i]);
    }
    return out.join("");
}

This function is actually working very well, the only problem ive got is that i want to transfer the encoded string via websockets and without additional encoding (base64 e.g.) but that doesnt work every time. Sometimes the compressed string is having chars which cant be transfered via websockets, it throws an javascript error that the string is having illegal chars. So my idea was to only use acceptable chars in the encoding process, like a "whitelist" of chars which should be used for compression. What i understood from the code
is that its taking the charCode of some number, so i though i could just create my own charCodeSet but i dont really know how to implement it and if it would even work.

*

*Q1: what can i do so my lzw encoding just uses chars of a string that i define?

*Q2: how else could i "http/s" transfer these chinese, arabic and control chars which websocket dont want to transfer?

By the way, this is the error which Chrome is throwing:
Websocket message contains invalid character(s).
Uncaught Error: SYNTAX_ERR: DOM Exception 12

Update1: though its might helpfull if you see the decoding function aswell
function lzw_decode(s) {
    var dict = {};
    var data = (s + "").split("");
    var currChar = data[0];
    var oldPhrase = currChar;
    var out = [currChar];
    var code = 256;
    var phrase;
    for (var i=1; i<data.length; i++) {
        var currCode = data[i].charCodeAt(0);
        if (currCode < 256) {
            phrase = data[i];
        }
        else {
           phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
        }
        out.push(phrase);
        currChar = phrase.charAt(0);
        dict[code] = oldPhrase + currChar;
        code++;
        oldPhrase = phrase;
    }
    return out.join("");
}

here i would have to implement my custom charset also, i guess?..

A: Determine what bytes you can and cannot send.  (Hopefully from a reliable source of documentation, as opposed to testing, but verified with testing.)
Design an escape code where you use one of the valid characters as an escape character, and the next character, also one of the valid characters, encodes a byte you cannot send.
Apply that to the output of your compressor.  It is best to leave the job of compression to the compressor, and not try to saddle it with encoding.  You should encode as a separate step.
Don't use LZW.  It is ineffective and obsolete as compared to modern methods (zlib, lz4, lzma, etc.)


text:
Q: HTML response when JAX-RS response is 404 I have a JAX-RS resource class that can return a 404 response when a certain request is made.  Unfortunately, even though the operation's method is annotated @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }), a 404 Response object always results in Tomcat shoving its own "not found" HTML error page into the body.
This is breaking clients that expect XML/JSON responses.  How do I shut Tomcat up in these cases?
My code looks like this now:
@GET
@Path("isbn/{isbn}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response isbn(@PathParam("isbn") String isbn) {

    ProductSearchDO productSearch = ProductSvc.find( isbn );
    if (productSearch == null)
        return Responses.notFound().build();

    return Response.ok( productSearch ).tag( String.valueOf( productSearch.hashCode() ) ).build();
}

A: You shouldn't return a 404. Just return an empty JSON, then your client will be able to handle it.
This approach is called "soft 404" (if I'm not wrong).
This approach is used also in Facebook:
https://graph.facebook.com/search?q=nlknrekjfndjkfnsjkefbnejkrbfjedbfjekfbekj
EDIT:
I'll explain it better. As the W3C says the 404 should be used if

The server has not found anything matching the Request-URI.

Actually your server has found a matching Request-URI, but simply the response will be empty. And also

This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.

You can apply another kind of response if you want.
If you still want to go your way you can try to override the standard Tomcat 404 page with an empty page, or ask to the client side to check for the status code
if(statusCode==404) { blablabla }

EDIT2:
A downvote for what? I don't think my answer is wrong, you can like it or not, but I don't think it's actually a wrong one.
In your case you're doing a research for a certain product. If you cannot find any product matching your search why you should return a 404?
More sources about this:
Should a RESTful API return 404 for arrays of objects?
also here:
Querystring in REST Resource url

"If the URL returns a search result then it shouldn't return a 404."

and same here:
REST: Mapping 404 HTTP Status codes
especially the comment:

Simply, "no results" is a valid search result. The resource exists,
  it's representation is simply "empty". So, 404 is not justified.

A: 404 Not Found is a client error meaning that the problem is on the client's side for requesting a non-existent page. In this case, it makes makes sense to return a 404.
I'd argue that the client should be able to appropriately handle a 404 response. You as a server are doing your due diligence by returning an error code. It's up to the client to be able to handle the response.


text:
Q: Using RemoteAuthenticatorView OnLogInSucceeded gives a second AzureAD login dialog box Having trouble to understand what going on and I really could use some thoughts and inputs. Please, I am not very good at describing in text what is the problem, so be gentle.
I have a Blazor wasm frontend and a Azure Function backend.
I do a standard, nothing special, Azure AD login.
Later in code, I connect with the AzFunction using the bearer token, and it works. The AzFunction evaluates the token and identifies the user for further processing. I should mention that the AzFunction connects to Graph and other APIs.
So everything is fine and working, here is my problem.
I want to connect to the AzFuntion at login time, to get some user profile information. For debugging I simply made a button, and again, everything works.
Then I moved "the button code" to a method called by RemoteAuthenticatorView OnLogInSucceeded, in Authenticator.razor.
<RemoteAuthenticatorView Action="@Action" LogInFailed="LogInFailedFragment" OnLogInSucceeded="LoginComplete" />
Here is my problem:
Using the OnLogInSucceeded I get 2 Azure AD logins that I have to respond to. After the first one, It goes directly to the second. All simply because I moved the code from a button to OnLogInSucceeded. When I debug, I clearly see that the token is present before it connects to AzFunction.
Also, when I set a breakpoint in visual studio at the LoginComplete function called from OnLogInSucceeded, and just holds it for a few seconds, it goes throught the login process with just one login dialog.
Could anyone please help me understand why?
Any pointers on a better please to put the "get User profile" code? What I need is the code to run, so when the login is completed, the user profile info is retrived, with just one login.
Edit:
The code seem to have a better solution, however I still do not understand what made the second login to apper... And that was kind of the main reson for my question.

A: Well thanks to Raymond, I was also sent i a good direction, and made a component to load this type of data. I had to combine the event and loading when the component initializes. I still feel like M$ should and probobly will find a better way to do this.
For this application I use Azure B2C to auth, and I'm using redirect instead of popup. When I initialize the userstate, I call my api which gets the user profile, or creates one if it's a new user.
InitialDataLoader.razor
@implements IDisposable
@inject NavigationManager _navigationManager
@inject UserState _userState
@inject AuthenticationStateProvider _authenticationStateProvider

@ChildContent

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }

    // The event can trigger multiple times when being redirected from the Authentication page to wherever you're going.
    // So we use this to check.
    public bool hasRunInit;

    protected override async Task OnInitializedAsync()
    {
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnInitializedAsync -> " + _navigationManager.Uri);

        // This component is already loaded and initialized on the Authentication page, so we have to subscribe to this event to
        // check when the user bounces back from Azure B2C and gets logged in. In that case, we do the initial load in on the event
        _authenticationStateProvider.AuthenticationStateChanged += this.OnAuthenticationStateChanged;

        // If the user is authenticated and reloads the page in the browser, the event won't trigger so we can do the initial load here.
        var user = (await _authenticationStateProvider.GetAuthenticationStateAsync()).User;
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnInitializedAsync -> IsUserAuthenticated: " + user.Identity.IsAuthenticated);
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnInitializedAsync -> IsStateInitialized: " + _userState.IsInitialized);

        if (user.Identity.IsAuthenticated && !_userState.IsInitialized)
        {
            hasRunInit = true;
            Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnInitializedAsync -> InitUser");
            await _userState.InitializeAsync(this);
        }
    }

    void IDisposable.Dispose()
    {
        _authenticationStateProvider.AuthenticationStateChanged -= this.OnAuthenticationStateChanged;
    }

    private async void OnAuthenticationStateChanged(Task<AuthenticationState> task)
    {
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnAuthenticationStateChanged -> " + _navigationManager.Uri);

        var user = (await task).User;
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnAuthenticationStateChanged -> IsUserAuthenticated: " + user.Identity.IsAuthenticated);
        Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnAuthenticationStateChanged -> IsStateInitialized: " + _userState.IsInitialized);

        if (user.Identity.IsAuthenticated && !_userState.IsInitialized)
        {
            if (!hasRunInit)
            {
                hasRunInit = true;

                Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " CascadingAppStateProvider -> OnInitializedAsync -> InitUser");
                await _userState.InitializeAsync(this);
            }
            else
            {
                Console.WriteLine(DateTime.Now.ToString("hh:mm:ss:fff") + " InitialDataLoader -> OnInitializedAsync -> Init has already been triggered!");
            }
        }
    }
}

App.razor
<CascadingAuthenticationState>

    <InitialDataLoader>

        <Router AppAssembly="@typeof(Program).Assembly">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <Authorizing>
                        ------------- Authorizing.. ------------------
                    </Authorizing>
                    <NotAuthorized>
                        @if (!context.User.Identity.IsAuthenticated)
                        {
                            <RedirectToLogin />
                        }
                        else
                        {

You are not authorized to access this resource.

                        }
                    </NotAuthorized>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">

Sorry, there's nothing at this address.

                </LayoutView>
            </NotFound>
        </Router>

    </InitialDataLoader>

</CascadingAuthenticationState>

When the user bounces back from the gateway, the component initializes before the application authenticates the user. Then the event triggers twice, once for the authentication page, and once for whatever page your are viewing.

A: Thanks to Zack Blazor Webassembly Authenticated Event, I was sent in a good direction and read Microsoft pages on AuthenticationStateChanged Event. It also simplified my code since I now have the retrival of UserProfile, in the UserProfile component than Authentication.razor.
@inject AuthenticationStateProvider AuthenticationStateProvider

private void OnAuthenticationStateChanged(Task<AuthenticationState> task)
{
    if(task.IsCompletedSuccessfully)
    {
        GetUserProfile();
    }
}

Not sure if this is "the final code", but it sure works and seems to me like a plausable way to go.


text:
Q: F# is unable to infer type arguments after annotation So I have some json response content represented as string and I want to get its property names.
What I am doing
 let properties = Newtonsoft.Json.Linq.JObject.Parse(responseContent).Properties()
 let propertyNames, (jprop: JProperty) = properties.Select(jprop => jprop.Name);

According to this answer I needed to annotate the call to the extension method, however, I still get the error.

A unique overload for method 'Select' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,'TResult>) : Collections.Generic.IEnumerable<'TResult>, (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,int,'TResult>) : Collections.Generic.IEnumerable<'TResult>

Am I doing something wrong?

A: First, the syntax x => y you're trying to use is C# syntax for lambda expressions, not F# syntax. In F#, the correct syntax for lambda-expressions is fun x -> y.
Second, the syntax let a, b = c means "destructure the pair". For example:
let pair = (42, "foo")
let a, b = pair  // Here, a = 42 and b = "foo"

You can provide a type annotation for one of the pair elements:
let a, (b: string) = pair

But this won't have any effect on pair the way you apparently expect it to work.
In order to provide type annotation for the argument of a lambda expression, just annotate the argument, what could be simpler?
fun (x: string) -> y

So, putting all of the above together, this is how your line should look:
let propertyNames = properties.Select(fun (jprop: JProperty) -> jprop.Name)

(also, note the absence of semicolon at the end. F# doesn't require semicolons)

If you have this level of difficulty with basic syntax, I suggest you read up on F# and work your way through a few examples before trying to implement something complex.


text:
Q: How to space first_name + last_name C++ My question is how can i use spaces between first_name and last_name after i instruct the user to input his name.
I am using code blocks and I'm kinda confused.
In Dev C++ i can do
   cout<<first_name<<" "<<last_name;

Now what I am doing is just practicing C++ using variables in a class.
Here is my code.
    #include<iostream>
    #include<string>
    using namespace std;

    class DanielClass
      {
     public:
        int setNameFunction(string first_name, string last_name)
        {
    cout<<"Enter your first name here: ";
    cin>>first_name;
    cout<<"Enter your last name here: ";
    cin>>last_name;
    name = first_name + last_name;
        }

        string getNameFunction()
        {

    return name;
        }

    private:
       string name;
    };

    int main()
    {

       DanielClass NameObject;
       NameObject.setNameFunction("", "");
       cout<<NameObject.getNameFunction();

       cout<<"\n\n";
       return 0;
     }

A: You can add string literals (which is just a term for a string entered directly into the code with quotes around it -- like the " " in the second line of code below) to string variables using the '+' operator.
You just need to change the line that reads:
    name = first_name + last_name;

to:
    name = first_name + " " + last_name;


text:
Q: How to unite views in GridView in the center? I am using GridView to create color picker. There is a circle inside each cell. Even if I set wrap content for layout_width and layout_height there is always gap between columns. I want to unite cells in the center or remove these gaps.
Here is my GridView's layout xml.
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/color_picker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:numColumns="3" />

CircleView class
public class CircleView extends View {
    private static final String TAG = "CircleView";
    private Paint mCirclePaint;
    private int mCircleColor;

    private Paint mStrokePaint;
    private int mStrokeColor;

    private int mWidthInDp;
    private int mHeightInDp;

    public CircleView(Context context){
        super(context);

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setColor(mCircleColor);
    }

    @Override
    protected void onMeasure(int widthMeasuredSpec, int heightMeasuredSpec) {
        Log.d(TAG, "onMeasure: ");

        setMeasuredDimension(mWidthInDp, mHeightInDp);
    }

    public void setLayoutParamsInDp(int width, int height){
        this.mWidthInDp = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, width, getResources().getDisplayMetrics());
        this.mHeightInDp = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height, getResources().getDisplayMetrics());
    }

    public void setCircleColor(int color){
        this.mCircleColor = color;
        mCirclePaint.setColor(mCircleColor);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int centerX = mWidthInDp / 2;
        int centerY = mHeightInDp / 2;

        float radius = Math.min(mWidthInDp, mWidthInDp) / 2;

        canvas.drawCircle(centerX, centerY, radius, mCirclePaint);
        canvas.save();
    }
}

GridView adapter
    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        CircleView circleView = new CircleView(mContext);
        circleView.setCircleColor(mColors.get(position));
        circleView.setLayoutParamsInDp(50, 50);
        return circleView;
    }

Here is the output. How can I delete gaps between circles?

A: I think the problem is in GridView as parent. Add another layout as parent and in there add GridView with width & height as wrap content!

A: use this
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/color_picker"
    android:numColumns="3"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:horizontalSpacing="0dip"
    android:verticalSpacing="0dip">
</GridView>