text:
Q: Calling FORTRAN subroutine from c++ yields illegal parameter value I'm currently trying to solve a particular eigenvalue problem (so-called gyroscopic eigenvalue problem)
with large, sparse matrices (from FEM dsicretization). The programming language is C++.
The standard reference for EVP is ARPACK. Alas, it implements only "classical" Arnoldi processes,
which is not suited for such problems (c.f. Structure Preserving Methods).
Recently I've found this Algorithm 961 reference, which also provides some code - in FORTRAN!
So i've tried to include the DGHUTR routine in C++, to no avail.
Below is the MWE, which is an adaptation of the test for DGHUTR (TDGHUTR.f) in C++:
#include <Eigen/Dense>
#include <Eigen/Sparse>
//definition stolen from ARPACK++
#define F77NAME(x) x ## _

//Interface to the SHEIG library function DGHUTR
#ifdef __cplusplus
extern "C"
{
#endif
  void F77NAME(dghutr)( char* JOB, char* COMPQ1, char* COMPQ2, int* N, double* A, int* LDA,
                        double* DE, int* LDDE, double* C1, int* LDC1, double* VW, int* LDVW,
                        double* Q1, int* LDQ1, double* Q2, int* LDQ2, double* B, int* LDB,
                        double* F, int* LDF, double* C2, int* LDC2, double* ALPHAR, double* ALPHAI,
                        double* BETA, int* IWORK, int* LIWORK, double* DWORK,int* LDWORK, int* INFO );
#ifdef __cplusplus
}
#endif

int main(void){
  // define system sizes
  int N(8),  M(N/2);
  std::cout << "Sizes: " << N << '\t' << M << std::endl;

  char job('E'),  compq1('I'),  compq2('I');
  int lda(M),  ldde(M),  ldq1(N),  ldq2(N),  ldb(M),  ldc1(M),  ldc2(M),  ldf(M),  ldvw(M);

  int ldwork = 2*N*N+std::max(4*N+4, 32);
  int liwork = N+12;

  // workspace arrays
  int* iwork = new int[liwork];
  double* dwork = new double[ldwork];
  int info(0);
  // auxiliary matrices and  vectors
  Eigen::MatrixXd F(ldf, M),  C2(ldc2, M),  Q1(ldq1, N),  Q2(ldq2, N),  B(ldb, M);
  Eigen::VectorXd alphaR(M),  alphaI(M),  beta(M);

  //matrices with data
  Eigen::MatrixXd A(lda,M), DE(ldde,M+1), C1(ldc1,M), VW(ldvw,M+1);

     A << 3.1472,   1.3236,   4.5751,   4.5717,
   4.0579,  -4.0246,   4.6489,  -0.1462,
  -3.7301,  -2.2150,  -3.4239,   3.0028,
   4.1338,   0.4688,   4.7059,  -3.5811;

   DE << 0.0000,   0.0000,  -1.5510,  -4.5974,  -2.5127,
   3.5071,   0.0000,   0.0000,   1.5961,   2.4490,
  -3.1428,   2.5648,   0.0000,   0.0000,  -0.0596,
   3.0340,   2.4892,  -1.1604,   0.0000,   0.0000;

   C1 <<  0.6882,  -3.3782,  -3.3435,   1.8921,
  -0.3061,   2.9428,   1.0198,   2.4815,
  -4.8810,  -1.8878,  -2.3703,  -0.4946,
  -1.6288,   0.2853,   1.5408,  -4.1618;

   VW <<  -2.4013,  -2.7102,   0.3834,  -3.9335,   3.1730,
  -3.1815,  -2.3620,   4.9613,   4.6190,   3.6869,
   3.6929,   0.7970,  0.4986,  -4.9537,  -4.1556,
   3.5303,   1.2206,  -1.4905,   0.1325,  -1.0022;

  /* outputs of each parameter save for dwork,iwork to check correctness. */

  F77NAME(dghutr)( &job, &compq1, &compq2, &N, A.data(), &lda, DE.data(), &ldde,  C1.data(), &ldc1, VW.data(), &ldvw,
                         Q1.data(), &ldq1,  Q2.data(), &ldq2,  B.data(), &ldb,
                         F.data(), &ldf,  C2.data(), &ldc2, alphaR.data(),  alphaI.data(),
                         beta.data(), iwork, &liwork, dwork, &ldwork, &info );
  std::cout << "result: " << info << std::endl;
  delete[] iwork;
  delete[] dwork;
}

Compilation is done with (it uses a lot of other stuff):
g++ -o eigensolver EigenSHEIGSolver.cpp -I/home/shared/eigen-eigen-1306d75b4a21  /home/shared/SHIRA/SHEVP/src/shheig64.a /home/shared/SHIRA/SLICOT_Lib/slicot64.a /home/shared/SHIRA/SLICOT_Lib/lpkaux64.a /home/shared/ATLAS/builddir/lib/libptlapack.a /home/shared/ATLAS/builddir/lib/libptcblas.a /home/shared/ATLAS/builddir/lib/libptf77blas.a /home/shared/ATLAS/builddir/lib/libatlas.a /home/shared/ATLAS/builddir/lib/libptcblas.a -lgfortran -lpthread

Alas, whenever I run the resulting executable it gives me:
 ** On entry to DGHUTR parameter number  8 had an illegal value

My FORTRAN knowledge is extremely limited and the above code was written mainly using
YoLinux Tutorial mixing FORTRAN and C
and
CRAY Docs
as references.
As I understand it the routine reports an error with the ldde variable. I've got no clue why, though.
Can anyone shed some light on this for me, please?
N.B. As per Eigen Docs: storage order
Eigen stores matrices per default in col-major order, thus it should be interfaceable with FORTRAN.
And the FORTRAN subroutine DGHUTR is
SUBROUTINE DGHUTR( JOB, COMPQ1, COMPQ2, N, A, LDA, DE, LDDE, C1,
 $                   LDC1, VW, LDVW, Q1, LDQ1, Q2, LDQ2, B, LDB, F,
 $                   LDF, C2, LDC2, ALPHAR, ALPHAI, BETA, IWORK,
 $                   LIWORK, DWORK, LDWORK, INFO )

Update: Here's the output of the modified DGHUTR subroutine (basically added printing):
 JOB T
 COMPQ1 I
 COMPQ2 I
 LDA          17179869188
 LDDE          34359738372
 LDC1          17179869188
 LDVW         704374636548
 LDQ1          34359738376
 LDB          17179869188
 LDF          17179869188
 LDC2          17179869188
 LIWORK                   20
 LDWORK          85899346084
 N          17179869192
 LDDE          34359738372
 INFO  6227620798727716864

As one can see the characters are received correctly, as is LIWORK, provided I compile with -O2 set. I'm guessing there's something g++ does which breaks the parameters. Trying to revert from gcc-5 to gcc-4.8 did not solve the issue. With no optimization the LDA value seems to be changing on each run of the program, whereas it remains fixed when compiled with -O2.

A: I think I have found the source of the problem which has been plaguing me.
The dependence of the values received by the fortran routine on the optimization flags was kind of
a hint that there might be something wrong with how the stored variables are interpreted by C++ and
FORTRAN.
After looking for the specific value of 17179869188 and finding this
SO post
I tried playing with the compiler flags for the libraries.
When I fetched SLICOT I took the source and a library precompiled with gfortran for linux (slicot_linux_gfortran.tar.gz).
This latter one came with a make.inc with OPTS = -O2 -fpic -fdefault-integer-8
The SHHEVP routines contained the following comment in the make.inc
IMPORTANT: Use the options -fPIC -fdefault-integer-8 for 64bit
architectures.

So I did as advised - and that was the problem!
Removing -fdefault-integer-8 and recompiling both SLICOT and DGHUTR solved my problem. Now the code given above
compiles and the FORTRAN subroutine receives the correct values. The results of the computation are
consistent with the reference results provided with the DGHUTR source.
Incidentally, the majority of the SLICOT tests are now working. With the old flags the compilation of examples
stopped at TAB01ND, which would always hang. Now I get down to TMB03LD, whose compilation fails with
IF( LSAME( COMPQ, 'C' ) .AND. NEIG.GT.0 ) THEN
                             1
Error: Operands of logical operator '.and.' at (1) are INTEGER(4)/LOGICAL(4)

But that is, for now, of no concern to me.


text:
Q: Displaying node.js file inside a node.js server? Trying to display this node.js file through my node.js server. However, all it does is display the code in proper format as if it were in notepad rather than actually displaying what it does in the console when executed. So in other words, I want my node.js file to execute and display on the browser, not just have the code display on the webpage.
var fs = require('fs');
var colour = require('colour');
var array = fs.readFileSync('songs/sister_golden_hair.txt').toString().split("\n");

var chordsArray =[];
var lyricsArray =[];
var count1 = 0;

for(var line in array) {
    count1++;
    if (count1 >= 3) {
        var count2 = 0;
        lyricsArray[count1-3] = [];
        chordsArray[count1-3] = [];
        while (array[line].indexOf("[") != -1) {
            lyricsArray[count1-3][count2] = array[line].substring(0, array[line].indexOf("["));
            array[line] = array[line].substring(array[line].indexOf("[")+1, array[line].length);
            chordsArray[count1-3][count2] = array[line].substring(0, array[line].indexOf("]"));
            array[line] = array[line].substring(array[line].indexOf("]")+1, array[line].length);
            count2++;
        }
        if (array[line].length > 0) {
            lyricsArray[count1-3][count2] = array[line];
            chordsArray[count1-3][count2] = "";
        }
    }
    else {
        console.log(array[line]);
    }
}

for (var i = 0; i < chordsArray.length; i++) {
    for (var j = 0; j < chordsArray[i].length; j++) {
        if (j == 0) {
            for (var k = 0; k < lyricsArray[i][j].length; k++) {
                process.stdout.write(" ");
            }
            process.stdout.write(chordsArray[i][j].green);
        }
        else {
            for (var k = 0; k < lyricsArray[i][j].length - chordsArray[i][j-1].length; k++) {
                process.stdout.write(" ");
            }
            process.stdout.write(chordsArray[i][j].green);
        }
    }
    console.log();
    for (var j = 0; j < lyricsArray[i].length; j++) {
            process.stdout.write(lyricsArray[i][j].yellow);
    }
}

and here is the node.js server I am running where I try to say that if the client goes to "http://127.0.0.1/sister_golden_hair.html" then it should display the above node.js Here is the node.js server:
var http = require('http');
var fs = require('fs');

var counter = 1000;

function serveStaticFile(res, path, contentType, responseCode){
   if(!responseCode) responseCode = 200;
   fs.readFile(__dirname + path, function(err, data){
     if(err){
       res.writeHead(200, {'Content-Type': 'text/plain'});
       res.end('[' + counter++ + ']: ' + '500 INTERNAL FILE ERROR' + '\n');
     }
     else {
       res.writeHead(responseCode , {'Content-Type': contentType});
       res.end(data);

     }
   });
}

http.createServer(function (request,response){
     var path = request.url.replace(/\/?(?:\?.*)$/,'').toLowerCase();

   //write HTTP header

   var page = '';
   switch(path){
     case '/sister_golden_hair.html':
       serveStaticFile(response,
                       '/Problem4.js',
                       'application/javascript');
       break;
}
}).listen(3000, "127.0.0.1");
console.log('Server Running at http://127.0.0.1:3000  CNTL-C to quit');

