text:
Q: Load data from Excel to sql server table using node.js I am trying to load an excel file to the sql server table, but I am getting error. I have shared the code and error for the same. Kindly point out what is wrong here.
Excel file consists of 4 columns Id, Date, Model and plan which I want to insert into mssql table, but unable to do it.
 //CODE
var express = require('express');
var http = require('http');
var oracledb = require('oracledb');
//var dbConfig = require('./dbconfig.js');
var app = express();
var bodyParser = require('body-parser');
var XLSX = require('xlsx');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Cors = require("cors");
app.use(Cors());

jsonArrayToValueArray = (jsonArray) => {
    let valueArray = new Array();
    for (let index = 0; index < jsonArray.length; index++) {
        let object = jsonArray[index];
        let keys = Object.keys(object);
        valueArray.push([object[keys[0]], object[keys[1]], object[keys[2]], object[keys[3]]]);
        console.log(valueArray) ;
    }
    return valueArray;
  }

app.get('/', function (req, res) {

    var sql = require("mssql");

    // Configuration object for your database
    var config = {
        user: 'sa',
    password: '******',
    database: '*****',
    server: '*******',
    port: 1433,
    //timezone: 'utc',
    //multipleStatements: true
    };
    // connect to the database
    sql.connect(config, function (err) {
    var workbook = XLSX.readFile(__dirname + '/uploads/delivery_excel.xlsx');
    var sheet_name_list = workbook.SheetNames;

    var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
     console.log();
    let valueArray = jsonArrayToValueArray(xlData);

        if (err) console.log(err);
        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query("INSERT INTO dbo.plan_excel Values(' + _Id + ', ' + _Date + ', ' + _Model + ', ' + _Plan + ')", [valueArray], function (err, recordset) {
       // request.query("INSERT INTO dbo.plan_excel Values(@Id, @Date, @Model, @Plan) ", [valueArray], function (err, recordset) {

            if (err) console.log(err)
            // send records as a response
            res.send(recordset);
            sql.close();
       });
    });
});
var server = app.listen(5050, function () {
    console.log('Server is running..');
});

Error I am getting is as follows, an array of 38 rows(excel data) followed by an error. Please help me with the changes required for this code to work, so that data will be inserted into the sql server. I am using that insert query with reference to few other links, please let me know if it is not the correct way.
I have achieved the same flow earlier, but it was for Mysql database, since I am new to sql server so not understanding much about it.
  [ 28, 43295, 'V45', 200 ],
  [ 29, 43296, 'V45', 200 ],
  [ 30, 43297, 'V45', 200 ],
  [ 31, 43298, 'V45', 200 ],
  [ 32, 43299, 'V45', 200 ],
  [ 33, 43299, 'V30', 213 ],
  [ 34, 43299, 'V26', 220 ],
  [ 35, 43299, 'V22', 200 ],
  [ 36, 43299, 'V34', 233 ],
  [ 37, 42895, 'v35', 123 ],
  [ 38, 42895, 'V32', 122 ] ]
(node:40820) UnhandledPromiseRejectionWarning: RequestError: Conversion failed when converting the varchar value ' + _Id + ' to data type int.
    at handleError (C:\Users\vishruti.pawar\.vscode\mssql_api\node_modules\mssql\lib\tedious.js:566:15)
    at emitOne (events.js:116:13)
    at Connection.emit (events.js:211:7)
    at Parser.tokenStreamParser.on.token (C:\Users\vishruti.pawar\.vscode\mssql_api\node_modules\tedious\lib\connection.js:716:12)
    at emitOne (events.js:116:13)
    at Parser.emit (events.js:211:7)
    at Parser.parser.on.token (C:\Users\vishruti.pawar\.vscode\mssql_api\node_modules\tedious\lib\token\token-stream-parser.js:27:14)
    at emitOne (events.js:116:13)
    at Parser.emit (events.js:211:7)
    at addChunk (C:\Users\vishruti.pawar\.vscode\mssql_api\node_modules\readable-stream\lib\_stream_readable.js:297:12)
(node:40820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:40820) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.

I have shared the alternate code, it is sending records to database, but some random records are being send there, can you please tell what might be the mistake. I am using for loop to add those values to table.
var express = require('express');
var http = require('http');
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
var app = express();
var bodyParser = require('body-parser');
var XLSX = require('xlsx');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Cors = require("cors");
app.use(Cors());

jsonArrayToValueArray = (jsonArray) => {
    let valueArrayN = new Array();
    let valueArray = new Array();
    let valueArray1 = new Array();
    let valueArray2 = new Array();
    let valueArray3 = new Array();

    for (let index = 0; index < jsonArray.length; index++) {
        let object = jsonArray[index];
        let keys = Object.keys(object);
        valueArray.push([object[keys[0]]])
        valueArray1.push([object[keys[1]]])
        valueArray2.push( [object[keys[2]]])
        valueArray3.push( [object[keys[3]]])
        //valueArrayN.push([object[keys[0]], object[keys[1]], object[keys[2]], object[keys[3]]]);
        console.log(valueArrayN) ;
    }
        valueArrayN = [valueArray, valueArray1, valueArray2, valueArray3];
      return valueArrayN;
 }

app.get('/', function (req, res) {
    var sql = require("mssql");
    var config = {
    user: 'sa',
    password: '******',
    database: '*****',
    server: 'localhost',
    port: 1433,
    timezone: 'utc',
    multipleStatements: true
    };
    // connect to the database
    sql.connect(config, function (err) {
    var workbook = XLSX.readFile(__dirname + '/uploads/delivery_excel.xlsx');
    var sheet_name_list = workbook.SheetNames;

    var xlData = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);

     console.log();
    let valueArrayN = jsonArrayToValueArray(xlData);

      var i;
      for(i=0; i < 45; i++)
        {

        if (err) console.log(err);
        // create Request object
        var request = new sql.Request();

        //setTimeout(function(){
        request.input('id', sql.Int, valueArrayN[0][da])
        request.input('Date', sql.Int, valueArrayN[1][da])
        request.input('Model', sql.NChar,valueArrayN[2][da])
        request.query("INSERT INTO dbo.plan_excel Values (@id, @Date, @Model)", function (err, recordset) {
           if (err) console.log(err)
           res.send(recordset);
      });

}  //for loop
});
});
var server = app.listen(5010, function () {
    console.log('Server is running..');
});

For this code I am getting the following error and every time I run different records are being inserted like sometimes 11 records sometimes only 4. what could be the reason for that?
[]
[]
[]
_http_outgoing.js:494
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at validateHeader (_http_outgoing.js:494:11)
    at ServerResponse.setHeader (_http_outgoing.js:501:3)
    at ServerResponse.header (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\express\lib\response.js:767:10)
    at ServerResponse.send (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\express\lib\response.js:158:21)
    at C:\Users\.vscode\MSSQL\oracle_api_working\example2.js:95:17
    at _query (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\mssql\lib\base.js:1347:9)
    at Request.tds.Request.err [as userCallback] (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\mssql\lib\tedious.js:671:15)
    at Request.callback (C:\Users\.vscode\MSSQL\oracle_api_working\node_modules\tedious\lib\request.js:37:27)
PS C:\Users\.vscode\MSSQL\oracle_api_working>

