问:
bootstrap 4, cursor doesn't change when hovering over a button but does on anchors
I'm using bootstrap 4 alpha, and it seems that the cursor on buttons has been removed for buttons but not anchor tags. example on the bootstrap site.

https://v4-alpha.getbootstrap.com/components/buttons/

In my application i have a form, with two buttons, one is to post to the form and the other is to redirec to another page. The input doesn't display the cursor but the anchor does. I know i can create a custom css class, but is there a reason why this has been removed or is it an issue with the current alpha version?

```<code><input type="submit" value="Sign In" class="btn btn-primary" />
<a role="button" href="@Url.Action("Register", "Account")" class="btn btn-secondary">Register Now</a>
</code>```

答:
Here's your explanation - https://medium.com/simple-human/buttons-shouldnt-have-a-hand-cursor-b11e99ca374b

I'm not sure Bootstrap v4 adds that on anchor elements either (can't check at the moment), but what I do know for sure is that browsers add the cursor by default whenever a link has the href attribute.

LE - The stable release was launched a week ago and it now features

```<code>.btn:not(:disabled):not(.disabled) {
    cursor: pointer;
}
</code>```

Announcement at https://blog.getbootstrap.com/2018/01/18/bootstrap-4/

Body:
I'm using bootstrap 4 alpha, and it seems that the cursor on buttons has been removed for buttons but not anchor tags. example on the bootstrap site.

https://v4-alpha.getbootstrap.com/components/buttons/

In my application i have a form, with two buttons, one is to post to the form and the other is to redirec to another page. The input doesn't display the cursor but the anchor does. I know i can create a custom css class, but is there a reason why this has been removed or is it an issue with the current alpha version?

<input type="submit" value="Sign In" class="btn btn-primary" />
Register Now

Body:
Here's your explanation - https://medium.com/simple-human/buttons-shouldnt-have-a-hand-cursor-b11e99ca374b

I'm not sure Bootstrap v4 adds that on anchor elements either (can't check at the moment), but what I do know for sure is that browsers add the cursor by default whenever a link has the href attribute.

LE - The stable release was launched a week ago and it now features

.btn:not(:disabled):not(.disabled) {
    cursor: pointer;
}

Announcement at https://blog.getbootstrap.com/2018/01/18/bootstrap-4/


来源: stackexchange

问:
Open an image in Groovy Script
I'm testing web services atm and I'm pulling files in a Base64 format.

I've managed to covert the files and save them to a location.

However I'd like the files to open directly, I'm working with PDF files and images so I think a browser would be the best to open the files in.

```<code>    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
import org.apache.commons.codec.binary.Base64;
Base64 coder = new Base64();

def filename = context.expand( '${DWG_OphalenBijlage (1)#Response#declare namespace b=\'http://schemas.datacontract.org/2004/07/Dynamics.Ax.Application\'; declare namespace ns1=\'http://www.XXXXXX.be/neptunus/moka/soconsult/getattachment\'; //ns1:MoKaGetAttachmentGetAttachmentResponse[1]/ns1:response[1]/b:MoKaSOAttachment[1]/b:FileType[1]}' )
def encodedString = context.expand( '${DWG_OphalenBijlage (1)#Response#declare namespace b=\'http://schemas.datacontract.org/2004/07/Dynamics.Ax.Application\'; declare namespace ns1=\'http://www.XXXXXXX.be/neptunus/moka/soconsult/getattachment\'; //ns1:MoKaGetAttachmentGetAttachmentResponse[1]/ns1:response[1]/b:MoKaSOAttachment[1]/b:DataFile[1]}' )
def decoded = encodedString.decodeBase64();
def f = new File(groovyUtils.projectPath + '/Bijlage1.' + filename);

f.delete();
f << decoded

log.info(groovyUtils.projectPath + '/Bijlage1.' + filename);
</code>```

This saves the image now can annybody suggest me what I should do next to open the file automaticly?

答:
You can do:

```<code>java.awt.Desktop.desktop.open(f)
</code>```

If that's what you mean?

ContentLicense: CC BY-SA 3.0

Title: Open an image in Groovy Script

Body:
I'm testing web services atm and I'm pulling files in a Base64 format.

I've managed to covert the files and save them to a location.

However I'd like the files to open directly, I'm working with PDF files and images so I think a browser would be the best to open the files in.

    def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
import org.apache.commons.codec.binary.Base64;
Base64 coder = new Base64();

def filename = context.expand( '${DWG_OphalenBijlage (1)#Response#declare namespace b=\'http://schemas.datacontract.org/2004/07/Dynamics.Ax.Application\'; declare namespace ns1=\'http://www.XXXXXX.be/neptunus/moka/soconsult/getattachment\'; //ns1:MoKaGetAttachmentGetAttachmentResponse[1]/ns1:response[1]/b:MoKaSOAttachment[1]/b:FileType[1]}' )
def encodedString = context.expand( '${DWG_OphalenBijlage (1)#Response#declare namespace b=\'http://schemas.datacontract.org/2004/07/Dynamics.Ax.Application\'; declare namespace ns1=\'http://www.XXXXXXX.be/neptunus/moka/soconsult/getattachment\'; //ns1:MoKaGetAttachmentGetAttachmentResponse[1]/ns1:response[1]/b:MoKaSOAttachment[1]/b:DataFile[1]}' )
def decoded = encodedString.decodeBase64();
def f = new File(groovyUtils.projectPath + '/Bijlage1.' + filename);

f.delete();
f << decoded

log.info(groovyUtils.projectPath + '/Bijlage1.' + filename);

This saves the image now can annybody suggest me what I should do next to open the file automaticly?

Body:
You can do:

java.awt.Desktop.desktop.open(f)

If that's what you mean?


问:
How to get distinct data from two tables using SQL Select query
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

```<code>Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000
</code>```

Table_Innovation

```<code>Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno
</code>```

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

```<code>counts
 2
</code>```

output: How many users started Innovation base on email need details of users.

```<code> Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000
</code>```

答:
Try below query, this will give you the required output as mentioned by you in question.

```<code>DECLARE @Table_UserInformation TABLE(Name  varchar(100),    Email         varchar(100),        mobile varchar(100))
DECLARE @Table_Innovation TABLE(Email  varchar(100),    DATA1         varchar(100),        DATA2 varchar(100))
INSERT INTO @Table_UserInformation VALUES
('mazhar',    'mazar@gmail.com',   '720000000'),
('rahul',    'rahul@gmail.com',   '992000000'),
('raj',       'raj@gmail.com',     '700000000')
INSERT INTO @Table_Innovation VALUES
('mazar@gmail.com',   'aim to achive LD',     'NA'),
('mazar@gmail.com',   'Search for LD',        'NA'),
('rahul@gmail.com',   'mind tech',            'Techno')
;WITH SAMPLEDATA
AS
(
SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email
)
SELECT T2.Name,T2.Email,T2.mobile,T1.COUNTS FROM SAMPLEDATA T1 JOIN     @Table_UserInformation T2
ON T1.Email=T2.Email
</code>```

OUTPUT

```<code>-----------------------------------------
--Name  Email   mobile  COUNTS
-----------------------------------------
mazhar  mazar@gmail.com 720000000   2
rahul   rahul@gmail.com 992000000   1
-----------------------------------------
</code>```

Separate queries for both:

```<code>SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email

;WITH SAMPLEDATA
AS
(
SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email
)
SELECT T2.Name,T2.Email,T2.mobile FROM SAMPLEDATA T1 JOIN     @Table_UserInformation T2
ON T1.Email=T2.Email
</code>```

OUTPUT

```<code>-----------------------
Email   COUNTS
-----------------------
mazar@gmail.com 2
rahul@gmail.com 1

------------------------------------
Name    Email   mobile
------------------------------------
mazhar  mazar@gmail.com 720000000
rahul   rahul@gmail.com 992000000
</code>```

Body:
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000

Table_Innovation

Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

counts
 2

output: How many users started Innovation base on email need details of users.

 Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000

Body:
Try below query, this will give you the required output as mentioned by you in question.

DECLARE @Table_UserInformation TABLE(Name  varchar(100),    Email         varchar(100),        mobile varchar(100))
DECLARE @Table_Innovation TABLE(Email  varchar(100),    DATA1         varchar(100),        DATA2 varchar(100))
INSERT INTO @Table_UserInformation VALUES
('mazhar',    'mazar@gmail.com',   '720000000'),
('rahul',    'rahul@gmail.com',   '992000000'),
('raj',       'raj@gmail.com',     '700000000')
INSERT INTO @Table_Innovation VALUES
('mazar@gmail.com',   'aim to achive LD',     'NA'),
('mazar@gmail.com',   'Search for LD',        'NA'),
('rahul@gmail.com',   'mind tech',            'Techno')
;WITH SAMPLEDATA
AS
(
SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email
)
SELECT T2.Name,T2.Email,T2.mobile,T1.COUNTS FROM SAMPLEDATA T1 JOIN     @Table_UserInformation T2
ON T1.Email=T2.Email

OUTPUT

-----------------------------------------
--Name  Email   mobile  COUNTS
-----------------------------------------
mazhar  mazar@gmail.com 720000000   2
rahul   rahul@gmail.com 992000000   1
-----------------------------------------

Separate queries for both:

SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email

;WITH SAMPLEDATA
AS
(
SELECT Email,COUNT(EMAIL)COUNTS FROM @Table_Innovation GROUP BY Email
)
SELECT T2.Name,T2.Email,T2.mobile FROM SAMPLEDATA T1 JOIN     @Table_UserInformation T2
ON T1.Email=T2.Email

OUTPUT

