问:
JHipster - Using server, embedded or external
when a JHipster app is run, it is using in default an embedded server, as far as I understood it is Undertow.

Questions:
How to configure to use another provided available embedded server (Tomcat for example)?
How to configure to not use an embedded server, but instead an external server like Tomcat?

Cheers

答:
all your need to do is copy and paste your *.war file to your tomcat external server, and run your jhipster app as server root or rename your jhipster war archieve into ROOT.war ( this is a bad way ).

i've done this before when i;m deployed my jhipster app with openshift which is must deployed inside of tomcat 8.


来源: stackexchange

问:
Month prints undefined in jquery
Currently, I am able to select values from from option boxes and date.
Then when I click on the anchor tag, I am able to pick all the data to form a url. However, when I see the url, the date comes as undefined.
The following jquery code is what I used to pick the dates:

```<code>$("#dt1").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    onSelect: function (date) {
        var dt2 = $('#dt2');
        var startDate = $(this).datepicker('getDate','+1d');
        startDate.setDate(startDate.getDate()+1);
        dt2.datepicker('option', 'minDate', startDate);
        dt2.datepicker('setDate', startDate);
    }
});

$('#dt2').datepicker({
    dateFormat: "dd-M-yy",
});

$("li#weskus").on('click', function() {
    $(this).addClass('weskusClass');
    num = 1;
    console.log(num);
});

$('a#atributo').click(function() {
    var monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Nov", "Dec"
      ];

    var date1 = $("#dt1").datepicker('getDate'),
        day_1  = date1.getDate(),
        month_1 = date1.getMonth() + 1,
        year_1 =  date1.getFullYear();

    var date2 = $("#dt2").datepicker('getDate'),
        day_2  = date2.getDate(),
        month_2 = date2.getMonth() + 1,
        year_2 =  date2.getFullYear();

    var where_in = $('.date-example-container li.weskusClass span.value-in').text();

    var where = $('.date-example-container li.selected span.value').text();
    var people = $('#search-pax :selected').val();

    if( num == 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie-in/"+where_in+"?q="+where_in+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
        num = 0;
    }
    else if( num < 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie/"+where+"?q="+where+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
    }

});
</code>```

Here my running snippet so you can test.

答:
Change your month_1 and month_2 to month_2 = date2.getMonth(), and month_2 = date2.getMonth(),.
Javascript date month are 0 based,i.e. January is 0, february is 1, so on and so forth.

So, for the month of December, your month value will be 12 but monthNames array is 0 based, so the monthNames[month_1] will be undefined.

ContentLicense: CC BY-SA 3.0

Title: Month prints undefined in jquery

Body:
Currently, I am able to select values from from option boxes and date.
Then when I click on the anchor tag, I am able to pick all the data to form a url. However, when I see the url, the date comes as undefined.
The following jquery code is what I used to pick the dates:

$("#dt1").datepicker({
    dateFormat: "dd-M-yy",
    minDate: 0,
    onSelect: function (date) {
        var dt2 = $('#dt2');
        var startDate = $(this).datepicker('getDate','+1d');
        startDate.setDate(startDate.getDate()+1);
        dt2.datepicker('option', 'minDate', startDate);
        dt2.datepicker('setDate', startDate);
    }
});

$('#dt2').datepicker({
    dateFormat: "dd-M-yy",
});

$("li#weskus").on('click', function() {
    $(this).addClass('weskusClass');
    num = 1;
    console.log(num);
});

$('a#atributo').click(function() {
    var monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Nov", "Dec"
      ];

    var date1 = $("#dt1").datepicker('getDate'),
        day_1  = date1.getDate(),
        month_1 = date1.getMonth() + 1,
        year_1 =  date1.getFullYear();

    var date2 = $("#dt2").datepicker('getDate'),
        day_2  = date2.getDate(),
        month_2 = date2.getMonth() + 1,
        year_2 =  date2.getFullYear();

    var where_in = $('.date-example-container li.weskusClass span.value-in').text();

    var where = $('.date-example-container li.selected span.value').text();
    var people = $('#search-pax :selected').val();

    if( num == 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie-in/"+where_in+"?q="+where_in+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
        num = 0;
    }
    else if( num < 1 ){
        $('a#atributo').attr("href", "http://www.lekkeslaap.co.za/akkommodasie/"+where+"?q="+where+"&start="+day_1+"+"+monthNames[month_1]+"+"+year_1+'&end='+day_2+'+'+monthNames[month_2]+'+'+year_2+'&pax='+people);
    }

});

Here my running snippet so you can test.


问:
Publish app to Azure from VS Code
Is there a way to publish an app from Visual Studio Code to Azure App service directly i.e. without going through Git or some other source control?</p>

答: No, there is no native way of doing so. You can créate a Task in Visual Studio code that does the git push or ftp push or something. But no native way yet.</p>

Title: Publish app to Azure from VS Code


问:
Why are MvvmLight.Command _and_ MvvmLight.Extras.WP7 both needed?
I had (note Extras.WP7):

```<code><phone:PhoneApplicationPage
  xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"
>
</code>```

...and it was working fine for my EventToCommand stuff like this:

```<code><phone:PhoneApplicationPage.Resources>
    <i:EventTrigger x:Key="KeyPadButtonTrigger" EventName="Click">
        <cmd:EventToCommand Command="{Binding Path=KeyPadButtonCommand}" CommandParameter="{Binding ElementName=Self, Path=Content }" />
    </i:EventTrigger>
</phone:PhoneApplicationPage.Resources>
</code>```

But then I wanted to use MmvmLight's ButtonBaseExtensions like this:

```<code><Button  x:Name="button1"
  cmd:ButtonBaseExtensions.Command="{Binding KeyPadButtonCommand}"
  cmd:ButtonBaseExtensions.CommandParameter="{Binding ElementName=button1, Path=Content }"/>
</code>```

...but when I did that I got "The attachable property 'Command' was not found in type 'ButtonBaseExtensions'" errors.

I found I had to add a namespace for assembly=GalaSoft.MvvmLight.WP7 as well, like this:

```<code><phone:PhoneApplicationPage
  xmlns:cmdxtras="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"
  xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.WP7"
>
</code>```

Note that I have BOTH xmlns:cmdxtras and xmlns:cmd.  Things don't work if I only have one or the other!

This seems really clumsy and doesn't jive with what I think others are suggesting.  Why do I need both?

答:
The Extras assembly exists because EventToCommand requires a reference to System.Windows.Interactivity, while ButtonBaseExtensions, RelayCommand, Messenger etc do not need it. Some people are reluctant to add references to assemblies if they can avoid it. So for those people who don't need EventtoCommand, they onlu use the base assembly, and the others who want the whole program can add Extras.

Cheers,
Laurent

ContentLicense: CC BY-SA 2.5

Body:
I had (note Extras.WP7):

<phone:PhoneApplicationPage
  xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"
>

...and it was working fine for my EventToCommand stuff like this:

<phone:PhoneApplicationPage.Resources>

        <cmd:EventToCommand Command="{Binding Path=KeyPadButtonCommand}" CommandParameter="{Binding ElementName=Self, Path=Content }" />

</phone:PhoneApplicationPage.Resources>

But then I wanted to use MmvmLight's ButtonBaseExtensions like this:

<Button  x:Name="button1"
  cmd:ButtonBaseExtensions.Command="{Binding KeyPadButtonCommand}"
  cmd:ButtonBaseExtensions.CommandParameter="{Binding ElementName=button1, Path=Content }"/>

...but when I did that I got "The attachable property 'Command' was not found in type 'ButtonBaseExtensions'" errors.

I found I had to add a namespace for assembly=GalaSoft.MvvmLight.WP7 as well, like this:

<phone:PhoneApplicationPage
  xmlns:cmdxtras="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7"
  xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.WP7"
>

Note that I have BOTH xmlns:cmdxtras and xmlns:cmd.  Things don't work if I only have one or the other!

This seems really clumsy and doesn't jive with what I think others are suggesting.  Why do I need both?


问:
Reference error: Restify is not defined
I'm trying to run the following node.js script(my first):

```<code>// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url);
});p

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: MY_ID_VALUE,
    appPassword:MY_PASSWORD_VALUE
});

// Listen for messages from users
server.post('/api/messages', connector.listen());

// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
    session.send("You said: %s", session.message.text);
});
</code>```

And i get the error Reference error :Restify is not defined, the full error message is attached below.
Error message

So obvious issue i could think of is installing restify again although i already have so i ran this command npm install --save restify as i already have following the instruction on https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-quickstart step by step, how can i fix it.

答:
did you import restify module before create the server?

var restify = require('restify');

Title: Reference error: Restify is not defined

Body:
I'm trying to run the following node.js script(my first):

// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url);
});p

// Create chat connector for communicating with the Bot Framework Service
var connector = new builder.ChatConnector({
    appId: MY_ID_VALUE,
    appPassword:MY_PASSWORD_VALUE
});

// Listen for messages from users
server.post('/api/messages', connector.listen());

// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
    session.send("You said: %s", session.message.text);
});

And i get the error Reference error :Restify is not defined, the full error message is attached below.
Error message

So obvious issue i could think of is installing restify again although i already have so i ran this command npm install --save restify as i already have following the instruction on https://learn.microsoft.com/en-us/bot-framework/nodejs/bot-builder-nodejs-quickstart step by step, how can i fix it.


问:
Last line in console not overwrite
I want to overwrite the last line in the console for looping a specific row with changes.

For example:
I want to print to console
. then .. then ...

This my code for that:

```<code>int dot = 1;
    while (true)
    {
        switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                Console.WriteLine(".");
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }
    }
}
</code>```

My problem is that after the first complete round(after it print the "..." in first time) it not print "." the console stay on "..."

I mean:

"." print

remove "." and print ".."

remove ".." and print "..."