A: If you want to use node.js code in the browser, you're going to need to use something like browserify.

A: Have you tried using eval() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval ? Check out the warning though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual Studio Code Intellisense stopped working I can not recall when it exactly happened but all of a sudden the Intellisense stopped working completly. I was programming Javascript and ReactNative
There is no autocomplete anymore and when I hover over a method there is only Loading... displayed.
I tried to reload the window, also with all extensions disabled but nothing changed. I have no idea how to get it back...
[EDIT]
Intellisense works on other folders/projects but not on this specific one.


text:
Q: MySQL help regarding AND AND OR Some quick help.. What I want to do is this:
If 'X' greater or equal to 100 and user logged on, do "the code", but only if user_id is 1 or 2.
Is the code below representing that? I am unsure because of the OR.. Does the OR apply to the last AND or to the complete query? How could I simplify/correct the code?
if($data['x'] >= 100 AND $_SESSION['user_logged'] = 1 AND $data['user_id']
== 1 OR $data['user_id'] == 2)

A: This part of your code AND $_SESSION['user_logged'] = 1
You're assigning using one equal sign, instead of comparing using two (or three).
So do:
AND $_SESSION['user_logged'] == 1

and make sure you've started the session. Meaning that session_start(); is inside (all) your page(s) using sessions.
Sidenote: && has precedence over AND, as does || over OR.
References:

*

*http://php.net/manual/en/language.operators.assignment.php

*http://php.net/manual/en/language.operators.comparison.php

*http://php.net/manual/en/session.examples.basic.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

A: You had an error in your if statement where you were assigning the value of $_SESSION['user_logged'] to 1. I fixed that in your code and I also wrapped your AND statements in parenthesis as you are requiring either the first three conditions be met OR the last condition be met and to achieve that you want to use parenthesis
if(
    ($data['x'] >= 100
    AND $_SESSION['user_logged'] == 1
    AND $data['user_id'] == 1)
    OR $data['user_id'] == 2
)

A: if(
($data['x'] >= 100
  AND $_SESSION['user_logged'] ==1 )
  AND ($data['user_id']== 1 || $data['user_id'] == 2))
{
// do something
}


text:
Q: Is it possible to copy an entire hdf5 file and expanding external links with h5copy? I have an HDF5 file with external links and would like to copy the file to one single file, so that there are no more external links.
Is there a way to do this with h5copy?
I tried with
h5copy --source "/" --destination "/" --flag ext \
       --input celldemo.ims --output output/celldemo_copied.ims

But I get the error:
HDF5-DIAG: Error detected in HDF5 (1.8.17) thread 140735996208000:
  #000: H5Ocopy.c line 248 in H5Ocopy(): destination object already exists
    major: Symbol table
    minor: Object already exists
Error in copy...Exiting

File details:
File: celldemo.ims
Groups:
  DataSet
  DataSetInfo
  Thumbnail

Properties of groups (as displayed in the HDFView tool):
DataSet
  Link To Target: subfolder/dataset.ims://DataSet
  Type: HDF5 Group
(same for DataSetInfo and Thumbnail)

Why do I get this error? Is the "/" an invalid source and destination object name?


text:
Q: Django Connection Pooling to Postgresql After two days of searching, I thought someone here might be able to help me.
I am using Python 3.6 and Django 2.0.4 and pulling client data from a Postgresql database.
We process the data to create trends for each client.
We then check to see if a trend currently exists and either add a new one or update the existing entry.
When this app was single threaded it worked as expected, but was slow.
Now that I've tried to add simple multithreading, I'm quickly maxing out my database connections.
From what I've read, Django should be using the existing connection instead of opening new connections, but that's not what I'm seeing.
Below is a simplified version of what I'm doing.
What am I doing wrong and what can I do better to stop opening new db connections?
I've looked at pgPool and gpBouncer, but shouldn't Django handle this itself?
def trend_starter(date_to_trend, grouping):
    customer_list = Clearance.objects.distinct('customer').values_list('customer', flat=True)

    thread_list = []
    for cust_name in customer_list:
        trend_object = TrendSetter(customer=cust_name, mode='RT')
        trend_thread = threading.Thread(name=cust_name, target=trend_object.trend_setter)
        thread_list.append(trend_thread)

    for thread in thread_list:
        thread.start()
        sleep(1)

    for thread in thread_list:
        thread.join()

class TrendSetter(object):
    def __init__(self, customer, mode):
        self.customer = customer
        self.mode = mode

    def trend_setter(self):
        customer_data = Clearance.objects.values_list('this', 'that').filter(customer=self.customer, mode=self.mode).order_by('-date')[:6]
        error_data = Clearance.objects.values_list('those').filter(customer=self.customer, mode=self.mode).order_by('-date')[:6]

        #processing routine
        #var1 = some_array
        #var2 = some_array

        newtrend=False
        try:
            check_trend = Clearance.objects.get(customer=self.customer, mode=self.mode)
        except:
            newtrend = True

        if newtrend == False:
            check_trend.var1 = var1
            check_trend.var2 = var2
            check_trend.save()
        else:
            new_entry = Clearance(var1 = var1,
                                  var2 = var2)
            new_entry.save()


text:
Q: Keep a screen active for x seconds I am working with a splash screen but am doing a network call on the splash screen so the data is ready on the home screen by the time the user gets there.
Once the network call is complete it goes to the next screen, I would like the splash screen to be open though for at least x seconds even if the network call took a couple ms because when the network call is ms then the splash screen cannot even be seen.
I know how to do the delay the splash screen for x seconds but would like the network call to be included in those x seconds as opposed to network call time + x amount seconds.
Thank you

A: Use Handler in side onPostExecute() Method. When your Network call in complete, call handler, it'll wait for x seconds and then after moves to another activity.
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            startActivity(new Intent(this, NextActivity.class));
        }
    }, x);// here x is time in millisecond 1 second = 1000 millseconds

} });

This will surely help you.


text:
Q: Cliente-Servidor entre APP que trackeia localização em tempo real Olá, possuímos um app que envia a cada 15 segundos a localização dos usuários para o servidor. Atualmente é um POST simples da (lat/lng) na API, haveria uma outra forma melhor de se fazer isso?
Alguma arquitetura específica?

A: Não creio que haja uma arquitetura específica para isso, vou só fazer algumas recomendações.
É interessante guardar as posições dentro de uma tabela no SQLite dentro do próprio app para os momentos em que não há internet disponível e descarregá-las no servidor quando houver. É a chamada bufferização. Sugiro o seguinte procedimento:
A cada 15 segundos:

*

*Captura uma posição;

*Guarda na tabela;

*Se houver Internet, faz um select trazendo as (digamos) cinquenta últimas posições e tenta enviá-las ao servidor.

Atenção para a data-hora da captura, ela é diferente da data-hora de envio e da data-hora da chegada no servidor. Talvez seja interessante para vocês tratar esses valores como coisas distintas.
De resto, a abordagem parece ok.
Considere guardar o máximo de informações que puder sobre cada posição (data-hora, lat, lng, altitude, velocidade, direção, IMEI ou outro identificador do aparelho, etc), pode ser que sejam úteis um dia.
Se o número de usuários crescer muito, pode ser preciso tomar cuidado com a frequência de envio para não sobrecarregar o servidor (reduzir para um intervalo entre um e cinco minutos, por exemplo).


text:
Q: Javascript adding values to radio buttons to input price Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
    var firstPrice = $25
    var secondPrice = $56
    var thirdPrice = $80
    var fourthPrice = $90

then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
    var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)

My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:

          <input type="radio" name="model" value="radio" id="item_0" />
          item 1

          <input type="radio" name="model" value="radio" id="item_1" />
          item2

          <input type="radio" name="model" value="radio" id="item_2" />
          item3

          <input type="radio" name="model" value="radio" id="item_3" />
          Item4

          <input type="radio" name="model" value="radio" id="item_4" />
          item5

          </form>

then my script looks something like:
    function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;

var totalPrice = (selectionFirst + selectionSecond + selectionThird +         selectionFourth);
       }

A: Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/

A: Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.

A: Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.

<form>
    <fieldset><legend>Model 1</legend>
    <input type="radio" name="model1" value="25">$25

    <input type="radio" name="model1" value="35">$35

    <input type="radio" name="model1" value="45">$45

    <input type="radio" name="model1" value="55">$55

    </fieldset>
    <fieldset><legend>Model 2</legend>
    <input type="radio" name="model2" value="1">$1

    <input type="radio" name="model2" value="2">$2

    <input type="radio" name="model2" value="3">$3

    <input type="radio" name="model2" value="4">$4

    <fieldset><legend>Include shipping?</legend>
      $5<input type="checkbox" value="5" name="shipping">

    </fieldset>

    <input name="totalPrice" readonly>

    <input type="reset" value="Clear form">
</form>

You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.


text:
Q: Pusher Java Client : Failed to subscribe to a presence channel as well as a private channel at a time I am using pusher java client (pusher-java-client by mdpye) to develop an android application which is using pusher for push notification. I can successfully subscribe to a presence channel after connecting to the Pusher. Once subscribed to the presence channel, When I try to subscribe to another private channel as well, it is showing an error: Invalid signature: Expected HMAC SHA256 hex digest of xxx:YYYY, but got xxxxxxxxxxxxx (possibly an authentication error).
The point is if there were a problem in authentication, I would not have been able to even connect to the first presence channel. so, what can be the problem?
code snippet:
authorizer = new HttpAuthorizer(endpointUrl);
PusherOptions options = new PusherOptions().setEncrypted(true).setAuthorizer(authorizer);
pusher = new Pusher(pusher_key, options);
pusher.getConnection().bind(ConnectionState.ALL, this);
String socketId = pusher.getConnection().getSocketId();
String selfJson = authorizer.authorize(PRESENCE_CHANNEL_NAME, socketId);
presenceChannel = pusher.subscribePresence(PRESENCE_CHANNEL_NAME, presenceEventListener);
notificationChannel = pusher.subscribePrivate(notificationChannelName, notificationEventListener);

A: Channels are authorised independently of each other - a call is made to the Authorizer for each private or presence subscription made, it's possible that your endpoint returns a correct result for one and incorrect for the other.
Note that there is a difference in the response required from the authorisation endpoint between private and presence channels, the latter includes data about the user which is not valid in the former. See http://pusher.com/docs/authenticating_users#implementing_endpoints


text:
Q: find the coordinates of $n$-D point from $(n-1)$ angles and distance I'm writing a program that can render $n$-D shapes, and, through the way I'm doing it, I have come to need to calculate the Cartesian coordinates of a point from $(n-1)$ angles and the distance of the point to the origin.
How can I calculate the coordinates $x_0, x_1, x_2, x_3, \ldots, x_n$ from the distance $r$ and the angles $\alpha_1, \alpha_2, \alpha_3, \ldots, \alpha_n$ wherein $\alpha_m$ is the angle measured from the axis $x_0$ towards the axis $x_m$?
Note: I have read Calculate 3D Vector out of two angles and vector length, but I'm having trouble generalizing it to $n$ dimensions. Above just an answer, an explanation would really be welcome.