-----------------------
Email   COUNTS
-----------------------
mazar@gmail.com 2
rahul@gmail.com 1

------------------------------------
Name    Email   mobile
------------------------------------
mazhar  mazar@gmail.com 720000000
rahul   rahul@gmail.com 992000000


问:
AX SSRS use expression from another dataset in total
I have a header section which is showing totals etc.  I have two fields in another dataset (dataset estimates) which I want to pull into header dataset.

Fee (circled) = IIf(Right(Fields!ProjCategoryId.Value, 3) <> "EXP", Fields!Value.Value, 0)

3rd Party (circled) = IIf(Right(Fields!ProjCategoryId.Value, 3) = "EXP", Fields!Value.Value, 0)

I know you can sum datasets from another dataset with no issues, but how to use IIF etc. as well?

答:
This is actually really simple.  Find the Textbox name that contains the expression.

(When we say textbox this does not have to be a textbox from the toolbox, it can be a field within tablix).  Where you want to reference the value simply add the expression and you can reference the result.


问:
Javascript - delayed button with cookie checker
i am trying to do something that it's still out of my league. I have used before script on website to show Button after 1 minute from video time. So when Video player comes to 01:00 the button is shown and after that it saves that to cookie so the next time you visit page it's shown right away and you don't have to wait another 1 minute so button can be shown.

But now i am trying to connect this timer to the website time, not the video time, and i am pretty lost.

Function calling in Index page:

```<code><script type="text/javascript">
var minuten = 0;
var sekunden = 5;

//==========================
cartt(minuten, sekunden);
</script>
</code>```

This is the original code of the video time:

```<code> $("#video").fitVids();
 var video = new Vimeo.Player($('#video iframe'));
 function cart(minuten, sekunden) {

    var button = $('.cart');
    var seconds = (minuten * 60) + sekunden;
    var url = window.location.pathname;
    url = url.split("/");
    var seite = url[url.length -1];
    var cookie_string = "cartbutton_" + seite + "=show";
    var cookieIsSet = function() { return document.cookie.indexOf(cookie_string) != -1; };

    if(!cookieIsSet()) {
        button.hide();

        video.on('timeupdate', function(data) {
            if (data.seconds >= seconds && !cookieIsSet()) {
                button.show();
                document.cookie = cookie_string + "; max-age=259200";
            }
        });
    }

}
</code>```

And this is how i am trying to get website time:

```<code>window.onload=function(){
      var start=Date.now();

}
function cartt(minuten, sekunden) {

    var button = $('.cartt');
    var seconds = (minuten * 60) + sekunden;
    document.write(seconds);
    var url = window.location.pathname;
    url = url.split("/");
    var seite = url[url.length -1];
    var cookie_string = "cartbutton_" + seite + "=show";
    var cookieIsSet = function() {
        return document.cookie.indexOf(cookie_string) != -1;

        };

    if(!cookieIsSet()) {

     start.on(function(data) {
            if (data.seconds >= seconds && !cookieIsSet()) {
                button.show();
                document.cookie = cookie_string + "; max-age=259200";
            }
        });

        button.hide();

    }

}
</code>```

答:
(Posted on behalf of the OP).

I have managed to make this by myself, since there are no answers and I couldn't find this answer on the web, I will share my solution.

On index page:

```<code>  <script type="text/javascript">
    var videoShow = getCookie('video-show');
    jQuery(document).ready(function() {
        if(videoShow) {
            jQuery('.cartt').show();
        }
        else {
            setTimeout(
                function(){
                    jQuery('.cartt').show();
                    setCookie('video-show', 1, 365);
                }, 5000            );
        }
  });
    </script>
</code>```

The script:

```<code>function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
var dpath = '/';
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+";path="+dpath;
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
</code>```

Body:
i am trying to do something that it's still out of my league. I have used before script on website to show Button after 1 minute from video time. So when Video player comes to 01:00 the button is shown and after that it saves that to cookie so the next time you visit page it's shown right away and you don't have to wait another 1 minute so button can be shown.

But now i am trying to connect this timer to the website time, not the video time, and i am pretty lost.

Function calling in Index page:

This is the original code of the video time:

 $("#video").fitVids();
 var video = new Vimeo.Player($('#video iframe'));
 function cart(minuten, sekunden) {

    var button = $('.cart');
    var seconds = (minuten * 60) + sekunden;
    var url = window.location.pathname;
    url = url.split("/");
    var seite = url[url.length -1];
    var cookie_string = "cartbutton_" + seite + "=show";
    var cookieIsSet = function() { return document.cookie.indexOf(cookie_string) != -1; };

    if(!cookieIsSet()) {
        button.hide();

        video.on('timeupdate', function(data) {
            if (data.seconds >= seconds && !cookieIsSet()) {
                button.show();
                document.cookie = cookie_string + "; max-age=259200";
            }
        });
    }

}

And this is how i am trying to get website time:

window.onload=function(){
      var start=Date.now();

}
function cartt(minuten, sekunden) {

    var button = $('.cartt');
    var seconds = (minuten * 60) + sekunden;
    document.write(seconds);
    var url = window.location.pathname;
    url = url.split("/");
    var seite = url[url.length -1];
    var cookie_string = "cartbutton_" + seite + "=show";
    var cookieIsSet = function() {
        return document.cookie.indexOf(cookie_string) != -1;

        };

    if(!cookieIsSet()) {

     start.on(function(data) {
            if (data.seconds >= seconds && !cookieIsSet()) {
                button.show();
                document.cookie = cookie_string + "; max-age=259200";
            }
        });

        button.hide();

    }

}

Body:
(Posted on behalf of the OP).

I have managed to make this by myself, since there are no answers and I couldn't find this answer on the web, I will share my solution.

On index page:

  <script type="text/javascript">
    var videoShow = getCookie('video-show');
    jQuery(document).ready(function() {
        if(videoShow) {
            jQuery('.cartt').show();
        }
        else {
            setTimeout(
                function(){
                    jQuery('.cartt').show();
                    setCookie('video-show', 1, 365);
                }, 5000            );
        }
  });
    </script>

The script:

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
var dpath = '/';
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString())+";path="+dpath;
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}


问:
How to backup of deploy rails application from server?
Hi I have a ruby on rails app hosted on AWS EC2 and it is using mysql3 as database.Now I have to take backup of the database to my local machine.</p>

答:
I did the same with a DigitalOcean application with PostgreSql, to do that, this is what I did, for that you will need a ssh connection, everywhere (DigitalOcean... and probably Amazon) explains how to do that

In the server (AWS in you case):

make a cron to execute daily a script to make a backup of the database

```<code>crontrb -e
</code>```

and add, to perform a copy every day at 23:00

```<code> 23 * * * sh /home/rails/backup/backup_dump.sh
</code>```

create /home/rails/backup/backup_dump.sh:

```<code>NOW=$(date +"%d")
FILE="app_production_$NOW.sql"
pg_dump -U rails -w app_production > /home/rails/backup/$FILE
</code>```

of course pg_dump is what I use to make a backup of my PostgreSql database, in you case with MySQL will need another

In your local machine:

Add in /etc/cron.daily directory the script file that contains the recover from AWS backup file, and populate:

```<code>NOW=$(date +"%d") # date - 1... the day before, don't remeber the script sintax
scp -r root@ip_server:/home/rails/backup/app_production_$NOW.sql /local_machine/user/local_backups
</code>```

And that's all, I hope will help you

Body:
I did the same with a DigitalOcean application with PostgreSql, to do that, this is what I did, for that you will need a ssh connection, everywhere (DigitalOcean... and probably Amazon) explains how to do that

In the server (AWS in you case):

make a cron to execute daily a script to make a backup of the database

crontrb -e

and add, to perform a copy every day at 23:00

 23 * * * sh /home/rails/backup/backup_dump.sh

create /home/rails/backup/backup_dump.sh:

NOW=$(date +"%d")
FILE="app_production_$NOW.sql"
pg_dump -U rails -w app_production > /home/rails/backup/$FILE

of course pg_dump is what I use to make a backup of my PostgreSql database, in you case with MySQL will need another

In your local machine:

Add in /etc/cron.daily directory the script file that contains the recover from AWS backup file, and populate:

NOW=$(date +"%d") # date - 1... the day before, don't remeber the script sintax
scp -r root@ip_server:/home/rails/backup/app_production_$NOW.sql /local_machine/user/local_backups

And that's all, I hope will help you


问:
C++ linker cannot find reference to local functions
I have this simple code inserted in myfile.hpp file inside a project of mine:

```<code>#ifndef _PERFORMANCE_INDEX_HPP_
#define _PERFORMANCE_INDEX_HPP_

#include <boost/math/special_functions/powm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
namespace calculus {
/*!
 * Parameters needed for calculating PI.
 */
typedef struct {
    double eval_cpu_mhz; /* CPU MHz */
    double eval_ram_mb; /* RAM in MegaBytes */
    unsigned int eval_core_num; /* Number of cores per processor */
    unsigned int eval_cpu_num; /* Number of processors */
    unsigned int eval_hops; /* INET hop distance */
    double eval_bandwidth; /* Bandwidth in KBit/s */
    unsigned int eval_load; /* Number of tasks in queue in worker */
} PerformanceEvalParams;
/*!
 * PI type.
 */
typedef double PIType;
}
}
//-----------------------------------------------------------------------------
// Constants
namespace middleware {
namespace calculus {
const double kPerformanceEvalBeta = 3.0;
const double kPerformanceEvalDelta = 1.0;
const double kPerformanceEvalG = 1.60;
const double kPerformanceEvalH = 1.014;
const double kPerformanceEvalR = 512;
}
}
//-----------------------------------------------------------------------------
// Functions declarations
namespace middleware {
namespace calculus {
/*!
 * Used to calculate log in a given base.
 */
double Log(double base, double arg);
/*!
 * Used to calculate sqrt.
 */
double Sqrt(double arg);
/*!
 * Used to calculate exp by a given base.
 */
double Exp(double base, double arg);
/*!
 * Used for calculate PI
 */
PIType CalulatePI(const PerformanceEvalParams& pep);
}
}
//-----------------------------------------------------------------------------
// Functions implementations
using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep) {
    double N = -1, S = -1, C = -1; /* Parts */
    double PI = -1; /* Final result */
    N = (double)(kPerformanceEvalBeta * pep.eval_bandwidth);
    N = (double)(N / (double)((kPerformanceEvalDelta * (pep.eval_hops + 1))));
    N = (double)(Sqrt(N));
    S = (double)(pep.eval_cpu_mhz * pep.eval_cpu_num);
    S = (double)(S / ((double)(pep.eval_load + 1)));
    C = Log(kPerformanceEvalG, pep.eval_core_num);
    C = (double)(C + 1);
    C = (double)((double)1 + Exp(kPerformanceEvalH, -(pep.eval_ram_mb - 512)));
    PI = (double)(N * S * C);
    return PI;
}
double Log(double base, double arg) {
    // Boost Log returns boost::math::log1p(x) = log(e, x + 1)
    double res = (double)(boost::math::log1p(arg - 1));
    // Base conversion: log(new, y) = log(old, y) / log(old, new)
    // Then ==> log(base, arg) = log(e, arg) / log(e, base)
    res = (double)(res / boost::math::log1p(base));
    return res;
}
double Sqrt(double arg) {
    // Boost Sqrt returns boost::math::sqrt1pm1(x) = sqrt(1 + x) - 1
    double res = (double)(boost::math::sqrt1pm1(arg - 1));
    res = (double)(res + 1);
    return res;
}
double Exp(double base, double arg) {
    // Boost Pow returns boost::math::powm1(x, y) = x^y - 1
    double res = (double)(boost::math::powm1(base, arg));
    res = (double)(res + 1);
    return res;
}

#endif
</code>```

I compile using this compilation directive:

g++ *.cpp

In main.cpp notice that there is #include "myfile.hpp", so it is compiled.

g++ tells me this:

/tmp/ccY04BAx.o: In function
  CalculatePI(middleware::calculus::PerformanceEvalParams
  const&)': main.cpp:(.text+0x1edd):
  undefined reference to
  middleware::calculus::Sqrt(double)'
  main.cpp:(.text+0x1f43): undefined
  reference to
  middleware::calculus::Log(double,
  double)' main.cpp:(.text+0x1f72):
  undefined reference to
  middleware::calculus::Exp(double,
  double)' collect2: ld returned 1 exit
  status

What's the problem? Thank you

答:
```<code>using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep)
</code>```

This does not define the CalculatePI function that you previously declared inside of the middleware::calculus namespace.  This declares and defines a new function in the global namespace.

You either need to qualify the function name in the definition:

```<code>using namespace middleware::calculus;
PIType middleware::calculus::CalculatePI(const PerformanceEvalParams& pep) {
    /* ... */
}
</code>```

or place the definition in the namespace:

```<code>namespace middleware {
    namespace calculus {
        PIType CalculatePI(const PerformanceEvalParams& pep) {
            /* ... */
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this simple code inserted in myfile.hpp file inside a project of mine:

#ifndef _PERFORMANCE_INDEX_HPP_
#define _PERFORMANCE_INDEX_HPP_

#include <boost/math/special_functions/powm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>

//-----------------------------------------------------------------------------
// Enum, struct, aliases
namespace middleware {
namespace calculus {
/*!
 * Parameters needed for calculating PI.
 */
typedef struct {
    double eval_cpu_mhz; /* CPU MHz */
    double eval_ram_mb; /* RAM in MegaBytes */
    unsigned int eval_core_num; /* Number of cores per processor */
    unsigned int eval_cpu_num; /* Number of processors */
    unsigned int eval_hops; /* INET hop distance */
    double eval_bandwidth; /* Bandwidth in KBit/s */
    unsigned int eval_load; /* Number of tasks in queue in worker */
} PerformanceEvalParams;
/*!
 * PI type.
 */
typedef double PIType;
}
}
//-----------------------------------------------------------------------------
// Constants
namespace middleware {
namespace calculus {
const double kPerformanceEvalBeta = 3.0;
const double kPerformanceEvalDelta = 1.0;
const double kPerformanceEvalG = 1.60;
const double kPerformanceEvalH = 1.014;
const double kPerformanceEvalR = 512;
}
}
//-----------------------------------------------------------------------------
// Functions declarations
namespace middleware {
namespace calculus {
/*!
 * Used to calculate log in a given base.
 */
double Log(double base, double arg);
/*!
 * Used to calculate sqrt.
 */
double Sqrt(double arg);
/*!
 * Used to calculate exp by a given base.
 */
double Exp(double base, double arg);
/*!
 * Used for calculate PI
 */
PIType CalulatePI(const PerformanceEvalParams& pep);
}
}
//-----------------------------------------------------------------------------
// Functions implementations
using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep) {
    double N = -1, S = -1, C = -1; /* Parts */
    double PI = -1; /* Final result */
    N = (double)(kPerformanceEvalBeta * pep.eval_bandwidth);
    N = (double)(N / (double)((kPerformanceEvalDelta * (pep.eval_hops + 1))));
    N = (double)(Sqrt(N));
    S = (double)(pep.eval_cpu_mhz * pep.eval_cpu_num);
    S = (double)(S / ((double)(pep.eval_load + 1)));
    C = Log(kPerformanceEvalG, pep.eval_core_num);
    C = (double)(C + 1);
    C = (double)((double)1 + Exp(kPerformanceEvalH, -(pep.eval_ram_mb - 512)));
    PI = (double)(N * S * C);
    return PI;
}
double Log(double base, double arg) {
    // Boost Log returns boost::math::log1p(x) = log(e, x + 1)
    double res = (double)(boost::math::log1p(arg - 1));
    // Base conversion: log(new, y) = log(old, y) / log(old, new)
    // Then ==> log(base, arg) = log(e, arg) / log(e, base)
    res = (double)(res / boost::math::log1p(base));
    return res;
}
double Sqrt(double arg) {
    // Boost Sqrt returns boost::math::sqrt1pm1(x) = sqrt(1 + x) - 1
    double res = (double)(boost::math::sqrt1pm1(arg - 1));
    res = (double)(res + 1);
    return res;
}
double Exp(double base, double arg) {
    // Boost Pow returns boost::math::powm1(x, y) = x^y - 1
    double res = (double)(boost::math::powm1(base, arg));
    res = (double)(res + 1);
    return res;
}

#endif

I compile using this compilation directive:

g++ *.cpp

In main.cpp notice that there is #include "myfile.hpp", so it is compiled.

g++ tells me this:

/tmp/ccY04BAx.o: In function
  CalculatePI(middleware::calculus::PerformanceEvalParams
  const&)': main.cpp:(.text+0x1edd):
  undefined reference to
  middleware::calculus::Sqrt(double)'
  main.cpp:(.text+0x1f43): undefined
  reference to
  middleware::calculus::Log(double,
  double)' main.cpp:(.text+0x1f72):
  undefined reference to
  middleware::calculus::Exp(double,
  double)' collect2: ld returned 1 exit
  status

What's the problem? Thank you

Body:
using namespace middleware::calculus;
PIType CalculatePI(const PerformanceEvalParams& pep)

This does not define the CalculatePI function that you previously declared inside of the middleware::calculus namespace.  This declares and defines a new function in the global namespace.

You either need to qualify the function name in the definition:

using namespace middleware::calculus;
PIType middleware::calculus::CalculatePI(const PerformanceEvalParams& pep) {
    /* ... */
}

or place the definition in the namespace:

namespace middleware {
    namespace calculus {
        PIType CalculatePI(const PerformanceEvalParams& pep) {
            /* ... */
        }
    }
}


问:
JS : exported Function fail to return True/False
I have a function in another file , the function suppose to check if there is an admin in the DB, if not to create him . If by the end there is an admin in the DB (created or already was) , return true if not  it will return false.

```<code>/*AdminUser.js*/
const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function() {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            return true;
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "delta@example.com",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    return false;
                } else {
                    console.log("Admin have been initialized");
                    return true;
                }
            });
        }
    });
}
}
</code>```

In the main app , I have this :

```<code>if (AdminUser.validate()) {
     app.listen(port, () => {
     console.log('Server started on port: ' + port);
     });
} else {
     console.log('Fail to run Server');
     process.exit();
}
</code>```

The function (.validate) always returns an 'undefined' object and the server fails to start . Can someone explain me why return value is not True/False .

The function(.validate) does print "Main admin is booted" and I guess it returns the true value next line.

Using app = express();

答:
AdminUser.validate() does indeed return undefined. If you look at the body of that function, you can see that it receives it's results via callbacks from Admin.addAdmin and Admin.getAdminByRealID. This means that to handle these results outside of the function body, you should provide a callback parameter to your validate method. This technique is pretty standard for node asynchronous programming (although Promises and await are more contemporary approaches - but that is outside of the scope of this answer).

```<code>const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function(done) {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            done(true);
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "delta@example.com",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    done(false);
                } else {
                    console.log("Admin have been initialized");
                    done(true);
                }
            });
        }
    });
}
}
</code>```

And you would call it like so:

```<code>AdminUser.validate((ok)=> {
  if(ok){
    app.listen(port, () => {
      console.log('Server started on port: ' + port);
    });
  } else {
    console.log('Fail to run Server');
    process.exit(1);
  }
});
</code>```

Body:
I have a function in another file , the function suppose to check if there is an admin in the DB, if not to create him . If by the end there is an admin in the DB (created or already was) , return true if not  it will return false.

/*AdminUser.js*/
const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function() {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            return true;
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "delta@example.com",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    return false;
                } else {
                    console.log("Admin have been initialized");
                    return true;
                }
            });
        }
    });
}
}

In the main app , I have this :

if (AdminUser.validate()) {
     app.listen(port, () => {
     console.log('Server started on port: ' + port);
     });
} else {
     console.log('Fail to run Server');
     process.exit();
}

The function (.validate) always returns an 'undefined' object and the server fails to start . Can someone explain me why return value is not True/False .

The function(.validate) does print "Main admin is booted" and I guess it returns the true value next line.

Using app = express();

Body:
AdminUser.validate() does indeed return undefined. If you look at the body of that function, you can see that it receives it's results via callbacks from Admin.addAdmin and Admin.getAdminByRealID. This means that to handle these results outside of the function body, you should provide a callback parameter to your validate method. This technique is pretty standard for node asynchronous programming (although Promises and await are more contemporary approaches - but that is outside of the scope of this answer).

const Admin = require('../models/admin');
const mongoose = require('mongoose');

module.exports = {
validate: function(done) {
    Admin.getAdminByRealID("1212", (error, admin) => {
        if (admin) {
            console.log("Main admin is Booted");
            done(true);
        } else {
            console.log("Booting main admin");
            let newAdmin = new Admin({
                ID: "1212",
                account: {
                    username: "Admin",
                    password: "1212",
                    token: "Admin"
                },
                name: {
                    first: "Admin",
                    last: "Delta"
                },
                communication: {
                    email: "delta@example.com",
                    phone: "1212"
                }
            });
            Admin.addAdmin(newAdmin, (error, admin) => {
                if (error) {
                    console.log("Admin reboot failed");
                    done(false);
                } else {
                    console.log("Admin have been initialized");
                    done(true);
                }
            });
        }
    });
}
}

And you would call it like so:

AdminUser.validate((ok)=> {
  if(ok){
    app.listen(port, () => {
      console.log('Server started on port: ' + port);
    });
  } else {
    console.log('Fail to run Server');
    process.exit(1);
  }
});


问:
the g:link not working while using inside the g:formremote
this is the code for ajax request to the controller i already tried.

```<code><g:formRemote onComplete="onComplete()" update="addBlock" autocomplete="off" url="[controller: 'someContoller', action:'someAction']">
</code>```

this is the link inside the form remote and it is not working.

```<code><g:link url="[controller:'anotherController',action:'anotherAction']"><button>Go</button></g:link></g:formremote>
</code>```

答: formRemote as well as linkRemote are deprecated in Grails 3.1. You should use proper Ajax-functions from your favorite JS library instead.

Body:
this is the code for ajax request to the controller i already tried.

<g:formRemote onComplete="onComplete()" update="addBlock" autocomplete="off" url="[controller: 'someContoller', action:'someAction']">

this is the link inside the form remote and it is not working.

<g:link url="[controller:'anotherController',action:'anotherAction']"><button>Go</button></g:link></g:formremote>


答:
If you need the Series_Date values to be in order:

```<code>top_dict = {
    raw: pd.melt(
        pd.DataFrame(top_dict[raw]),
        id_vars='Series_Date']
    ).sort_values('Series_Date').to_dict('list')
    for raw in top_dict
}
</code>```

Otherwise ommitting the sort_values() above would do.

Title: Rearranging elements inside a superset of dictionaries

Body:
I have a dictionary in Python that comprises of multiple individual dicts:

raw1 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,-3.4],'3M':[24,-31,53,5]}
raw2 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[-7.8,56,56,5.4],'3M':[24,-31,53,5]}
raw3 = {'Series_Date':['2017-03-10','2017-03-13','2017-03-14','2017-03-15'],'SP':[35.6,56.7,41,41],'1M':[9.8,56,56,7.4],'3M':[24,-31,53,5]}
top_dict = {
  'raw1': raw1,
  'raw2': raw2,
  'raw3': raw3
  }
print top_dict

I would like to flip the columns and rows in the individual dictionaries in my top_dict in such a manner that all the value fields get transposed to the Value Column and the date is appended as a row item.

As an example raw_1 in my top_dict after the flipping will look like this:

 raw_1 = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13','2017-03-14','2017-03-14','2017-03-14','2017-03-15','2017-03-15','2017-03-15'],'Value':[35.6,-7.8,24,56.7,56,-31,41,56,53,41,-3.4,5],'Desc':['SP','1M','3M','SP','1M','3M','SP','1M','3M','SP','1M','3M']}

I know I can use pandas melt on each individual dict but how to iterate that over the entire dictionary of top_dict?

Body:
If you need the Series_Date values to be in order:

top_dict = {
    raw: pd.melt(
        pd.DataFrame(top_dict[raw]),
        id_vars='Series_Date']
    ).sort_values('Series_Date').to_dict('list')
    for raw in top_dict
}

Otherwise ommitting the sort_values() above would do.


问:
Android: problem in getText method of EditText
In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.

In the first class I wrote this code but it seems has problem.

```<code>public String getTextMessage()
{
    return textMessage.getText().toString();
}
</code>```

because in second class when I want to get it, program crashes.

```<code>message = encode.getTextMessage();
</code>```

What is your suggestion?

答: You have to pass the value through intents</p>

Body:
In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.

In the first class I wrote this code but it seems has problem.

public String getTextMessage()
{
    return textMessage.getText().toString();
}

because in second class when I want to get it, program crashes.

message = encode.getTextMessage();

What is your suggestion?


答:
Your validate() function is asynchronous: it does not return anything when it's executed (quite literally, since it has no return instruction). Instead, it queries the database and does something when it's finished.

So in the main app, you can't just call validate() and expect to have a result; instead, you have to set it up so that when validate() finishes your app can go on. The classic way to do this is to use callbacks. Something like:

```<code>validate: function(callback) {
    ...
    if (error) {
        console.log("Admin reboot failed");
        callback(false);
    } else {
        console.log("Admin have been initialized");
        callback(true);
    }
    ...
}
</code>```

Your snippet in the main app could be something like:

```<code>AdminUser.validate(function afterValidation(isValid) {
    if (isValid) {
        app.listen(port, () => {
            console.log('Server started on port: ' + port);
        });
    } else {
        console.log('Fail to run Server');
        process.exit();
    }
});
</code>```

The basic idea is that you give your async function something to do after it's finished, by passing a callback function to execute.

Title: JS : exported Function fail to return True/False

Body:
Your validate() function is asynchronous: it does not return anything when it's executed (quite literally, since it has no return instruction). Instead, it queries the database and does something when it's finished.

So in the main app, you can't just call validate() and expect to have a result; instead, you have to set it up so that when validate() finishes your app can go on. The classic way to do this is to use callbacks. Something like:

validate: function(callback) {
    ...
    if (error) {
        console.log("Admin reboot failed");
        callback(false);
    } else {
        console.log("Admin have been initialized");
        callback(true);
    }
    ...
}

Your snippet in the main app could be something like:

AdminUser.validate(function afterValidation(isValid) {
    if (isValid) {
        app.listen(port, () => {
            console.log('Server started on port: ' + port);
        });
    } else {
        console.log('Fail to run Server');
        process.exit();
    }
});

The basic idea is that you give your async function something to do after it's finished, by passing a callback function to execute.


问:
Creating a table in SQL with column of unique entries
I have the following table:

```<code>Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)
</code>```

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

答:
You have created an unique constraint, that is what it is called.

It is however always better to name your indexes and constraints, also the primary key you can give a name. Look at below examples.

You can create an unique index for an existing table like this

```<code>CREATE UNIQUE NONCLUSTERED INDEX idx_Gebruikersnaam
ON dbo.Medewerker(Gebruikersnaam)
</code>```

in the table create it looks like this

```<code>Create table [dbo].[Medewerker]
(
    [Id] int IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,

    constraint PK_MedewerkerId primary key (Id),
    constraint idx_Gebruikersnaam unique (Gebruikersnaam)
)
</code>```

Also I would use nvarchar in stead of varchar.

Body:
I have the following table:

Create table [dbo].[Medewerker]
(
    [Id] int PRIMARY KEY IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) UNIQUE NOT NULL
)

I'm trying to make it so that the bottom line makes it so that each entry in the "Gebruikersnaam" column is unique. Is what I did right? What do you call this type of feature?

Body:
You have created an unique constraint, that is what it is called.

It is however always better to name your indexes and constraints, also the primary key you can give a name. Look at below examples.

You can create an unique index for an existing table like this

CREATE UNIQUE NONCLUSTERED INDEX idx_Gebruikersnaam
ON dbo.Medewerker(Gebruikersnaam)

in the table create it looks like this

Create table [dbo].[Medewerker]
(
    [Id] int IDENTITY 91,1 NOT NULL,
    [Wachtwoord] varchar(50) NOT NULL,
    [Rechten] varchar(100) NOT NULL,
    [Gebruikersnaam] varchar(30) NOT NULL,

    constraint PK_MedewerkerId primary key (Id),
    constraint idx_Gebruikersnaam unique (Gebruikersnaam)
)

Also I would use nvarchar in stead of varchar.


问:
How to test a local bot?
I developed a simple bot on my machine (http://localhost:3978). I would like to embed a custom chat client in my web site using direct line API. Is there a way I can test this without deploying my bot to an Azure website ? I would like to be able to debug on my local machine (without having to do Azure remote debugging...).

I tried to register my bot with a localhost endpoint (http without basic auth and https) but it did not work...

答: by using the ngrock it create a fake url that redirect to your machine.</p>

Title: How to test a local bot?


问:
Moving single message in RabbitMq
I have got several messages on error queue which has name TestQueue_errors.

One of the messages on error queue is important and should be moved back to service queue TestQueue so it can be processed again. The other messages on error queue are broken and should stay on error queue.

I have tried to do that with shovel plugin but it seems it is able only to move all messages from one queue to another. Is there a way I could achieve that, to move single message from one queue to another?

答:
As far as I know Rabbit Management does not allow to do it. The only thing you can do is to publish this message again.

Maybe there are some tools which give possibility to achieve it but it is not a standard behaviour.

Here are actions which you are able to perform on the queue (from RabbitMQ Management page):

Move all messages from one queue to another

Get all messages without requeue option (they would not be in the queue anymore)

Get first N messages without requeue option and then move the rest of messages to another queue

Title: Moving single message in RabbitMq


问:
Mutliple URL Segments to Index Function With CodeIgniter
Please excuse me if this is an incredibly stupid question, as I'm new to CodeIgniter.

I have a controller for my verification system called Verify. I'd like to be able to use it something like site.com/verify/123/abcd, but I only want to use the index function, so both URL segments need to go to it.

I'm sure this can be done with URL routing somehow, but I can't figure out how to pass both URL segments into Verify's index function..

答: You will either need to edit the routes or write an htaccess rule, however i didn't understand why you want to limit to just the index function.</p>


问:
Mark location of all companies on map
I want to mark the location(longitude and latitude) of all companies listed as posts in wordpress on a map just like http://finntakst.no/ have done it.
I have been trying it since 5 hours</p>

答:
You can use plugin to achieve it

Try intergeo map plugin, here is a link to download it https://wordpress.org/plugins/intergeo-maps/

Simply activate the plugin and you can do it easily

Title: Mark location of all companies on map


问:
Git: How to check if a local repo is up to date?
I would like to know if my local repo is up to date (and if not, ideally, I would like to see the changes).

How could I check this without doing git fetch or git pull ?

答:
```<code>git remote show origin
</code>```

Result:

```<code>HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (local out of date) <-------
</code>```

Body:
git remote show origin

Result:

HEAD branch: master
  Remote branch:
    master tracked
  Local branch configured for 'git pull':
    master merges with remote master
  Local ref configured for 'git push':
    master pushes to master (local out of date) <-------


问:
to MSMQ or not to MSMQ? (or SQL Table as the Queue)
I've got a distributed system where there will be 1 SQL Server, 1-n processing servers, and 1-n data suppliers (hardware devices across the network).  The data being supplied will require processing prior to going into the relational DB structure - performed by the processing servers (as windows services - .net code to parse the data, process it, and insert it into the relational structure.)

To handle the potential load and not slow down the data suppliers, I want to implement a queue, but I'm not sure I want to add the complexity of an MSMQ server to the mix.  Is there a good alternative to MSMQ, such as using the DB (a flat table) as the queue?  Does .NET provide any out-of-the-box support for DB queues, or is there another option for reliable queueing?

Thanks

EDIT: (29 Nov, 11:30pm)

sounds like SQL Service Broker (SSB) might do the trick.

http://www.netframeworkdev.com/windows-communication-foundation/service-broker-vs-msmq-as-reliable-queueing-mechanism-63981.shtml

EDIT: (30 Nov, 7:45am)

Found another very useful link on this subject:

http://social.msdn.microsoft.com/Forums/en-US/sqlservicebroker/thread/52687510-0852-44f3-bfcd-83610d1c1b9a

I'm also looking into the max/min size of the data that will be supplied.  Of the top of their head, does anyone know the max size accommodated by MSMQ and/or SSB?

MSMQ: 4MB message size

SSB: 2GB message size

EDIT: (30 nov, 8;15am)

Great comparison between MSMQ & SSB here:

Good Strategy for Message Queuing?

答: I would use MSMQ, it doesnt add that much complexity, and it is so easy to backup the messages, so processing can continue even after a system restart. You could use something like SSB.</p>


问:
How to convert a string into condition in the IF statement
Let say I have a string stored in the $condition variable:

```<code>$condition = '2 == 2'; // returns TRUE
</code>```

or

```<code>$condition = 'my_own_function()'; // which also returns TRUE
</code>```

How can I convert them into a condition in an IF statement? Say:

```<code>if (some_magic_converter_function($condition)){
    // execute something
}
</code>```

it will be the same as if I execute

```<code>if (my_own_function()){
    // execute something
}
</code>```

Is there any other ways I can safely evaluate the string into a condition of an IF statement? How?

答:
The basic rule of thumb: If you need to use eval(), you're doing something very very wrong.

But for entertainment purposes:

```<code>$condition = "return 2==2;";
$test = eval($condition);
if ($test) {
    echo 'Oh Noes';
}