now it stay "..." instead remove "..." and print ".".

Someone has idea why?

答:
You want to replace ... after you last iteration , for that you can do like this, you can make use of PadRight function. PadRight is good way to go as you can configure number value in it.

```<code>var str = ".";
var padded = str.PadRight(2);
// padded = ".  "
</code>```

so your code will become like this

```<code>switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                 var str = ".";
                var padded = str.PadRight(2);
                Console.WriteLine(str);
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }
</code>```

Title: Last line in console not overwrite

Body:
I want to overwrite the last line in the console for looping a specific row with changes.

For example:
I want to print to console
. then .. then ...

This my code for that:

int dot = 1;
    while (true)
    {
        switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                Console.WriteLine(".");
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }
    }
}

My problem is that after the first complete round(after it print the "..." in first time) it not print "." the console stay on "..."

I mean:

"." print

remove "." and print ".."

remove ".." and print "..."

now it stay "..." instead remove "..." and print ".".

Someone has idea why?

Body:
You want to replace ... after you last iteration , for that you can do like this, you can make use of PadRight function. PadRight is good way to go as you can configure number value in it.

var str = ".";
var padded = str.PadRight(2);
// padded = ".  "

so your code will become like this

switch (dot)
        {
            case 1:
                Console.SetCursorPosition(0, Console.CursorTop-1);
                 var str = ".";
                var padded = str.PadRight(2);
                Console.WriteLine(str);
                dot++;
                Thread.Sleep(500);
                break;
            case 2:
                Console.SetCursorPosition(0, Console.CursorTop -1);
                Console.WriteLine("..");
                dot++;
                Thread.Sleep(500);
                break;
            case 3:
                Console.SetCursorPosition(0, Console.CursorTop - 1);
                Console.WriteLine("...");
                dot = 1;
                Thread.Sleep(500);
                break;
        }


问:
MySQL SELECT using WHERE & BETWEEN
I've serveral databases with the same structure:

dsid, tag, timestamp, value

Timestamp is in unixtime, and I can select data to plot like this:

```<code>SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs`
 , t.`value` - (SELECT `value`
                FROM `MY-DB`
                WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
                tag, dsid, value,
                FROM_UNIXTIME(timestamp, '%y-%d-%m %H:%i')
FROM `MY-DB` t limit 10000;
</code>```

But I want to select it based on a "where date between" structure, so I can choose a month or week... Or even better "last" week, month, year (full calendar year or just the last 12 month).

But if I try like that it fails:

```<code>SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs`
 , t.`value` - (SELECT `value`
                FROM `MY-DB`
                WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
                tag, dsid, value, (FROM_UNIXTIME(timestamp, '%y-%d-%m %H:%i') WHERE 'timestamp' BETWEEN UNIX_TIMESTAMP('16-27-03 23:45')) AND UNIX_TIMESTAMP('16-25-02 00:00')
FROM `MY-DB` t limit 10000;
</code>```

What is wrong?

答:
What was wrong is that I placed the WHERE & BETWEEN in the wrong place, this is how it works for me:

```<code>SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs` , t.`value` - (SELECT `value`
            FROM `MYDB`
            WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
            tag, dsid, value,
            FROM_UNIXTIME(timestamp, '%y-%m-%d %H:%i') as time
FROM `MYDB` t
WHERE timestamp
BETWEEN UNIX_TIMESTAMP('16-08-01') AND UNIX_TIMESTAMP('16-08-31 23:59:59')
</code>```

Might not be the most efficient way to do it..

Title: MySQL SELECT using WHERE & BETWEEN

Body:
I've serveral databases with the same structure:

dsid, tag, timestamp, value

Timestamp is in unixtime, and I can select data to plot like this:

SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs`
 , t.`value` - (SELECT `value`
                FROM `MY-DB`
                WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
                tag, dsid, value,
                FROM_UNIXTIME(timestamp, '%y-%d-%m %H:%i')
FROM `MY-DB` t limit 10000;

But I want to select it based on a "where date between" structure, so I can choose a month or week... Or even better "last" week, month, year (full calendar year or just the last 12 month).

But if I try like that it fails:

SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs`
 , t.`value` - (SELECT `value`
                FROM `MY-DB`
                WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
                tag, dsid, value, (FROM_UNIXTIME(timestamp, '%y-%d-%m %H:%i') WHERE 'timestamp' BETWEEN UNIX_TIMESTAMP('16-27-03 23:45')) AND UNIX_TIMESTAMP('16-25-02 00:00')
FROM `MY-DB` t limit 10000;

What is wrong?

Body:
What was wrong is that I placed the WHERE & BETWEEN in the wrong place, this is how it works for me:

SELECT CONCAT(t.`dsid` ,' - ', t.`dsid` - 1) AS `DSIDs` , t.`value` - (SELECT `value`
            FROM `MYDB`
            WHERE `dsid` = t.`dsid` - 1 * 20) AS `kWh`,
            tag, dsid, value,
            FROM_UNIXTIME(timestamp, '%y-%m-%d %H:%i') as time
FROM `MYDB` t
WHERE timestamp
BETWEEN UNIX_TIMESTAMP('16-08-01') AND UNIX_TIMESTAMP('16-08-31 23:59:59')

Might not be the most efficient way to do it..


问:
How to show all columns after performing GenomicRanges::subsetByOverlaps
I have the following two GenomicRanges objects. First one gr1 is this:

library(GenomicRanges)
set.seed(1)
gr1 <- GRanges(
        seqnames=Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)),
        ranges=IRanges(1:10, width=10:1, names=head(letters,10)),
        strand=Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)),
        motif_score=seq(1, 0, length=10),
         motif_name=paste0("Motif_", toupper(sample(c(letters,letters))))[1:10]
      )
gr1
#> GRanges object with 10 ranges and 2 metadata columns:
#>     seqnames    ranges strand | motif_score  motif_name
#>        <Rle> <IRanges>  <Rle> |   <numeric> <character>
#>   a     chr1  [ 1, 10]      - |   1.0000000     Motif_N
#>   b     chr2  [ 2, 10]      + |   0.8888889     Motif_S
#>   c     chr2  [ 3, 10]      + |   0.7777778     Motif_C
#>   d     chr2  [ 4, 10]      * |   0.6666667     Motif_S
#>   e     chr1  [ 5, 10]      * |   0.5555556     Motif_J
#>   f     chr1  [ 6, 10]      + |   0.4444444     Motif_Q
#>   g     chr3  [ 7, 10]      + |   0.3333333     Motif_R
#>   h     chr3  [ 8, 10]      + |   0.2222222     Motif_D
#>   i     chr3  [ 9, 10]      - |   0.1111111     Motif_B
#>   j     chr3  [10, 10]      - |   0.0000000     Motif_C
#>   -------
#>   seqinfo: 3 sequences from an unspecified genome; no seqlengths
```

<p>And the second object <code>gr2</code>:</p>

<pre class="lang-r prettyprint-override"><code>gr2 <- GRanges(seqnames="chr2",
               ranges=IRanges(4:3, 6),
               peak_name=c("peak_1", "peak_2"),
               strand="+", peak_score=5:4)
gr2
#> GRanges object with 2 ranges and 2 metadata columns:
#>       seqnames    ranges strand |   peak_name peak_score
#>          <Rle> <IRanges>  <Rle> | <character>  <integer>
#>   [1]     chr2    [4, 6]      + |      peak_1          5
#>   [2]     chr2    [3, 6]      + |      peak_2          4
#>   -------
#>   seqinfo: 1 sequence from an unspecified genome; no seqlengths
</code>```

Then I perform the region overlap using subsetByOverlaps between gr1 and gr2

 subsetByOverlaps(gr1, gr2)
#> GRanges object with 3 ranges and 2 metadata columns:
#>     seqnames    ranges strand | motif_score  motif_name
#>        <Rle> <IRanges>  <Rle> |   <numeric> <character>
#>   b     chr2   [2, 10]      + |   0.8888889     Motif_S
#>   c     chr2   [3, 10]      + |   0.7777778     Motif_C
#>   d     chr2   [4, 10]      * |   0.6666667     Motif_S
#>   -------
#>   seqinfo: 3 sequences from an unspecified genome; no seqlengths
```

as you can see the peak_name and peak_score column does not appear after intersection. How can I show them all?

答:
First we find all overlaps of features in gr1 (the query object) with features in gr2 (the subject object).

```<code># Find overlaps
m <- findOverlaps(gr1, gr2);
</code>```

We then store matching features in gr1.matched, and add metadata from gr2.

```<code># Features from gr1 with overlaps in gr2
# Note: The same feature from gr1 can overlap with mulitple features from gr2
gr1.matched <- gr1[queryHits(m)];

# Add the metadata from gr2
mcols(gr1.matched) <- cbind.data.frame(
    mcols(gr1.matched),
    mcols(gr2[subjectHits(m)]));

gr1.matched;
#GRanges object with 6 ranges and 4 metadata columns:
#    seqnames    ranges strand | motif_score  motif_name   peak_name peak_score
#       <Rle> <IRanges>  <Rle> |   <numeric> <character> <character>  <integer>
#  b     chr2   [2, 10]      + |   0.8888889     Motif_S      peak_2          4
#  b     chr2   [2, 10]      + |   0.8888889     Motif_S      peak_1          5
#  c     chr2   [3, 10]      + |   0.7777778     Motif_C      peak_2          4
#  c     chr2   [3, 10]      + |   0.7777778     Motif_C      peak_1          5
#  d     chr2   [4, 10]      * |   0.6666667     Motif_S      peak_2          4
#  d     chr2   [4, 10]      * |   0.6666667     Motif_S      peak_1          5
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths
</code>```

Body:
I have the following two GenomicRanges objects. First one gr1 is this:

library(GenomicRanges)
set.seed(1)
gr1 <- GRanges(
        seqnames=Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)),
        ranges=IRanges(1:10, width=10:1, names=head(letters,10)),
        strand=Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)),
        motif_score=seq(1, 0, length=10),
         motif_name=paste0("Motif_", toupper(sample(c(letters,letters))))[1:10]
      )