A: replace your request.query line to this.
request.query("INSERT INTO dbo.plan_excel Values ${valueArray.join().split(",").map(x => '(' + x + ')').join()}", function (err, recordset) {

A: request.query(`INSERT INTO dbo.plan_excel Values(${id}, ${date}, '${model}', ${plan})`, [valueArray], function (err, recordset)

You should only quote model as it is the only one declared as string on your matrix.


text:
Q: C# MongoDB InsertMany missing _id after insert So I have two functions as follows. The InsertOne() function works fine, and the BsonDocument is updated with the newly created _id. However, the InsertMany() function is not returning object ids. I debugged the code, and none of the individual documents are updated with an _id field.
The InsertMany() function does insert the documents into the database, and I can see they all have object ids from the Mongo shell.
The models in my code do not have an Id field. And they are being converted using code like MyModel.ToBsonDocument().
Am I missing something to get back the IDs generated from a bulk insert?
    public string InsertOne(BsonDocument document)
    {
        MongoCollection.InsertOne(document);
        return document["_id"].ToString();
    }

    public string[] InsertMany(IEnumerable<BsonDocument> documents)
    {
        MongoCollection.InsertMany(documents);
        return documents.Select(item => Convert.ToString(item["_id"])).ToArray();
    }

EDIT - Not sure if this is a bug, but I just realized if I use a list instead of IEnumerable, the InsertMany() works as expected.

A: It has to do with how collections are created our of IEnumerable in LINQ. MongoCollection.InsertMany materializes the collection under the hood by enumerating over it and populating _id. However it's a new collection and it's not the IEnumerable that you initially passed in, that's why it doesn't have the ids. If you pass List the collection has already been materialized, so it just populates the fields in it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como fazer um lookbehind utilizando quantificadores como o "\d+"? Preciso dar match no texto "teste", porém nem sempre a string começará com um numero fixo de caracteres/digitos, pode ser que ela comece com qualquer numero de caracteres, exemplo:
001  teste
0002  teste
20458  teste
Como faço para que a regexp abaixo funcione?
(?<=^\d+)teste

Esse lookbehind (?<=^\d+) não funciona, dá expressão inválida, não deixa usar o quantificador \d+ dentro do lookbehind, se eu fizer (?<=^\d\d\d) ele dá match somente na primeira situação. Eu gostaria que ele pudesse ser "variável" o número de dígitos/caracteres antes do texto do match.
Existe como criar um lookbehind usando quantificadores +, * ou {1,}?

A: Em vez de usar lookbehind, você está mais bem servido usando um grupo de captura para obter uma referência à sequência test:
/^\d+(test)/

Aí você acessa o grupo 1 para obter a string test. Tudo bem que é meio inútil, se tratando de uma string fixa, mas o conceito é o mesmo quando se quer extrair parte de uma sequência de caracteres.

A: A Resposta do @Wtrmute esta de acordo com sua necessidade, mas vamos focar em sua duvida.

Como fazer um look-behind utilizando quantificadores?

Resposta
Você não faz, o look-behind teria a logica de que você sabe o que vem antes da sua real captura.
E um quantificador quebra essa regra, pois se você usa um quantificador é justamente porque você não sabe ao certo quantas vezes "algo" deve ocorrer.
Adendo
Você deve lembrar que o look-behind ao certo trabalha de traz para frente.
Ele primeiramente vai procurar por teste apos ele "anda pra traz" verificando o look-behind.
0002 teste
   ^^|---| captura
   ||- 1ª verificação do look-behind
   |- 2ª verificação do look-behind

A: RegEx sem lookbehind (lembrando que assim você precisa acessar o grupo1 pra obter somente "teste".)
\d*? (teste)

Usando lookbehind (esse lookbehind identifica o uso de 1 digito e espaço antes da palavra "teste", assim capturaria independente do número de dígitos.)
(?<=\d\s)teste

A:
Existe como criar um lookbehind usando quantificadores +, * ou {1,}?

Dependendo da engine/linguagem/ferramenta utilizada, pode ou não ser possível.
Em PHP e Python, por exemplo - pelo menos nas versões atuais - não é possível, inclusive expressões que contém quantificadores dentro de um lookbehind dão erro.

Obs: em Python, você pode usar o módulo regex. Com ele, é possível usar quaisquer quantificadores no lookbehind:
# módulo externo, instalar com "pip install regex"
# https://pypi.org/project/regex/
import regex as re

r = re.compile(r'(?<=^\d+)teste', re.M)
print(r.findall('001teste\n0002teste\n20458teste\nabcdef')) # ['teste', 'teste', 'teste']

Inclusive, isto está descrito na documentação: "A lookbehind can match a variable-length string".

Em outros casos é parcialmente possível. Por exemplo, nas versões mais antigas do Java, você podia usar ? (que indica algo opcional), ou quantificadores fixos (como {1,5}), desde que tivesse o valor máximo especificado.
Porém, nas versões mais recentes, não existem mais estas restrições (se não me engano, desde a versão 13), e agora isso é perfeitamente possível:
String s = "001teste\n0002teste\n20458teste\n fasdfsadfasd";
// nas versões mais recentes do Java, isso é permitido
Matcher m = Pattern.compile("(?<=^\\d+)teste", Pattern.MULTILINE).matcher(s);
while (m.find()) { // imprime "teste" 3 vezes
    System.out.println(m.group());
}

E nas versões mais recentes do JavaScript, também é possível (testado no Chrome e Firefox mais recentes):

const regex = /(?<=^\d+)teste/mg;
const s = '001teste\n0002teste\n20458teste\nabcdef';
console.log(s.match(regex)); // [ 'teste', 'teste', 'teste' ]

E em C#, já faz tempo que isso é possível (inclusive, se não me engano, na época em que esta pergunta foi feita):
var matches = Regex.Matches("001teste\n0002teste\n20458teste\nabcdef", @"(?<=^\d+)teste",
                            RegexOptions.Multiline);
foreach (Match match in matches)
{ // imprime "teste" 3 vezes
    Console.WriteLine(match.Value);
}

Portanto, a resposta que diz não dá para fazer não está mais correta (talvez estivesse na época, pois muitas linguagens que hoje implementam, o fizeram em versões posteriores).
Para saber os motivos pelos quais muitas linguagens não implementavam este recurso, só perguntando para quem tomou tais decisões. Meu palpite é que a dificuldade de implementação e/ou os custos no desempenho da regex acabavam não compensando. Afinal, tanto lookaheads quanto lookbehinds já são custosos por si só, pois você tem que avançar ou retroceder na string e depois voltar onde estava para continuar procurando os matches. E um quantificador como * ou + (sem limite superior) faz com que você tenha que voltar uma quantidade indeterminada de caracteres, tornando tudo mais custoso ainda (algumas engines "resolvem" isso invertendo a regex e fazendo a busca da direita para a esquerda; apesar de ser menos custoso, ainda sim não é uma implementação tão trivial, principalmente se começarmos a incluir outros lookarounds dentro do lookbehind).
Apesar desses poréns, várias engines decidiram implementar mesmo assim (o que mudou? só perguntando para quem decidiu incluir este recurso).
De qualquer forma, na época da pergunta isso podia não ser possível na maioria dos casos. Mas hoje, dependendo da linguagem e/ou versão e/ou bibliotecas que você usa, pode ser possível sim (ver também este artigo para mais detalhes).


text:
Q: Filename as text watermark, ffmpeg/mencoder I have a bunch of photos (from ip cam) witch i pack into video using mencoder, is there a way to tell mencoder to put each filename on produced video?
(file names, has the photo shot time)

A: I would use Imagemagick to preprocess each image, putting the filename on it.


text:
Q: UIPickerView alternative for iphone something like combo box? Are there any alternative controls instead of UIPickerView in XCode. If yes, how do they work? Can anyone suggest an alternative for UIPickerView?

A: You can see one in action if you download the free One Stop Plus app (women's clothes), drill down on the products until you get a view with Color, Size, etc. Tapping those buttons animates a table out of the button, with choices. Selecting one causes the table to animate back into the button. If you like that post a comment to this answer and I can tell you how to do it.

A: With iPhone interface, it is not feasible to enable a Combo box like a website. (I believe even Apple Guidelines would say not to do it). What you need to do is the use the UITableView to enable users to pick one option.
One thing you can do is decide whether you want to have the choice in a view shared with other controls. OR if your list if too long you can chose to push in a new view with only the choices on them and when a user selects one, the view will pop back one level.
Here is a screen shot of what i mean (maybe not the best example out there):


text:
Q: BUG: PHP pre-increment and post-increment variable for array keys <?php
$options = array();
$currentYear = 2012;

while($currentYear < (2012 + 3) ) {
    $options[$currentYear++] = $currentYear;
}

var_dump($options);
?>

expected output:

array(3) {
     [2012]=> int(2012)
     [2013]=> int(2013)
     [2014]=> int(2014)
}

Generic theory: Executes the RHS of an assignment first and assigns the RHS value to LHS. It would execute post-increment in LHS after it executed the RHS. According to this scenario, we can explain the iteration as follows.
In 1st iteration, RHS $currentYear value is 2012 and assigns that value to array options with key 2012. Increment the variable $currentYear by 1, and proceed with the iteration. In 2nd iteration, RHS $currentYear value is 2013 and assigns that value to array options with key 2013. Increment the variable $currentYear by 1, and proceed with the iteration. What happened to this generic programming concept down below?
Actual output:

 array(3) {
     [2012]=> int(2013)
     [2013]=> int(2014)
     [2014]=> int(2015)
 }

If someone can come up with a better explanation that would be great, and much appreciate.

A: Above theory is wrong.
In PHP arrays have higher precedence than increment/decrement. Therefore PHP executes the array keys first (that's why first element of the array key appeared as 2012) and then goes to the assignment.
In this scenario, PHP keeps array key as $currentYear value 2012 and increment by 1. Then it comes to the RHS takes $currentYear value and assigns it to the array options with the key 2012. Likewise, it continues with the iteration.

A: Try to keep in mind the concepts of Incrementing/Decrementing Operators and you will understand better these operators.
Post-increment returns $currentYear, then increments $currentYear by one, based in this, what is happening in your case is the following:
$currentYear = 2012;

$options[$currentYear++] = $currentYear;

/* Post-increment will return 2012 to the array, after this will increment it to
 * 2013, so in the right side it will be 2013, then you'll get the result below.
 * Remember that PHP analyses the code from left to right.
 */

$options[2012] == 2013;

To get your expected result you must use pre-increment because it will increment $currentYear by one, then returns $currentYear. For instance:
$currentYear = 2012;

$options[++$currentYear] = $currentYear;

/* Pre-increment will increment $currentYear first, after this will return the
 * value to array, so $currentYear will have the same value in both sides.
 * Like below.
 */

$options[2013] == 2013;

EDIT 1
As your first index and $currentYear must be equals you must use a different logic, something like this:
$options = array();
$currentYear = 2012;

while($currentYear < (2012 + 3) ) {
    $options[$currentYear] = $currentYear;

    $currentYear++; // "++$currentYear" and "$currentYear += 1" will work too
}


text:
Q: Is square of difference between variables bounded by square of difference between corresponding means? Assume we have two variables $f_i$ and $f_j$, both of which follows Gaussian distribution, with corresponding means $\mu_i$ and $\mu_j$.
Can we get to the conclusion that:
||$\mu_i$ - $\mu_j$||$^2_2$ $\leq$ $\frac{1}{N_i}\frac{1}{N_j}$$\Sigma$||$f_i$-$f_j$||$^2_2$ ?
Where $N_i$ is the total number of samples in the first Gaussian distribution, and $N_j$ is the total number of samples in the second Gaussian distribution.
Sorry that I don't have a mathematical background and I might lost some coefficients or terms in the above formula. It seems a lot of ML papers are using such conclusions to derive some upper bound for KL divergence. After some searching online, it may also be related to kernel density estimation, is it right?
Could anybody provide any guidance on that? Thanks in advance


text:
Q: Best way to load non-JS scripts from an assets folder: getElementbyID vs fetch, remote files or write their content in the html? For context:
I'm rather new to this section of Javascript (I'm mostly from a C++ background) and I'm trying to implement webGL in my Jekyll generated website.
I'm following the great tutorial at: https://webglfundamentals.org/webgl/lessons/webgl-fundamentals.html but I've reached a bit of a problem. In the tutorial they basically type everything directly into the html which is a less than ideal solution for bigger projects, so I've put them in separate .glsl files in the _assets folder in my jekyll build.
Eitherway, now for the important bit:
I need to load the content of a file into a variable in javascript.
I've tried first to do this on my html:
<canvas id="myCanvas"></canvas>
<script type="notjs" src="/assets/2dVertexShader.glsl"   id="2dVertexShader"  ></script>
<script type="notjs" src="/assets/2dFragmentShader.glsl" id="2dFragmentShader"></script>
<script type="text/javascript" src="/assets/test.js" ></script>

Matched with, on that javascript:
var vertexShaderSource = document.getElementById("2dVertexShader").text;
var fragmentShaderSource = document.getElementById("2dFragmentShader").text;

Now this isn't working. I cannot tell why. I've also tried using fetch('/assets/2dVertexShader.glsl') but this is another can of worms since I only get a promise back and, as far as I can tell, forces me to encapsulate most of the relevant code into async function so I can use await. Less than ideal.
I can tell you that actually typing the content of the glsl scripts inside the <script> tags in html has worked but this is not ideal. At all.
I can paste the rest of my html and my js and my glsl stuff but I highly doubt it's relevant.

A: Your question might get closed as mostly opinion but....
My suggestion, use es6 modules with multi-line templates.
// some-vs-shader.glsl
export default `
attribute vec4 position;
uniform mat4 matrix;
void main() {
  gl_Position = matrix * position;
}
`;

Then you can import in some other script like this
import someVertexShaderSource from './some-vs-shader.glsl';

And if you want you can later run rollup or webpack or parcel to read through your code and generate one large file that downloads faster.
This is what three.js does.
note that in order to use the import keyword you need to use type="module" as in either
<script type="module" src="somescript.js"><script>

or inline
<script type="module">
import someVertexShaderSource from './some-vs-shader.glsl';
...
</script>

Note: I threw together a working example. I had to name the files so they end in .js because glitch.com's server sends the wrong Content-Type header otherwise. So you have to decide if you want end your files to end in .glsl you'll need to find out how to configure your server to send the correct content-type header.
As for your question of why
<script type="notjs" src="/assets/2dVertexShader.glsl"   id="2dVertexShader"  ></script>

doesn't work, TL;DR It's because the spec says it's not supposed to.


text:
Q: Copy directory but not recurse I want to copy a directory without recursing, preserving "everything", sort of like cp -a except that -a will do the unwanted recursing.
The reason is I am making a script to copy/backup from an unreliable source, so I copy files and directories one by one, keeping a log that is used to avoid redoing already successful copies and stay away from problematic source files when starting over after a failure.
Since cp -a is equivalent to cp -dR --preserve=all, I tried taking the -R away from that, but cp then skips directories because the recursion is off.


text:
Q: Reading variable from another function Python class Home(tk.Frame):
    readName = ""
    def canteenStallsNameOfUser(self,readName):
        self.readName = readName

    def __init__(self, parent, controller):
       Label = tk.Label(self, text="Welcome , " + self.readName)

I am passing a value to canteenStallsNameOfUser Function from another .py file and i want the self.readName in __init__ function to show the value that I pass. How can I take the value from readName in canteenStallsNameOfUser function and display it in the __init__ function?
Basically , I want the name of user to be displayed on the label.
I passed the value from another .py file using this after importing the class "Home":
Home.canteenStallsNameOfUser(Home,readNameOfUser)

A: Add readName as a parameter to __init__:
class Home(tk.Frame):
     readName = ""
     def canteenStallsNameOfUser(self,readName):
         self.readName = readName

     def __init__(self, parent, controller, readName):
        self.readName = readName
        Label = tk.Label(self, text="Welcome , " + self.readName)


text:
Q: Error message from Java to Ajax is not returned properly When the java program does not find the required information I want to return an appropriate error message (could be one of a number of identified reasons). My java code is:
}else{
    response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");
    response.getWriter().write("Captcha description incorrect.");
}

And the ajax is:
$.ajax({
    type: "POST",
    url: "AccountRecoveryQuestionsView",
    cache: false,
    data: $(questionForm).serialize(),
    success: function(data){
        $('#ajaxGetUserServletResponse').text(data);
    },
    error: function(data) {
        $("#accountName").focus();
        //$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
        $('#ajaxGetUserServletResponse').text(data);
    }
});

The error function is triggered; however, the message is not displayed.
I have changed the code to:
          statusCode: {
                400: function(jqXHR, textStatus, errorThrown){
                    alert(jqXHR.status);
                    alert(textStatus);
                    alert(errorThrown);
                    $("#accountName").focus();
                    $('#ajaxGetUserServletResponse').text(errorThrown);
                }
            },

And the result is 400, error, blank.
I have changed the ajax to:
          .fail (function(jqXHR, textStatus, errorThrown) {
                alert(jqXHR.status);
                alert(textStatus);
                alert(errorThrown);
                alert(jqXHR.statusText);
                alert(jqXHR.responseText);
                $("#accountName").focus();
                //$('#ajaxGetUserServletResponse').text('An error occured validating the questions.');
                //$('#ajaxGetUserServletResponse').text(errorThrown);
                $('#ajaxGetUserServletResponse').text(jqXHR.responseText);
            });

And alert(jqXHR.responseText); is returning:
<!doctype html><title>HTTP Status [400] – [Bad Request]</title>
HTTP Status [400] – [Bad Request]

Type Status Report

Message Captcha description not correct

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

Apache Tomcat/8.5.15

How do I just get the error message "Captcha description not correct". This is contained in the above.

A: The HttpServletResponse object should not be written to after #sendError has been called, as stated

If the response has already been committed, this method throws an
  IllegalStateException. After using this method, the response should be
  considered to be committed and should not be written to.

hence:
response.sendError(...);
response.getWriter().write(...); // Should not be done

You should use the static field access of the error codes. In your code, you use response.SC_BAD_REQUEST, when you should use HttpServletResponse.SC_BAD_REQUEST. Writing the int code yourself, e.g. sendError(400, ...), does not change the outcome.
The .error call for the $.ajax-function in jQuery, has been removed since version 3.0, so do not use it. Instead, you should use .done, .fail and .always. .done is the equivalent of .success, while .fail is the equivalent of .error, and .always is kinda like a finally-block in a try-catch (will, as the name implies, always run, regardless).
$.ajax always returns a jQuery XMLHttpRequest object, jqXHR. You can thus run method calls directly on the $.ajax-call, like
var jqxhrobj = $.ajax({
    type: "POST",
    url: "AccountRecoveryQuestionsView",
    cache: false,
    data: $(questionForm).serialize()
})
.done(function(jqXHR, textStatus, errorThrown) {
    // Success here
    $('#ajaxGetUserServletResponse').text(jqXHR.responseText);
})
.fail(function(jqXHR, textStatus, errorThrown) {
    // Fail, do something about the error
    // Since you have several error codes you want to handle
    // you could for instance use a switch case
    switch(jqXHR.status) {
        case "400":
            // It might be an int, or even "400 Bad request",
            // change accordingly

            // Do something to handle the error
            break;
        default:
            // Handle errors not specified with a case
            break;
    }
});

// Later in the js code

jqxhrobj.always(function() {
    // Execute something here, regardless of success/failure of the $.ajax-call
});

Further information on the jqXHR object can be read here.
The responseText will contain a fully formatted html-output, with head, body and so on. If you look at the body of the responseText, it looks like this:

HTTP Status [errorCode] – [errorCode description]

Type Status Report

Message [message passed as 2nd argument in the sendError-call]

Description [full errorCode description]

Apache Tomcat/8.5.15

You could use .find (see here) on the jqXHR.responseText - find the p-tags inside of the body. You should have 3 elements returned; the message will be inside the 2nd result element. You might want to do some sort of substr, to get rid of Message.
A simple but naive approach, that relies on the output to always have exactly the same structure:
var message = jqXHR.responseText.find("p:eq(1)").text();
// text() will not return the -tags, just "Message [msg passed as argument]"
// We'll just substr from the end of "Message"
message = message.substr(7));
// Remove any leading/trailing whitespace
message = message.trim();
// message now contains the error message from #sendError
alert(message);

A: Try to flush and close your writer
...
response.getWriter().flush();
response.getWriter().close();

If it didnt help, make sendError call the last one like this
response.getWriter().write("Captcha description incorrect.");
response.sendError(response.SC_BAD_REQUEST, "Captcha description not correct");

A: you can return the following
Response.status(500).entity("Captcha description incorrect. ").build();

Modify the error code based on your requirement,


text:
Q: Get the more accurate user location android I'm building an app that track user movement. I found on the net and I'm still  blocked about how to get a reliable user location.
For that purpose, I started by use the GPS_PROVIDER to get user location every minutes. But that drains a lot of battery.
Now I'm using NETWORK_PROVIDER which have better yield on battery, but as per my understanding, is not really accurate.
So firstly, I want to know to deal between usage of those providers to have good yield regarding battery consumption and user location accuracy.
Secondly, I read there (Significant Motion)  that:

At the high level, the significant motion detector is used to reduce the power consumption of location determination. When the localization algorithms detect that the device is static, they can switch to a low power mode, where they rely on significant motion to wake the device up when the user is changing location.

Does it mean that this sensor is already used by GPS_NETWORK or that applications have to implement the described behavior?
Thanks

A: The link you provided (significant motion) relates to accelerometer, which you shouldn't be conncerned much when implementing location tracking.
What you probably need is Fused Location Provider API from Google Play Services, read more here: https://developer.android.com/training/location/index.html. It automatically merges data from GPS and Network providers, also synchronising access to location information between applications. It gives you fairly simple configuration options (how accurate location do you want? How often would you like to get updates?), and Play Services framework takes care of providing you with location in very efficient manner.
Since this is pretty extensive topic, I'll just refer to you documentation: the link above specifically this section. You should find plenty of tutorials too.


text:
Q: how can know ssh is disconected and retry with bash script I'm using reverse ssh for connecting to remote client , Operator run reverse one time and leave client system
how can i write bash script , when reverse ssh disconnected from server retry to connect to server (ssh)

A: Use autossh.  Autossh "automatically restart[s] SSH sessions and tunnels"
sudo apt-get install autossh

I use autossh to to keep open reverse tunnel that I depend on.  It works very well, even with long periods of lost connection.
Here is the script I use to create the tunnel:
#!/bin/bash
AUTOSSH_GATETIME=0
export AUTOSSH_GATETIME
autossh -f -N -R 8022:localhost:22 username@host -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2"

I execute this script at boot with this cronjob:
@reboot /home/scripts/./persistent-tunnel.sh

A: If you simply want to retry a command until it succeeds, you can use this pattern:
while ! ssh [...]
do
    echo "Command failed, retrying..." >&2
done

A: I have a slightly different method.
My method always tries to reconnect you if you have a dirty disconnection: '~.' or 'Connection closed by remote host.'
But if you disconnect with 'CRTL+D' or with 'exit' it just disconnects and show you some info of the connections.
I have a slightly different method.
My method always tries to reconnect you if you have a dirty disconnection: '~.' or 'Connection closed by remote host.'
But if you disconnect with 'CRTL+D' or with 'exit' it just disconnects and show you some info of the connections.
#/bin/bash
if [ -z "$1" ]
then
        echo '''
        Please also provide ssh connection details.
        '''
        exit 1
fi
retries=0
repeat=true
today=$(date)
while "$repeat"
do
        ((retries+=1)) &&
        echo "Try number $retries..." &&
        today=$(date) &&
        ssh "$@" &&
        repeat=false
        sleep 5
done
echo """
        Disconnected sshx after a successful login.
        Total number of tries = $retries
        Connected at:
        $today
"""

A: You might want to take a look into ssh options ServerAliveInterval, ServerAliveCountMax and TCPKeepAlive because sometimes your line dies without making this obvious, let me demonstrate:
#!/bin/sh

while true; do

ssh -T user@host \
  -o IdentityFile=~/.ssh/tunnel \
  -o UserKnownHostsFile=~/.ssh/known_hosts.tunnel \
  pkill -f "^sshd:\ user\ \ \ \ $" # needs to be edited for nearly every case

sleep 2

ssh -T -N user@host \
  -o IdentityFile=~/.ssh/tunnel \
  -o UserKnownHostsFile=~/.ssh/known_hosts.tunnel \
  -o Batchmode=yes \
  -o ExitOnForwardFailure=yes \
  -o ServerAliveCountMax=1 \
  -o ServerAliveInterval=60 \
  -o LocalForward=127.0.0.1:2501=127.0.0.1:25 \
  -o RemoteForward=127.0.0.1:2501=127.0.0.1:25

sleep 60

done

A: You can use netstat -ntp | grep ":22" or ss -ntp | grep ":22" to see established connections to ssh port, then use grep to filter the ip address you're looking for. If you don't find a connection then reconnect the tunnel.

A: Use autossh if it works on your version of Linux. It did not on mine as it was an outdated Linux distribution for a custom NAS box.
The alternative is a simple bash script in crontab like this:
maintain_reverse_ssh_tunnel.sh
if ! netstat -planet |grep myserver_ip_or_name |grep ESTABLISHED > /dev/null; then
    echo "REVERSE SSH DOWN - Restarting the tunnels"
    ssh -fN -R 32999:localhost:22 -R 28080:localhost:80 myusername@myserver_ip_or_name
fi
Replace myusername and myserver_ip_or_name with those of your user and server.
Then add an entry to crontab by typing crontab -e and adding the following line:
1 * * * * /path_to_my_script/maintain_reverse_ssh_tunnel.sh
Make sure to have the execute permissions on the script:
chmod 755 maintain_reverse_ssh_tunnel.sh


text:
Q: How to find bounding box lat longs of worldwind current view? I'm working with worldwind and I'm trying to find the cordinates upper left, upper right, lower left, lower right of the current worldwind view.
When I say cordinates i'm looking for the +/- 90 degrees latitude and +/- 180 degrees longitude.  Whats the easiest way to do this.

A: If you have a gov.nasa.worldwind.WorldWindow, say, worldWindow, then you can get its current view like so:
View curView = worldWindow.getView();

... where curView is of the class gov.nasa.worldwind.View; see here.  Then, you can get the view's "view port" like so:
Rectangle viewPort = curView.getViewport();

... where viewPort is a java.awt.Rectangle.  Next, we need to compute the position from the screen point of each point of that rectangle:
Position topLeft = curView.computePositionFromScreenPoint(0, 0);
Position botRight = curView.computePositionFromScreenPoint(viewPort.width, viewPort.height);

... where topLeft, botRight are each of the class gov.nasa.worldwind.geom.Position.  The lower left and upper right should be obvious from the construction given above.

A: gov.nasa.worldwind.View has a method computePositionFromScreenPoint


text:
Q: SQL Percentile function missing? It is a mystery to me with this text book example. We have simply:
Transaction_ID (primary key),   Client_ID,  Transaction_Amount, Month

1                   1       500         1
2                   1       1000            1
3                   1       10          2
4                   2       11          2
5                   3       300         2
6                   3       10          2
...                 ...     ...         ...

I want to calculate in SQL the mean(Transaction_Amount), std(Transaction_Amount) and the some percentile(Transaction amount) grouped by Client_ID. But is seems, even given that percentile is a very similar calculation than the standard deviation, SQL cannot do it with a simple statement as:
SELECT
    mean(Transaction_Amount),
    std(Transaction_Amount),
    percentile(Transaction_Amount)
FROM
    myTable
GROUP BY
    Client_ID, Month

Or can it?
It gets worse becuase I also need to Group By Month in addition to Client_ID.
Thanks a lot!
Sven

A: I'm sure Oracle can do the calculations you want.  I just don't know what they are.  You specify that you want something grouped by ClientId.  Yet, your sample query has two keys in the GROUP BY.
Some functions that you want to look at are:

*

*AVG()

*STDDEV()

*PERCENT_RANK()
Without sample data and desired results (or a very clear explanation of what you are trying to calculate), I can't put together a query.


text:
Q: Difference from two set of nodes - XSLT I have a sample Xml like below. This has two Root Elements named "Param" and "Dimension".
Param Element is also having a child node named "Dimension", and it contains some elements named "Member". This has two attributes id and name.
<Root>
    <Param>
        <Pattern id="P1" name="Pattern1">
            <Dimension name="Dim1">
                <Member id= "1" name="Member1" />
                <Member id= "4" name="Member4" />
                <Member id= "5" name="Member5" />
                <Member id= "6" name="Member6" />
                <Member id= "7" name="Member7" />
                <Member id= "9" name="Member9" />
                <Member id= "10" name="Member10" />
                <Member id= "11" name="Member11" />
                <Member id= "12" name="Member12" />
                <Member id= "13" name="Member13" />
                <Member id= "16" name="Member16" />
                <Member id= "17" name="Member17" />
                <Member id= "18" name="Member18" />
                <Member id= "19" name="Member19" />
            </Dimension>
        </Pattern>
        <Pattern id="P2" name="Pattern2">
            <Dimension name="Dim1">
                <Member id= "1" name="Member1" />
                <Member id= "2" name="Member2" />
                <Member id= "3" name="Member3" />
                <Member id= "4" name="Member4" />
                <Member id= "5" name="Member5" />
                <Member id= "6" name="Member6" />
                <Member id= "8" name="Member8" />
                <Member id= "11" name="Member11" />
                <Member id= "12" name="Member12" />
                <Member id= "13" name="Member13" />
                <Member id= "14" name="Member14" />
                <Member id= "15" name="Member15" />
                <Member id= "16" name="Member16" />
                <Member id= "17" name="Member17" />
            </Dimension>
        </Pattern>
    </Param>
    <Dimension name="Dim1">
        <Member id= "1" name="Member1" >
            <Member id= "2" name="Member2" >
                <Member id= "3" name="Member3" />
                <Member id= "4" name="Member4" />
                <Member id= "5" name="Member5" />
                <Member id= "6" name="Member6" />
                <Member id= "7" name="Member7" />
            </Member>
            <Member id= "8" name="Member8" >
                <Member id= "9" name="Member9" />
                <Member id= "10" name="Member10" />
                <Member id= "11" name="Member11" />
            </Member>
            <Member id= "12" name="Member12" >
                <Member id= "13" name="Member13" />
                <Member id= "14" name="Member14" />
                <Member id= "15" name="Member15" />
                <Member id= "16" name="Member16" />
                <Member id= "17" name="Member17" />
                <Member id= "18" name="Member18" />
                <Member id= "19" name="Member19" />
                <Member id= "20" name="Member20" />
            </Member>
        </Member>
    </Dimension>
</Root>

members from Pattern/Dimension/Member has to be compared to root Dimension element and in the out put the difference is required like below.
<Root>
    <Pattern id="P1" name="Pattern1">
        <Dimension name="Dim1">
            <Member id= "2" name="Member2" />
            <Member id= "3" name="Member3" />
            <Member id= "8" name="Member8" />
            <Member id= "14" name="Member14" />
            <Member id= "15" name="Member15" />
            <Member id= "20" name="Member20" />
        </Dimension>
    </Pattern>
    <Pattern id="P2" name="Pattern2">
        <Dimension name="Dim1">
            <Member id= "7" name="Member7" />
            <Member id= "9" name="Member9" />
            <Member id= "10" name="Member10" />
            <Member id= "18" name="Member18" />
            <Member id= "19" name="Member19" />
            <Member id= "20" name="Member20" />
        </Dimension>
    </Pattern>
</Root>

for Pattern1,
when compared to /Root/Dimension//Members, the below difference found in the sample example
Member2
Member3
Member8
Member14
Member15
Member20
same logic for different pattern. is it possible to achieve by XSLT 1.0? Can any one please help on this.
Thanks in advance.

A: Firstly start off with the identity template...
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

Then, from looking at your requirements, you only want Param/Pattern elements in your output, so you can start off by selecting them...
<xsl:template match="Root">
    <xsl:copy>
        <xsl:apply-templates select="Param/Pattern"/>
    </xsl:copy>
</xsl:template>

Pattern elements themselves are unchanged, so will be handled by the identity template, but for the child Dimension elements you want to select Member elements from the Root\Dimension element that do not correspond to the current Dimension, so the template would look like this
<xsl:template match="Pattern/Dimension">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="/Root/Dimension//Member[not(@id = current()/Member/@id)]" />
    </xsl:copy>
</xsl:template>

You would also need a template to stop the whole hieracrhical structure of the Member element being copied, and only copy the parent one.
<xsl:template match="Member">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
    </xsl:copy>
</xsl:template>

Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" indent="yes" />
    <xsl:strip-space elements="*" />

    <xsl:template match="Root">
        <xsl:copy>
            <xsl:apply-templates select="Param/Pattern"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Pattern/Dimension">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="/Root/Dimension//Member[not(@id = current()/Member/@id)]" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Member">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>


text:
Q: integrating sonarqube with jenkins insufficient privileges error I followed this video https://www.youtube.com/watch?v=jh7utASgKj4 to integrate sonarqube with jenkins. However, I get the insufficient privileges error when scanning the code by sonarqube server. The version of sonarqube server is 6.7. how can I solve this problem?
Here is the analysis properties in the jenkins project
# Required metadata
sonar.projectKey = test-sonar

# Path to source directory
sonar.sources = /var/jenkins_home/workspace/$JOB_NAME/test-sonar/src

# bind sonar.java.binaries property
sonar.java.binaries=/var/jenkins_home/workspace/$JOB_NAME/test-sonar/target/classes

Here is the output of console.
INFO: SCM provider for this project is: git
INFO: 16 files to be analyzed
INFO: 16/16 files analyzed
INFO: 5 files had no CPD blocks
INFO: Calculating CPD for 8 files
INFO: CPD calculation finished
INFO: Analysis report generated in 132ms, dir size=124 KB
INFO: Analysis reports compressed in 48ms, zip size=61 KB
INFO: ------------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: ------------------------------------------------------------------------
INFO: Total time: 48.028s
INFO: Final Memory: 15M/304M
INFO: ------------------------------------------------------------------------
ERROR: Error during SonarQube Scanner execution
ERROR: Insufficient privileges
ERROR:
ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.
WARN: Unable to locate 'report-task.txt' in the workspace. Did the SonarScanner succedeed?
ERROR: SonarQube scanner exited with non-zero code: 1

A: Please make sure that you configure the Sonarqube UserID and Password having privileges to access sonar server (execute analysis permissions) in the Sonar plugin for Jenkins. This error might appear for 5.3 and higher versions when the anonymous access to sonar is disabled.

A: If you are running the Sonar Analysis via Execute shell plugin for Jenkins, you need to supply the Username Password of a User which has the Execute Analysis rights on the SonarQube server you are trying to access.
To supply the username in the shell, you can use
-Dsonar.login=yourLoginName -Dsonar.password=*****
To set the Execute Analysis permission you can ask your DevOps team to give you access or if you are looking into that,
Goto Administration > Security > User/Groups.


text:
Q: 'git reset --hard' Multiple Rebased Branches I have a local ref that contains a few branches that I recently performed git rebase on:
A---B---C---D master
     \
      E---F---G topic1
               \
                H---I---J topic2

Which turned it into:
A---B---C---D master
             \
              E'---F'---G' topic1
                         \
                          H'---I'---J' topic2

by using the following set of commands:
git checkout topic1
git rebase master
git checkout topic2
git rebase topic1

The problem?
I accidentally forgot to do git rebase --no-ff in order to keep track of all of my previously merged branches.  Now, I have no way of easily telling (by using gitk --all) where my merges occurred.  I know that they happened somewhere between HEAD@{E} and HEAD@{J}, but without going through each commit individually, I'm lost.
What I have decided to do:
So, I figured that I would use git reflog as suggested here, along with git reset --hard HEAD@{#} to revert back to the original state before the two rebases occurred and then attempt to git rebase branchname --no-ff as I suggested.
My ultimate question is this (with a few additional):
Can I simply go all the way back to the last commit before the first rebase or do I need to rollback each of the rebases individually?  Will each of the top branches be exactly as I used to have them (showing the non-fast forwarded merges that I'm looking for)?  Am I making this too difficult/is there a simpler way to do this?  Anything I'm neglecting to think about?
Thanks.

A: If you reset each branch to the commit it was on before the rebase of that branch occurred, it will be like the rebase never happened.  Each branch has its own history independent of any other branch, so you will need to reset each branch individually.

A: Please take a look at git reflog. It has the previous references. You can reset to a commit from the reflog by doing git reset --hard HEAD@{2} to get the 2nd most recent commit being pointed to by HEAD. Same applies for branches.
You can even do that without checking them out like so:
git push . +topic1@{1}:topic1
git push . +topic2@{1}:topic2


text:
Q: How to use databinding together with ratingbar's android:progressBackgroundTint attribute? I got the following RatingBar and I attempted to use databinding to set its android:progressBackgroundTint attribute, but it gives me a compilation error of the following:

Error:(61, 39) Cannot find the setter for attribute
  'android:progressBackgroundTint' with parameter type int on
  android.widget.RatingBar.

<RatingBar
        android:id="@+id/item_rating_bar"
        style="@style/StarRatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_item_space_title"
        android:layout_marginBottom="2dp"
        android:backgroundTint="@{space.themeColorResourceInt}"
        android:clickable="false"
        android:isIndicator="true"
        android:progressBackgroundTint="@{space.themeColorResourceInt}"
        android:progressTint="@{space.themeColorResourceInt}"
        android:rating="2.5"
        android:secondaryProgressTint="@{space.themeColorResourceInt}"
        tools:rating="2.5"/>

android:progressTint, android:backgroundTint and android:secondaryProgressTint are okay to use databinding but not android:progressBackgroundTint. May I know how to solve it?
Here is the getThemeColorResourceInt() of my Space class:
...

@Nullable
@Bindable
public int getThemeColorResourceInt() {
    // lazy instiantate
    if (themeColorResourceInt > -1) {
        return themeColorResourceInt;
    }

    if (themeColor != null) {
        themeColorResourceInt = Color.parseColor(themeColor);
        return themeColorResourceInt;
    }

    if (spaceId > -1) {
        try {
            String floorSpaceThemeColor = SpaceBean.getInstance().getCurrentFloor().getSpaceWithSpaceId(spaceId).getThemeColor();
            themeColorResourceInt = Color.parseColor(floorSpaceThemeColor);
            return themeColorResourceInt;
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            Logger.getLogger().e(ex.getLocalizedMessage());
        }
    }

    return MainApplication.sContext.getResources().getColor(R.color.btn_brown);
}
...


text:
Q: Process multiple passed parameters I am passing a parameter to a program that is based on the following code. The code calls a method of a specific class based on the parameter value. I would like to expand this to allow multiple parameters. What sort of code is needed that will allow to pass multiple parameters as well keeping the current functionality?
if (args != null && args.Length > 0)
{
    if (args[0] == "1")
    {
        Order.RunOrder();
    }
    if (args[0] == "2")
    {
        Shipment.RunShipment();
    }
    if (args[0] == "3")
    {
        Acknowledgments.RunAcknowledgments();
    }
    if (args[0] == "4")
    {
        Invoices.RunInvoices();
    }
}
else
{
    Helper.AddtoLogFile("------ No program type parameter found");
}
Helper.AddtoLogFile("-------Program Ends ----------");
return 0;

A: args is just an array of arguments, therefore you always have support for multiple parameters. Currently you are starting your application with
foo.exe 4

but you can also start it with
foo.exe 4 DoSomethingFancyWithBar

and then the code would look like this for example
if (args != null && args.Length > 1)
{
  if (args[1] == "DoSomethingFancyWithBar")
  {
     // do something fancy with the bar here

A: You can have each of your SomeClass.DoSomething() methods take a string[] args parameter. Then you can store all of the parameters except the first: var argsRest = args.Skip(1).ToList() (you'll need to be using Linq for this) and then you can pass the args on: SomeClass.DoSomething(argsRest).
This will let you have your main deal with selecting which class to call, then leave each of those classes to decide how it wants to handle the rest of the args.


text:
Q: Transaction replication with horizontal filtering To make a long story short, is it possible to replicate rows of a table in SQL server with horizontal filtering function that being evaluated continuously?
For instance, I need to replicate a table rows to subscriber which are created or updated since last two days or more. I need any rows that are being created in source table but their creation date is older than two days get replicated to subscriber and this get done continuously on any newly created/updated rows. I mean that I don't need to replicate records that are newer than two days.
I have tried transaction replication with filtering function on SQL server 2017, but filtering function just get evaluated on replication creation time and after that, any new rows didn't get propagated to subscriber.

A: *

*Add a column to your table: Alter Table yourTable Add Old_Enough Bit Not Null Default 0

*Create a job that runs regularly (e.g. hourly) and runs Update yourTable Set Old_Enough = 1 Where Old_Enough = 0 And DateAdd(Day, 2, yourCreationDateColumn) < GetDate()

*Create an indexed view that takes Select ... From yourTable Where Old_Enough = 1

*Replicate your indexed view


text:
Q: How to type a smokesignals event handler with JSDOC I have a old project writed with javascript, and now I want to generate a d.ts with JSDOC and use it for code completions in vs code.
And now stuck at the event handler typings.
code in javascript:
// I have two different classes

// class 1
// MyClass_1

// class 2
// MyClass_2

// when MyClass_1 created, emit a `class_1_created` event,
// and set the `MyClass_1` instance `my_class_1` as parameter
obj.emit('class_1_created', my_class_1)

// when MyClass_2 created, emit a `class_2_created` event,
// and set the `MyClass_2` instance `my_class_2` as parameter
obj.emit('class_2_created', my_class_2)

In the client side, use on to register the event handler
//
// how to get my_class_1's type in d.ts?
//
obj.on('class_1_created', my_class_1 => {})
obj.on('class_2_created', my_class_2 => {})

THE QUESTION IS:
How to get my_class_1 and my_class_2 's type in the client side code completions?, how to JSDOC it in My_Class?


text:
Q: Axis2 is "overriding" my JAXB web service So basically I have had a simple web service made with JAXB (As simple as Endpoint.publish()). It is working great. As soon as I try and use my service with another aplication that is itself using an Axis2 web service I cannot publish my web server anymore.
Since the second application was not made by me i cannot check the source code. I think that the AxisEngine is listening to my web server publishing and it wont let it be "created".
For example:

*

*Before this Axis2 application I would publish my webservice at http://ip:port/server and I was able to open the page http://ip:port/server?wsdl.

*Now I publish the server at the same address but when I open the page http://ip:port/server?wsdl I automatically get redirected to http://ip:port/services/ with the fault exception (The service cannot be found for the endpoint reference (EPR)).

A: I have resolved this by following this steps on another question:
JAX-WS = When Apache CXF is installed it "steals" default JDK JAX-WS implementation, how to solve?


text:
Q: What is causing __builder does not exist in current context error from compiler? "Error  CS0103  The name '__builder' does not exist in the current context"
Here is my code that causes the error:
@code {
    public void Calc()
    {
        for (int i = 0; i < 55; )
        {

This is the number"  @i

        }
    }
}

A: You can't render HTML in @code or @functions block. You can do this in a @{ } code bock.

A: As per ltwlf's answer, HTML markup is not allowed within the @Code block.  I received the same error, but I was positive that I had no HTML within my @code block.  However, after careful review I noted that there were HTML comment tags  inside my @code block.  This displays correctly as green comments and is easily missed - Therefore carefully review your @code block for any HTML markup if you get this error.

A: The correct answer is at this SO link.
In short you cannot mix markup with C# code inside @code block.
Consider make a component for reusing the markup.

A: Members of the component class are defined in one or more @code blocks. In @code blocks.
Component members are used in rendering logic using C# expressions that start with the @ symbol. For example, a C# field is rendered by prefixing @ to the field name.(more info)
The RenderFragment delegate must accept a parameter called __builder of type RenderTreeBuilder so that the Razor compiler can produce rendering instructions for the fragment.
Sample1:
@using Microsoft.AspNetCore.Components.Rendering

@{ load1(__builder); }
@code {
    void load1(RenderTreeBuilder __builder)
    {
        @for (int i = 0; i < 1; i++)
        {

This is the number @i

        }
    }
}

Sample2:
<button class="btn btn-success" @onclick="()=>Calc()">Action</button>
@((MarkupString)myMarkup)
@code {
    string myMarkup = "";
    void Calc()
    {
        @for (int j = 0; j < 55; j++)
        {
            myMarkup += getMarkup(j);
        }
    }

    string getMarkup(int j) {
        var myMarkup = "
";
        myMarkup += $"
This is the number {j}
";
        myMarkup += "
";
        return myMarkup;
    }
}

A: In order to use the "onclick" within a razor page you must prefix it with the @ symbol.
Event Handling


text:
Q: Storing data into Accumulo with Pyspark I am trying to store data into Accumulo using Pyspark (Python + Spark). Right now I am using the pyaccumulo library to write data into Accumulo by passing the pyaccumulo egg file to the SparkContext using the pyFiles argument. I was wondering if there was a better way to do this. I have seen the examples for the Cassandra and HBase output formats and was wondering if something like that could be done for Accumulo. Cassandra and HBase seem to be using the saveAsNewAPIHadoopDataset(conf, keyConv, valueConv) function and pass a config dict, a keyconverter and a valueconverter. Does anyone have any idea as to what could be the corresponding values to be passed to saveAsNewAPIHadoopDataset() for Accumulo?

A: Taking a guess, as I have no idea how it's supposed to work, you'd need something like

*

*AccumuloOutputFormat.ConnectorInfo.principal

*AccumuloOutputFormat.ConnectorInfo.token

*AccumuloOutputFormat.InstanceOpts.zooKeepers

*AccumuloOutputFormat.InstanceOpts.name

To get a full list of properties, I'd run a normal MapReduce example (http://accumulo.apache.org/1.7/examples/mapred.html) and look at the configuration values.


text:
Q: Issue iterating state from firebase in react I have this component in react that get todo from firebase, build an array and set a state, but when I render the component I only can see the elements the first time, if I reload the page the state seems to be empty.
import React, { PureComponent } from 'react';
import firebase from 'firebase'

class Charts extends PureComponent {
    constructor(props) {
        super(props);
        this.state = { data: [] };
        this.todoRef = firebase.database().ref('Todo');
    }

    componentDidMount = () => {
        var data = [];
        this.todoRef.on('value', (snapshot) => {
            const todos = snapshot.val();
            for (let id in todos) {
                data.push({ id, ...todos[id] });
            }
        });

        this.setState({ data: data })
    }

    render() {
        return

            {this.state.data.map(item => (

{item.name}

            ))}

    }
}

export default Charts;

If I use console log I get an array(0) with elements inside. I have tried locating the setState in different life cicles methods but don't seems to work.

A: Issue
You are calling this.setState outside the snapshot handler, so you are only passing the empty ([]) data array to the state updater.
Solution
You should move the state update into the function processing the snapshot.
componentDidMount = () => {
  const data = [];
  this.todoRef.on('value', (snapshot) => {
    const todos = snapshot.val();
    for (let id in todos) {
      data.push({ id, ...todos[id] });
    }
    this.setState({ data });
  });
}


text:
Q: Initialization of gene in binary array for timetable scheduling with GA in C# I am currently working on a project for driver scheduling and it's at the initial stage.
I have decided to use GA to generate optimized schedule for a driver, and as most of GA project do, the population shall be represented in binary.
e.g. if a driver is assigned two hours of task and his working duration is 9 hours, the possible population for that specific day looks like 110000000, 011000000, 001100000 and so on.
As GA's initialization, I would like to produce possible gene like 000110000 dynamically with two parameters (working duration of driver, and duty duration).
I managed to get fully random binary code in boolean list (see below) but this is not what I want to represent as the initialization.
This is the partial code which generates random binary string (technically bunch of boolean values) in a list.
private Random Rnd = new Random();
        //initial data
    private List<bool[]> CreateInitialData()
    {
        //generate 4 random genes (might be more)
        return Enumerable.Range(0, 1).Select(_ =>
        {
            var array = new bool[GeneLength];
            for(int i = 0; i < GeneLength; i++)
            {
                array[i] = Rnd.Next(0, 2) == 1;
            }
            return array;
        }).ToList();
    }

How could I implement the initialization function to produce the binary code which meets the requirement (driver's working hours, estimated duty duration)?
If there is a better way to represent it other than boolean list, please do suggest as well.

A: Based on 1 hour tasks I came up with this:
private static void Main(string[] args)
{
    var genes = GetGenes(9, 2);
}

private static List<bool[]> GetGenes(int workinghours, int estimateddutyduration)
{
    // get the base representation
    var hours = GetHours(workinghours, estimateddutyduration);
    var list = new List<bool[]>();
    for (int i = 0; i < (workinghours-estimateddutyduration)+1; i++)
    {
        // add
        list.Add(hours);
        // switch
        hours = SwitchArray(hours);
    }
    return list;
}

private static bool[] SwitchArray(bool[] array)
{
    // copy the array to a list
    var temp = array.ToList();
    // insert the last element at the front
    temp.Insert(0, temp.Last());
    // remove the last
    temp.RemoveAt(temp.Count-1);
    // return as array
    return temp.ToArray();
}

private static bool[] GetHours(int totalhours, int taskduration)
{
    // initialise the list
    var hours = new List<bool>(totalhours);
    // fill the list for the number of working hours
    for (int i = 0; i < totalhours; i++)
    {
        hours.Add(false);
    }
    // iterate for the task duration and set the hours as working
    for (int i = 0; i < taskduration; i++)
    {
        hours[i] = true;
    }
    // return as array
    return hours.ToArray();
}

for 9, 2 returns
110000000
011000000
001100000
000110000
000011000
000000110
000000011

for 9, 9 returns
111111111

For 9, 4 returns
111100000
011110000
001111000
000111100
000011110
000001111

This code is quite verbose and I have no doubt it can be optimized. But it's the idea I want to convey more than anything.
EDIT: If you want to display the results on the console
private static void ShowGenes(List<bool[]> genes)
{
    foreach (var gene in genes)
    {
        foreach (var bit in gene)
        {
            Console.Write(bit ? "1" : "0");
        }
        Console.Write("\n");
    }
}


text:
Q: Catching error on a merged observable and continue the others in RxJS Use-case:
I am trying to implement a save procedure in javascript using RxJS. I have a method named for example set and in it, I want first save the object into the local DB and then also send it to the server. So, for example, I have this code:
set({ obj, group = 'main' }) {
    // tell the LocalDB to store obj in appropriate name and group (appropriate table)
    const storageObservable = this.parealDB.storage.set(this.name, group, { ...obj, status: 0 }); // status 0 means that the records need to be synced (sent) to the server
    // tell the WebClient to sync obj to appropriate name and group (appropriate table)
    const webclientObservable = this.parealDB.webclient.set(this.name, group, obj); // try to send to server and then set status=1 on the localDB / this request should not be failed

    storageObservable.pipe(
        catchError(error => of({
            action: 'STORAGE_ERROR',
            data: error,
        }))
    );

    webclientObservable.pipe(
        tap(result => this.parealDB.storage.set(this.name, group, { _id: obj._id, status: 1 })),
        catchError(error => of({
            action: 'WEBCLIENT_ERROR',
            data: error,
        }))
    );

    return merge(storageObservable, webclientObservable);
}

And I want to return a merged observable outside the set method and while catching error of each inner job, also continue the others.
Problem:
I have tested this idea with some test observables. First, have a look on the sample:
//emit every 2.5 seconds
const first = interval(200).pipe(
  map(val => "" + val + " A"),
  take(3)
);
//emit every 2 seconds
const second = interval(100).pipe(
  mergeMap(val => {if(val === 1) return throwError('salam'); return of('' + val + " B");}),
  // tap(val => console.log('tapped ', val)),
  take(3)
)
// .pipe(
//   onErrorResumeNext(),
// )

//emit every 1.5 seconds
const third = interval(300).pipe(
  map(val => val + " C"),
  take(3)
);

merge(first, second, third)
// .pipe(
//   catchError(error => of(error)),
// )
.subscribe({
  next: console.log,
  error: console.error,
  complete: () => console.log('completed')
});

Now when the second one fails, it brokes the whole job and output is like this:
0 B
0 A
salam // (error)

And if I try uncommenting the catch error pipe on the merged observable, it will put salam as a normal output and also completing the job but still short-circuiting it:
0 B
0 A
salam
completed

The best solution I have found is to pipe onErrorResumeNext on each inner observable before merging them together. So uncommenting the mentioned operator on the second observable (which makes the problem) results in this output:
0 B
0 A
0 C
1 A
2 A
1 C
2 C
completed

It is very near to what I am searching for but out of the set method, I couldn't catch errors (listen on errors)!
Question:
So am I miss-using the RxJS observables or is there a better way to handle this situation?

A: You can keep the stream alive but using repeat() operator, but use it with care, you have to make sure the source stream is an hot observable or you may run into infinite looping.
streamA.pipe(
catch(e=>of(e)),
repeat())


text:
Q: A conceptual problem of angular momentum operator I learnt from my quantum mechanics courses that angular momentum operator is the generator of rotation, and applying angular momentum operator is like performing an infinitesimal rotation in 3D space.
Here is my question: why would a wavefunction "lengthen" under infinitesimal rotation? For instance, let's take a wavefunction $\psi$ with $l=2$ as an example. Obviously, it is invariant under rotation in z-axis and $l_{z}\psi=2\hbar\psi$, but I don't understand why a function will be scaled by a factor of $2\hbar$ when it is rotated. How can rotation reduce (or enhance) the amplitude of a function?
I understand that in this case it doesn't matter because wavefunction must be normalized and a constant factor in front won't change any observables. However, if I understand correctly, the use of rotational generator should be something universal, i.e. I could just as well apply the generators of rotation to any scalar field that maybe changing the amplitude do carry physical significance. This brings back to may question, how can an infinitesimal rotation change the amplitude of a function?
I am guessing that my interpretation of angular momentum operator is wrong. I can answer my homework's questions just fine as they mostly ask for mathematical calculations, which I have less trouble with, but I am having a hard time understanding intuitively how different operators operate. Thank you very much for your help.

A: The rotation operator is $$R(\hat{n},\varphi)=e^{-\frac{i}{\hbar}\varphi\hat{n} \cdot \vec{L}}$$, set $\hat{n}=\hat{z}$,so rotate the wave-function $\psi_{lm}$, we obtain $$R(\hat{n},\varphi)\psi_{lm}=e^{-i\varphi m}\psi_{lm}$$ the "length" is invariant. Considering an infinitesimal rotation $\hat{n}=\hat{z},\varphi \to \delta \varphi$, the rotation operator is approximate to $$1-\frac{i}{\hbar}\delta \varphi \hat{n}\cdot\vec{L}$$
then $$R(\hat{n},\delta\varphi)\psi_{lm}=\psi_{lm}-i\,\delta \varphi \,m\psi_{lm} \approx\psi_{lm}$$
the "length" is also invariant.

A: What a great question! The answer, I think, is that $l_z$ is not a generator of rotations per se. So for example your typical spin-$\frac12$ system the angular momentum operator in the $z$-direction is$$\frac\hbar 2 \begin{bmatrix}1&0\\0&-1\end{bmatrix}$$and you can just "see" that this is not a rotation matrix (and it's not just the scale factor, though that helps).
Note especially that this "length" is actually a probability to observe the system in any state therefore it better not change, even for simpler systems. What gives?
I think that there is a misunderstanding deep inside this, that Hermitian observables are directly affecting the wavefunctions in quantum mechanics. They never do this directly, they always have to go through something else, usually the Schrödinger equation. In the latter case, if $\hat H = \hbar\omega\sigma_z$, then the actual evolution operator is $U = e^{-i\omega t\sigma_z}=\cos(\omega t) I -i\sin(\omega t)\sigma_z$, which looks much more familiar as some sort of generated rotation.


text:
Q: Rails App doesn't work on production enviroment I have a rails app set up with Nginx + Passenger. When i have rails_env development; on my nginx.conf everything works fine, but when I remove it so the app get server on production env it just doesnt work, seems like its not loading gems or something. Feel free to take a look at the  errors here www.luisurraca.co.cc
error message:
undefined method `has_attached_file' for #<Class:0x00000003b0be10>
Exception class:
NoMethodError

Right now its referring to the paperclip gem, but if i start removing gems from the gemfile it will display error from some other gem and so on.
Any ideas what the issue might be?

A: You probably defined paperclip/whatever in development group and it is not installed with bundle install --deployment. To see installed gems do bundle show not gem list.
did you specify ruby path for nginx? it should look like this:
    http {
        passenger_root /home/rlisowski/.rvm/gems/ruby-1.9.3-p194/gems/passenger-3.0.13;
        passenger_ruby /home/rlisowski/.rvm/wrappers/ruby-1.9.3-p194/ruby;
        # ....


text:
Q: Variable stays null when switch cards with CardLayout I have a program that asks the user a series of questions where they choose options. They choose which job they want, which then (ideally) enters the amount of money cooresponding with that job into the balance. Then they choose a house which will then remove the cooresponding amount from the balance and so on. I have a class that houses an array that holds the amount from each decision. The problem is that while I can access the corresponding array position (position 0 for job, position 1 for house decision). I tried using a variable for the original amount, but it says it is zero, even if it prints the correct amount while in the Job code.
The problem is that I can't access other positions in the array when I'm in a different card. It gives me a null pointer exception, which happens in the line in the House class when I attempt to print the current balance amount left. I access the array when the user hits a button (called "Submit") and with an Actionlistener which decides exactly what to print based on which radio button was selected. I also print a dialog box printing the amount the user has left, using position 0 in the array (where Job writes the original amount). The program uses CardLayout.
I have done my best to include all relevant information, but, let's be real. I probably forgot something important. I've spent several hours on this and haven't been able to figure it out, so it's probably an issue with how CardLayout operates.
Here is the main class.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Main extends JPanel {
private Arrow arrow = new Arrow();                          //creates a new Arrow object
public Main() {
    JPanel btnPanel = new JPanel();
    btnPanel.add(new JButton(new NextAction("Next")));      //creates a "Next" button that is universal

    setLayout(new BorderLayout());

    add(arrow, BorderLayout.NORTH);
    add(btnPanel, BorderLayout.PAGE_END);
}

private class NextAction extends AbstractAction {
    public NextAction(String name) {
        super(name);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        arrow.next();  // *** call arrow's public next method
    }
}

private static void createAndShowGui() {
    Main mainPanel = new Main();
    JFrame frame = new JFrame("Iowa Budget Simulation");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> createAndShowGui());
}

}

Here is the class that creates the card holder.
import java.awt.BorderLayout;
 import java.awt.CardLayout;
 import java.awt.Color;
 import java.awt.Dimension;
import java.awt.Font;
import javax.swing.*;

class Arrow extends JPanel {
    private static final long serialVersionUID = 1L;
    private CardLayout cardLayout = new CardLayout();       // make me a field
    private JPanel cardHolder = new JPanel(cardLayout);     //creates a master JPanel

public Arrow() {
    for (int i = 0; i < 1; i++) {
        cardHolder.add(createCard(i), "card " + i);
    }

    Job j = new Job();
    HousingPurchase ownHouse = new HousingPurchase();
    HousingRent rentHouse = new HousingRent();
    HealthCare hc = new HealthCare();
    Transport t = new Transport();
    Child c = new Child();
    Clothes clo = new Clothes();
    Entertainment e = new Entertainment();

    cardHolder.add(j, "Job");
    cardHolder.add(ownHouse, "Housing - Own");
    cardHolder.add(rentHouse, "Housing - Rent");
    cardHolder.add(t, "Transport");
    //cardHolder.add(hc, "Health Care");
    cardHolder.add(c, "Childcare");
    setLayout(new BorderLayout());
    add(cardHolder, BorderLayout.NORTH);
}

// public method that other objects can call
public void next() {
    cardLayout.next(cardHolder);  // call next on the correct object
}

// simply creates a "pretty" new JPanel to be the "title" screen
private JComponent createCard(int i) {
    setLayout(null);
    setBounds(0, 0, 10 , 10);
    JLabel label = new JLabel("Iowa Budget Simulation");
    label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));

    float h = (float)Math.random();
    Color c = Color.getHSBColor(h, 1f, 1f);
    label.setForeground(c.darker());

    //JPanel panel = new JPanel(new GridBagLayout());

    JPanel panel = new JPanel();

    panel.add(label);
    panel.setBorder(BorderFactory.createLineBorder(c.darker(), 20));
    panel.setBackground(c.brighter().brighter());

    panel.setPreferredSize(new Dimension(860, 870)); // first number is width, second number is height
    return panel;
}
}

Here is the DecisionObject class. This class holds the array.
public class DecisionObject {
    private String decision;
    double amount;
    public double total;
    public DecisionObject finalMSG[] = new DecisionObject[10];

public DecisionObject(String d, double a){
    decision = d;
    amount = a;
}

public DecisionObject(){

}

    public double getAmount(){
        return amount;
}

public double getAmount(int a){
    return total;
}

public double getAmount(DecisionObject x){
    return x.getAmount();
}

public void changeBalance(double x){
    total = total - x;
}

public void setBalance(double x){
    total = x;
}

public double getTotal(){
    return total;
}
}

Here is the Job Class. I removed duplicate parts for simplicity
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class Job extends JPanel {

public DecisionObject x = new DecisionObject();
private static final long serialVersionUID = 1L;

public Job() {
    setLayout(null);
    setBounds(0, 0, 10 , 10);
    //label.setFont(label.getFont().deriveFont(Font.BOLD, 50f));

    JLabel titlelable = new JLabel("JOB");
    titlelable.setFont(new Font("Times New Roman", Font.PLAIN, 22));
    titlelable.setBounds(409, 11, 49, 27);
    add(titlelable);

    JTextArea highend = new JTextArea();
    highend.setWrapStyleWord(true);
    highend.setLineWrap(true);
    highend.setText("\"This job is for a warehouse associate. The hours are Monday - Friday, from 6AM to 6PM. Applicants must have a mode of reliable transportation, will be on their feet for 12 hrs a day, and be able to lift 75 pounds. The pay is $12/hr.\"");
    highend.setBounds(99, 49, 306, 197);
    DecisionObject h1 = new DecisionObject("Let's hope you don't mind physical labor. You're gonna be on your feet for 12 hours and will be doing some lifting.", 2880);
    add(highend);

    JTextArea house2 = new JTextArea();
    house2.setWrapStyleWord(true);
    house2.setLineWrap(true);
    house2.setText("\"This job is for a sterile fill technician. The hours are Monday - Friday, from 6AM to 2:30PM. The pay is $13/hr.\"");
    DecisionObject h3 = new DecisionObject("", 2210);
    house2.setBounds(99, 299, 306, 177);
    add(house2);

    JRadioButton LeftTop = new JRadioButton("Job 1: ");
    LeftTop.setBounds(99, 253, 109, 23);
    add(LeftTop);

    ButtonGroup group = new ButtonGroup();
    group.add(LeftTop);

    JButton submit = new JButton("SUBMIT");
    submit.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    submit.setBounds(342, 751, 184, 48);
    add(submit);

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            if (LeftTop.isSelected()){
                x.finalMSG[0] = h1;
                double b = x.finalMSG[0].getAmount();
                //double b = x.getAmount(x.finalMSG[0]);
                x.setBalance(b);
                String a = "Balance: " + x.getTotal();
                JOptionPane.showMessageDialog(null, a);
            }

            x.setBalance(2800);
        }
    });//Close submit button actionlistener

}

}
Finally, here is the House class.
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

class HousingPurchase extends JPanel {

private DecisionObject x = new DecisionObject();
private static final long serialVersionUID = 1L;

public HousingPurchase() {
    setLayout(null);
    setBounds(0, 0, 10 , 10);

    JLabel titlelable = new JLabel("HOUSING - PURCHASE");
    titlelable.setFont(new Font("Times New Roman", Font.PLAIN, 22));
    titlelable.setBounds(358, 11, 227, 27);
    add(titlelable);

    JTextArea highend = new JTextArea();
    highend.setWrapStyleWord(true);
    highend.setLineWrap(true);
    highend.setText("\"This house costs $1,011 per month. It has 2 beds, 1 bath, and was built in 1922. It has had recent updates, has refinished hardwood and tiled floors as well as new yard landscaping. In addition, it has an enclosed front porch and a screened back porch as well as a garage with a new driveway. If it were not more perfect, it is very close to schools and the freeway.\"");
    DecisionObject h1 = new DecisionObject("Let's hope you don't mind physical labor. You're gonna be on your feet for 12 hours and will be doing some lifting.", 1011);
    highend.setBounds(99, 49, 306, 197);
    add(highend);

    JRadioButton LeftTop = new JRadioButton("House 1: ");
    LeftTop.setBounds(99, 253, 109, 23);
    add(LeftTop);

    ButtonGroup group = new ButtonGroup();
    group.add(LeftTop);
    JButton submit = new JButton("SUBMIT");
    submit.setFont(new Font("Times New Roman", Font.PLAIN, 20));
    submit.setBounds(342, 751, 184, 48);
    add(submit);

    submit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            if (LeftTop.isSelected()){
                x.finalMSG[1] = h1;
                double b = x.getAmount(h1);
                JOptionPane.showMessageDialog(null, "Balance: " + (/*x.finalMSG[0].getAmount()*/ x.getTotal() - x.finalMSG[1].getAmount()));
            }
        }
    });//Close submit button actionlistener
}
}

Here is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at HousingPurchase$1.actionPerformed(HousingPurchase.java:117)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)


text:
Q: Change UEFI boot order from busybox After generate a new efi boot entry with efibootmgr:
# efibootmgr -c -g -L "Debian (EFI stub)" -l '\EFI\debian\vmlinuz' -u "root=UUID=955548bd-9c77-4893-8633-3a5e7966dfc9 ro quiet rootfstype=ext4 add_efi_memmap initrd=\\EFI\\debian\\initrd.img"

The system doesn't start, only fall into a BusyBox shell.
How is possible to change the boot order to the old entry? Something like
# efibootmgr -o 0004,0005,0000,0001,0002,0003

A: These are the steps to change the efi boot order on a Debian system:
On the BusyBox, load kernel module for the fs, in our case:
# modprobe ext4

Mount the required partitions needed. Note that root fs is on sda3 in our particular case:
# mkdir /mnt
# mount -t ext4 /dev/sda3 /mnt
# mount /proc /mnt/proc
# mount /sys /mnt/sys

Chroot into it:
# chroot /mnt

Load the kernel modules needed to mount the filesystems and to work with efibootmgr:
# modprobe efivars
# modprobe vfat
# modprobe efivarfs

Mount the required path:
# mount -t efivarfs efivarfs /sys/firmware/efi/efivars

Now, you can play with efibootmgr:
# bin/efibootmgr -v
# bin/efibootmgr -o 0005,0004,0000,0001,0003,0001,0002

End with the chroot and exit:
# sync
# exit

Reboot and enjoy.


text:
Q: Joi validation set default as empty object I'm running into an issue (or what I believe to be one) with Joi validation.  I'm trying to assign a value to a non-existent key if it's been passed as part of the request body.
So for example:
parameters: Joi.object().keys({
  keyA: Joi.string().allow('').allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string(),
    b2: Joi.string(),
    b3: Joi.object().keys({
      b3_1: Joi.string(),
      b3_2: Joi.string(),
      b3_3: Joi.string()
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number(),
    c2: Joi.number(),
    c3: Joi.boolean(),
    c4: Joi.boolean()
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number(),
    d2: Joi.number()
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number()
  }).default({})
}).allow(null)

So to be specific if I were to pass in:
{
  keyA: "foo",
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

I would get this in return
{
  keyA: "foo",
  keyB: {},
  keyC: {},
  keyD: {
    d1: 21.9,
    d2: 21.1
  },
  keyE: {
    e1: 42
  }
}

With :eyes: on the empty objects.  What am I missing with the Joi.default() method?  Am I overextending what Joi is meant for?

A: I'll start by pointing out that the schema in your question isn't valid JavaScript, you've closed a few too many brackets before declaring the rule for keyC. I'll assume this is simply a formatting error with the question and your actual schema is currently valid.
Secondly, there's nothing wrong with how you've declared your defaults.. it works just fine. I'll assume it's the way you're validating the schema which is the problem.
Try running this. I've mimicked the validation method in the docs for default().
const schema = Joi.object().keys({
    keyA: Joi.string().allow('').allow(null).default(null),
    keyB: Joi.object().keys({
        b1: Joi.string(),
        b2: Joi.string(),
        b3: Joi.object().keys({
            b3_1: Joi.string(),
            b3_2: Joi.string(),
            b3_3: Joi.string()
        })
    }).default({}),
    keyC: Joi.object().keys({
        c1: Joi.number(),
        c2: Joi.number(),
        c3: Joi.boolean(),
        c4: Joi.boolean()
    }).default({}),
    keyD: Joi.object().keys({
        d1: Joi.number(),
        d2: Joi.number()
    }).default({}),
    keyE: Joi.object().keys({
        e1: Joi.number()
    }).default({})
}).allow(null);

Joi.validate({
    keyA: "foo",
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    }
}, schema, (err, value) =>
{
    if (err)
        throw err;

    console.log(value);
});

I get this in the console:
{
    keyA :'foo',
    keyD: {
        d1: 21.9,
        d2: 21.1
    },
    keyE: {
        e1: 42
    },
    keyB: {},
    keyC: {}
}

The keys are unlikely to look ordered like your expected output, but that shouldn't matter as object keys are not ordered anyway.

A: You can set the default values, you should try this:
parameters: Joi.object().keys({
  keyA: Joi.string().allow(null).default(null),
  keyB: Joi.object().keys({
    b1: Joi.string().default("abc"),
      b2: Joi.string().default("abc"),
      b3: Joi.object().keys({
        b3_1: Joi.string().default("abc"),
        b3_2: Joi.string().default("abc"),
        b3_3: Joi.string().default("abc")
      })
    })
  }).default({}),
  keyC: Joi.object().keys({
    c1: Joi.number().default(0),
    c2: Joi.number().default(0),
    c3: Joi.boolean().default(0),
    c4: Joi.boolean().default(0)
  }).default({}),
  keyD: Joi.object().keys({
    d1: Joi.number().default(0),
    d2: Joi.number().default(0)
  }).default({}),
  keyE: Joi.object().keys({
    e1: Joi.number().default(0)
  }).default({})
}).allow(null)


text:
Q: Is it fine to delete my answer and post new one in case I did something wrong, but due to fast downvoters I had no time to edit it? I have met few problems when answering.
My scenario:

*

*I answer question

*I'm testing some better solutions

*I'm just about to edit it because I know my first answer was wrong and it should be improved

*There are at least 3 downvotes

Am I able/Is it fine to delete my old answer (because I'm pretty sure there wouldn't be downvoters monitoring my answer to watch if they could remove their downvote after edit) and create new one?

A: Don't post bad answers that you only think through afterwards.  Do the prep work beforehand.

A: My experience has been that once you fix the problem, you get a number of upvoters who bring it up to at or above 0.
In other words, you get a lot more rep by being downvoted, fixing it, then upvoted than you would by deleting it and starting a new one.
I'm not a big fan of getting rid of downvotes by deleting an answer and adding a new one, but the system allows it, awards a badge for it (peer pressure), and the whole reason to contribute to the site is to provide high quality answers to problems, so in the long run it won't matter.
I suggest you simply update the answer and see what happens.  It might surprise you.


text:
Q: CoreData(MagicalRecord) getting saved objects I have structure with entity 'wall post', it has same structured entity 'repost'. They have relationships ( 'wall post' have 'repost' with Destination as 'wall post' and inverse as 'repost').
Now I am getting objects with code
     NSArray *newsEntities = [[NSArray alloc] init];
     newsEntities = [WallpostEntity findAllSortedBy:@"pubDate" ascending:NO];

I have WallpostEntity and reposts in array. How can I get only 'wall posts'?

A: The only way I can think of that you're getting two different types of entities on this fetch request is that you've modeled your WallPost Entity to be a base class of Repost. That is, Repost is a subclass of Wallpost. If you only want Wallposts returned from your request, then you need to modify your code like so:
NSFetchRequest *request = [WallpostEntity MR_requestAllSortedBy:@"pubDate" ascending:NO];
[request setIncludesSubEntities:NO];
newsEntities = [WallpostEntity MR_executeRequest:request];


text:
Q: Manipulating lists with constant values let us assume we have some data in the following form.
Table[data[[1,i,{1,2}]],{i,1,Length[data[[1]]]}]

This would give all $x-y$ pairs of the first file. What I want to do now is to multipliy this table with constant factors but different factors for $x$ and $y$. I found a solution for this with
MapThread[ Composition[Flatten, List], {xlist, #}] & /@ ylist

where xlist is
 Table[data[[1,i,1]],{i,1,Length[data[[1]]]}]*c1

and ylist is
 {Flatten[Table[data[[1,i,2]],{i,1,Length[data[[1]]]}]]}*c2

Is there a more comfortable way to do this?
Thank you in adavance
Sincerely

EDIT:
 test= {{0.0015856, -1486.76}, {0.00157776, -1483.45}}

I need :
 test2= {{1.5856, -148.676}, {1.57776, -148.345}}

So the $x$ values should be multiplied with $1000$ and the $y$ values multiplied with $0.1$
EDIT2:
Transpose is exactly what I need, thank you very much

A: Try this:
    test = {{0.0015856, -1486.76}, {0.00157776, -1483.45}};
Map[{1000*#[[1]], 0.1*#[[2]]} &, test]

(*   {{1.5856, -148.676}, {1.57776, -148.345}}   *)


text:
Q: The spectrum of a ring minus a prime of height $1$ Let $R$ be a ring (commutative, with unit) and let $Q$ be the localization of $R$ at its regular elements (non zero divisors). Let $\mathfrak{p}$ be a prime ideal in $R$.
Let $R[\mathfrak{p}^{-1}]\subset Q$ be the subring of $Q$ containing $R$ defined as:
$$
R[\mathfrak{p}^{-1}]:= \{r\in Q~|~\exists n\geq 0,~\forall p\in \mathfrak{p}^n,~px\in R\}.
$$
It is the union of the $\mathfrak{p}^{-n}R$ in $Q$.
The canonical map $R\to R[\mathfrak{p}^{-1}]$ induces a morphism of spectra:
$$
\iota:\operatorname{Spec}R[\mathfrak{p}^{-1}] \longrightarrow \operatorname{Spec}R.
$$
I was wondering in which cases we can claim that $\iota$ induces an isomorphism $\operatorname{Spec}R[\mathfrak{p}^{-1}]\cong (\operatorname{Spec}R)\setminus V(\mathfrak{p})$ of ringed spaces. This does not happen very often:

*

*If $\mathfrak{p}=(0)$, then $R[\mathfrak{p}^{-1}]=R$ and thus $\iota$ is the identity but $(\operatorname{Spec}R)\setminus V(\mathfrak{p})=\emptyset$.

*As in @reuns's example (in comment), consider $R=\mathbb{C}[x,y]$ and $\mathfrak{p}=(x,y)\subset R$. $V(\mathfrak{p})$ is closed in $\operatorname{Spec} R=\mathbf{A}^2_{\mathbb{C}}$, and $(\operatorname{Spec} R)\setminus V(\mathfrak{p})$ is a scheme, obtained by glueing of $\operatorname{Spec} \mathbb{C}[x,y,x^{-1}]$ and $\operatorname{Spec} \mathbb{C}[x,y,y^{-1}]$ along $\operatorname{Spec} R$. It follows that
$$
(\operatorname{Spec} R)\setminus V(\mathfrak{p})=\operatorname{Spec}\mathbb{C}[x,y,x^{-1},y^{-1}].
$$
On the other-hand, we have an inclusion $\mathbb{C}[x,y,x^{-1},y^{-1}]\subset R[\mathfrak{p}^{-1}]$ which is strict, as  $(x+y)^{-1}$ belongs to latter and not to the former. Therefore, $\iota$ induces:
$$
\operatorname{Spec}R[\mathfrak{p}^{-1}] \longrightarrow (\operatorname{Spec}R)\setminus V(\mathfrak{p})
$$
but it is not an isomorphism of ringed spaces.

*If $R$ is a Dedekind domain and $\mathfrak{p}$ is not zero, then we have  $R\cap \mathfrak{p}R[\mathfrak{p}^{-1}]=R$, and if $\mathfrak{q}\neq \mathfrak{p}$ is a prime of $R$, then $R\cap \mathfrak{q}R[\mathfrak{p}^{-1}]=\mathfrak{q}R$. In particular,
$$
\operatorname{Spec}R[\mathfrak{p}^{-1}] \longrightarrow (\operatorname{Spec}R)\setminus V(\mathfrak{p})
$$
is an isomorphism of ringed spaces.

EDITED: My question is the following. If $\mathfrak{p}$ has codimension/height $1$, does $\iota$ induces an isomorphism $\operatorname{Spec}R[\mathfrak{p}^{-1}]\cong (\operatorname{Spec}R)\setminus V(\mathfrak{p})$ of ringed spaces?
Many thanks!


text:
Q: Scrape data-view value from website using Simple HTML DOM I'm ok at configuring /altering PHP, but not proficient enough to write it from scratch - was wondering if someone can help me with this please?
Basically I wish to scrape a small amount of data from the website, which is in the format:

and I wish to extract just the XYZ bit
$html->load($result["body"]);

    $rows = $html->find("div.PDPVariantOption");
    foreach ($rows as $row)
    {
        echo "\t" . $row . "\n";
    }

This is the code I'm using (in conjunction with http://barebonescms.com/documentation/ultimate_web_scraper_toolkit/ ) but this extracts everything which is within the div tag - I've tried various options using getAttribute and similar to get the "data-value" value (pure guesswork from me I'm afraid!) but no luck - can anyone help?
Many thanks in advance
Joey

A: OK this is my complete code which works:
$dom = new DOMDocument();
$html = '

';

$dom->loadHTML($html);

$finder = new DomXPath($dom);
$result = $finder->query("//*[contains(@class, 'PDPVariantOption')]");

for ($i; $i < $result->length; $i++) {
    $row = $result->item($i)->getAttribute('data-value');
    echo $row . "\n";
}