function my_own_function()
{
    return true;
}
$condition = 'return my_own_function();';
$test = eval($condition);
if ($test) {
    echo "More Noes";
}
</code>```

Body:
Let say I have a string stored in the $condition variable:

$condition = '2 == 2'; // returns TRUE

or

$condition = 'my_own_function()'; // which also returns TRUE

How can I convert them into a condition in an IF statement? Say:

if (some_magic_converter_function($condition)){
    // execute something
}

it will be the same as if I execute

if (my_own_function()){
    // execute something
}

Is there any other ways I can safely evaluate the string into a condition of an IF statement? How?

Body:
The basic rule of thumb: If you need to use eval(), you're doing something very very wrong.

But for entertainment purposes:

$condition = "return 2==2;";
$test = eval($condition);
if ($test) {
    echo 'Oh Noes';
}

function my_own_function()
{
    return true;
}
$condition = 'return my_own_function();';
$test = eval($condition);
if ($test) {
    echo "More Noes";
}


问:
C# Stack Array, Push method pushes the value to ALL entries
I create a stack array and initialize the first element like this:

```<code>Stack[] snowmen = new Stack[numberOfOperations+1];
snowmen[0] = new Stack();
</code>```

I then iterate through the array and want to perform 2 things:

Copy the stack from a specific index to the i-th position of the array

Push/Pop an integer from the new i-th stack

code for that:

```<code>for(int i = 1; i <= numberOfOperations; i++)
{
    . . .

    else if (addSnowball == 0)
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Pop();
    }
    else
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Push(addSnowball);
    }

    . . .
}
</code>```

If I call the push or pop method now, EVERY stack in my array will be changed, not only the i-th stack, which may tell me that my copies all refer to the same storage location. Am I right, what am I making wrong, what can I do?

答:
If other people may have the same problem, I want to add something:

if you do it like the answer of the question:

```<code>snowmen[i] = new Stack(snowmen[copySnowmanNr]);
</code>```

the items of the new stack are reversed, I have just found out that I can fix that with:

```<code>snowmen[i] = (Stack)snowmen[copySnowmanNr].Clone();
</code>```

I don't know exactly why I have to typcast it with Stack, if not there will be an error, I think it has something to do with the items of a stack which are of the 'Object' type.

ContentLicense: CC BY-SA 4.0

Body:
I create a stack array and initialize the first element like this:

Stack[] snowmen = new Stack[numberOfOperations+1];
snowmen[0] = new Stack();

I then iterate through the array and want to perform 2 things:

Copy the stack from a specific index to the i-th position of the array

Push/Pop an integer from the new i-th stack

code for that:

for(int i = 1; i <= numberOfOperations; i++)
{
    . . .

    else if (addSnowball == 0)
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Pop();
    }
    else
    {
        snowmen[i] = new Stack();
        snowmen[i] = snowmen[copySnowmanNr];
        snowmen[i].Push(addSnowball);
    }

    . . .
}

If I call the push or pop method now, EVERY stack in my array will be changed, not only the i-th stack, which may tell me that my copies all refer to the same storage location. Am I right, what am I making wrong, what can I do?

Body:
If other people may have the same problem, I want to add something:

if you do it like the answer of the question:

snowmen[i] = new Stack(snowmen[copySnowmanNr]);

the items of the new stack are reversed, I have just found out that I can fix that with:

snowmen[i] = (Stack)snowmen[copySnowmanNr].Clone();

I don't know exactly why I have to typcast it with Stack, if not there will be an error, I think it has something to do with the items of a stack which are of the 'Object' type.


问:
How to allow only one edit at time using Angular js inline editing
Hello I am using Angular js and creating one application with table inline editing using this demo jsfiddle.

Here if you see you can edit multiple row at a time but I just want to allow one row edit at a time.

How I can stop the user to edit other row if any one row is already in edit mode?

答: You can keep one Scope variable isBeingEdited. Set it to true in editAppKey and false in saveField. In editAppKey only do operation if isBeingEdited is false</p>


问:
WPF Prism initializing tabs with ICollection using Navigation
I have a tab view model, it works by when you create a new tab, it generates a new instance of Class B.

However, there is the possibility that the program can load a file which, using JSON, gets an instance of Class A which has a collection of Class B.

How can I instantiate the tabs with the existing collection of Class B Object? Preferably still using Navigation instead of View Injection/Discovery.

Here is my code for adding a new tab

```<code>   public void AddTabCommandAction()
   {
    _regionManager.RequestNavigate(RegionNames.TabRegion, "ClassBView");
   }
</code>```

And my class B viewmodel.

```<code>   public ClassBViewModel(ClassB b){
     _b = b;
   }