A: Assuming $\alpha_m$ is the polar angle measured in the plane spanned by $0$-th and $m$-th basis vectors, it's a fairly trivial exercise. We have $x_0 = r_m\cos\alpha_m$ and $x_m = r_m\sin\alpha_m$ for some $r_m$ (the length of a projection of our vector $(x_0,\ldots,x_n)$ to that plane), then also we have
$$r^2 = x_0^2 + \ldots + x_n^2 = x_0^2\left(1 + (x_1/x_0)^2 + \ldots + (x_m/x_0)^2\right) = x_0^2\left(1 + \tan^2\alpha_1 + \ldots + \tan^2\alpha_n\right),$$
assuming $x_0\ne0$. Then we have found
$$x_0 = \frac r{\sqrt{1 + \tan^2\alpha_1 + \ldots + \tan^2\alpha_n}}.$$
And then we also have found all the $x_m = x_0\tan\alpha_m$.
The case $x_0 = 0$ holds iff $\tan\alpha_m$ are undefined, and then there is an ambiguity unless $r$ is also zero (then all the coordinates are obviously zero).


text:
Q: Promise does not seem to be calling resolve I have the following code:
const multer = require('multer');

const multerUploadWorker = async(req, res, storage) => {
    console.log('worker called');

    const upload = multer({ storage: storage }).single('file');

    upload(req, res, function (error) {
        if (error) {
            return Promise.reject();
        } else {
            console.log('resolve called');
            return Promise.resolve();
        }
    });
};

module.exports = multerUploadWorker;

and:
const { success, fail } = require('../utils/response-util');
const multer = require('multer');
const multerUploadWorker = require('../workers/multer-upload-worker');
const path = require('path');

const upload = async(req, res) => {

    const storage = multer.diskStorage({
        destination: function (_, _, cb) {
            cb(null, 'uploads/')
        },

        filename: function (_, file, cb) {
            const ext = path.extname(file.originalname);

            switch (ext) {
                case '.jpg':
                case '.JPG':
                case '.jpeg':
                case 'JPEG':
                case '.png':
                case '.PNG':
                case '.gif':
                case '.GIF':
                    cb(null, Date.now() + ext);
                    break;
                default:
                    cb('File type error', false);
                    break;
            }
        }
    });

    try {
        if (await multerUploadWorker(req, res, storage)) {
            return success(res, { message: req.file });
        }
    } catch(error) {
        return fail(
            res, 'Something went wrong, please check the image type is \
JPEG, GIF or PNG', '500'
        );
    }
};

module.exports = {
    upload
};

It seems that although the console logs resolve called inside multerUploadWorker it doesn't trigger the if (await multerUploadWorker(req, res, storage)) condition. No error is thrown, just nothing happens. What am I doing wrong here?

A: Your use of Promises is incorrect. multerUploadWorker should return promise but in your case it returns nothing.
const multer = require('multer');

const multerUploadWorker = async(req, res, storage) => {
    console.log('worker called');

    const upload = multer({ storage: storage }).single('file');

    return new Promise((resolve, reject) => {
        upload(req, res, function (error) {
        if (error) {
            reject(error)
        } else {
            console.log('resolve called');
            resolve();
        }
      });
    });
};

module.exports = multerUploadWorker;

Also the way you handle result, there is no need to check for result because you are not returning boolean, just wait for upload to finish and in case of error handle in catch statement:
    try {
       await multerUploadWorker(req, res, storage))
       return success(res, { message: req.file });
    }


text:
Q: register module mainactivity.java react native I'm trying to follow these instructions: https://www.npmjs.com/package/react-native-text-input-layout. I'm confused at the register module in mainactivity.java part. My mainactivity.java doesn't look at all like the one from the instructions.
This is my mainactivity.java:
package com.starterkit;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import java.util.Arrays;
import java.util.List;

public class MainActivity extends ReactActivity {

/**
 * Returns the name of the main component registered from JavaScript.
 * This is used to schedule rendering of the component.
 */
@Override
protected String getMainComponentName() {
    return "StarterKit";
}

/**
 * Returns whether dev mode should be enabled.
 * This enables e.g. the dev menu.
 */
@Override
protected boolean getUseDeveloperSupport() {
    return BuildConfig.DEBUG;
}

   /**
   * A list of packages used by the app. If the app uses additional views
   * or modules besides the default ones, add more packages here.
   */
@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
    new MainReactPackage()
  );
}
}

And this is the mainactivity.java from the instructions:
 import com.memox.rntextinputlayout.RNTextInputLayoutPackage;  // <---       import

 public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
 ......

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);

mReactInstanceManager = ReactInstanceManager.builder()
  .setApplication(getApplication())
  .setBundleAssetName("index.android.bundle")
  .setJSMainModuleName("index.android")
  .addPackage(new MainReactPackage())
  .addPackage(new RNTextInputLayoutPackage()) // <------ add this line to your MainActivity class
  .setUseDeveloperSupport(BuildConfig.DEBUG)
  .setInitialLifecycleState(LifecycleState.RESUMED)
  .build();

mReactRootView.startReactApplication(mReactInstanceManager, "AndroidRNSample", null);

setContentView(mReactRootView);
}
......
}

A: You can add like this:
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
    new MainReactPackage()
   ,new RNTextInputLayoutPackage()
  );
}


text:
Q: Missing url parameters values after running powershell script as scheduled task I have a Powershell script that gets the name of a computer as string and the processes running on it as json array, creates parameters from the variables, then makes a web request to a url and has 2 parameters sent through the POST method as shown below:
$comp_id = (Get-WmiObject win32_operatingsystem) | Select-Object  csname | Format-Table -HideTableHeaders | out-string
$processes = get-process | Where-Object {$_.StartTime -ne $null -and $_.MainWindowTitle.Length -gt 10}  | Select-Object id,description,FileVersion,mainWindowTitle,startTime| ConvertTo-Json

# create parameters from variables
$param1= @{id=$comp_id}
$param2 = @{data=$processes} #the variable $process is a JSON array string
$bothParams = $param1+$param2

Invoke-WebRequest -Uri http://my.webserver.comp:8080/galileo/peeker -Method POST-Body $bothParams

Everything is OK when I run the script directly i.e both parameter values are accesible from a servlet.
I want to run this script as a scheduled task so I've created a batch script file that calls the powershell script. The problem is that when the script runs as a scheduled task, the second parameter,supposed to be a JSON array string, is empty. What could be the problem?
My batch script has the following 2 lines:
 @echo OFF
# used batch script tag(%~dpn0) to get path (p) and file name similar to this file
Powershell.exe -Command "& '%~dpn0.ps1'"

A: You can run PowerShell scripts directly from Task Scheduler so you don't need the batch script. As for why JSON string ends up empty, the most likely reason is that Where-Object doesn't capture anything.
Adding some basic debug logging to your script could help you get some idea about what's going on. Example:
$logFile = "script.log"