gr1
#> GRanges object with 10 ranges and 2 metadata columns:
#>     seqnames    ranges strand | motif_score  motif_name
#>        <Rle> <IRanges>  <Rle> |   <numeric> <character>
#>   a     chr1  [ 1, 10]      - |   1.0000000     Motif_N
#>   b     chr2  [ 2, 10]      + |   0.8888889     Motif_S
#>   c     chr2  [ 3, 10]      + |   0.7777778     Motif_C
#>   d     chr2  [ 4, 10]      * |   0.6666667     Motif_S
#>   e     chr1  [ 5, 10]      * |   0.5555556     Motif_J
#>   f     chr1  [ 6, 10]      + |   0.4444444     Motif_Q
#>   g     chr3  [ 7, 10]      + |   0.3333333     Motif_R
#>   h     chr3  [ 8, 10]      + |   0.2222222     Motif_D
#>   i     chr3  [ 9, 10]      - |   0.1111111     Motif_B
#>   j     chr3  [10, 10]      - |   0.0000000     Motif_C
#>   -------
#>   seqinfo: 3 sequences from an unspecified genome; no seqlengths

And the second object gr2:

gr2 <- GRanges(seqnames="chr2",
               ranges=IRanges(4:3, 6),
               peak_name=c("peak_1", "peak_2"),
               strand="+", peak_score=5:4)
gr2
#> GRanges object with 2 ranges and 2 metadata columns:
#>       seqnames    ranges strand |   peak_name peak_score
#>          <Rle> <IRanges>  <Rle> | <character>  <integer>
#>   [1]     chr2    [4, 6]      + |      peak_1          5
#>   [2]     chr2    [3, 6]      + |      peak_2          4
#>   -------
#>   seqinfo: 1 sequence from an unspecified genome; no seqlengths

Then I perform the region overlap using subsetByOverlaps between gr1 and gr2

 subsetByOverlaps(gr1, gr2)
#> GRanges object with 3 ranges and 2 metadata columns:
#>     seqnames    ranges strand | motif_score  motif_name
#>        <Rle> <IRanges>  <Rle> |   <numeric> <character>
#>   b     chr2   [2, 10]      + |   0.8888889     Motif_S
#>   c     chr2   [3, 10]      + |   0.7777778     Motif_C
#>   d     chr2   [4, 10]      * |   0.6666667     Motif_S
#>   -------
#>   seqinfo: 3 sequences from an unspecified genome; no seqlengths

as you can see the peak_name and peak_score column does not appear after intersection. How can I show them all?

Body:
First we find all overlaps of features in gr1 (the query object) with features in gr2 (the subject object).

# Find overlaps
m <- findOverlaps(gr1, gr2);

We then store matching features in gr1.matched, and add metadata from gr2.

# Features from gr1 with overlaps in gr2
# Note: The same feature from gr1 can overlap with mulitple features from gr2
gr1.matched <- gr1[queryHits(m)];

# Add the metadata from gr2
mcols(gr1.matched) <- cbind.data.frame(
    mcols(gr1.matched),
    mcols(gr2[subjectHits(m)]));

gr1.matched;
#GRanges object with 6 ranges and 4 metadata columns:
#    seqnames    ranges strand | motif_score  motif_name   peak_name peak_score
#       <Rle> <IRanges>  <Rle> |   <numeric> <character> <character>  <integer>
#  b     chr2   [2, 10]      + |   0.8888889     Motif_S      peak_2          4
#  b     chr2   [2, 10]      + |   0.8888889     Motif_S      peak_1          5
#  c     chr2   [3, 10]      + |   0.7777778     Motif_C      peak_2          4
#  c     chr2   [3, 10]      + |   0.7777778     Motif_C      peak_1          5
#  d     chr2   [4, 10]      * |   0.6666667     Motif_S      peak_2          4
#  d     chr2   [4, 10]      * |   0.6666667     Motif_S      peak_1          5
#  -------
#  seqinfo: 3 sequences from an unspecified genome; no seqlengths


问:
How to use the Tooltip() function to be global
I have 2 file.php, file1.php it is a file for the core page, file2.php to display the added form.
file2.php included to file1.php in a statement.
when i need to use function from Boostraps.js, to beautify tooltip, i call function from Boostraps.js in file1.php as follows:

$('.Btn').Tooltip({
placement: 'bottom'
});```
</div>
</div>
</p>

<p>why tooltip() function only runs on <em>file1.php</em> only, does not work for <em>file2.php</em> included in <em>file1.php</em>
how to keep this tooltip function running in 2 different files that are included.
if calling globally I've used action just like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on('click',function(){
// Bla bla bla ...
})</code>```

答:
You have 2 totally separate files, so how they should communicate to each other? Are they share a core? like wordpress CMS. If not you should include same js file into both php file otherwise it wont work.

This code:

```<code>$('.Btn').Tooltip()
</code>```

means be global and every where in document you find this class .btn turn it to tooltip, "BUT" when there is not .btn in document "OR" you didn't add this code in that document, you will get anything and the code will not work.

Body:
I have 2 file.php, file1.php it is a file for the core page, file2.php to display the added form.
file2.php included to file1.php in a statement.
when i need to use function from Boostraps.js, to beautify tooltip, i call function from Boostraps.js in file1.php as follows:

$('.Btn').Tooltip({
placement: 'bottom'
});

why tooltip() function only runs on file1.php only, does not work for file2.php included in file1.php
how to keep this tooltip function running in 2 different files that are included.
if calling globally I've used action just like this:

$(document).on('click',function(){
// Bla bla bla ...
})

Body:
You have 2 totally separate files, so how they should communicate to each other? Are they share a core? like wordpress CMS. If not you should include same js file into both php file otherwise it wont work.

This code:

$('.Btn').Tooltip()

means be global and every where in document you find this class .btn turn it to tooltip, "BUT" when there is not .btn in document "OR" you didn't add this code in that document, you will get anything and the code will not work.


问:
android FirebaseInstanceId.getToken(authorizedEntity, scope) timeout
I got the timeout exception when retrieve the firebase token that,

```<code>public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        try {
            String token = FirebaseInstanceId.getInstance().getToken("projectId", "FCM");
        } catch(IOException e) {
             e.printStackTrace();
        }
    }
}
</code>```

How can I solve this issue?

or If timeout exception has occurred, Firebase call onTokenRefresh automatically?

答:
Please make sure you declared service in manifest file ?
Still if you are getting same problem, let me know.
Thanks</p>

Body:
I got the timeout exception when retrieve the firebase token that,

public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        try {
            String token = FirebaseInstanceId.getInstance().getToken("projectId", "FCM");
        } catch(IOException e) {
             e.printStackTrace();
        }
    }
}

How can I solve this issue?

or If timeout exception has occurred, Firebase call onTokenRefresh automatically?


问:
Unable to mergedex after updating to android studio 3.0
After Updating my Studio to 3.0, I encountered with the issue:

```<code>Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0) from [com.android.support:design:26.0.0]
AndroidManifest.xml:28:13-35 is also present at [com.android.support:appcompat-v7:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:26:9-28:38 to override.
</code>```

I solved that issue by adding the following code:

```<code>configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.2'
        }
    }
}
</code>```

}

but after introducing that code at the end of my build.gradle, it displays another error when I try to run my application on my phone :

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
</code>```

I referred to many links with the similar problems, but I couldn't find the solution to my problem.

This is my build.gradle (Module:app)

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
    multiDexEnabled true
    applicationId "com.example.mahe.blooddonation"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}

buildTypes {
    release {
        minifyEnabled false

        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.android.gms:play-services:11.6.2'
implementation 'com.google.firebase:firebase-auth:11.6.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile files('libs/activation.jar')
compile files('libs/additionnal.jar')
compile files('libs/google-play-services.jar')
compile files('libs/http-core-4.1.jar')
compile files('libs/httpclient-4.0.3.jar')
compile files('libs/mail.jar')  }
</code>```

My build.gradle for the Project is:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    classpath 'com.google.gms:google-services:3.0.0'
}
}

allprojects {
repositories {
    maven{
        url "https://github.com/omadahealth/omada-nexus/raw/master/release"
    }
    jcenter()
    google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

My Manifest File is:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mahe.blooddonation">

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/dexter"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".IntroScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SignUp" />
    <activity android:name=".Login" />
    <activity
        android:name=".DonorOrReciever"
        android:label="@string/title_activity_donor_or_reciever" />
    <activity android:name=".RecieverActivity" />
    <activity android:name=".ActivityProfile" />
    <activity android:name=".EditProfile"></activity>
</application>
</code>```

And I have removed the configurations block  of code from my gradle, and it compiles  fine without it, but still, I encounter with unable to merge dex.

my complete Stack Trace:

```<code>Error:java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
</code>```

I Hope someone could be helpful to me.

答:
I tried with an empty project and the following build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        multiDexEnabled true
        applicationId "bla.bla.bla"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.android.gms:play-services:11.6.2'
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    implementation 'com.mcxiaoke.volley:library-aar:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}
</code>```

... and everything works for me. Maybe try the same and add your local libs one after the other to see what is causing this error. I hope you find the problem like this.

Body:
After Updating my Studio to 3.0, I encountered with the issue:

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0) from [com.android.support:design:26.0.0]
AndroidManifest.xml:28:13-35 is also present at [com.android.support:appcompat-v7:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:26:9-28:38 to override.

I solved that issue by adding the following code:

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '26.0.2'
        }
    }
}

}

but after introducing that code at the end of my build.gradle, it displays another error when I try to run my application on my phone :

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
> java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