</code>```

I am using UnityContainer to resolve types of ClassB.

答:
Probably not the best solution but I solved the issue by using the Navigation journal.

The on navigated to method in the tabs view model

```<code> foreach (var item in list)
        {
            AddTabCommandAction(item);
        }
</code>```

Passing in the item as a naviagaion parameter

OnNavigatedTo method of the tab view model

```<code>   var classB= navigationContext.Parameters["ClassB"];
        if (classB!= null)
            _classB= (ClassB) classB;
</code>```

Body:
I have a tab view model, it works by when you create a new tab, it generates a new instance of Class B.

However, there is the possibility that the program can load a file which, using JSON, gets an instance of Class A which has a collection of Class B.

How can I instantiate the tabs with the existing collection of Class B Object? Preferably still using Navigation instead of View Injection/Discovery.

Here is my code for adding a new tab

   public void AddTabCommandAction()
   {
    _regionManager.RequestNavigate(RegionNames.TabRegion, "ClassBView");
   }

And my class B viewmodel.

   public ClassBViewModel(ClassB b){
     _b = b;
   }

I am using UnityContainer to resolve types of ClassB.

Body:
Probably not the best solution but I solved the issue by using the Navigation journal.

The on navigated to method in the tabs view model

 foreach (var item in list)
        {
            AddTabCommandAction(item);
        }

Passing in the item as a naviagaion parameter

OnNavigatedTo method of the tab view model

   var classB= navigationContext.Parameters["ClassB"];
        if (classB!= null)
            _classB= (ClassB) classB;


问:
Android Sending Email
I Wrote This Code To Send An Email But Give Me " No App Can Perform This action " Error ?!! Can Any One Help Me .!

```<code>public class MainActivity extends Activity {
Button startBtn;
Intent chooser = null , emailIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    startBtn = (Button) findViewById(R.id.sendEmail);
    startBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendEmail();
        }
    });
}
</code>```

protected void sendEmail()

```<code>    {
        String[] TO = {"a.gadelkareem94@gmail.com"};
        emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Thanks For Your Job");
        emailIntent.setType("message/rfc822");
        emailIntent.setPackage("com.Gmail");
        chooser = Intent.createChooser(emailIntent, "Send Email");
        startActivity(chooser);
    }
</code>```

}

but no emails Send

答:
You should use intent.setType("text/plain");

We can use "message/rfc822" instead of "text/plain" as the MIME type. However, that is not indicating "only offer email clients" -- it indicates "offer anything that supports message/rfc822 data". That could readily include some application that are not email clients.

message/rfc822 supports MIME Types of .mhtml, .mht, .mime

as alredy answered here: Send Email Intent

Title: Android Sending Email

Body:
I Wrote This Code To Send An Email But Give Me " No App Can Perform This action " Error ?!! Can Any One Help Me .!

public class MainActivity extends Activity {
Button startBtn;
Intent chooser = null , emailIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    startBtn = (Button) findViewById(R.id.sendEmail);
    startBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendEmail();
        }
    });
}

protected void sendEmail()

    {
        String[] TO = {"a.gadelkareem94@gmail.com"};
        emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Thanks For Your Job");
        emailIntent.setType("message/rfc822");
        emailIntent.setPackage("com.Gmail");
        chooser = Intent.createChooser(emailIntent, "Send Email");
        startActivity(chooser);
    }

}

but no emails Send


问:
JMS connection kills websocket
I have a website which opens a websocket and displays a message sent from the server in an alert. However, as soon as I create a JMS connection, the websocket won't connect anymore. The app runs on glassfish 4. This is the code:

wstest.xhtml:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
  <h:head>
    <title>TODO supply a title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <h:outputScript name="websocket.js" library="js" target="head"/>
  </h:head>
  <h:body>
    TODO
  </h:body>
</html>
</code>```

websocket.js:

```<code>var host = 'ws://localhost:8095/path';
var websocket = new WebSocket(host);

websocket.onopen = function () {
  alert('Websocket open!');
};

websocket.onmessage = function (event) {
  alert(event.data);
};
</code>```

WebsocketEndpoint.java:

```<code>@ServerEndpoint("/path")
public class WebsocketEndpoint {

  private WebsocketChat chat = new WebsocketChat();

  @OnOpen
  public void onOpen(Session session) {
    System.out.println("Session opened");
    session.getAsyncRemote().sendText("Hello Javascript");
  }
}
</code>```

WebsocketChat.java:

```<code>public class WebsocketChat {

  @Resource(mappedName="jms/ConnectionFactory")
  private ConnectionFactory connectionFactory;

  public WebsocketChat() {
    //init();
  }

  public final void init() {
    try {
      Connection con = connectionFactory.createConnection();
    } catch (JMSException ex) {
      Logger.getLogger(WebsocketChat.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}
</code>```

Note that the call to the init method in the constructor of WebsocketChat is commented. This way I can see both javascript alerts: 'Websocket open!' when the websocket is opened, and 'Hello Javascript', which comes from server. The message "Session opened" is also visible in the glassfish output.

However, when I uncomment the init method in the WebsocketChat constructor, I can still see the 'Websocket opened' alert, but the 'Hello Javascript' alert will not be displayed. The "Session opened" message also vanished from the glassfish output. The init method is responsible for creating the JMS connection.

答:
I expect that your init() method is throwing NullPointerException because connectionFactory will not have been initialised:

```<code>public class WebsocketChat {

    @Resource(mappedName="jms/ConnectionFactory")
    private ConnectionFactory connectionFactory;

    public WebsocketChat() {
        // You can't access the connectionFactory here because the container cannot
        // inject it before the the object is created.
        // The object will not be created until this constructor has completed
        // executing.
    }

    /* The container will call this after the object is created */
    @PostConstruct
    public final void init() {
        try {
            try (Connection con = connectionFactory.createConnection()) {
                // do something with the connection...
            }
        } catch (JMSException ex) {
            Logger.getLogger(WebsocketChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Updated WebsocketEndpoint:

```<code>@ServerEndpoint("/path")
public class WebsocketEndpoint {

    /*
     * You need to inject this. The container will create and initialise it for you.
     */
    @Inject
    private WebsocketChat chat;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Session opened");
        session.getAsyncRemote().sendText("Hello Javascript");
    }
}
</code>```

FWIW, the above code works for me in WildFly 10.1 with one change:

```<code>    @Resource(lookup="java:/ConnectionFactory")
    private ConnectionFactory connectionFactory;
</code>```

which happens to be the default ConnectionFactory in WildFly.

Also, your JavaScript probably needs to include the webapp context in it's web socket URL:

```<code> var host = 'ws://localhost:8095/<webapp-context>/path';
</code>```

The code above also works in GlassFish 4.1.1 with the following change:

```<code>    @Resource(name="java:comp/DefaultJMSConnectionFactory")
    private ConnectionFactory connectionFactory;
</code>```

Title: JMS connection kills websocket

Body:
I have a website which opens a websocket and displays a message sent from the server in an alert. However, as soon as I create a JMS connection, the websocket won't connect anymore. The app runs on glassfish 4. This is the code:

wstest.xhtml:

<!DOCTYPE html>

  <h:head>
    <title>TODO supply a title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <h:outputScript name="websocket.js" library="js" target="head"/>
  </h:head>
  <h:body>
    TODO
  </h:body>

websocket.js:

var host = 'ws://localhost:8095/path';
var websocket = new WebSocket(host);

websocket.onopen = function () {
  alert('Websocket open!');
};

websocket.onmessage = function (event) {
  alert(event.data);
};

WebsocketEndpoint.java:

@ServerEndpoint("/path")
public class WebsocketEndpoint {

  private WebsocketChat chat = new WebsocketChat();

  @OnOpen
  public void onOpen(Session session) {
    System.out.println("Session opened");
    session.getAsyncRemote().sendText("Hello Javascript");
  }
}

WebsocketChat.java:

public class WebsocketChat {

  @Resource(mappedName="jms/ConnectionFactory")
  private ConnectionFactory connectionFactory;

  public WebsocketChat() {
    //init();
  }

  public final void init() {
    try {
      Connection con = connectionFactory.createConnection();
    } catch (JMSException ex) {
      Logger.getLogger(WebsocketChat.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

Note that the call to the init method in the constructor of WebsocketChat is commented. This way I can see both javascript alerts: 'Websocket open!' when the websocket is opened, and 'Hello Javascript', which comes from server. The message "Session opened" is also visible in the glassfish output.

However, when I uncomment the init method in the WebsocketChat constructor, I can still see the 'Websocket opened' alert, but the 'Hello Javascript' alert will not be displayed. The "Session opened" message also vanished from the glassfish output. The init method is responsible for creating the JMS connection.

Body:
I expect that your init() method is throwing NullPointerException because connectionFactory will not have been initialised:

public class WebsocketChat {

    @Resource(mappedName="jms/ConnectionFactory")
    private ConnectionFactory connectionFactory;

    public WebsocketChat() {
        // You can't access the connectionFactory here because the container cannot
        // inject it before the the object is created.
        // The object will not be created until this constructor has completed
        // executing.
    }

    /* The container will call this after the object is created */
    @PostConstruct
    public final void init() {
        try {
            try (Connection con = connectionFactory.createConnection()) {
                // do something with the connection...
            }
        } catch (JMSException ex) {
            Logger.getLogger(WebsocketChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

Updated WebsocketEndpoint:

@ServerEndpoint("/path")
public class WebsocketEndpoint {

    /*
     * You need to inject this. The container will create and initialise it for you.
     */
    @Inject
    private WebsocketChat chat;

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Session opened");
        session.getAsyncRemote().sendText("Hello Javascript");
    }
}

FWIW, the above code works for me in WildFly 10.1 with one change:

    @Resource(lookup="java:/ConnectionFactory")
    private ConnectionFactory connectionFactory;

which happens to be the default ConnectionFactory in WildFly.

Also, your JavaScript probably needs to include the webapp context in it's web socket URL:

 var host = 'ws://localhost:8095/<webapp-context>/path';

The code above also works in GlassFish 4.1.1 with the following change:

    @Resource(name="java:comp/DefaultJMSConnectionFactory")
    private ConnectionFactory connectionFactory;


问:
NAudio decode stream of bytes
Hi
I am using the NAudio library at http://naudio.codeplex.com/

I have this hardware made by some manufacturer which claims to send
audio with the following characteristics.

aLaw 8khz, AUD:11,0,3336,0

Not sure what it all  means at this stage.

I received bunch of bytes from this device when a user speaks into the
equipment.
Hence I am constantly recieving a stream of bytes at particular times

At this stage I have been unable to decode the audio so I can hear
what is spoken into the device with my headphones.

I have tried writing the audio to a file doing code like

FWaveFileWriter = new WaveFileWriter("C:\Test4.wav",
WaveFormat.CreateALawFormat(8000, 1));

And have been unable to playback the sound using the sample demo apps.

I have tried similar code from

http://naudio.codeplex.com/Thread/View.aspx?ThreadId=231245 and
http://naudio.codeplex.com/Thread/View.aspx?ThreadId=83270

and still have not been able to achieve much.

Any information is appreciated.
Thanks
Allen

答:
If you are definitely receiving raw a-law audio (mono 8kHz) then your code to create a WAV file should work correctly and result in a file that can play in Windows Media Player. </p>

<p>I suspect that maybe your incoming byte stream is wrapped in some other kind of protocol. I'm afraid I don't know what "AUD:11,0,3336,0" means, but that might be a place to start investigating. Do you hear anything intelligible at all when you play back the file? </p>

Title: NAudio decode stream of bytes

Body:
If you are definitely receiving raw a-law audio (mono 8kHz) then your code to create a WAV file should work correctly and result in a file that can play in Windows Media Player.

I suspect that maybe your incoming byte stream is wrapped in some other kind of protocol. I'm afraid I don't know what "AUD:11,0,3336,0" means, but that might be a place to start investigating. Do you hear anything intelligible at all when you play back the file?


问:
Gitlab runner + autoscaling + scaled runner options
I'm using gitlab runner with docker+machine executor to fire up autoscaled runners on AWS. I would like to use docker-in-docker setup inside the runners to build containers, but I can't find out how to define the needed [runners.docker] properties for the spawned runners to enable docker usage.

Is it possible to somehow pass some config info to autoscaled runners?

答:
you just need this in your config.toml of your autoscale runner:

```<code>[runners.docker]
  privileged = true