$env:USERNAME | Out-File -FilePath $logFile -Append
Get-Process | Select-Object Id, Description, FileVersion, MainWindowTitle, StartTime `
    | Out-File -FilePath $logFile -Append


text:
Q: Regex to remove whitespaces I'm trying to write a regular expression to remove white spaces from just the beginning of the word, not after, and only a single space after the word.
This is the regex that I've tried:
var re = new RegExp(/^([a-zA-Z0-9]+\s?)*$/);
Output -
re.test("")
true - required false
re.test(" ")
false
re.test(" word")
false - required word - true
re.test(" word ")
false - required word - true
re.test("word ")
true
re.test("word  ")
false - - required word(with single space ) - true

Exp:
See, I have to send a request to backend where if
1) key term is ""(blank) no need to send the request.
2) If key is " string" need to send the request.
3) If user enter something like this "string    string" need to send the request.
4) if user enter "string " need to send the request.
5) if user enter string with a space need to send the request but at the moment he enter another space no need to send the request.

This thing i am trying to achieve using regular expression.

A: I think following should take care of all the space replacements for you:
var str      = "   this is     my  string    ";
var replaced = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// repl = 'this is my string'

A: This would fit your case:
var myString = "   this is my string    ";
myString = myString.replace(/^\s+/ig, "").replace(/\s+$/ig,"")+" ";
alert(myString);

Tinker: http://tinker.io/e488a/1

A: // this should do what you want
var re = new RegExp(/^([a-zA-Z0-9]+\s?)+$/);

A: I think the word boundary perfectly suits for this. Try this regexp:
var myString = "   test    ";
myString = myString.replace(/\s+\b|\b\s/ig, "");
alert('"' + myString + '"');

The regexp removes all spaces before all words and the first space after all words


text:
Q: jQuery character count if statement I have the following character count plugin:if there is more than 9 characters the alert class is added to change the color to red.
What I want is when I say 'if number of character is more than 9', to replace the number 9 with a var.
if(number_of_characters >= 9) {

So this value can always be adjusted from the plugin options, instead of changing this value inside the jQuery plugin.
How should I do this?
My working fiddle

A: Here is a working Fiddle.
What I did was add a new option - number_of_characters (you can name it w/e you want):
$(textarea).CountCharacters({
    Start_Count: 0,
    Amount_Result: "counter",
    Alert_Class: "alert-counter",
    Amount_Limit: 19,
    number_of_characters: 5
});

Then, instead of hardcoding the value, I referred to the new option:
if(number_of_characters >= options.number_of_characters) {
    $("#"+options.Amount_Result).addClass(options.Alert_Class);
}

I also set a new default option:
var defaults = {
  Start_Count: 0,
  Amount_Result: false,
  Alert_Class: false,
  number_of_characters: 9
}

A: You can add a new property to the defaults object, and read from that. This can then be overridden as needed for each instance. Try this:
// declaration:
var defaults = {
    Start_Count: 0,
    Amount_Result: false,
    Alert_Class: false,
    maximumCharacters: 9
}

// usage:
 if (number_of_characters >= options.maximumCharacters) {
    $("#" + options.Amount_Result).addClass(options.Alert_Class);
} else {
    $("#" + options.Amount_Result).removeClass(options.Alert_Class);
}

Updated fiddle

A: use the option Amount_Limit
$(textarea).CountCharacters({
    Start_Count: 0,
    Amount_Result: "counter",
    Alert_Class: "alert-counter",
    Amount_Limit: 9
});

if(number_of_characters >= options.Amount_Limit)


text:
Q: how to set up Sustainability Cloud I am interested to try out Sustainability Cloud however I don't find anywhere I can set it up as a demo org, is there a way to do this?

A: You need to Configure and Install Sustainability Cloud in your org.  Before installing the app verify that your org has the Sustainability Cloud permission set license. If it doesn't, contact your account executive. Assign this permission set license to atleast one user.
Install Sustainability Cloud from appexchange listed.
Thanks


text:
Q: Cucumber + XCTest integration? We have an automation framework that uses Cucumber + Appium to test an iOS application.
Appium is fine, but one of its limitations is that we need to run every test from the beginning, which slows down development. XCTest seems to offer more breakpoint type flexibility, i.e. we can just re-run a small part of the test, as we already do with browser-based applications in Selenium.
XCTest seems easy to use and powerful, and we would like to start using it as soon as possible. Has anyone managed to integrate Cucumber with XCTest? We use Ruby for our framework and would like to keep using that also if possible.
Thanks in advance!

A: I have recently integrated Quick(a Swift BDD framework) with the new XCTest and it all seems to be coming along fine.
As far as I know Cucumber don't have a Swift implementation yet so it is not possible to integrate Cucumber with XCTest.


text:
Q: Equation of Sun Orbit Spiral on Azimuthal Equidistant Earth Map From the perspective of the AE map:
The sun circles the earth. Every complete circle it makes is approximately one day. However, the sun is not always on the circle of the equator. It spirals inward from the equator to the tropic of cancer, and outward from the equator to the tropic of capricorn.
Let's assume the year starts at the spring equinox (about March 20th). At that point the sun is circling the equator. Around 3 months later (summer solstice) the sun has spiraled inward and is now at the tropic of cancer. Around 3 months later again (fall equinox) the sun has spiraled outward and is back at the equator. Around 3 months later (winter solstice) the sun has spiraled outward further and is at the tropic of capricorn. Around 3 months later (back at spring equinox again) the sun has spiraled inward and returned to the equator again. The year is complete.
My question is, how does one find the equation of the spiral of the sun for the AE map? If this equation is found, you could calculate the exact position of the sun at any given point of time on the AE map (which is ultimately the goal).
AE MAP: Visual aid for help understanding explanation
Hand-done speculation of what spiral would look like


text:
Q: Is it possible to merge several pdfs using iText7 I have several datasheets for products. Each is a separate file. What I want to do is to use iText to generate a summary / recommended set of actions, based on answers to a webform, and then append to that all the relevant datasheets. This way, I only need to open one new tab in the browser to print all information, rather than opening one for the summary, and one for each datasheet that is needed.
So, is it possible to do this using iText?

A: I found a solution that works quite well.
public byte[] Combine(IEnumerable<byte[]> pdfs)
{
    using (var writerMemoryStream = new MemoryStream())
    {
        using (var writer = new PdfWriter(writerMemoryStream))
        {
            using (var mergedDocument = new PdfDocument(writer))
            {
                var merger = new PdfMerger(mergedDocument);

                foreach (var pdfBytes in pdfs)
                {
                    using (var copyFromMemoryStream = new MemoryStream(pdfBytes))
                    {
                        using (var reader = new PdfReader(copyFromMemoryStream))
                        {
                            using (var copyFromDocument = new PdfDocument(reader))
                            {
                                merger.Merge(copyFromDocument, 1, copyFromDocument.GetNumberOfPages());
                            }
                        }
                    }
                }
            }
        }

        return writerMemoryStream.ToArray();
    }
}

Use
DirectoryInfo d = new DirectoryInfo(INPUT_FOLDER);

var pdfList = new List<byte[]> { };

foreach (var file in d.GetFiles("*.pdf"))
{
    pdfList.Add(File.ReadAllBytes(file.FullName));
}

File.WriteAllBytes(OUTPUT_FOLDER + "\\merged.pdf", Combine(pdfList));

Autor:
https://www.nikouusitalo.com/blog/combining-pdf-documents-using-itext7-and-c/

A: Yes, you can merge PDFs using iText 7. E.g. look at the iText 7 Jump-Start tutorial sample C06E04_88th_Oscar_Combine, the pivotal code is:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
PdfMerger merger = new PdfMerger(pdf);

//Add pages from the first document
PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());

//Add pages from the second pdf document
PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());

firstSourcePdf.close();
secondSourcePdf.close();
pdf.close();

(C06E04_88th_Oscar_Combine method createPdf)

Depending on your use case, you might want to use the PdfDenseMerger with its helper class PageVerticalAnalyzer instead of the PdfMerger here. It attempts to put content from multiple source pages onto a single target page and corresponds to the iText 5 PdfVeryDenseMergeTool from this answer. Due to the nature of PDF files this only works for PDFs without headers, footers, and similar artifacts.

A: If you want to add two array of bytes and return one array of bytes as PDF/A
public static byte[] mergePDF(byte [] first, byte [] second) throws IOException {
    // Initialize PDF writer
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    PdfWriter writer = new PdfWriter(arrayOutputStream);

    // Initialize PDF document
    PdfADocument pdf = new PdfADocument(writer, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "",
            "https://www.color.org", "sRGB IEC61966-2.1", new FileInputStream("sRGB_CS_profile.icm")));

    PdfMerger merger = new PdfMerger(pdf);

    //Add pages from the first document
    PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(new ByteArrayInputStream(first)));
    merger.merge(firstSourcePdf, 1, firstSourcePdf.getNumberOfPages());

    //Add pages from the second pdf document
    PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(new ByteArrayInputStream(second)));
    merger.merge(secondSourcePdf, 1, secondSourcePdf.getNumberOfPages());

    firstSourcePdf.close();
    secondSourcePdf.close();
    writer.close();
    pdf.close();

    return arrayOutputStream.toByteArray();
}

A: The question doesn't specify the language, so I'm adding an answer using C#; this works for me. I'm creating three separate but related PDFs then combining them into one.
After creating the three separate PDF docs and adding data to them, I combine them this way:
PdfDocument pdfCombined = new PdfDocument(new PdfWriter(destCombined));
PdfMerger merger = new PdfMerger(pdfCombined);

PdfDocument pdfReaderExecSumm = new PdfDocument(new PdfReader(destExecSumm));
merger.Merge(pdfReaderExecSumm, 1, pdfReaderExecSumm.GetNumberOfPages());

PdfDocument pdfReaderPhrases = new PdfDocument(new PdfReader(destPhrases));
merger.Merge(pdfReaderPhrases, 1, pdfReaderPhrases.GetNumberOfPages());

PdfDocument pdfReaderUncommonWords = new PdfDocument(new PdfReader(destUncommonWords));
merger.Merge(pdfReaderUncommonWords, 1, pdfReaderUncommonWords.GetNumberOfPages());

pdfCombined.Close();

So the combined PDF is a PDFWriter type of PdfDocument, and the merged pieces parts are PdfReader types of PdfDocuments, and the PdfMerger is the glue that binds it all together.

A: Here is the minimum C# code needed to merge file1.pdf into file2.pdf creating new merged.pdf:
var path = @"C:\Temp\";

var src0 = System.IO.Path.Combine(path, "merged.pdf");
var wtr0 = new PdfWriter(src0);
var pdf0 = new PdfDocument(wtr0);

var src1 = System.IO.Path.Combine(path,  "file1.pdf");
var fi1 = new FileInfo(src1);
var rdr1= new PdfReader(fi1);
var pdf1 = new PdfDocument(rdr1);

var src2 = System.IO.Path.Combine(path,  "file2.pdf");
var fi2 = new FileInfo(src2);
var rdr2 = new PdfReader(fi2);
var pdf2 = new PdfDocument(rdr2);

var merger = new PdfMerger(pdf0);

merger.Merge(pdf1, 1, pdf1.GetNumberOfPages());
merger.Merge(pdf2, 1, pdf2.GetNumberOfPages());

merger.Close();
pdf0.Close();

A: Here is a VB.NET solution using open source iText7 that can merge multiple PDF files to an output file.
Imports iText.Kernel.Pdf
Imports iText.Kernel.Utils

    Public Function Merge_PDF_Files(ByVal input_files As List(Of String), ByVal output_file As String) As Boolean
        Dim Input_Document As PdfDocument = Nothing
        Dim Output_Document As PdfDocument = Nothing
        Dim Merger As PdfMerger

        Try
            Output_Document = New iText.Kernel.Pdf.PdfDocument(New iText.Kernel.Pdf.PdfWriter(output_file))
            'Create the output file (Document) from a Merger stream'
            Merger = New PdfMerger(Output_Document)

            'Merge each input PDF file to the output document'
            For Each file As String In input_files
                Input_Document = New PdfDocument(New PdfReader(file))
                Merger.Merge(Input_Document, 1, Input_Document.GetNumberOfPages())
                Input_Document.Close()
            Next

            Output_Document.Close()
            Return True
        Catch ex As Exception
            'catch Exception if needed'
            If Input_Document IsNot Nothing Then Input_Document.Close()
            If Output_Document IsNot Nothing Then Output_Document.Close()
            File.Delete(output_file)

            Return False
        End Try
    End Function

USAGE EXAMPLE:
Dim success as boolean = false
Dim input_files_list As New List(Of String)

input_files_list.Add("c:\input_PDF1.pdf")
input_files_list.Add("c:\input_PDF2.pdf")
input_files_list.Add("c:\input_PDF3.pdf")

success = Merge_PDF_Files(input_files_list, "c:\output_PDF.pdf")
'Optional: handling errors'
if success then
    'Files merged'
else
    'Error merging files'
end if

A: I use this code, and It works...
using System;
using System.IO;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;

namespace iText7_Merge
{
    internal class MergedPdf
    {
        public const String SRC1 = @"C:\tmp\trash\Pdf_1.pdf";
        public const String SRC2 = @"C:\tmp\trash\Pdf_2.pdf";
        public const String DEST = @"C:\tmp\trash\Pdf_merged.pdf";

        static void Main(string[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            new MergedPdf().createPdf(DEST);
        }

        public void createPdf(String dest)
        {
            //Initialize PDF document with output intent
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
            PdfMerger merger = new PdfMerger(pdf);

            //Add pages from the first document
            PdfDocument firstSourcePdf = new PdfDocument(new PdfReader(SRC1));
            merger.Merge(firstSourcePdf, 1, firstSourcePdf.GetNumberOfPages());

            //Add pages from the second pdf document
            PdfDocument secondSourcePdf = new PdfDocument(new PdfReader(SRC2));
            merger.Merge(secondSourcePdf, 1, secondSourcePdf.GetNumberOfPages());

            firstSourcePdf.Close();
            secondSourcePdf.Close();
            pdf.Close();
        }
    }
}


text:
Q: Remove specific PFObject from PFObject array I m trying to create a function that could remove items such as following:
var array = [23,36,12,45,52,63]
removeItem(12,array)
result : array = [23,36,45,52,63]

I m trying to implement this for PFObject but I m getting error:
public func removeObjectFromArray(user:PFObject,array:[PFObject]) -> [PFObject]{

    for var i = 0;i < array.count ; i++ {
        if array[i].objectId == user.objectId{
            array.removeAtIndex(i)
            return array
        }
    }
}

The error that I m getting:
Immutable type of [PFObject] only ha mutating members named 'removeAtIndex'

Any solution for this?
Thank you

A: Try doing this:
public func removeObjectFromArray(user: PFObject, array: [PFObject]) -> [PFObject] {
    var a = array
    for i in 0..<a.count {
        if a[i].objectId == user.objectId {
            a.removeAtIndex(i)
            return a
        }
    }
    return a
}

The problem is that you try to modify function argument.
You can also make function parameter mutable by adding var keyword, here is related question: Swift make method parameter mutable?

A: I'm not a swift developer, but I never like to remove objects in a loop. Here's how I would do it (pseudo code):
var a = empty array
for i in (0 -> length of array) {
    if array[i].objectId != user.objectId {
        a.addObject(array[i])
    }
}
return a


text:
Q: Primes written as the sum of two squares A well known result due to Fermat states that any prime $p \equiv 1 \pmod 4$ can be written as the sum of two squares,$\,$ $p = a^2 + b^2$ .$\,$ We can define a set $\,A\,$ by collecting together all the $a$'s and $b$'s  which arise in this way (ignoring multiplicity).$\,$ Examples include:$\;$ $5 = 1^2 + 2^2$,$\;$$13 = 2^2 + 3^2$,$\;$$17 = 1^2 + 4^2$,$\;$$29 = 2^2 + 5^2$,$\;$and $\,$$37 = 1^2 + 6^2$. $\;$From these examples we see that $\,A\,$ begins with $\;A = \,${$\,$$1,2,3,4,5,6, ...$$\,$}$\;$.
Questions: $\;$ 1) Does the set $\,A\,$ coincide with the set of all natural numbers?
$\qquad$$\qquad$$\quad$2) If not or if this is not known, is there at least a good lower bound for the density of$\qquad$$\qquad$$\quad$$\;$$\;$ the set$\,A\,$?
Thanks.

A: 1) is almost certainly true, though it does not seem to be a known result.
It is equivalent to show that every vertical line in the Gaussian integers contains a Gaussian prime.  There are many similar results along these lines, such as Tao's result that the Gaussian primes contain arbitrarily shaped constellations.
In fact, it is likely that every vertical line contains infinitely many primes, but this would imply Landau's fourth problem, and so it's certainly difficult.
Since it is frequently just as difficult to show that a sequence contains one prime as it is to show that it contains infinitely many, I would not be optimistic that this conjecture will be resolved anytime soon.

There may be a way to get a nice answer to 2) using known results.  For example, a standard density theorem is that the Gaussian primes are distributed evenly through sectors, which might lead to a lower bound on the density of their $x$-coordinates.

A: 2) By looking at this derivation, there are asymptoticaly $2n^2/\log n$ Gaussian primes in the circle $|z|<n$, and so, in the square $0<\Re z,\Im z<n$ there are at least (asymptoticaly) $n^2/2\log n$ Gaussian primes. Hence, by pigeonhole principle, at least $n/2\log n$ abscissas out of first $n$ contain at least one Gaussian prime.
This is a very crude lower bound, but it's better than nothing.


text:
Q: Precision error in FindMinimum I am trying to solve a system of three non-linear equations for three unknowns (e1, e2, phi). I am using FindMinimum to solve the system (I am minimizing the norm of residuals of the system). The system gives me an answer which kind of makes sense given the context. But also gives me an error message:
FindMinimum: Line search unable to find a sufficient decrease in the function value with MachinePrecision digit precision.
Here is a simplified version of the code that I am running:
a1p0 = (-29.2 e2 -
  1.4427 ProductLog[-277.259 2.^(e1 - 29.2 e2) e2])/e2;

a1p1 = -9.7 +
  400. 2.^(e1 - 29.2 e2 -
    1.4427 ProductLog[-277.259 2.^(e1 - 29.2 e2) e2]);

a2 = (-18.8 e2 - 1.4427 ProductLog[-554.518 2.^(e1 - 18.8 e2) e2])/e2;

t0 = SetPrecision[0, 100];
t1 = 0.5;
b1p0 = 2.92;
b1p1 = 1.95;
b2 = 1.88;
zstar1 = 400;
zstar2 = 800;
delta = 10;

 FindMinimum[{Norm[
    Evaluate[{(1 - t1) (((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
          delta b1p0 - zstar1) - (1 - t0)/(
        1 + 1/(e1 +
          a1p0 e2)) (((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
          delta b1p0 - (((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
             delta b1p0)^(-1/(e1 + a1p0 e2)) zstar1^(
           1 + 1/(e1 + a1p0 e2))) + phi,  (1 - t0) (zstar1 -
          1/(1 + 1/(
            e1 + e2 a1p1)) ((((1 - t0)/(
                 1 - t1))^(e1 + a1p0 e2) zstar1 - delta b1p0 +
               delta b1p1)^(-1/(e1 + e2 a1p1)) zstar1^(
             1 + 1/(e1 + e2 a1p1))) - (((1 - t0)/(
             1 - t1))^(e1 + a1p0 e2) zstar1 - delta b1p0 +
           delta b1p1)/(1 + e1 + e2 a1p1)) + phi, (1 -
          t1) ((((1 - t0)/(1 - t1))^(e1 + a2 e2) zstar2 - delta b2)/(
           1 + e1 + e2  a2) ((1 - t1)/(1 - t0))^(e1 + e2 a2) -
          zstar2) + (1 - t0)/(
        1 + 1/(e1 +
          a2 e2)) ((((1 - t0)/(1 - t1))^(e1 + a2 e2) zstar2 -
            delta b2)^(-1/(e1 + a2 e2)) zstar2^(
          1 + 1/(e1 + a2 e2))) + phi}]]}, {e1, 1}, {e2,
   0}, {phi, 10}, MaxIterations -> 1000]

Mathematica then outputs:
    FindMinimum: Line search unable to find a sufficient decrease in the function value with MachinePrecision digit precision.

along with the solution. What does that really mean?

A: This means that it is necessary to lower WorkingPrecision to 10, and all data to enter with no less accuracy. I'll give an example of the code, but I'm not sure that in this case there is an unambiguous answer.
p = 10;
a1p0 = SetPrecision[(-292/10 e2 - (14427/10^4) N[
        ProductLog[-(277259/1000) 2^(e1 - (292/10) e2) e2], p])/e2, p];

a1p1 = SetPrecision[-97/10 +
    400 2^(e1 - (292/10) e2 -
        1.4427 N[ProductLog[-(277259/1000) 2^(e1 - (292/10) e2) e2],
          p]), p];

a2 = SetPrecision[(-188/10 e2 - (14427/10^4) N[
        ProductLog[-(554518/1000) 2^(e1 - (188/10) e2) e2], p])/e2, p];

t0 = SetPrecision[0, p];
t1 = 1/2;
b1p0 = 292/100;
b1p1 = 195/100;
b2 = 188/100;
zstar1 = 400;
zstar2 = 800;
delta = 10;

FindMinimum[
 Norm[Evaluate[{(1 - t1) (((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
        delta b1p0 -
        zstar1) - (1 - t0)/(1 +
         1/(e1 + a1p0 e2)) (((1 - t0)/(1 - t1))^(e1 +
            a1p0 e2) zstar1 -
        delta b1p0 - (((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
            delta b1p0)^(-1/(e1 + a1p0 e2)) zstar1^(1 +
            1/(e1 + a1p0 e2))) +
     phi, (1 - t0) (zstar1 -
        1/(1 + 1/(e1 +
               e2 a1p1)) ((((1 - t0)/(1 - t1))^(e1 + a1p0 e2) zstar1 -
               delta b1p0 +
              delta b1p1)^(-1/(e1 + e2 a1p1)) zstar1^(1 +
              1/(e1 + e2 a1p1))) - (((1 - t0)/(1 - t1))^(e1 +
               a1p0 e2) zstar1 - delta b1p0 + delta b1p1)/(1 + e1 +
           e2 a1p1)) +
     phi, (1 -
        t1) ((((1 - t0)/(1 - t1))^(e1 + a2 e2) zstar2 - delta b2)/(1 +
             e1 + e2 a2) ((1 - t1)/(1 - t0))^(e1 + e2 a2) -
        zstar2) + (1 - t0)/(1 +
         1/(e1 + a2 e2)) ((((1 - t0)/(1 - t1))^(e1 + a2 e2) zstar2 -
           delta b2)^(-1/(e1 + a2 e2)) zstar2^(1 + 1/(e1 + a2 e2))) +
     phi}]], {e1, 1}, {e2, 0}, {phi, 10}, WorkingPrecision -> p]
{8.185352772, {e1 -> 82555.79812, e2 -> -2302.430797,
  phi -> 5.888522753}}


text:
Q: Angularjs, why this service is executed automatically? The following code is expected to trigger the 'ei' alert only after the user makes the click, but it is not the case. The alert appears at the begining. Why? And how to solve it? I'm not following the logic here (remarking my newcomer status)
Check it at http://jsfiddle.net/yDhv8/4/
html
<div ng-controller='StartAnalysis' ng-click="Process()">
{{status}} CLICK HERE TO START PROCESSING
</div>

js
var app = angular.module('myApp', []);

angular.module('myApp').controller('StartAnalysis',
['$scope', 'Erase_added_panels', function ($scope, Erase_added_panels) {

$scope.status = 'waiting files ...';

$scope.Process = function() {
    alert('mm')
    Erase_added_panels;
    $scope.status = 'starting process ...';
    return false;
}
}]);

angular.module('myApp').factory('Erase_added_panels', function() {
    alert('ei')
    return true;
});

Cheers,

A: You are declaring a factory, so this is a singleton that is executed:
angular.module('myApp').factory('Erase_added_panels', function() {
    alert('ei')
    return true;
});

If you want to trigger the alert later just return an object with a method doing what you need it to do:
angular.module('myApp').factory('Erase_added_panels', function() {
    return {
        foo: function () {
            alert('ei')
            return true;
        }
    };
});

And to call it
angular.module('myApp')
.controller('BarController', ['Erase_added_panels', function (Erase_added_panels) {
    Erase_added_panels.foo();
}]);

NOTE:
Angular specifies that a service is executed as soon as you require it somewhere in your application, here, it means the simple fact of adding it as a dependency makes it executed.
Angular says (as stated here):

All services in Angular are instantiated lazily. This means that a
  service will be created only when it is needed for instantiation of a
  service or an application component that depends on it. In other
  words, Angular won't instantiate services unless they are requested
  directly or indirectly by the application.

A: The function you provide to the factory method gets executed once when your application loads (services are singletons).
so this code:
alert('ei')
    return true;

gets executed during initialisation in order create your service.
So from this function, you should return an object to work with in your controller:
If you want to alert something from within a service, you should return an object:
angular.module('myApp').factory('Erase_added_panels', function() {
    return {
     alertUser : function(){
         alert('hey!');
     };
});

Then from your controller, you can use the object you just returned to call its methods:
angular.module('myApp').controller('StartAnalysis',
['$scope', 'Erase_added_panels', function ($scope, Erase_added_panels) {

    $scope.status = 'waiting files ...';

    $scope.Process = function() {
        Erase_added_panels.alertUser();
    }
}]);

please read the documentation as well: http://docs.angularjs.org/guide/dev_guide.services.creating_services


text:
Q: Radio button not clickable on position I am styling some radio buttons to make it look unique. But i got problem, the problem is when i give it position, it does give me look which i want, but i am unable to click on the radio button labels to act them as radio button. Here is my codepen and code that is making my input radio button non clickable. I am unable to choose either as my radio button is off screen. It seem like i cannot select anyone of them.
input[type="radio"]{
  position:absolute;
  left:-9999;
}

A: Your codepen example has a typo: label for="male" is also used for the female case.
Once that is fixed I can click anywhere on those labels.


text: Q: Scale national economic data down to a watershed Economic Input Output databases such as e.g. the World Input-Output Database by the European Commission contain economic (and often environmental) statistics. The spatial resolution of data provided in these databases is usually given on a country level e.g. "the turnover of the agricultural sector in the Netherlands per year is X milion €". I would like to link national trade data to individual watersheds. However obviosuly, the boundaries of a watershed rarely coincide with the political boundaries of a country. Does anyone have an idea/a suggestion, how I can relate national economic data to individual watersheds within the respective country?


text:
Q: What is moduleclass_sfx about? I saw this $params->get('moduleclass_sfx') in one of the custom modules and found it is also part of the core code as well. Wondering what this is about? Could not find any links to any Joomla documentation on the google search hence not sure what exactly this is about?

A: A module class suffix is a paramater used to add a custom class to a module.
For example, let's say you have a template with a left sidebar and in that sidebar you have two different modules. The default background colour for modules in the sidebar is grey. However, you want the first module background colour to be red. This is when module class suffixes come in handy.
Default modules would be like so:
html:

css:
.module { background: grey; }

If you insert a module class suffix such as "test", it would result in the following:

The css for this would then look like the following:
.module.test { background: red; }

Template providers use module class suffixes to provide more of a variety of styling for modules. Take a look at this template, on the top menu, go to "Features", then "Layouts" to get a good example.
Hope this helps.

A: I haven't been using Joomla! in a while, but as far as I remember moduleclass_sfx in itself is nothing special, it's just one of the parameter of a module you can modify in your admin panel.
Usually it was a CSS classname you could add to a module (for the frontend view) in order to personalize it further.
So that expression , $params->get('moduleclass_sfx') simply takes (usually in a Controller) the "moduleclass_sfx" index (i.e. the name of the admin panel input for that module in which you insert the CSS class) out of all the module parameters ($params).
I guess the high occurence is because it's a standard way to name that input field (it's a useful and common feature after all, which allows a greater deal of customization), that's why you find it both in custom modules and core ones, but I don't think is something vital: I mean, in your custom module you could name it 'css_suffix', call it with $params->get('css_suffix') and achieve the same result.


text:
Q: How can I test input and output of a Java Application? I have a simple Java console application and would like to test its input / output automatically. The input is always only one line, but the output is sometimes more than one line.
How can I do this? (with a Linux shell / Python / Eclipse / Java)

A: You could use pipes in Linux. For example, run your problem like this:
java myProgram < input_file > output_file

This will run myProgram and feed input from input_file. All output will be written to a file called output_file.
Now create another file called expected_file which you should handcreate to specify the exact output you expect on some input (specifically, the input you have in input_file).
Then you can use diff to compare the output_file and the expected_file:
diff output_file expected_file

This will output any differences between the two files. If there are no differences, nothing will be returned. Specifically, if something gets returned, your program does not work correctly (or your test is wrong).
The final step is to link all these commands in some scripting language like Ruby (:)) or Bash (:().
This is the most straight-forward way to do this sort of testing. If you need to write more tests, consider using some test frameworks like junit.

A: In eclipse you can log your console output to a physical file using the Run configuration settings. Run-> Run Configuration-> Select your application->go to common tab-> in 'Standard input and output' section specify physical file path.

A: You can execute any Unix command using watch command. Watch command will be executed until you terminate it either by CTRL+C or kill the process.
$ watch -n 5 ls

By default watch command uses 2 second interval, you can change it using -n option.
Or you could write a function like this in your .bashrc (from here)
function run() {
    number=$1
    shift
    for i in {1..$number}; do
      $@
    done
}

And use it like this
run 10 command


text:
Q: Restore failed for server (Microsoft.SqlServer.SmoExtended) I am using SQL Server 2008. While I am restoring database from backup file I got the error.

Restore failed for Server 'WIN-TUT3YRM1MMN\SQLEXPRESS'. (Microsoft.SqlServer.SmoExtended)
  System.Data.SqlClient.SqlError: RESTORE detected an error on page (44262:41495) in database "KBCLDBNEW" as read from the backup set. (Microsoft.SqlServer.Smo)

I have tried restoring in new database but still gives the error. I am cannot find the what is the problem. Thanks for helping me.

A: Try running RESTORE VERIFYONLY and see if you get more information about the failure.
You could also try running RESTORE with CONTINUE_AFTER_ERROR and then run DBCC CHECKDB:
RESTORE DATABASE database_name
FROM backup_device WITH CONTINUE_AFTER_ERROR

(i.e. running as TSQL rather than through SMO)
DBCC CHECKDB(N'databasename') WITH EXTENDED_LOGICAL_CHECKS;

Specifying WITH CONTINUE_AFTER_ERROR in a RESTORE statement attempts
  to restore the database. However, there are many kinds of corruption
  that prevent recovering a database. We strongly recommend that you
  reserve using the CONTINUE_AFTER_ERROR option until you have exhausted
  all alternatives.

All backup strategies should include regular DBCC CHECKDB runs.
Also NOTE: You do not have a backup unless you periodically successfully test restores.
Responding to SQL Server Restore Errors Caused by Damaged Backups


text:
Q: Trouble connecting to MS SQL from Alpine Linux Docker I have a Docker Image that's built from this docker file.  The docker image is with a Vagrant VM which is Ubuntu 14.04 and I'm running it all in OSX 10.11.6.  The Microsoft SQL Server is in an aws-ec2 instance.  Since my program is in Python, I have tried 2 python libraries for connecting to the database, but each fail in the same way.  Here's an overview of what's happened so far:

*

*apk add freetds-dev because FreeTDS needs to be installed for interacting with Microsoft SQL databases.

*pip install pymssql and pip install pyobdc both fail with the same error message:

{
    bash-4.3# pip install pymssql
Collecting pymssql
  Using cached pymssql-2.1.3.tar.gz
    Complete output from command python setup.py egg_info:
    setup.py: platform.system() => 'Linux'
        Download error on     https://pypi.python.org/simple/setuptools_git/:         [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) -- Some packages may not be found!
    Download error on https://pypi.python.org/simple/setuptools-git/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) -- Some packages may not be found!
    Couldn't find index page for 'setuptools_git' (maybe misspelled?)
    Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) -- Some packages may not be found!
    No local packages or download links found for setuptools-git
    setup.py: platform.architecture() => ('64bit', '')
    setup.py: platform.linux_distribution() => ('', '', '')
    setup.py: platform.libc_ver() => ('', '')
    setup.py: Not using bundled FreeTDS
    setup.py: include_dirs = []
    setup.py: library_dirs = ['/usr/local/lib']
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-macbkK/pymssql/setup.py", line 477, in <module>
        ext_modules = ext_modules(),
      File "/usr/lib/python2.7/distutils/core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "/usr/lib/python2.7/site-packages/setuptools/dist.py", line 268, in __init__
        self.fetch_build_eggs(attrs['setup_requires'])
      File "/usr/lib/python2.7/site-packages/setuptools/dist.py", line 313, in fetch_build_eggs
        replace_conflicting=True,
      File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 846, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1091, in best_match
        return self.obtain(req, installer)
      File "/usr/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1103, in obtain
        return installer(requirement)
      File "/usr/lib/python2.7/site-packages/setuptools/dist.py", line 380, in fetch_build_egg
        return cmd.easy_install(req)
      File "/usr/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 633, in easy_install
        raise DistutilsError(msg)
distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('setuptools-git')

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-macbkK/pymssql/

(It's the same error with pyodbc)  When I try install setuptools-git (like the error message says), I get a gcc compile error.
In addition to trying pip install..., I've downloaded the SQLAlchemy library directly from the Alpine Linux repo using apk add --no-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community/ py-sqlalchemy and the installs still fail/python libraries still fail.
I have found very little documentation on Alpine Linux and Microsoft SQL Server, so I'm wondering if I've missed something that says they're not compatible.  Has anyone tried doing this before?  If connecting via Python isn't suggested, I am considering connecting via Shell commands, can anyone suggest best practices for this?
Thank you!

A: you have to install odbc driver first.
so, add this to your docker file, and then install pyodbc
apk add g++ gcc unixodbc-dev

A: Microsoft has officially started supporting ODBC driver installation on Alpine.

A: Related question from me here
I recall installing msodbcsql17 driver to connect to sql server. But I used Ubuntu 18.04 as base image for my docker, and sql server was on azure. Additionally I had to install unixodbc unixodbc-dev gcc g++ gfortran, so not sure if that helps you.
But when I tried for alpine as base image this wasn't possible.
I found a related issue on github but it is under the msphpsql repo so I'm not sure if it applies to the driver in general for alpine. It says MS does not support yet.
Official MS installation page has installation instructions only for Debian, RedHat, SUSE, Ubuntu.


text:
Q: Post using curl and HTTP Requester generates different dictionaries I am using django-oauth2-provider to generate access tokens. Problem is that different POST requests are getting forged when using curl and browser based HTTP requester
This is what is forged when using curl:
{u'username': [u'admin'], u'client_secret':[u'50c96e6351c623b271a61e197a22de9fcdbfa'], u'password': [u'admin'], u'grant_type': [u'password'], u'client_id': [u'7f1ad1344d6d0a0e7b44']}

and this is what is formed when using the browser based HTTP Requester
{u"{'grant_type': 'password','client_id': 7f1ad1344d6d0a0e7b44,'client_secret': 50c96e6351c623b271a61e197a22de9fcdbfa,'username': admin,'password': admin}": [u'']}

The first one works fine, the second one obviously does not. What could be going wrong in the second case?

A: The problem was that I was entering JSON into the requester:
{'grant_type': 'password','client_id': 7f1ad1344d6d0a0e7b44,'client_secret': 50c96e6351c623b271a61e197a22de9fcdbfa,'username': admin,'password': admin}

Since I was supposed to send it as

application/x-www-form-urlencoded

it had to be sent as
client_id=7f1ad1344d6d0a0e7b44&client_secret=50c96e6351c623b271a61e197a22de9fcdbfa&grant_type=password&username=admin&password=admin


text:
Q: Android Studio - compileOptions(ERROR: No signature of method: ...) https://developers.kakao.com/docs/latest/en/getting-started/sdk-android
I was doing configuration according to the contents of this page.
However, there was a problem with the code below.
android {

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }

}

The code above spit out the error below.
No signature of method: build_2qf378v0zqbxe3d5cxom7rwd9.android() is applicable for argument types: (build_2qf378v0zqbxe3d5cxom7rwd9$_run_closure1) values: [build_2qf378v0zqbxe3d5cxom7rwd9$_run_closure1@6a47dac4]

In fact, there was a question with the same content as this question, but the answer is not good, so I'm asking this question.
Please help me solve this problem.

A: There are couple of reason that you have it but in my case it was due ti incorrect way of signing keys.
Create a file called key.properties on adnroid root directory and add these on key.properties file.
storePassword=xxxx
keyPassword=xxxxxx
keyAlias=my
storeFile=/home/master/Android/signature/my.keystore

and remember to replace values with your values.
then Add these lines on build.gradle(app)
def keystoreProperties = new Properties()
    def keystorePropertiesFile = rootProject.file('key.properties')
    if (keystorePropertiesFile.exists()) {
        keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
    }

and just replace your build type block
 buildTypes {
    release {

        signingConfig signingConfigs.release
    }
}

with this
signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           signingConfig signingConfigs.release
       }
   }

in your build.gradle(app) file.
This is the issue in my case. Will feel glad if it helps you too..
Happy coding...


text:
Q: Which function has the same behaviour as collect but keep the elements that do not satisfy the predicate I am looking for a function that looks like collect. This function must keep the element that do not satisfy the predicate.
This behaviour be could expressed using map. Example :
@ (0 to 10).map{
      case e if e > 5 => e * e
      case e          => e // I want to keep elements to does not satisfy the predicate !
  }
res3: collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

I would like to be able to write this function like this :
@ (0 to 10).map{
      case e if e > 5 => e * e
  }
scala.MatchError: 0 (of class java.lang.Integer)
  $sess.cmd4$$anonfun$1.apply$mcII$sp(cmd4.sc:1)
  $sess.cmd4$$anonfun$1.apply(cmd4.sc:1)
  $sess.cmd4$$anonfun$1.apply(cmd4.sc:1)
  scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
  scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
  scala.collection.immutable.Range.foreach(Range.scala:160)
  scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
  scala.collection.AbstractTraversable.map(Traversable.scala:104)
  $sess.cmd4$.<init>(cmd4.sc:1)
  $sess.cmd4$.<clinit>(cmd4.sc:-1)

Unfortunately, I have not found a function that takes a PartialFunction to avoid MatchErrors.
Do you know a function with such a behaviour ?

A: I don't think there is a pre-defined method that does what you want, but you can use a PartialFunction's .applyOrElse to do it:
scala> implicit class MySeq[A](r: Seq[A]) {
         def mapIfDefined(f: PartialFunction[A, A]): Seq[A] = {
           r.map(f.applyOrElse[A, A](_, identity))
         }
       }

scala> (0 to 10).mapIfDefined{
         case e if e > 5 => e * e
       }
res1: Seq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

A: Unless I'm mistaken, collect does exactly what you're asking:
scala> List(1,2,3,4,5,6,7,8,9,10).collect {
     |   case e if e > 5 => e * e
     |   case e => e
     | }
res0: List[Int] = List(1, 2, 3, 4, 5, 36, 49, 64, 81, 100)


text:
Q: How to insert platform specific paths into a database in Java I am working on an application that processes a large number of files placed in a directory. I want to insert the fully qualified path of each file that is processed by my application into the database. If a file that is already processed by the application is re-submitted for re-processing by the user, then I want to delete all the data processed for the file from the database by specifying the fully qualified path of the file and then proceed with the file as if it were a new file.
The problem that I am facing is that when I run the application through eclipse, the path name inserted into the database is as follows:-
   D:\Trunk\App\Source

Afer I concatenate the file name with its path (pathString + File.seperator + fileNameString) i.e, the fully qualified path inserted into the database is as follows
   D:\Trunk\App\Source/file1.txt

But if I create a jar for my application and run the jar by double clicking on the jar, the path name inserted into the database is as follows:-
   D:/Trunk/App/Source

After I concatenate the file name with its path (pathString + File.seperator + fileNameString) i.e, the fully qualified path inserted into the database is as follows
  D:/Trunk/App/Source/file1.txt

The application fails to delete the data for a file that is resubmitted for processing if the application is run by double clicking on the jar instead of running the application from eclipse. The query used for deleting is the same regardless of running the application from eclipse or by double clicking the jar
    delete from file_table where where file = 'D:\Trunk\App\Source/file1.txt'

A: Just convert all "\" to "/" or vice versa for all file paths that you process.

A: Convert path to URI and store in database. Then recreate file from URI.
String uriName = new File(path).toURI().toString()
String path = new File(new URI(uriName)).getAbsolutePath();


text:
Q: Netbeans: Creating custom build target to let sources be packaged to JAR...? I ask the question more specific:
Using Netbeans, is there a possibility to create an additional custom build target,
which would:

*

*either package all project sources along with the binaries into a singe JAR,

*or package all project sources without the binaries into an additional JAR?

Notes:

*

*It's not an option for me to modify the text field "Exclude from JAR file:"
in the project properties, because it wouldn't provide me with an additional
build target ;)

*As you can guess, it's for an open source project ;)

A: Thank to Mark's resource hint, I reduces the example to minimum complexity:
Following is done to pack only the sources:
<!-- depends="jar" have to stay:
    without it, we haven't the variable ${application.title} -->
<target name="MY-EXPORT-SOURCES" depends="jar">
    <echo>MY TARGET: PACKAGING ${application.title} SOURCES</echo>
    <delete file="dist/${application.title}.SOURCES.zip"/>
    <zip destfile="dist/${application.title}.SOURCES.zip" basedir="src"
        includes="**/*.java"/>
</target>

To run in Netbeans, do:
build.xml rightclick -> run targets -> other targets -> MY-EXPORT-SOURCES.

A: Check this out:
http://java.sun.com/developer/technicalArticles/java_warehouse/single_jar/
Might be the trick, just change the targets names to be more appropriate for your use

A: Yes Sure,
In Netbeans Project...
Right Click on Project and then select Properties.
In Properties window...
Go -> Build -> Packaging...
Remove -> */.java,
in Exclude From war file...
thats it...
Let me know, if it helps you...


text:
Q: Streams API: possible to undo .pipeTo()? The Streams API provides a neat way of piping a ReadableStream to a WritableStream using readableStream.pipeTo(writableStream). This would appear to be more convenient than obtaining readableStream.getReader() and manually gluing it to writableStream.getWriter() or directly to underlying functionality.
I have a use case where I am provided a ReadableStream object which may eventually need to "go away" and be replaced by a new ReadableStream object. It would be nice to use a single custom WritableStream to wrap the functionality which these ReadableStream objects interface with and pipe them together for as long as needed, but have not found how to "undo" the piping process.
Q: Is it possible to "undo"/"break"/"teardown" a pipe created with .pipeTo(), or are pipes "permanent" and not appropriate for this use case?
Example using Serial API, where I would like to be able to call doConnectPort() and then doDisconnectPort() repeatedly:
var customWritable = new WritableStream(…);
var port;

async function doConnectPort() {
  port = await navigator.serial.requestPort();
  await port.open({ baudrate: …});
  await port.readable.pipeTo(customWritable);
}

async function doDisconnectPort() {
  // What to do here? Can't close the port yet—port.readable is still locked!
  await port.close();
}

Currently, I manually glue things together and clean up when it's time to disconnect the port:
var port;
var portReader;

async function doConnectPort() {
  port = await navigator.serial.requestPort();
  await port.open({ baudrate: …});
  portReader = port.readable.getReader();
  while (true) {
    const { value, done } = await portReader.read();
    if (done) {
      break;
    }
    // do something with value
  }
}

async function doDisconnectPort() {
  await portReader.cancel();
  await portReader.releaseLock();
  await port.close();
}

A: You can pass an AbortSignal in the pipeTo's option object's signal.

const btn = document.querySelector( "button" );
const checkbox = document.querySelector( "input" );

if( !ReadableStream.prototype.pipeTo ) {
  console.warn( "Your browser doesn't support pipeTo" );
}
else {

btn.onclick = (evt) => {

  console.clear( "" );
  const blob = new Blob( [ "hello" ] );
  const readable = blob.stream();
  const target = new TransformStream();
  const abort_controller = new AbortController();

  target.readable.getReader().read().then( console.log );

  readable.pipeTo( target.writable, { signal: abort_controller.signal } )
    .catch( console.error )

  if( checkbox.checked ) {
    abort_controller.abort();
  }

};

}
Abort pipe<input type="checkbox" checked>

<button id="btn">new test</button>


text:
Q: Question about Axler's proof that every linear operator has an eigenvalue I am puzzled by Sheldon Axler's proof that every linear operator on a finite dimensional complex vector space has an eigenvalue (theorem 5.10 in "Linear Algebra Done Right").  In particular, it's his maneuver in the last set of displayed equations where he substitutes the linear operator $T$ for the complex variable $z$.  See below.

What principle allows Axler to make this substitution of linear operator for complex variable and still claim that the RHS equals the LHS, and that the LHS goes from being the number zero (in the preceding set of equations) to the zero vector (in the final set of equations)?
As a possible answer to my own question, on the preceding page he offers these remarks:

Is linearity of the map from "polynomial over complex variable" to "polynomial over T" the property that makes this work?  If so, I don't feel very enlightened.  Any further insight here is greatly appreciated, especially since Axler makes a side comment that this proof is much clearer than the usual proof via the determinant.

A: You are right that there is more going on here that just linearity. The principle used here is that for any linear operator $T$ on a space $V$ over a field $K$, the map $\eta_T:\def\End{\operatorname{End}}K[X]\to\End(E)$ given by $\sum_ic_iX^i\mapsto\sum_ic_iT^i$ (substitution of the operator $T$ for the indeterminate $X$, or "evaluation in $T$") is a morphism of rings: not only is it $K$-linear, but it also respects multiplication: $\eta_T(PQ)=\eta_T(P)\circ\eta_T(Q)$. To check the validity of this is a fairly formal matter: the way the product $PQ$ of polynomials is computed just uses rearranging/combining of powers of $X$ and scalars, and the same operations are valid when $X$ is systematically replaced by$~T$. Note that one particular instance is the commutation of scalars and powers: $aX^ibY^j=abX^iY^j=abX^{i+j}$, and the corresponding equality $aT^ibT^j=abT^{i+j}$ is valid because $T$ commutes with scalar multiplication, which is because it is a linear operator. Note that if one would try to do the same thing for a non linear operator in place of $T$, then the resulting map $K[X]\to E^E$ (we no longer get an endomorphism as result, but still a map $E\to E$, and the set of all such maps is still a $K$ vector space) would still be $K$-linear, but would fail to respect multiplication.
By the way, I find that one can do a bit better than the cited proof (which is the centrepiece of Axler's somewhat dubious "down with determinants" claim). Note that if one uses the first linear dependency that arises among the vectors $v,Tv,T^2v,\ldots$, say $0=c_0v+c_1Tv+\cdots+c_dT^d$, then $c_d\neq0$ by minimality and after dividing everything by it one may assume $c_d=1$. This means that $p[T](v)=0$ where $p=X^d+c_{d-1}X^{d-1}+\cdots+c_1X+c_0$, and no monic polynomial in$~T$ of lower degree vanishes when applied to$~v$ (because by the minimality assumption $v,Tv,\ldots,T^{d-1}v$ are linearly independent).
The subspace $V'=\ker(p[T])$ contains $v$ so that it is nonzero, and is closed under application of$~T$; it will be all of$~V$ if $d=n$ (as often happens), but in any case we can henceforth restrict our attention to $V'$, and call $T'$ the restriction of $T$ to $V'$. Then $p$ is the minimal polynomial of$~T'$: one has $p[T']=0$, and it is the minimal degree monic polynomial with this property. (This minimal polynomial property is all that will be used.)
In this situation not only $p$ has some root that is an eigenvalue of $T'$ and therefore of $T$ (assuming one works over the complex numbers), but every root of$~p$ is an eigenvalue (this is true over arbitrary fields, though of course only over algebraically closed fields one knows the existence of such roots). Here's why: if $\lambda$ is a root of$~p$ one can factor by $X-\lambda$ and write $p=(X-\lambda)q$, where $\deg q=\deg p-1$ so that for degree reasons mentioned above $q[T']\neq0$. Now $0=p[T']=(T'-\lambda I)\circ q[T']$, and every vector in the (nonzero) image of $q[T']$ is an eigenvector of$~T'$ for the eigenvalue$~\lambda$, in other words an eigenvector of$~T$ for$~\lambda$ lying in the subspace$~V'$.

A: You're on the right track.  The map from "polynomial over complex variable" to "polynomial over T" is linear, but also it preserves multiplication.  If $h(x) = f(x) g(x)$ as polynomials over x, then $h(T) = f(T) g(T)$ as polynomials over T.  So if you factor in terms of $x$ that factors in terms of $T$.

A: The essential point here is not just linearity, but also compatibility with multiplication.
This means the following. When
$$p(X) = \sum_n a_n X^n, \qquad q(X) = \sum_n b_n X^n$$
we define multiplication of polynomials in the usual way by
$$(pq)(X) = \sum_n c_n X^n, \quad \text{ where } c_n = \sum_{i + j = n} a_i b_j.$$
Then not only do we have
$$(pq)(z) = p(z)q(z)$$
for any $z \in \mathbf{C}$, but also
$$(pq)(T) = p(T)q(T)$$
for any vector space endomorphism $T$.
By induction, this can be extended to products of an arbitrary finite number of polynomials.
Thus the equality of polynomials
$$a_0 + a_1 X + \ldots + a_n X^n = c(X - \lambda_1) \cdots (X - \lambda_n)$$
entails both
$$a_0 + a_1 z + \ldots + a_n z^n = c(z - \lambda_1) \cdots (z - \lambda_n)$$
and
$$a_0 I+ a_1 T + \ldots + a_n T^n = c(T - \lambda_1 I) \cdots (T - \lambda_n I)$$
In abstract terms, for any $\mathbf{C}$-algebra $A$ and an element $a \in A$, the evaluation map $\operatorname{ev}_a \colon \mathbf{C}[X] \to A, \ p \mapsto p(a)$ is a morphism of $\mathbf{C}$-algebras. This holds in particular both for $A = \mathbf{C}$ and for $A = L(V)$.

A: He doesn't claim that, and you're right, they are different equations and different zeros.
What he says is: if one substituted the $T$ for $z$ in the polynomial, a natural factorization of the form $c(z-\lambda_1)...(z-\lambda_m)$ would arise. Now coming back to the $T$-polynomial, one can verify that a similar factorization with the same $c$ is also observed in this equation (but now the zero is vectorial). To prove it, just defactorize the $T$-polynomial.


text:
Q: Is there a way to use rowwise to get means across rows the correct way? Am not sure whether I have fully understood the rowwise function in dplyr. I seem to get the expected results. Below is the code and  the expected results.
library(dplyr)

set.seed(123)

mydf <- tibble(
  a1 = floor(rnorm(10, 5, 2)),
  a2 = floor(rnorm(10, 6, 3)),
  a3 = floor(rnorm(10, 8, 3))
)

mydf %>%
  rowwise() %>%
  mutate(allmeanrow = mean(a1:a3))

# Expected
mydf %>%
  mutate(allmeanrow = rowMeans(.))

A: You need to wrap your columns into c_across:
mydf %>%
  rowwise() %>%
  mutate(allmeanrow = mean(c_across(a1:a3))) %>%
  ungroup()

which gives:
# A tibble: 10 x 4
# Rowwise:
      a1    a2    a3 allmeanrow
   <dbl> <dbl> <dbl>      <dbl>
 1     3     9     4       5.33
 2     4     7     7       6
 3     8     7     4       6.33
 4     5     6     5       5.33
 5     5     4     6       5
 6     8    11     2       7
 7     5     7    10       7.33
 8     2     0     8       3.33
 9     3     8     4       5
10     4     4    11       6.33

Note, i would always ungroup after the rowwise operation because rowwise groups your data by row, so any following action would still be performed rowwise.
See also here: https://dplyr.tidyverse.org/articles/rowwise.html

A: We may use pmap which would be more efficient compared to rowwise.  Just loop over the data (cur_data()), capture the row values as a vector (c(...)) and get the mean
library(purrr)
library(dplyr)
mydf %>%
    mutate(allmeanrow = pmap_dbl(cur_data(), ~ mean(c(...))))
# A tibble: 10 × 4
      a1    a2    a3 allmeanrow
   <dbl> <dbl> <dbl>      <dbl>
 1     3     9     4       5.33
 2     4     7     7       6
 3     8     7     4       6.33
 4     5     6     5       5.33
 5     5     4     6       5
 6     8    11     2       7
 7     5     7    10       7.33
 8     2     0     8       3.33
 9     3     8     4       5
10     4     4    11       6.33


text:
Q: how to get courses created by particular user in moodle 3 Currently I'm working on moodle-3 plug-in development,and I have a user Id who is a course creator and i want to get all courses created by that user,is their any function, I can use or if you can help me with names of tables where I can fetch this data.I tried table called standard log where I can get all events is that only way to do it.

A: Not sure if this will work but you could try searching for courses that have the coursecreator role assigned.
SELECT r.shortname, u.username, c.fullname AS coursename
FROM mdl_role r
JOIN mdl_role_assignments ra ON ra.roleid = r.id
JOIN mdl_context ctx ON ctx.id = ra.contextid AND ctx.contextlevel = 50
JOIN mdl_course c ON c.id = ctx.instanceid
JOIN mdl_user u ON u.id = ra.userid
WHERE r.shortname = 'coursecreator'


text:
Q: MySQL query 0 rows affected in simple I try do that in PhpMyAdmin:

update wp_postmeta.meta_value = wp_posts.id where
wp_posts.post_name=articles.image
AND wp_posts.post_type=attachment
AND wp_postmeta.meta_key=_thumbnail_id

by this MySQL query:
update wp_postmeta m
join articles a on (m.post_id = a.id)
join wp_posts p on (m.post_id = p.ID)
set m.meta_value = p.ID
where p.post_name=a.image
AND a.image != NULL
AND p.post_type='attachment'
AND m.meta_key='_thumbnail_id'

it's work but 0 rows affected!
anyone can help?

A: This statement:
AND a.image != NULL

always evaluates to unknown.  And where clause filters out rows which are not true.  So a where filters out both unknown and false.  Try this instead:
AND a.image is not null

See this wikipedia article for more information.

A: Use subqueries with Andomar's answer. Using joins with update and delete statements is not good.
It should be something like
UPDATE wp_postmeta m SET m.meta_value = (SELECT p.ID FROM wp_posts p, articles a
WHERE m.post_id=p.ID AND m.post_id = a.id AND a.image IS NOT NULL
   AND p.post_type='attachment' AND p.post_name=a.image)
WHERE m.meta_key='_thumbnail_id'

BACKUP FIRST! I didn't test this.
If doesn't work try to execute a select query if you can select them. If it doesn't select (and probably it won't) please check the structure of your query corresponding to your design.
SELECT m.meta_value, (SELECT p.ID FROM wp_posts p, articles a
WHERE m.post_id=p.ID AND m.post_id = a.id AND a.image IS NOT NULL
   AND p.post_type='attachment' AND p.post_name=a.image)  AS pID
FROM wp_postmeta m
WHERE m.meta_key='_thumbnail_id'

Also try your first query too
SELECT m.meta_value, p.ID AS pID FROM wp_postmeta m
INNER JOIN articles a on (m.post_id = a.id)
INNER JOIN wp_posts p on (m.post_id = p.ID)
WHERE p.post_name=a.image
AND a.image IS NOT NULL
AND p.post_type='attachment'
AND m.meta_key='_thumbnail_id'

Try to play with/modify the select queries to find out the problem.


text:
Q: Unable to Make Prometheus Read the web-config.yml for TLS Encryption (Error: unknown long flag '--web.config.file') I am following the official documentation regarding the TLS encryption of Prometheus. My Spring Boot uses https endpoints and thus I want Prometheus to scrap them as is. I am following the instructions but I am having problem in configuring Prometheus to read my web-config.yml. Specifically the following command,
prometheus \
--config.file=/mnt/d/Projects/Msc-Thesis-Project/prometheus.yml \
--web.config.file=/mnt/d/Projects/Msc-Thesis-Project/web-config.yml \
--web.external-url=https://localhost:8443/

throws the following error,

Error parsing commandline arguments: unknown long flag '--web.config.file'
prometheus: error: unknown long flag '--web.config.file'

Does anyone had encountered the issue? Any advices?


text:
Q: add another background image to change background during playing game func createBackgrounds() {
    for i in 0...2 {
       let bg = SKSpriteNode(imageNamed: "BG Day")
       bg.name = "BG"
       bg.zPosition = 0;
       bg.anchorPoint = CGPoint(x: 0.5, y: 0.5)
       bg.position = CGPoint(x: CGFloat(i) * bg.size.width, y: 0)
       self.addChild(bg)
    }
}

If I want to add another background image after 2 minutes to BG Night, how can I write coding in swift 2?

A: You can use SKAction.runBlock to run some code in the future
class GameScene: SKScene {

    var background: SKSpriteNode?

    override func didMoveToView(view: SKView) {
        super.didMoveToView(view)
        changeBackgroundIn2Mintues()
        self.background = SKSpriteNode(imageNamed: "OLD_BG_IMAGE_NAME")
    }

    private func changeBackgroundIn2Mintues() {

        let wait = SKAction.waitForDuration(60 * 2)
        let changeBG = SKAction.runBlock { [unowned self] in
            self.background?.removeFromParent()
            self.background = SKSpriteNode(imageNamed: "NEW_BG_IMAGE_NAME")
        }
        let sequence = SKAction.sequence([wait, changeBG])
        self.runAction(sequence)

    }
}

A: You can do this simply by animating a UIImage. As follows:
let bgImageArray = [UIImage(named: "BG Day")!, UIImage(named: "BG Night")!]

bg.animationImages = bgImageArray
bg.animationDuration = 120 //seconds
bg.animationRepeatCount = 0 //forever
bg.startAnimating()

Then just put the image bg at the back of your view.


text:
Q: How to hide a _Layout.cshtm menu in a speciefic view? In my MVC 4 project, i have 2 menus, one top fixed menu and a side menu. The top menu is always visible, even when the user isnt logged. But the side menu is only visible when the user is logged. But if the user has a admin role he is able to acces the "Create User" view, and i wish the side menu would not be visible in that speciefic view. How can i do that?
Here´s the side menu part in my layout view:
        @if (Request.IsAuthenticated)
        {

Comparações

                        Item 1
                        Item 2

         }

A: I used css - you can make this into "HideMenu.cshtml" and call @RenderPage("HideMenu.cshtml") in any cshtml file where you don't want to see the menu.

In this css, "navbar" is the class of the menu item I want to hide.
Use F12 from your browser to find the class name of the element you want to hide.

A: I use ViewBag to set a flag from the controller. This flag determines whether to do something, but make sure that missing value is also valid and it indicates default action. In that case, only the actions that are affected by the additional part of the layout are free to set the ViewBag item to specific value.
For example, I have a sign in form in layout. But sign in should not be rendered when user visits sign up page, obviously. So, there is a HideSignInForm with default False (and missing equals False). In _Layout.cshtml this is covered by this piece of code:
bool hideSignInForm = false;
if (ViewBag.HideSignInForm != null)
{
    hideSignInForm = (bool)ViewBag.HideSignInForm;
}

Later on in the _Layout.cshtml, I use the flag normally:
if (!hideSignInForm)
{

        ...

}

A: Try:
@if (Request.IsAuthenticated && !HttpContext.Current.User.IsInRole("Admin"))
    {

Comparações

                    Item 1
                    Item 2

     }