I referred to many links with the similar problems, but I couldn't find the solution to my problem.

This is my build.gradle (Module:app)

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
    multiDexEnabled true
    applicationId "com.example.mahe.blooddonation"
    minSdkVersion 19
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}

buildTypes {
    release {
        minifyEnabled false

        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:design:26.1.0'
implementation 'com.android.support:cardview-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.google.android.gms:play-services:11.6.2'
implementation 'com.google.firebase:firebase-auth:11.6.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

compile 'com.mcxiaoke.volley:library-aar:1.0.0'
compile files('libs/activation.jar')
compile files('libs/additionnal.jar')
compile files('libs/google-play-services.jar')
compile files('libs/http-core-4.1.jar')
compile files('libs/httpclient-4.0.3.jar')
compile files('libs/mail.jar')  }

My build.gradle for the Project is:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    classpath 'com.google.gms:google-services:3.0.0'
}
}

allprojects {
repositories {
    maven{
        url "https://github.com/omadahealth/omada-nexus/raw/master/release"
    }
    jcenter()
    google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

My Manifest File is:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mahe.blooddonation">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/dexter"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".IntroScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SignUp" />
    <activity android:name=".Login" />
    <activity
        android:name=".DonorOrReciever"
        android:label="@string/title_activity_donor_or_reciever" />
    <activity android:name=".RecieverActivity" />
    <activity android:name=".ActivityProfile" />
    <activity android:name=".EditProfile"></activity>
</application>

And I have removed the configurations block  of code from my gradle, and it compiles  fine without it, but still, I encounter with unable to merge dex.

my complete Stack Trace:

Error:java.lang.RuntimeException: java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

Error:com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

I Hope someone could be helpful to me.

Body:
I tried with an empty project and the following build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        multiDexEnabled true
        applicationId "bla.bla.bla"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    //noinspection GradleCompatible
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    implementation 'com.android.support:cardview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.android.gms:play-services:11.6.2'
    implementation 'com.google.firebase:firebase-auth:11.6.2'
    implementation 'com.mcxiaoke.volley:library-aar:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

... and everything works for me. Maybe try the same and add your local libs one after the other to see what is causing this error. I hope you find the problem like this.


问:
How to find specific date from js array?
I have this array in my data.js file. And I want to find the specific date from other html file to data.js file using javascript.

For example:

Here is the date to search

var searchDate = '12-25-2017';

I want to search that date from data.js file ( Variable name : jpHolidays )and show in html or console.log().

I was googling and i didn't find how to find the specific date. Please help me.

```<code>var jpHolidays = {
     '01-01-2017' : '<span>お正月 <br> New Year\'s Day</span>',
     '01-02-2017' : '<span>お正月 <br> New Year\'s Day observed</span>',
     '01-09-2017' : '<span>成人の日 <br> Coming of Age Day</span>',
     '02-11-2017' : '<span>建国記念日 <br> National Foundation Day</span>',
     '03-20-2017' : '<span>春分の日 <br> Vernal Equinox Day</span>',
     '04-29-2017' : '<span>昭和の日 <br> Shōwa Day</span>',
     '05-03-2017' : '<span>憲法記念日 <br> Constitution Memorial Day</span>',
     '05-04-2017' : '<span>みどりの日 <br> Greenery Day</span>',
     '05-05-2017' : '<span>こどもの日 <br> Children\'s Day</span>',
     '07-17-2017' : '<span>海の日 <br> Marine Day / Ocean Day</span>',
     '08-11-2017' : '<span>山の日 <br> Mountain Day</span>',
     '09-18-2017' : '<span>敬老の日 <br> Respect for the Aged Day</span>',
     '09-23-2017' : '<span>秋分の日 <br> Autumnal Equinox Day</span>',
     '10-09-2017' : '<span>体育の日 <br> Health and Sports Day </span>',
     '11-03-2017' : '<span>文化の日 <br> Culture Day</span>',
     '11-23-2017' : '<span>勤労感謝の日 <br> Labour Thanksgiving Day </span>',
     '12-23-2017' : '<span>天皇誕生日 <br> The Emperor\'s Birthday</span>',
 };
</code>```

答:
First off, jpHolidays is an object and not an array.

```<code>var jpHolidays = {
     '01-01-2017' : '<span>お正月 <br> New Year\'s Day</span>',
     '01-02-2017' : '<span>お正月 <br> New Year\'s Day observed</span>',
     '01-09-2017' : '<span>成人の日 <br> Coming of Age Day</span>',
     '02-11-2017' : '<span>建国記念日 <br> National Foundation Day</span>',
.....
....
}

//assume that this is the holiday you are looking for
var isHoliday = '12-25-2017';

// access the jpHolidaysObject. if found, return the value. If not, print 'not holiday' or whatever suits you.

console.log(jpHolidays[isHoliday] || 'not holiday');
</code>```

Body:
I have this array in my data.js file. And I want to find the specific date from other html file to data.js file using javascript.

For example:

Here is the date to search

var searchDate = '12-25-2017';

I want to search that date from data.js file ( Variable name : jpHolidays )and show in html or console.log().

I was googling and i didn't find how to find the specific date. Please help me.

var jpHolidays = {
     '01-01-2017' : 'お正月
 New Year\'s Day',
     '01-02-2017' : 'お正月
 New Year\'s Day observed',
     '01-09-2017' : '成人の日
 Coming of Age Day',
     '02-11-2017' : '建国記念日
 National Foundation Day',
     '03-20-2017' : '春分の日
 Vernal Equinox Day',
     '04-29-2017' : '昭和の日
 Shōwa Day',
     '05-03-2017' : '憲法記念日
 Constitution Memorial Day',
     '05-04-2017' : 'みどりの日
 Greenery Day',
     '05-05-2017' : 'こどもの日
 Children\'s Day',
     '07-17-2017' : '海の日
 Marine Day / Ocean Day',
     '08-11-2017' : '山の日
 Mountain Day',
     '09-18-2017' : '敬老の日
 Respect for the Aged Day',
     '09-23-2017' : '秋分の日
 Autumnal Equinox Day',
     '10-09-2017' : '体育の日
 Health and Sports Day ',
     '11-03-2017' : '文化の日
 Culture Day',
     '11-23-2017' : '勤労感謝の日
 Labour Thanksgiving Day ',
     '12-23-2017' : '天皇誕生日
 The Emperor\'s Birthday',
 };

Body:
First off, jpHolidays is an object and not an array.

var jpHolidays = {
     '01-01-2017' : '<span>お正月 <br> New Year\'s Day</span>',
     '01-02-2017' : '<span>お正月 <br> New Year\'s Day observed</span>',
     '01-09-2017' : '<span>成人の日 <br> Coming of Age Day</span>',
     '02-11-2017' : '<span>建国記念日 <br> National Foundation Day</span>',
.....
....
}

//assume that this is the holiday you are looking for
var isHoliday = '12-25-2017';

// access the jpHolidaysObject. if found, return the value. If not, print 'not holiday' or whatever suits you.

console.log(jpHolidays[isHoliday] || 'not holiday');


问:
How can I print to table?
I would appreciate it if anyone willing to tell how to echoing /print.

Below is the process of entering data into the database, before inserting it how can I echoing it to the table?

```<code><?php
session_start();
if(isset($_POST['submit']))
{
 include('class/stock_class.php');
 $st = new st_exchange_conv(DEFAULT_SOURCE);
 $from = mysql_real_escape_string(stripslashes($_POST['from']));
 $value = floatval($_POST['amount']);
 $date = date('Y-m-d H:i:s');
 $_SESSION['selected'] = $from;
 $stocks = $st->stocks();
 asort($stocks);
 foreach($stocks as $key=>$stock)
 {
  $st->convert($from,$key,$date);
  $stc_price = $st->price($value);
  $stock = mysql_real_escape_string(stripslashes($stock));
  $count = "SELECT * FROM oc_stock WHERE stock = '$key'";
  $result = mysql_query($count) or die(mysql_error());
  $sql = '';
  if(mysql_num_rows($result) == 1)
  {
   $sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
  }
  else
  {
  $sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
  }
  $result = mysql_query($sql) or die(mysql_error().'<br />'.$sql);
 }
 header("Location: index.php");
 exit();
}
?>
</code>```

答:
Insert this:

```<code>echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";
</code>```

Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.

Title: How can I print to table?

Body:
I would appreciate it if anyone willing to tell how to echoing /print.

Below is the process of entering data into the database, before inserting it how can I echoing it to the table?

<?php
session_start();
if(isset($_POST['submit']))
{
 include('class/stock_class.php');
 $st = new st_exchange_conv(DEFAULT_SOURCE);
 $from = mysql_real_escape_string(stripslashes($_POST['from']));
 $value = floatval($_POST['amount']);
 $date = date('Y-m-d H:i:s');
 $_SESSION['selected'] = $from;
 $stocks = $st->stocks();
 asort($stocks);
 foreach($stocks as $key=>$stock)
 {
  $st->convert($from,$key,$date);
  $stc_price = $st->price($value);
  $stock = mysql_real_escape_string(stripslashes($stock));
  $count = "SELECT * FROM oc_stock WHERE stock = '$key'";
  $result = mysql_query($count) or die(mysql_error());
  $sql = '';
  if(mysql_num_rows($result) == 1)
  {
   $sql = "UPDATE oc_stock SET stock_title = '$stock', stc_val = '$stc_price', date_updated = '$date' WHERE stock = '$key'";
  }
  else
  {
  $sql = "INSERT INTO oc_stock(stock_id,stock_title,stock,decimal_place,stc_val,date_updated) VALUES ('','$stock','$key','2',$stc_price,'$date')";
  }
  $result = mysql_query($sql) or die(mysql_error().'
'.$sql);
 }
 header("Location: index.php");
 exit();
}
?>

Body:
Insert this:

echo "<table><tr><th>".implode(array_keys($stocks), '</th><th>')."</th></tr>";
foreach($stocks as $row) echo "<tr><td>".implode('</td><td>', $row)."</tr>";
echo "</table>";

Edit: If printing the data is the goal and the table-view is not important, I recommend print_r($stocks) instead.


答:
You can use the hasOwnProperty method to check for a key.</p>

```<code>var searchDate = '12-25-2017';

if(jpHolidays.hasOwnProperty(searchDate)){
  //write your logic here or return jpHolidays[searchDate];
}
</code>```

Title: How to find specific date from js array?

Body:
You can use the hasOwnProperty method to check for a key.

var searchDate = '12-25-2017';

if(jpHolidays.hasOwnProperty(searchDate)){
  //write your logic here or return jpHolidays[searchDate];
}


问:
What is the best package to use SVG inline in NuxtJS?
I find the best package to use SVG inline in NuxtJS, which can be rendered HTML. I use this package: svg-inline-loader. It's display SVG HTML but it must have insert all SVG in document to use: View this example. It must have insert <svg v-html="require('~/assets/sprite.svg')"></svg> to render SVG.

Do you guys know what package is better to make SVG inline?

答:
Yes, use vue-svg-loader.

Install it with either npm or yarn:

```<code>npm install --save-dev vue-svg-loader
yarn add --dev vue-svg-loader
</code>```

Then configure your webpack config:

```<code>{
  test: /\.svg$/,
  loader: 'vue-svg-loader'
}
</code>```

Edit: or with vue-cli-3.* (in your vue.config.js):

```<code>chainWebpack: config => {
  const svgRule = config.module.rule('svg')

  svgRule.uses.clear()
  svgRule
    .use('vue-svg-loader')
    .loader('vue-svg-loader')
    .options({
      svgo: false
    })
}
</code>```

And finally a usage example in your .vue file:

```<code><template>
  <nav id="menu">
    <a href="...">
      <SomeIcon class="icon" />
      Some page
    </a>
  </nav>
</template>

<script>
import SomeIcon from './assets/some-icon.svg'

export default {
  name: 'menu',
  components: { SomeIcon }
}
</script>
</code>```

See more: docs.

Body:
Yes, use vue-svg-loader.

Install it with either npm or yarn:

npm install --save-dev vue-svg-loader
yarn add --dev vue-svg-loader

Then configure your webpack config:

{
  test: /\.svg$/,
  loader: 'vue-svg-loader'
}

Edit: or with vue-cli-3.* (in your vue.config.js):

chainWebpack: config => {
  const svgRule = config.module.rule('svg')

  svgRule.uses.clear()
  svgRule
    .use('vue-svg-loader')
    .loader('vue-svg-loader')
    .options({
      svgo: false
    })
}

And finally a usage example in your .vue file:

<template>
  <nav id="menu">
    <a href="...">
      <SomeIcon class="icon" />
      Some page
    </a>
  </nav>
</template>

<script>
import SomeIcon from './assets/some-icon.svg'

export default {
  name: 'menu',
  components: { SomeIcon }
}
</script>

See more: docs.

ContentLicense: CC BY-SA 4.0


问:
Get WooCommerce orders Items by variation ID
How can I list order items based on a specific product variations?

Given a variation ID, I would like to generate a list of all order items that include that particular variation.

In my case I'm using variations to represent dates and the product itself is a recurring event, so the purpose of this is to list the people attending that specific date.

It would be amazing if this could be accomplished by something simple like a get_posts using meta_keys or something in that vein, but otherwise I'm guessing a custom query would be the way.

I just can't seem to figure out how the tables relate in this case or if this is stored in a searchable way.

Any help very much appreciated.

Thanks!

答:
I tried to do the same, after looking at db I was getting 0 in front of '_variation_id'. But got the orders items using my custom hack for the future people who are looking for the same issue. We need to compare using product_name, variaion_name such as Size etc. And variation_value LIKE 'S', 'L' etc. Consider this function:

```<code>function get_all_orders_that_have_a_product_variation( $product_name, $variation_name, $variation_value ){

global $wpdb;
// Getting all Order IDs with that variation ID

$order_ids_arr = $wpdb->get_col($wpdb->prepare ( "
        SELECT * FROM wpcc_woocommerce_order_items items
        LEFT JOIN wpcc_woocommerce_order_itemmeta itemmeta ON items.order_item_id = itemmeta.order_item_id
        WHERE items.order_item_name LIKE %s
        AND itemmeta.meta_key LIKE %s
        AND itemmeta.meta_value = %s", $product_name, $variation_name, $variation_value ));

 return $order_ids_arr; // return the array of orders ids

}
</code>```

Now call it, say our product name is Raleigh sport, variation name is size and value is s. In simple form, we want to get the order items id of the product whose name is Raleigh sport and we want to fetch only whose size is S

simple call by function:

print_r(get_all_orders_that_have_a_product_variation( "Raleigh Sport", "Size", "S" ));

thanks.

Body:
I tried to do the same, after looking at db I was getting 0 in front of '_variation_id'. But got the orders items using my custom hack for the future people who are looking for the same issue. We need to compare using product_name, variaion_name such as Size etc. And variation_value LIKE 'S', 'L' etc. Consider this function:

function get_all_orders_that_have_a_product_variation( $product_name, $variation_name, $variation_value ){

global $wpdb;
// Getting all Order IDs with that variation ID

$order_ids_arr = $wpdb->get_col($wpdb->prepare ( "
        SELECT * FROM wpcc_woocommerce_order_items items
        LEFT JOIN wpcc_woocommerce_order_itemmeta itemmeta ON items.order_item_id = itemmeta.order_item_id
        WHERE items.order_item_name LIKE %s
        AND itemmeta.meta_key LIKE %s
        AND itemmeta.meta_value = %s", $product_name, $variation_name, $variation_value ));

 return $order_ids_arr; // return the array of orders ids

}

Now call it, say our product name is Raleigh sport, variation name is size and value is s. In simple form, we want to get the order items id of the product whose name is Raleigh sport and we want to fetch only whose size is S

simple call by function:

print_r(get_all_orders_that_have_a_product_variation( "Raleigh Sport", "Size", "S" ));

thanks.


问:
Self-Sizing Table View Cell in Xcode 9
I have a UITableViewController where the cell's self sized correctly using Xcode 8 and Swift 3.  Now that I'm using Xcode 9 and Swift 4, they aren't expanding and are just using the default height of 44.

(I have about a sentence or two in each UITableViewCell)

I was using this before:

```<code>// MARK: - Table view delegate

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}
</code>```

... but was able to comment it out because per Updating Your App for iOS 11 said that the default would be self-sizing now:

I've tried playing around with changing the deployment target to iOS 11, playing around in Storyboard (but I'm using a Table View Cell style Basic so there is not much AutoLayout to be done), and I can't figure out what is going on.

I have the UILabel title set to 0 Lines, and have Line Break Word Wrap, but still not getting anywhere close to getting the cell to expand based on the text content inside of it in Xcode 9.  Any ideas?

Thanks!

Edit:

Here's the options (that I don't have) for pinning since it is a Basic cell:

答: For me, Safe Area was checked. Unchecking "Safe Area" did the work for me.

Title: Self-Sizing Table View Cell in Xcode 9

Body:
I have a UITableViewController where the cell's self sized correctly using Xcode 8 and Swift 3.  Now that I'm using Xcode 9 and Swift 4, they aren't expanding and are just using the default height of 44.

(I have about a sentence or two in each UITableViewCell)

I was using this before:

// MARK: - Table view delegate

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

... but was able to comment it out because per Updating Your App for iOS 11 said that the default would be self-sizing now:

I've tried playing around with changing the deployment target to iOS 11, playing around in Storyboard (but I'm using a Table View Cell style Basic so there is not much AutoLayout to be done), and I can't figure out what is going on.

I have the UILabel title set to 0 Lines, and have Line Break Word Wrap, but still not getting anywhere close to getting the cell to expand based on the text content inside of it in Xcode 9.  Any ideas?

Thanks!

Edit:

Here's the options (that I don't have) for pinning since it is a Basic cell:


问:
How to preserve the list of data frame form after using parallel apply
I have the following function my_func which takes parameter stored in a data frame params and take one extra param as another df independently indf

library(tidyverse)

my_func <- function (x=NULL,y=NULL,z=NULL, indf=NULL) {
 out <- (x * y *z )
 out * indf
}

params <- tribble(
  ~x, ~y, ~z,
  5,     1,  1,
  10,     5,  3,
  -3,    10,  5
)

indf <- tribble(
  ~A, ~B, ~C,
  100,     10,  1,
  1000,     300,  3,
  20,    10,  5
)

params %>%
  pmap(my_func, indf=indf)
```

<p>It produces the following list of data frames:</p>

<pre class="lang-r prettyprint-override"><code>#> [[1]]
#>      A    B  C
#> 1  500   50  5
#> 2 5000 1500 15
#> 3  100   50 25
#>
#> [[2]]
#>        A     B   C
#> 1  15000  1500 150
#> 2 150000 45000 450
#> 3   3000  1500 750
#>
#> [[3]]
#>         A      B    C
#> 1  -15000  -1500 -150
#> 2 -150000 -45000 -450
#> 3   -3000  -1500 -750
</code>```

What I want to do then is to run the above function with parallel package. I did it this way:

library(parallel)
params %>%
  lift(mcmapply, mc.cores = detectCores() - 1)(FUN = my_func, indf=indf)
```

<p>But it produces the following matrix instead. </p>

<pre class="lang-r prettyprint-override"><code>     [,1]  [,2] [,3]
[1,]  500  1500 -150
[2,] 5000 45000 -450
[3,]  100  1500 -750
</code>```

How can I use parallel so that it produces a list of data frames like the initial output?

Body:
I have the following function my_func which takes parameter stored in a data frame params and take one extra param as another df independently indf

library(tidyverse)

my_func <- function (x=NULL,y=NULL,z=NULL, indf=NULL) {
 out <- (x * y *z )
 out * indf
}

params <- tribble(
  ~x, ~y, ~z,
  5,     1,  1,
  10,     5,  3,
  -3,    10,  5
)

indf <- tribble(
  ~A, ~B, ~C,
  100,     10,  1,
  1000,     300,  3,
  20,    10,  5
)

params %>%
  pmap(my_func, indf=indf)

It produces the following list of data frames:

#> [[1]]
#>      A    B  C
#> 1  500   50  5
#> 2 5000 1500 15
#> 3  100   50 25
#>
#> [[2]]
#>        A     B   C
#> 1  15000  1500 150
#> 2 150000 45000 450
#> 3   3000  1500 750
#>
#> [[3]]
#>         A      B    C
#> 1  -15000  -1500 -150
#> 2 -150000 -45000 -450
#> 3   -3000  -1500 -750

What I want to do then is to run the above function with parallel package. I did it this way:

library(parallel)
params %>%
  lift(mcmapply, mc.cores = detectCores() - 1)(FUN = my_func, indf=indf)

But it produces the following matrix instead.

     [,1]  [,2] [,3]
[1,]  500  1500 -150
[2,] 5000 45000 -450
[3,]  100  1500 -750

How can I use parallel so that it produces a list of data frames like the initial output?

Body:
library(parallel)

nc <- max(detectCores() - 1, 1L)

params %>%
  lift(mcmapply, SIMPLIFY = FALSE, mc.cores = nc)(FUN = my_func, MoreArgs = list(indf = indf))

# [[1]]
#      A    B  C
# 1  500   50  5
# 2 5000 1500 15
# 3  100   50 25
#
# [[2]]
#        A     B   C
# 1  15000  1500 150
# 2 150000 45000 450
# 3   3000  1500 750
#
# [[3]]
#         A      B    C
# 1  -15000  -1500 -150
# 2 -150000 -45000 -450
# 3   -3000  -1500 -750

Edit

Here is a "cleaner" option, that should feel more like using pmap:

nc <- max(parallel::detectCores() - 1, 1L)

par_pmap <- function(.l, .f, ..., mc.cores = getOption("mc.cores", 2L)) {
  do.call(
    parallel::mcmapply,
    c(.l, list(FUN = .f, MoreArgs = list(...), SIMPLIFY = FALSE, mc.cores = mc.cores))
  )
}

library(magrittr)

params %>%
  par_pmap(my_func, indf = indf, mc.cores = nc)

# [[1]]
#      A    B  C
# 1  500   50  5
# 2 5000 1500 15
# 3  100   50 25
#
# [[2]]
#        A     B   C
# 1  15000  1500 150
# 2 150000 45000 450
# 3   3000  1500 750
#
# [[3]]
#         A      B    C
# 1  -15000  -1500 -150
# 2 -150000 -45000 -450
# 3   -3000  -1500 -750


问:
how to handle array of 'promis'
I built a database that contains a list of users who receive messages from firebase with a request key. Every time a new request with status 'open' inserted, I am trying to sort them all by the value of 'Timestamp' and send it by this order to the receivers(each receiver will get one message).
if the list of receivers is empty I want to hold it, until another receiver will be added to the list and continue to the next request.
I am not sure how to send each 'promise' separately one after another-</p>

```<code>exports.notificationListener=functions.database.ref('requests')
.onWrite(event=>{
    const ref = event.data.ref;
    let requests= [];
    var query=ref.orderByChild('TimeStamp');

    query.once('value',function(snap){
        snap.forEach(request=>{
            if(request.val().Status==OPEN)
                requests.push(request.key);
        });
    });
    for (let key of requests) {
       return getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
       )};
     }
 });

function getOnlinReceiversToken() {
    let result = new Promise((resolve, reject) => {
     receiverRef.once('value', (snap) => {
      resolve(snap);
        },
       (err) => {
         reject(err);
      });
    });
    return result.then(snap => {
        snap.forEach(child => {
            if(child.Status == ONLINE){
                let token = helper.getToken(child.key,db);
                break;
            }
        });
        return token;
    });
  }
</code>```

答:
try something like this</p>

```<code>var promisesArray = [];
for (let key of requests) {
   var currentPromise = getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
     });
  promisesArray.push(currentPromise);
}

return Promise.all(promisesArray);
</code>```

Title: how to handle array of 'promis'

Body:
I built a database that contains a list of users who receive messages from firebase with a request key. Every time a new request with status 'open' inserted, I am trying to sort them all by the value of 'Timestamp' and send it by this order to the receivers(each receiver will get one message).
if the list of receivers is empty I want to hold it, until another receiver will be added to the list and continue to the next request.
I am not sure how to send each 'promise' separately one after another-

exports.notificationListener=functions.database.ref('requests')
.onWrite(event=>{
    const ref = event.data.ref;
    let requests= [];
    var query=ref.orderByChild('TimeStamp');

    query.once('value',function(snap){
        snap.forEach(request=>{
            if(request.val().Status==OPEN)
                requests.push(request.key);
        });
    });
    for (let key of requests) {
       return getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
       )};
     }
 });