</code>```

I use docker-in-docker to build my own php containers for testing and store them in gitlabs registry. see https://gitlab.cwd.at/docker/php/builds/21582 for a build example and https://gitlab.cwd.at/docker/php/blob/master/.gitlab-ci.yml for the build definition

see here my current config - its using S3 for caching and digitalocean for the runners:

```<code>concurrent = 10

[[runners]]
  name = "ec2-autoscale-runner"
  url = "https://gitlab.mydomain.at/ci"
  token = "12345"
  executor = "docker+machine"
  limit = 10
  environment = ["COMPOSER_CACHE_DIR=/cache"]
  [runners.machine]
    OffPeakPeriods = [               # Set the Off Peak time mode on for:
      "* * 0-9,18-23 * * mon-fri *", # - Monday to Friday for 12am to 9am and 6pm to 11pm
      "* * * * * sat,sun *"          # - whole Saturday and Sunday
    ]
    OffPeakIdleCount = 0             # There must be 1 machine in Idle state - when Off Peak time mode is on
    OffPeakIdleTime = 3550           # Each machine can be in Idle state up to 1200 seconds (after this it will be removed) - when Off Peak time mode is on
    IdleCount = 0                    # There must be 5 machines in Idle state - when Off Peak time mode is off
    IdleTime = 3550                  # Each machine can be in Idle state up to 600 seconds (after this it will be removed) - when Off Peak time mode is off
    MaxBuilds = 100                    # Each machine can handle up to 100 builds in a row (after this it will be removed)
    MachineName = "auto-scale-%s"    # Each machine will have a unique name ('%s' is required)
    MachineDriver = "digitalocean"   # Docker Machine is using the 'digitalocean' driver
    MachineOptions = [
        "digitalocean-image=21937863",
        #"digitalocean-image=20969606",
        "digitalocean-access-token=12345",
        "digitalocean-region=fra1",
        "digitalocean-size=4gb",
        "digitalocean-private-networking",
        "digitalocean-ipv6=true"
    ]
  [runners.ssh]
    user = "root"
    identity_file = "/etc/gitlab-runner/id_rsa"
  [runners.docker]
    privileged = true
  [runners.cache]
    Type = "s3"
    ServerAddress = "s3.amazonaws.com"
    AccessKey = "1234"
    SecretKey = "1234"
    BucketName = "cwd-gitlab-cache"
    BucketLocation = "eu-central-1"
    Insecure = false
</code>```

Body:
you just need this in your config.toml of your autoscale runner:

[runners.docker]
  privileged = true

I use docker-in-docker to build my own php containers for testing and store them in gitlabs registry. see https://gitlab.cwd.at/docker/php/builds/21582 for a build example and https://gitlab.cwd.at/docker/php/blob/master/.gitlab-ci.yml for the build definition

see here my current config - its using S3 for caching and digitalocean for the runners:

concurrent = 10

[[runners]]
  name = "ec2-autoscale-runner"
  url = "https://gitlab.mydomain.at/ci"
  token = "12345"
  executor = "docker+machine"
  limit = 10
  environment = ["COMPOSER_CACHE_DIR=/cache"]
  [runners.machine]
    OffPeakPeriods = [               # Set the Off Peak time mode on for:
      "* * 0-9,18-23 * * mon-fri *", # - Monday to Friday for 12am to 9am and 6pm to 11pm
      "* * * * * sat,sun *"          # - whole Saturday and Sunday
    ]
    OffPeakIdleCount = 0             # There must be 1 machine in Idle state - when Off Peak time mode is on
    OffPeakIdleTime = 3550           # Each machine can be in Idle state up to 1200 seconds (after this it will be removed) - when Off Peak time mode is on
    IdleCount = 0                    # There must be 5 machines in Idle state - when Off Peak time mode is off
    IdleTime = 3550                  # Each machine can be in Idle state up to 600 seconds (after this it will be removed) - when Off Peak time mode is off
    MaxBuilds = 100                    # Each machine can handle up to 100 builds in a row (after this it will be removed)
    MachineName = "auto-scale-%s"    # Each machine will have a unique name ('%s' is required)
    MachineDriver = "digitalocean"   # Docker Machine is using the 'digitalocean' driver
    MachineOptions = [
        "digitalocean-image=21937863",
        #"digitalocean-image=20969606",
        "digitalocean-access-token=12345",
        "digitalocean-region=fra1",
        "digitalocean-size=4gb",
        "digitalocean-private-networking",
        "digitalocean-ipv6=true"
    ]
  [runners.ssh]
    user = "root"
    identity_file = "/etc/gitlab-runner/id_rsa"
  [runners.docker]
    privileged = true
  [runners.cache]
    Type = "s3"
    ServerAddress = "s3.amazonaws.com"
    AccessKey = "1234"
    SecretKey = "1234"
    BucketName = "cwd-gitlab-cache"
    BucketLocation = "eu-central-1"
    Insecure = false


问:
Workaround for Fragment URLs not allowed with Google Redirect URI
I use mac to develop a MEAN stack project. My web pages https://localhost:3000/#/login and https://localhost:3000/#/new work (note that all my pages need to have /#/ in the middle to work). https://localhost:3000/#/new has a button that leads to a google login by passportjs. In my routes ==> index.js I set

```<code>var express = require('express');
var router = express.Router();
... ...

router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
  passport.authenticate('google', { successRedirect: '/login',
                                    failureRedirect: '/login' }));
</code>```

In Google APIs ==> Credentials, when I set https://localhost:3000/auth/google/callback as Authorized redirect URIs. Clicking on the login button on my page returns an error

```<code>Error: redirect_uri_mismatch

The redirect URI in the request, https://localhost:3000/auth/facebook/callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/367100934152-7csfhcdnkapil4obku1pr2cnrsmthk61.apps.googleusercontent.com?project=367100934152 to update the authorized redirect URIs.
</code>```

I guess it is because https://localhost:3000/auth/facebook/callback is not a valid URI for my app, but if I set https://localhost:3000/#/auth/facebook/callback in the setting page, it is NOT allowed: Invalid Redirect: https://localhost:3000/#/auth/google/callback cannot contain a fragment.

So, does anyone know if I could modify my app to work without #, so that https://localhost:3000/login and https://localhost:3000/new, etc. will work? As a result, https://localhost:3000/auth/facebook/callback will be a valid URI too...

Edit 1:

Following the answer of @Sevran and the doc how to configure your server to work with html5mode, I did the following:

1) added $locationProvider.html5Mode(true) in app.config

2) added <base href="/" /> in index.ejs (note I don't have index.html in the project)

3) keeps .state('new', url: '/new', ... in app.config

4) did NOTHING in httpd-vhosts.conf, which has <VirtualHost *:80> and <VirtualHost *:433>, because I think my server is controlled by express.js rather than httpd-vhosts.conf, and the port is 3000.

5) did NOT add .htaccess in the project like this answer

6) added in app.js the following, I also tried to change index.html to index.ejs.

```<code>app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});
</code>```

The tests shows

entering https://localhost:3000/#/new in the URL bar becomes https://localhost:3000/new, and it loads the corresponding page.

entering https://localhost:3000/new in the URL bar raises a not found 404 error.

entering https://localhost:3000/auth/google in the URL bar raises the Error: redirect_uri_mismatch as above.

To conclude, I think the rewriting (of a url without #) should be managed by express, but the code I posted did not do the job. Regarding .htaccess, I tried also to put it in the DocumentRoot of httpd-vhosts.conf or the root folder of the project, it did not help.

答:
The changes you have to make:

1) Angular Side: as you already changed

```<code>$locationProvider.html5Mode(true) in app.config