function getOnlinReceiversToken() {
    let result = new Promise((resolve, reject) => {
     receiverRef.once('value', (snap) => {
      resolve(snap);
        },
       (err) => {
         reject(err);
      });
    });
    return result.then(snap => {
        snap.forEach(child => {
            if(child.Status == ONLINE){
                let token = helper.getToken(child.key,db);
                break;
            }
        });
        return token;
    });
  }

Body:
try something like this

var promisesArray = [];
for (let key of requests) {
   var currentPromise = getOnlinReceiversToken().then(token=>{
       let msg = {
        data: {
          source: key
               }
         };
         return admin.messaging().sendToDevice(token, msg);
     });
  promisesArray.push(currentPromise);
}

return Promise.all(promisesArray);


问:
Using HAL-browser with spring-hateoas WITHOUT spring-data-rest
We're starting a new project, and we're looking into using spring-hateoas / hypermedia. The HAL browser also looks interesting, so we wanted to check it out.

However, the HAL browser seems bundled to spring-data-rest, which we don't want to use (for different reasons).

At a minimum we don't want to auto-expose all repositories as rest-resources, but when doing this we need to explicity define the links for the HAL browser in addition to defining the links with
spring-hateoas.

When NOT auto-exposing the repositories, we have to define

```<code>implements ResourceProcessor<RepositoryLinksResource>
</code>```

and

```<code>@Override
    RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(link('/{id}').withRel('my-dummy'))

        return resource
    }
</code>```

in addition to already defined links (using hateoas)

```<code>link('/{id}').expand(entity.id).withSelfRel()
</code>```

This seems cumbersome, and doesnt comply with the DRY principle.
We would rather not implement the @Override method RepositoryLinksResource process(RepositoryLinksResource resource) as these links are already defined elsewhere.

My initial thought was that the HAL browser would re-use the links already defined with hateoas.
But apparanlty I did not understand it correctly?

So the question is

Is there a way of using the spring-bundled HAL browser without using spring-data-rest?

And without having to manually define the links explicitly for the HAL browser when not auto-exposing the repositories?

答:
The HAL browser provided by Spring can not be used without spring-data-rest.

I had a similar need and had considered the following options...

Package the Spring HAL browser in a separate project (hosted on a different port) and mark your original project with @CrossOrigin.

Package the generic HAL browser.

I did not attempt the first approach and so don't know if you would face any other issues with it.

The second approach was done by downloading the HAL browser (https://github.com/mikekelly/hal-browser) and adding it to the Spring Boot project folder src/resources/public (https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot).

Body:
We're starting a new project, and we're looking into using spring-hateoas / hypermedia. The HAL browser also looks interesting, so we wanted to check it out.

However, the HAL browser seems bundled to spring-data-rest, which we don't want to use (for different reasons).

At a minimum we don't want to auto-expose all repositories as rest-resources, but when doing this we need to explicity define the links for the HAL browser in addition to defining the links with
spring-hateoas.

When NOT auto-exposing the repositories, we have to define

implements ResourceProcessor<RepositoryLinksResource>

and

@Override
    RepositoryLinksResource process(RepositoryLinksResource resource) {
        resource.add(link('/{id}').withRel('my-dummy'))

        return resource
    }

in addition to already defined links (using hateoas)

link('/{id}').expand(entity.id).withSelfRel()

This seems cumbersome, and doesnt comply with the DRY principle.
We would rather not implement the @Override method RepositoryLinksResource process(RepositoryLinksResource resource) as these links are already defined elsewhere.

My initial thought was that the HAL browser would re-use the links already defined with hateoas.
But apparanlty I did not understand it correctly?

So the question is

Is there a way of using the spring-bundled HAL browser without using spring-data-rest?

And without having to manually define the links explicitly for the HAL browser when not auto-exposing the repositories?


问:
How to upload multiple files to BlobStore?
I'm trying to upload multiple files in a form to the BlobStore.

Form:

```<code><form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  <label>Key Name</label><input type="text" name="key_name" size="50"><br/>
  <label>name</label><input type="text" name="name" size="50"><br/>
  <label>image</label><input type="file" name="image" size="50"><br/>
  <label>thumb</label><input type="file" name="thumb" size="50"><br/>
  <input type="submit" name="submit" value="Submit">
</form>
</code>```

I'm then trying to fetch the BlobInfo objects for each of those files uploaded:

```<code>def post(self):
    image_upload_files = self.get_uploads('image')
    thumb_upload_files = self.get_uploads('thumb')
    image_blob_info = image_upload_files[0]
    thumb_blob_info = thumb_upload_files[0]
</code>```

I'm seeing some weird behavior.  Both files are making it into the BlobStore, but I cannot figure out how to get the Keys so that I can store those on another Entity.  The code above manages to get the key for image_blob_info, but not thumb_blob_info.  I don't understand how to use get_uploads.  I want to pass multiple files through the form and then fetch them by name so I can store them in the appropriate BlobReferenceProperties on another Entity.

答:
You could post the files to the same name, followed by [], which will post an array:

```<code><form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  <label>Key Name</label><input type="text" name="key_name" size="50"><br/>
  <label>name</label><input type="text" name="files[]" size="50"><br/>
  <label>image</label><input type="file" name="files[]" size="50"><br/>
  <label>thumb</label><input type="file" name="thumb" size="50"><br/>
  <input type="submit" name="submit" value="Submit">
</form>
</code>```

Then in your form handler, you can something like this (depending on your web framework):

```<code>for uploaded_file in request.FILES.getlist('files'):
    #do something with uploaded_file
</code>```

Body:
I'm trying to upload multiple files in a form to the BlobStore.

Form:

<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  Key Name<input type="text" name="key_name" size="50">

  name<input type="text" name="name" size="50">

  image<input type="file" name="image" size="50">

  thumb<input type="file" name="thumb" size="50">

  <input type="submit" name="submit" value="Submit">
</form>

I'm then trying to fetch the BlobInfo objects for each of those files uploaded:

def post(self):
    image_upload_files = self.get_uploads('image')
    thumb_upload_files = self.get_uploads('thumb')
    image_blob_info = image_upload_files[0]
    thumb_blob_info = thumb_upload_files[0]

I'm seeing some weird behavior.  Both files are making it into the BlobStore, but I cannot figure out how to get the Keys so that I can store those on another Entity.  The code above manages to get the key for image_blob_info, but not thumb_blob_info.  I don't understand how to use get_uploads.  I want to pass multiple files through the form and then fetch them by name so I can store them in the appropriate BlobReferenceProperties on another Entity.

Body:
You could post the files to the same name, followed by [], which will post an array:

<form action="{{upload_url}}" method="POST" enctype="multipart/form-data">
  <label>Key Name</label><input type="text" name="key_name" size="50"><br/>
  <label>name</label><input type="text" name="files[]" size="50"><br/>
  <label>image</label><input type="file" name="files[]" size="50"><br/>
  <label>thumb</label><input type="file" name="thumb" size="50"><br/>
  <input type="submit" name="submit" value="Submit">
</form>

Then in your form handler, you can something like this (depending on your web framework):

for uploaded_file in request.FILES.getlist('files'):
    #do something with uploaded_file


问:
How to change variable value in return of render with reactjs?
```<code>render() {
    let inputText=this.props.searchData
    console.log(inputText);
    let Inputreg = inputText.toLowerCase()
    console.log(Inputreg)
    console.log(this.state.Product)
    let Product= this.state.Product;
    let flag = 0;
        return(
            <div>
           { this.state.Product.map((obj,index)=> {

                let productNameLow = obj.name.toLowerCase()
                console.log(productNameLow)
                var arr = productNameLow.split(' ');
                console.log(arr)
                console.log(Inputreg)
                let n =(inArray(arr, Inputreg));
                console.log(n)
                if (n > 0) {
                    return (
                            <div className ="Product" key={index}>
                                <div className="card">
                                    {<Link to ={{pathname: './ProductDescription' , state: { item: obj } }} className="card-img-top"><img src={obj.thumbBig[0]} alt="" /></Link>}
                                    <div className="card-body">
                                        <h4 className="card-title">{obj.name}</h4>
                                        <p className="card-text-right"></p>
                                        <input type="button" value="Add to Cart" onClick={e=>this.handleClick(obj.name,obj.price,obj.thumbBig[0],index)}/>
                                        <input type="button" value="Add to Favourite" className="fav-button" id={index} onClick={e=>this.props.getFavourite(index)}/>
                                    </div>
                                </div>
                            </div>
                    )
                    {flag = 1}// flag value is not being set to 1
                }
            })}

                {(() => {
                        if(flag == 1){
                            return (
                                <div>
                                <h2>No such product exist. Try another search</h2>
                                </div>
                            )
                        }
                    })()} // function is self invoked , although i wanted to invoke this flag condition after my if(n>0) loop is completely iterated.

        </div>
    )
}
</code>```

I want to return the search products according to the if(n>0)condition and set flag value to 1 , if flag value remains 0 which i have initialized to 0 only , then i want to return only message. But the flag condition should be checked after the completion of if loop.

答:
```<code>render() {
    let inputText = this.props.searchData;
    let Inputreg = inputText.toLowerCase();
    let Product = this.state.Product;
    let flag = 0;
        return(
           <div>
           { this.state.Product.map((obj,index)=> {

                let productNameLow = obj.name.toLowerCase()
                console.log(productNameLow)
                var arr = productNameLow.split(' ');
                console.log(arr)
                console.log(Inputreg)
                let n =(inArray(arr, Inputreg));
                console.log(n)
                if (n > 0) {
                    return (
                            <div className ="Product" key={index}>
                                <div className="card">
                                    {<Link to ={{pathname: './ProductDescription' , state: { item: obj } }} className="card-img-top"><img src={obj.thumbBig[0]} alt="" /></Link>}
                                    <div className="card-body">
                                        <h4 className="card-title">{obj.name}</h4>
                                        <p className="card-text-right"></p>
                                    </div>
                                </div>
                            </div>
                    )
                    {flag = 1}
                }
            })}

             {(flag == 0) &&
                     <h2>No such product exist. Try another search</h2>

             }
             {(flag !== 0) &&
              <h2>Some other message</h2>
             }
        </div>
    )
}
</code>```

Let me know if it helped. As far as my understanding this should solve your problem

Body:
render() {
    let inputText=this.props.searchData
    console.log(inputText);
    let Inputreg = inputText.toLowerCase()
    console.log(Inputreg)
    console.log(this.state.Product)
    let Product= this.state.Product;
    let flag = 0;
        return(

           { this.state.Product.map((obj,index)=> {

                let productNameLow = obj.name.toLowerCase()
                console.log(productNameLow)
                var arr = productNameLow.split(' ');
                console.log(arr)
                console.log(Inputreg)
                let n =(inArray(arr, Inputreg));
                console.log(n)
                if (n > 0) {
                    return (

                                    {<Link to ={{pathname: './ProductDescription' , state: { item: obj } }} className="card-img-top"></Link>}

{obj.name}

                                        <input type="button" value="Add to Cart" onClick={e=>this.handleClick(obj.name,obj.price,obj.thumbBig[0],index)}/>
                                        <input type="button" value="Add to Favourite" className="fav-button" id={index} onClick={e=>this.props.getFavourite(index)}/>

                    )
                    {flag = 1}// flag value is not being set to 1
                }
            })}

                {(() => {
                        if(flag == 1){
                            return (

No such product exist. Try another search

                            )
                        }
                    })()} // function is self invoked , although i wanted to invoke this flag condition after my if(n>0) loop is completely iterated.

    )
}

I want to return the search products according to the if(n>0)condition and set flag value to 1 , if flag value remains 0 which i have initialized to 0 only , then i want to return only message. But the flag condition should be checked after the completion of if loop.

Body:
render() {
    let inputText = this.props.searchData;
    let Inputreg = inputText.toLowerCase();
    let Product = this.state.Product;
    let flag = 0;
        return(
           <div>
           { this.state.Product.map((obj,index)=> {

                let productNameLow = obj.name.toLowerCase()
                console.log(productNameLow)
                var arr = productNameLow.split(' ');
                console.log(arr)
                console.log(Inputreg)
                let n =(inArray(arr, Inputreg));
                console.log(n)
                if (n > 0) {
                    return (
                            <div className ="Product" key={index}>
                                <div className="card">
                                    {<Link to ={{pathname: './ProductDescription' , state: { item: obj } }} className="card-img-top"><img src={obj.thumbBig[0]} alt="" /></Link>}
                                    <div className="card-body">
                                        <h4 className="card-title">{obj.name}</h4>
                                        <p className="card-text-right"></p>
                                    </div>
                                </div>
                            </div>
                    )
                    {flag = 1}
                }
            })}

             {(flag == 0) &&
                     <h2>No such product exist. Try another search</h2>

             }
             {(flag !== 0) &&
              <h2>Some other message</h2>
             }
        </div>
    )
}

Let me know if it helped. As far as my understanding this should solve your problem


问:
How to make an extension for nvarchar max? Fluent nHibernate + Nhibernate
I been looking around for how to do this but I can't get it to work. I seen many tutorials that using

PropertyMap or IProperty but I can't figure out what using statement to use and VS intellisense does not know either

http://serialseb.blogspot.com/2009/01/fluent-nhibernate-and-nvarcharmax.html

I am using fluent nhibernate and nihbernate 3.0. So did they remove these?

答:
I haven't tested, but try extending PropertyBuilder, using the method PropertyBuilder.Length(int length).

https://github.com/jagregory/fluent-nhibernate/blob/master/src/FluentNHibernate/Mapping/Builders/PropertyBuilder.cs


问:
DataGrid for Android
Hello i want to build an Android application to handle my budget. I have build an budget-app before but that was in WPF and with C#. In WPF there is something called DataGrid that looks something like this

https://www.codeproject.com/KB/WPF/WPFDataGridExamples/datasetgrid.png
(I am not allowed to post images)

And i was wondering if there was something like this in Android, that could display a table of information to the user.

Thank you.

答: You can use RecyclerView with GridLayoutManager. It is very easy to implement.

Title: DataGrid for Android


问:
SQL: Missing right parenthesis and table or view does not exist errors
I am trying to create 5 tables, however the first 3 drop and create fine with no issues but the last 2 band and fan do not seem to have much luck.

```<code>DROP TABLE festival cascade constraints;
CREATE TABLE festival (
 Festival_ID    VARCHAR2(4) PRIMARY KEY,
 Festival_Organizer     varchar2(30),
 Festival_Location  varchar2(20));

DROP TABLE venue cascade constraints;
CREATE TABLE venue(
 Venue_ID   VARCHAR2(3) PRIMARY KEY,
 Venue_Name     VARCHAR2(25),
 Venue_Location VARCHAR2(15),
 Venue_Contact_Person VARCHAR2(30),
 Venue_Contact_Number NUMERIC(9,2),
 Venue_Type VARCHAR2(15),
 Venue_Size VARCHAR2(6),
 Venue_HirePrice FLOAT(8));

DROP TABLE staff cascade constraints;
CREATE TABLE staff(
 Staff_ID   VARCHAR2(3) PRIMARY KEY,
 Staff_Firstname    VARCHAR2(20),
 Staff_Surname  VARCHAR2(25),
 Staff_Specialism   VARCHAR2(20),
 Staff_Salary   NUMERIC(8,2),
 Staff_Contact_Number   NUMERIC(9,2),
 Staff_Address  VARCHAR2(50),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE band cascade constraints;
CREATE TABLE band(
 Band_ID    VARCHAR2(3) PRIMARY KEY,
 Band_Name  VARCHAR2(25),
 Band_ContactNo NUMERIC(8,2),
 Band_PlayDate  DATE NOT NULL,
 Band_PlayTime  TIME (8) NOT NULL,
 Band_Storage_Location  VARCHAR2(30),
 Band_Agent VARCHAR2(25),
 Band_AE    VARCHAR2 (3),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE fan cascade constraints;
CREATE TABLE fan(
 Fan_ID VARCHAR(6) PRIMARY KEY,
 Fan_Firstname  VARCHAR2(15),
 Fan_Surname    VARCHAR2(30),
 Fan_Contact_Number NUMERIC(9,2),
 Fan_Address    VARCHAR2(50),
 Fan_DOB    DATE NOT NULL,
 Band_ID    VARCHAR2(5) REFERENCES band(Band_ID));
</code>```

When I run the code I get the following errors:

DROP TABLE band cascade constraints    ORA-00942: table or view does not exist

CREATE TABLE band( Band_ID VARCHAR2(3) PRIMARY KEY, Band_Nam   ORA-00907: missing right parenthesis

DROP TABLE fan cascade constraints ORA-00942: table or view does not exist

CREATE TABLE fan( Fan_ID   VARCHAR(6) PRIMARY KEY, Fan_Firstna ORA-00942: table or view does not exist

答:
The ORA-00942 errors for the DROP TABLE statements are expected because you are indeed trying to drop tables which do not exist. So you don't need to worry about those.

The ORA-00907 error when you try to create the BAND table is because of this line:

"Venue_Contact_Number NUMERIC(9,2),"

numeric is not a valid Oracle data type. You meant NUMBER.

Then, because you didn't create the BAND table you get ORA-00942 when you try to create the FAN table. This is because FAN has a foreign key which references the BAND table.

As a beginner you need to learn how to read your own code with a cool eye so that you can spot the bugs. When you run a whole bunch of related statements in one script there is the risk that a single bug will cascade into a series of errors. When this happens, extract the first failing statement and work it on in isolation. Quite often removing that bug will clear up all the other fails, which should be the case here.

Body:
I am trying to create 5 tables, however the first 3 drop and create fine with no issues but the last 2 band and fan do not seem to have much luck.

DROP TABLE festival cascade constraints;
CREATE TABLE festival (
 Festival_ID    VARCHAR2(4) PRIMARY KEY,
 Festival_Organizer     varchar2(30),
 Festival_Location  varchar2(20));

DROP TABLE venue cascade constraints;
CREATE TABLE venue(
 Venue_ID   VARCHAR2(3) PRIMARY KEY,
 Venue_Name     VARCHAR2(25),
 Venue_Location VARCHAR2(15),
 Venue_Contact_Person VARCHAR2(30),
 Venue_Contact_Number NUMERIC(9,2),
 Venue_Type VARCHAR2(15),
 Venue_Size VARCHAR2(6),
 Venue_HirePrice FLOAT(8));

DROP TABLE staff cascade constraints;
CREATE TABLE staff(
 Staff_ID   VARCHAR2(3) PRIMARY KEY,
 Staff_Firstname    VARCHAR2(20),
 Staff_Surname  VARCHAR2(25),
 Staff_Specialism   VARCHAR2(20),
 Staff_Salary   NUMERIC(8,2),
 Staff_Contact_Number   NUMERIC(9,2),
 Staff_Address  VARCHAR2(50),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE band cascade constraints;
CREATE TABLE band(
 Band_ID    VARCHAR2(3) PRIMARY KEY,
 Band_Name  VARCHAR2(25),
 Band_ContactNo NUMERIC(8,2),
 Band_PlayDate  DATE NOT NULL,
 Band_PlayTime  TIME (8) NOT NULL,
 Band_Storage_Location  VARCHAR2(30),
 Band_Agent VARCHAR2(25),
 Band_AE    VARCHAR2 (3),
 Venue_ID   VARCHAR2(5) REFERENCES venue(Venue_ID));

DROP TABLE fan cascade constraints;
CREATE TABLE fan(
 Fan_ID VARCHAR(6) PRIMARY KEY,
 Fan_Firstname  VARCHAR2(15),
 Fan_Surname    VARCHAR2(30),
 Fan_Contact_Number NUMERIC(9,2),
 Fan_Address    VARCHAR2(50),
 Fan_DOB    DATE NOT NULL,
 Band_ID    VARCHAR2(5) REFERENCES band(Band_ID));

When I run the code I get the following errors:

DROP TABLE band cascade constraints    ORA-00942: table or view does not exist

CREATE TABLE band( Band_ID VARCHAR2(3) PRIMARY KEY, Band_Nam   ORA-00907: missing right parenthesis

DROP TABLE fan cascade constraints ORA-00942: table or view does not exist

CREATE TABLE fan( Fan_ID   VARCHAR(6) PRIMARY KEY, Fan_Firstna ORA-00942: table or view does not exist


问:
code to close a matlab app
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:</p>

```<code> % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end
</code>```

答:
You can do this</p>

```<code>%Draw EXIT push button refer to exitFcn function
uicontrol(handles(1),'Style','PushButton','Units','normalized',...
    'Position',[0.8158 0.05 0.1 0.1],...
    'String','Exit',...
    'Callback',@ButtonexitFcn);

return;
%---------------------------------------------------------------------
function ButtonexitFcn(varargin)
%This function close all figures and terminate program
    close all;
return;
</code>```

Title: code to close a matlab app

Body:
I have written a Matlab app with the app designer tool, and have successfully coded everything except the pesky (and most likely simple) exit button. The button itself should do what it says, close the app when clicked, but looking online has just led me to dead ends. Here is what I have written down for the exit function; it doesn't work, but its better than writing no code:

 % Button pushed function: ExitButton
    function ExitButtonPushed(app, event)
        Figurename = app.UIFigure ;
        close Figurename
    end

Body:
You can do this

%Draw EXIT push button refer to exitFcn function
uicontrol(handles(1),'Style','PushButton','Units','normalized',...
    'Position',[0.8158 0.05 0.1 0.1],...
    'String','Exit',...
    'Callback',@ButtonexitFcn);

return;
%---------------------------------------------------------------------
function ButtonexitFcn(varargin)
%This function close all figures and terminate program
    close all;
return;


答:
```<code>public class MainActivity extends AppCompatActivity {

    // i used this array list for quick purpose
    // better way to use data models

    private String[][] gradingData = new String[][]{
            {"S.N", "Range", "Grading", "Description", "GP"},
            {"1", "90-100", "A+", "Outstanding", "4.0"},
            {"2", "80-90", "A", "Excellent", "3.6"},
            {"3", "70-80", "B+", "Very Good", "3.2"},
            {"4", "60-70", "B", "Good", "2.8"},
            {"5", "50-60", "C", "Average", "2.4"},
            {"6", "Below 50", "D", "Below Average", "2.0"},
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout parentLayout = findViewById(R.id.parentLayout);
        parentLayout.addView(createTableLayout(7, 5));
    }

    private TableLayout createTableLayout(int rowCount, int columnCount) {
        // 1) Create a tableLayout and its params
        TableLayout.LayoutParams tableLayoutParams = new TableLayout.LayoutParams();
        TableLayout tableLayout = new TableLayout(this);
        //  tableLayout.setBackgroundColor(Color.BLACK);

        // 2) create tableRow params
        TableRow.LayoutParams tableRowParams = new TableRow.LayoutParams();
        tableRowParams.weight = 1;

        for (int i = 0; i < rowCount; i++) {
            // 3) create tableRow
            TableRow tableRow = new TableRow(this);
            // tableRow.setBackgroundColor(Color.BLACK);
            for (int j = 0; j < columnCount; j++) {
                // 4) create textView
                TextView textView = new TextView(this);
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(10, 10, 10, 10);
                textView.setBackground(getResources().getDrawable(R.drawable.textview_border));
                textView.setText(gradingData[i][j]);
                if (i == 0) {
                    textView.setBackgroundColor(Color.parseColor("#aeaeae"));
                }
                tableRow.addView(textView, tableRowParams);
            }
            tableLayout.addView(tableRow, tableLayoutParams);
        }

        return tableLayout;
    }
}
</code>```

Title: DataGrid for Android

Body:
Hello i want to build an Android application to handle my budget. I have build an budget-app before but that was in WPF and with C#. In WPF there is something called DataGrid that looks something like this

https://www.codeproject.com/KB/WPF/WPFDataGridExamples/datasetgrid.png
(I am not allowed to post images)

And i was wondering if there was something like this in Android, that could display a table of information to the user.

Thank you.