added <base href="/" /> in index.ejs

keeps .state('new', url: '/new', ... in app.config
</code>```

2) hta access

```<code>RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]
</code>```

3) This change you need from server side,

If using apache:

```<code><VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>
</code>```

In the above my-app will be the application name. and DocumentRoot and Directory paths should be complete path to your application root

For Express:

```<code>var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use
</code>```

Here is the Documentation regarding it

Body:
I use mac to develop a MEAN stack project. My web pages https://localhost:3000/#/login and https://localhost:3000/#/new work (note that all my pages need to have /#/ in the middle to work). https://localhost:3000/#/new has a button that leads to a google login by passportjs. In my routes ==> index.js I set

var express = require('express');
var router = express.Router();
... ...

router.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/auth/google/callback',
  passport.authenticate('google', { successRedirect: '/login',
                                    failureRedirect: '/login' }));

In Google APIs ==> Credentials, when I set https://localhost:3000/auth/google/callback as Authorized redirect URIs. Clicking on the login button on my page returns an error

Error: redirect_uri_mismatch

The redirect URI in the request, https://localhost:3000/auth/facebook/callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/367100934152-7csfhcdnkapil4obku1pr2cnrsmthk61.apps.googleusercontent.com?project=367100934152 to update the authorized redirect URIs.

I guess it is because https://localhost:3000/auth/facebook/callback is not a valid URI for my app, but if I set https://localhost:3000/#/auth/facebook/callback in the setting page, it is NOT allowed: Invalid Redirect: https://localhost:3000/#/auth/google/callback cannot contain a fragment.

So, does anyone know if I could modify my app to work without #, so that https://localhost:3000/login and https://localhost:3000/new, etc. will work? As a result, https://localhost:3000/auth/facebook/callback will be a valid URI too...

Edit 1:

Following the answer of @Sevran and the doc how to configure your server to work with html5mode, I did the following:

1) added $locationProvider.html5Mode(true) in app.config

2) added <base href="/" /> in index.ejs (note I don't have index.html in the project)

3) keeps .state('new', url: '/new', ... in app.config

4) did NOTHING in httpd-vhosts.conf, which has <VirtualHost *:80> and <VirtualHost *:433>, because I think my server is controlled by express.js rather than httpd-vhosts.conf, and the port is 3000.

5) did NOT add .htaccess in the project like this answer

6) added in app.js the following, I also tried to change index.html to index.ejs.

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

The tests shows

entering https://localhost:3000/#/new in the URL bar becomes https://localhost:3000/new, and it loads the corresponding page.

entering https://localhost:3000/new in the URL bar raises a not found 404 error.

entering https://localhost:3000/auth/google in the URL bar raises the Error: redirect_uri_mismatch as above.

To conclude, I think the rewriting (of a url without #) should be managed by express, but the code I posted did not do the job. Regarding .htaccess, I tried also to put it in the DocumentRoot of httpd-vhosts.conf or the root folder of the project, it did not help.

Body:
The changes you have to make:

1) Angular Side: as you already changed

$locationProvider.html5Mode(true) in app.config

added <base href="/" /> in index.ejs

keeps .state('new', url: '/new', ... in app.config

2) hta access

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

3) This change you need from server side,

If using apache:

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

In the above my-app will be the application name. and DocumentRoot and Directory paths should be complete path to your application root

For Express:

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use

Here is the Documentation regarding it


问:
Change Chromecast casting icon color
I'm using Google's method to add a Cast button to my app, but it's defaulted to the white icon, which is invisible against my white menu bar. How do I go about changing the color of the Cast icon to black?</p>

答:
I've just extended MediaRouteActionProvider like this:

```<code>    public class ThemeableMediaRouteActionProvider extends MediaRouteActionProvider {
    public ThemeableMediaRouteActionProvider(Context context) {
        super(context);
    }

    @Override
    public MediaRouteButton onCreateMediaRouteButton() {
        MediaRouteButton button = super.onCreateMediaRouteButton();
        colorWorkaroundForCastIcon(button);
        return button;
    }

    @Nullable
    @Override
    public MediaRouteButton getMediaRouteButton() {
        MediaRouteButton button = super.getMediaRouteButton();
        colorWorkaroundForCastIcon(button);
        return button;
    }

    private void colorWorkaroundForCastIcon(MediaRouteButton button) {
        if (button == null) return;
        Context castContext = new ContextThemeWrapper(getContext(), androidx.mediarouter.R.style.Theme_MediaRouter);

        TypedArray a = castContext.obtainStyledAttributes(null, androidx.mediarouter.R.styleable.MediaRouteButton, androidx.mediarouter.R.attr.mediaRouteButtonStyle, 0);
        Drawable drawable = a.getDrawable(androidx.mediarouter.R.styleable.MediaRouteButton_externalRouteEnabledDrawable);
        a.recycle();
        DrawableCompat.setTint(drawable, getContext().getResources().getColor(R.color.primary));
        drawable.setState(button.getDrawableState());
        button.setRemoteIndicatorDrawable(drawable);
    }
}
</code>```

R.color.primary is what color i wanted.

then just replace actionProviderClass in menu from MediaRouteActionProvider to your like that:

```<code><item
    android:id="@+id/media_route_menu_item"
    android:title="@string/media_route_menu_title"
    bwq:actionProviderClass="tv.test.playback.chromecast.ThemeableMediaRouteActionProvider"
    bwq:showAsAction="always">
</item>
</code>```

Title: Change Chromecast casting icon color

Body:
I've just extended MediaRouteActionProvider like this:

    public class ThemeableMediaRouteActionProvider extends MediaRouteActionProvider {
    public ThemeableMediaRouteActionProvider(Context context) {
        super(context);
    }

    @Override
    public MediaRouteButton onCreateMediaRouteButton() {
        MediaRouteButton button = super.onCreateMediaRouteButton();
        colorWorkaroundForCastIcon(button);
        return button;
    }

    @Nullable
    @Override
    public MediaRouteButton getMediaRouteButton() {
        MediaRouteButton button = super.getMediaRouteButton();
        colorWorkaroundForCastIcon(button);
        return button;
    }

    private void colorWorkaroundForCastIcon(MediaRouteButton button) {
        if (button == null) return;
        Context castContext = new ContextThemeWrapper(getContext(), androidx.mediarouter.R.style.Theme_MediaRouter);

        TypedArray a = castContext.obtainStyledAttributes(null, androidx.mediarouter.R.styleable.MediaRouteButton, androidx.mediarouter.R.attr.mediaRouteButtonStyle, 0);
        Drawable drawable = a.getDrawable(androidx.mediarouter.R.styleable.MediaRouteButton_externalRouteEnabledDrawable);
        a.recycle();
        DrawableCompat.setTint(drawable, getContext().getResources().getColor(R.color.primary));
        drawable.setState(button.getDrawableState());
        button.setRemoteIndicatorDrawable(drawable);
    }
}

R.color.primary is what color i wanted.

then just replace actionProviderClass in menu from MediaRouteActionProvider to your like that:

<item
    android:id="@+id/media_route_menu_item"
    android:title="@string/media_route_menu_title"
    bwq:actionProviderClass="tv.test.playback.chromecast.ThemeableMediaRouteActionProvider"
    bwq:showAsAction="always">
</item>


答:
Using base plot you could just pass a vector to the pos argument:

```<code>for (i in 1:2) {
    BP <- barplot(HOLD[,i], main=M[[i]], ylab="%", ylim=c(-1, 1), col=SEQUENTIAL)
    text(BP, HOLD[,i], labels=HOLD[,i], pos=ifelse(HOLD[i,] >= 0, 3, 1),
        offset=0.8)
}
</code>```

Title: Position Numbers Above & Below Bars of a Barplot

Body:
I would like to have positive numbers on my barplots displayed above the bars and negative numbers displayed below the bars. Is there anyway to do this in R? Thanks

par(mfrow=c(2,1))
HOLD <- matrix(c(0.711993046435892, 0.732294839190538,
                 0.393938967564015, -0.456254046041675,
                 -0.284020839130226, 0.544765413396821,
                 0.349792656944892, 0.395227638605604,
                 0.55130390493582, -0.513905184144522,
                 0.0989034381192891, 0.0908636716369119), ncol=6, nrow=2)

for (i in 1:2) {
  BP <- barplot(HOLD[,i], main=M[[i]], ylab="%", ylim=c(-1, 1), col=SEQUENTIAL)
  text(BP, HOLD[,i], labels=HOLD[,i], pos=3, offset=0.8)
}

Body:
Using base plot you could just pass a vector to the pos argument:

for (i in 1:2) {
    BP <- barplot(HOLD[,i], main=M[[i]], ylab="%", ylim=c(-1, 1), col=SEQUENTIAL)
    text(BP, HOLD[,i], labels=HOLD[,i], pos=ifelse(HOLD[i,] >= 0, 3, 1),
        offset=0.8)
}