问:
how to exclude mongodb _id field in php result
I'm trying to exclude the _id field from PHP-MongoDB result.below is my PHP script.What I can add to the script to exclude _id from the output.</p>

```<code><?php
try
{
    $connection = new Mongo('mongodb://user:pass@xxxx.mlab.com:xxxxx/stats');
    $database   = $connection->selectDB('stats');
    $collection = $database->selectCollection('stat');
}
catch(MongoConnectionException $e)
{
    die("Failed to connect to database ".$e->getMessage());
}

$cursor = $collection->find();

echo json_encode(iterator_to_array($cursor));

?>
</code>```

答:
Add:-

```<code>$cursor->fields(array('_id'=>false));
</code>```

After the find...

Body:
I'm trying to exclude the _id field from PHP-MongoDB result.below is my PHP script.What I can add to the script to exclude _id from the output.

<?php
try
{
    $connection = new Mongo('mongodb://user:pass@xxxx.mlab.com:xxxxx/stats');
    $database   = $connection->selectDB('stats');
    $collection = $database->selectCollection('stat');
}
catch(MongoConnectionException $e)
{
    die("Failed to connect to database ".$e->getMessage());
}

$cursor = $collection->find();

echo json_encode(iterator_to_array($cursor));

?>

Body:
Add:-

$cursor->fields(array('_id'=>false));

After the find...


来源: stackexchange

问:
PHP Security - Sanitize & Clean
I have a built a script around class.upload from http://www.verot.net/php_class_upload.htm

Basically what it is that all my images are stored on the server in a directory called /images/

The script I built basically takes some parameters from my website such as /xyzDir/tomnjerry.jpg?w=100&h=100&fill=1&color=fff

Then I have mod_rewrite which reads the file from /xyzDir/ into a php script which then translates the width and height and returns the image.

Lately I have noticed some idiots from Turkey trying to input weird characters into the parameters w= and h=

On my script I do check to make sure only integer is allowed in width and heigh and fill can be either 1 or 2 and color can only be certain values which i check via array.

I just want to see if there is anything else I should be doing in order to avoid getting hacked.

Thanks

答:
Always remember, Filter In, Escape Out for all user supplied (or untrusted) input.

When reading user supplied data, filter it to known values.  DO NOT BLACKLIST!  Always always always always whitelist what you are expecting to get.  If you're expecting a hex number, validate it with a regex like: ^[a-f0-9]+$.  Figure out what you expect, and filter towards that.  Do none of your filenames have anything but alpha, numeric and .?  Then filter to ^[a-z0-9.]+$.  But don't start thinking blacklisting against things.  It won't work.

When using user-data, escape it properly for the use at hand.  If it's going in a database, either bind it as a parameterized query, or escape it with the database's escape function.  If you're calling a shell command, escape it with escapeshellarg().  If you're using it in a regex pattern, escape it with preg_quote().  There are more than that, but you get the idea.

When outputting user data, escape it properly for the format you're outputting it as.  If you're outputting it to HTML or XML, use htmlspecialchars().  If you're outputting to raw headers for some reason, escape any linebreaks (str_replace(array("\r", "\n"), array('\r', '\n'), $string)).  Etc, etc, etc.

But always filter using a white-list, and always escape using the correct method for the context.  Otherwise there's a significant chance you'll miss something...

ContentLicense: CC BY-SA 2.5

Title: PHP Security - Sanitize & Clean


问:
Detect call events in iOS?
I have seen some examples on how to detect incoming/outgoing call events on background in iOS. Apparently, I have to use CTCallCenter.

Will this solution work only for iOS 10+/swift 3?

Will I be able to open the app immediately after the call has ended?

Will I be able to record calls? Starting with what iOS version this is possible?

答:
Yes this class is available in iOS 10.

No, you can only detect a phone call while in the foreground.

No, this is not really possible, you might be able to start recording sound but only the user mic.

ContentLicense: CC BY-SA 3.0

Title: Detect call events in iOS?


问:
pip install returning invalid syntax
I've just installed python 3.6 which comes with pip

However, in Windows command prompt, when I do: 'pip install bs4' it returns 'SyntaxError: invalid syntax' under the install word.

Typing 'python' returns the version, which means it is installed correctly. What could be the problem?

答:
Try:

```<code>pip3 install bs4
</code>```

If you have python2 installed you typically have to make sure you are using the correct version of pip.

Title: pip install returning invalid syntax

Body:
Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.


问:
Operator '!=' cannot be applied to operands of type 'bool' and 'int' (CS0019)
I get the error in the title when i do this:

```<code>else if (celsius<73 != 0)
{
    Console.WriteLine("Tyvärr så är " + celsius + "° för låg temperatur, ställ in värmen mellan 73 till 77 grader."); //
    Console.Write("Välj temperatur igen : ");
</code>```

I want it to come out false if celsius is 0, sry for my bad english.

答:
You cannot compare a bool(which is what celsius<73 returns) with an integer 0.

I think you want that celsius is <73 and != 0:

```<code>else if (celsius < 73 && celsius != 0)
{}
</code>```

Body:
I get the error in the title when i do this:

else if (celsius<73 != 0)
{
    Console.WriteLine("Tyvärr så är " + celsius + "° för låg temperatur, ställ in värmen mellan 73 till 77 grader."); //
    Console.Write("Välj temperatur igen : ");

I want it to come out false if celsius is 0, sry for my bad english.

Body:
You cannot compare a bool(which is what celsius<73 returns) with an integer 0.

I think you want that celsius is <73 and != 0:

else if (celsius < 73 && celsius != 0)
{}


答:
I want it to come out false if celsius is 0

If you want to do multiple comparisons against a variable, they need to be specified separately.

Thus:

```<code>else if (celsius<73 != 0)
</code>```

should instead be:

```<code>else if (celsius<73 && celsius != 0)
</code>```

Title: Operator '!=' cannot be applied to operands of type 'bool' and 'int' (CS0019)

Body:
I want it to come out false if celsius is 0

If you want to do multiple comparisons against a variable, they need to be specified separately.

Thus:

else if (celsius<73 != 0)

should instead be:

else if (celsius<73 && celsius != 0)


问:
Rails Hartl Tutorial: Getting an SSL error every time I go to the page to activate a new user
I'm following along Michael Hartl's Rails tutorial, and I've seem to hit a wall in Chapter 11 Link to relevant section.  I'm running this from my own computer, so I'm visiting localhost:3000.  I create a new user via the signup page in the app, and I can check the rails server logs to see the email that is generated with the link for activation.  However, when I follow the link I get an error in chrome (and other browsers as well) saying:

This site can’t provide a secure connection

localhost sent an invalid response.

Try running Windows Network Diagnostics.

ERR_SSL_PROTOCOL_ERROR

My server logs state:

```<code>2017-06-01 21:03:21 -0400: HTTP parse error, malformed request (): #
<Puma::HttpParserError: Invalid HTTP format, parsing fails.>
2017-06-01 21:03:21 -0400: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#<IO:
<STDERR>>, "rack.multithread"=>true, "rack.multiprocess"=>false,
"rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"",
"SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"puma 3.4.0 Owl Bowl
Brawl", "GATEWAY_INTERFACE"=>"CGI/1.2"}
</code>```

I've tried turning off my firewall, resetting my cache and cookies, and other solutions I found on the web, but nothing seems to do the trick.  I know common practice is to give relevant snippets of application code, but I honestly don't even know where to begin with that.  If there's any files you need to see, then I'll be happy to post them.  Thanks.

答:
I ran into the same Problem and it took me some time to solve it. Probably You solved it by now.
So to save others the time finding the solution, I just want to share it here. The solution is to just hit localhost:3000 without the https://
This way there is now ssl decryption/parsing involved, which is not necessary in development and will only cause a parsing error.

Best Sebastian

Body:
I'm following along Michael Hartl's Rails tutorial, and I've seem to hit a wall in Chapter 11 Link to relevant section.  I'm running this from my own computer, so I'm visiting localhost:3000.  I create a new user via the signup page in the app, and I can check the rails server logs to see the email that is generated with the link for activation.  However, when I follow the link I get an error in chrome (and other browsers as well) saying:

This site can’t provide a secure connection

localhost sent an invalid response.

Try running Windows Network Diagnostics.

ERR_SSL_PROTOCOL_ERROR

My server logs state:

2017-06-01 21:03:21 -0400: HTTP parse error, malformed request (): #
<Puma::HttpParserError: Invalid HTTP format, parsing fails.>
2017-06-01 21:03:21 -0400: ENV: {"rack.version"=>[1, 3], "rack.errors"=>#<IO:
<STDERR>>, "rack.multithread"=>true, "rack.multiprocess"=>false,
"rack.run_once"=>false, "SCRIPT_NAME"=>"", "QUERY_STRING"=>"",
"SERVER_PROTOCOL"=>"HTTP/1.1", "SERVER_SOFTWARE"=>"puma 3.4.0 Owl Bowl
Brawl", "GATEWAY_INTERFACE"=>"CGI/1.2"}

I've tried turning off my firewall, resetting my cache and cookies, and other solutions I found on the web, but nothing seems to do the trick.  I know common practice is to give relevant snippets of application code, but I honestly don't even know where to begin with that.  If there's any files you need to see, then I'll be happy to post them.  Thanks.


问:
Where to find the Facebook cookie?
I'm kinda new to this so bear with me.
I've installed a "Login with Facebook" button via the Javascript SDK, which works fine.
I've also set up the PHP code (facebook.php)
I can login successfully to Facebook via javascript but then can't access the UID from the session via php.
So, how can I get php to access the session javascript sets?
thanks

Edit: (Posting code from below here so it'll be easier to read)

I can console log the response and see it.

```<code>FB.getLoginStatus(function(response) {
    console.log(response.session.uid);
});
</code>```

Refresh the page, and try to access the session that was set via php, it comes up null.

```<code>require_once(RELATIVE_PATH.'applibs/facebook.php');
$config = array('appId'=>Config::$fb_app_id, 'secret'=>Config::$fb_secret, 'cookie'=>true);
$fb = new Facebook($config);
$fb->getUser(); // this will equal null because the $fb object isnt finding the cookie supposedly set by javascript
</code>```

* Did some debugging in the facebook.php

on line 358...
    $cookieName = $this->getSessionCookieName();

    // retuns fbs_myNumericAppId, seems like that worked..

    if (isset($_COOKIE[$cookieName])) {

    // FAILS! there is no $_COOKIE['fbs_myNumericAppId']

That seems logical as how could logging into facebook.com know what my app ID is?

I also noticed after logging into facebook.com, there's NOTHING facebook related in $_COOKIE.
So, in order to log into facebook via facebook.com, then have a website notice that login, you have to run FB.login on a page load.
Then you have to set a cookie via the javacript info returned into $_COOKIE so the php can pick it up anywhere else.

答:
I happen to have a blog post and some previous answers that may be of use to you as reference points.

Have you registered your site on Facebook as an "application"?  If not, you'll need to do that.  The cookie which Facebook sets that allows your site to access a user's information (once they've agreed to give your "application" access) uses a combination of your application's ID and "secret" (a long alphanumeric string that you must not share, or other applications would be able to impersonate yours) to set an encrypted value with the user's ID and an authentication token unique to the user and your application (representing the permission they've given you to their data).

The cookie is posted to your site alongside requests like any other cookie.  You'd use your application's secret to decrypt it and extract the user's ID and authentication token, which you would then use to access data via Facebook's graph API.

Title: Where to find the Facebook cookie?

Body:
I'm kinda new to this so bear with me.
I've installed a "Login with Facebook" button via the Javascript SDK, which works fine.
I've also set up the PHP code (facebook.php)
I can login successfully to Facebook via javascript but then can't access the UID from the session via php.
So, how can I get php to access the session javascript sets?
thanks

Edit: (Posting code from below here so it'll be easier to read)

I can console log the response and see it.

FB.getLoginStatus(function(response) {
    console.log(response.session.uid);
});

Refresh the page, and try to access the session that was set via php, it comes up null.

require_once(RELATIVE_PATH.'applibs/facebook.php');
$config = array('appId'=>Config::$fb_app_id, 'secret'=>Config::$fb_secret, 'cookie'=>true);
$fb = new Facebook($config);
$fb->getUser(); // this will equal null because the $fb object isnt finding the cookie supposedly set by javascript

* Did some debugging in the facebook.php

on line 358...
    $cookieName = $this->getSessionCookieName();

    // retuns fbs_myNumericAppId, seems like that worked..

    if (isset($_COOKIE[$cookieName])) {

    // FAILS! there is no $_COOKIE['fbs_myNumericAppId']

That seems logical as how could logging into facebook.com know what my app ID is?

I also noticed after logging into facebook.com, there's NOTHING facebook related in $_COOKIE.
So, in order to log into facebook via facebook.com, then have a website notice that login, you have to run FB.login on a page load.
Then you have to set a cookie via the javacript info returned into $_COOKIE so the php can pick it up anywhere else.


答:
If this is true ....

I want it to come out false if celsius is 0, sry for my bad english.

... then change it to:

```<code>if (celsius != 0)
{
}
</code>```

Body:
If this is true ....

I want it to come out false if celsius is 0, sry for my bad english.

... then change it to:

if (celsius != 0)
{
}


问:
Nightmare.js script on quora not working properly

I have written this script to log into quora.

```<code>var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
  .goto('https://www.quora.com/')
  .type('input[name="email"]','xyz@gmail.com')
  .type('input[type="password"]','pass123')
  .click('input[type="submit"]')
  .wait(5000)
  .click('.disable_click_on_edit_mode')
  .wait(5000)
  .evaluate(function () {
    return document.querySelectorAll('.question_link').href;
  })
  .end()
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.error('Error message:', error);
  });
</code>```

It should easily login to quora by entering my email in the email field and my password in my password field and then clicking the login button.

But when i run this script, it enters the email as well as the password, both inside the email field and then results into an error.

答:
Ok, I tried and found another solution that is working. As only there are two input box in that login page, you can use this:</p>

```<code>nightmare
  .goto('https://www.quora.com/')
  .type('input[tabindex="1"]','xyz@gmail.com')
  .type('input[tabindex="2"]','pass123')
  .click('input[type="submit"]')
  .wait(5000)
  .click('.disable_click_on_edit_mode')
  .wait(5000)
  .evaluate(function () {
    return document.querySelectorAll('.question_link').href;
  })
</code>```

Body:
I have written this script to log into quora.

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });

nightmare
  .goto('https://www.quora.com/')
  .type('input[name="email"]','xyz@gmail.com')
  .type('input[type="password"]','pass123')
  .click('input[type="submit"]')
  .wait(5000)
  .click('.disable_click_on_edit_mode')
  .wait(5000)
  .evaluate(function () {
    return document.querySelectorAll('.question_link').href;
  })
  .end()
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.error('Error message:', error);
  });

It should easily login to quora by entering my email in the email field and my password in my password field and then clicking the login button.

But when i run this script, it enters the email as well as the password, both inside the email field and then results into an error.

Body:
Ok, I tried and found another solution that is working. As only there are two input box in that login page, you can use this:

nightmare
  .goto('https://www.quora.com/')
  .type('input[tabindex="1"]','xyz@gmail.com')
  .type('input[tabindex="2"]','pass123')
  .click('input[type="submit"]')
  .wait(5000)
  .click('.disable_click_on_edit_mode')
  .wait(5000)
  .evaluate(function () {
    return document.querySelectorAll('.question_link').href;
  })


问:
Need margin for LinearAxis by OxyPlot
I use C#, wpf, OxyPolt.

I need margin for label "Title name, m".

```<code>xmlns:oxy="http://oxyplot.org/wpf"

<oxy:Plot>
   <oxy:Plot.Series>
      <oxy:LineSeries ItemsSource="{Binding DataVM}"
                      StrokeThickness="2" DataFieldX="X" DataFieldY="Y"/>
   </oxy:Plot.Series>
   <oxy:Plot.Axes>
       <oxy:LinearAxis Position="Bottom" Title="Title name"/>
       <oxy:LinearAxis Position="Left" Title="Title name, m"/>
   </oxy:Plot.Axes>
</oxy:Plot>
</code>```

答:
You can use following property:   AxisTitleDistance="30"  </p>

```<code> <oxy:Plot>
        <oxy:Plot.Series>
            <oxy:LineSeries ItemsSource="{Binding DataVM}"
                  StrokeThickness="2" DataFieldX="X" DataFieldY="Y"/>
        </oxy:Plot.Series>
        <oxy:Plot.Axes>
            <oxy:LinearAxis Position="Bottom" AxisTitleDistance="30" Title="Title name"/>
            <oxy:LinearAxis Position="Left" AxisTitleDistance="30"  Title="Title name, m"/>
        </oxy:Plot.Axes>
    </oxy:Plot>
</code>```

Title: Need margin for LinearAxis by OxyPlot

Body:
I use C#, wpf, OxyPolt.

I need margin for label "Title name, m".

xmlns:oxy="http://oxyplot.org/wpf"

<oxy:Plot>
   <oxy:Plot.Series>
      <oxy:LineSeries ItemsSource="{Binding DataVM}"
                      StrokeThickness="2" DataFieldX="X" DataFieldY="Y"/>
   </oxy:Plot.Series>
   <oxy:Plot.Axes>
       <oxy:LinearAxis Position="Bottom" Title="Title name"/>
       <oxy:LinearAxis Position="Left" Title="Title name, m"/>
   </oxy:Plot.Axes>
</oxy:Plot>

Body:
You can use following property:   AxisTitleDistance="30"

 <oxy:Plot>
        <oxy:Plot.Series>
            <oxy:LineSeries ItemsSource="{Binding DataVM}"
                  StrokeThickness="2" DataFieldX="X" DataFieldY="Y"/>
        </oxy:Plot.Series>
        <oxy:Plot.Axes>
            <oxy:LinearAxis Position="Bottom" AxisTitleDistance="30" Title="Title name"/>
            <oxy:LinearAxis Position="Left" AxisTitleDistance="30"  Title="Title name, m"/>
        </oxy:Plot.Axes>
    </oxy:Plot>


问:
Lucene TermFrequenciesVector
what do I obtain if I call IndexReader.getTermFrequenciesVector(...) on an index created with TermVector.YES option?

答:
The documentation already answers this, as Xodorap notes in a comment.

The TermFreqVector object returned can retrieve which terms (words produced by your analyzer) a field contains and how many times each of those terms exists within that field.

You can cast the returned TermFreqVector to the interface TermPositionVector if you index the field using TermVector.WITH_OFFSETS, TermVector.WITH_POSITIONS or TermVector.WITH_POSITIONS_OFFSETS. This gives you access to GetTermPositions with allow you to check where in the field the term exists, and GetOffsets which allows you to check where in the original content the term originated from. The later allows, combined with Store.YES, highlighting of matching terms in a search query.

There are different contributed highlighters available under Contrib area found at the Lucene homepage.

Title: Lucene TermFrequenciesVector


问:
plot with x axis at the bottom and y axis on top in ggplot2?
I have a table with coordinate data that looks like this,

```<code>V1       V2      V3       V4
10253363 10273825 9982154 10003803
10265080 10285697 9993266 10015040
10250800 10271301 9979709 10001394
10254775 10275140 9983264 10004815
10268607 10288871 9995004 10016450
10263978 10284276 9992831 10014300
</code>```

And I'd like to generate a plot similar to the one shown below,

I tried this,

```<code>blast <- fread("../plots/coords.tsv")
blast$id = as.numeric(rownames(blast))
ggplot(blast)+
  geom_rect(aes(xmin=V1,xmax=V2,ymin=V3,ymax=V4, group = id), alpha=0.2) +
  scale_y_continuous(position = "top")
</code>```

and ended up with the plot below instead.

It seems like y axis position could only be flipped between right and left. Therefore, this isn't working for me.

How do I generate the intended plot in ggplot2? Or is there another way to get at that?

答:
That's not so easy, as you need to reshape and then trick ggplot2 a little.

The conversion factor is needed, since ggplot doesn't really allow separate axes, only relabeling based on simple conversions.

Also see this related answer.

You have a bunch of overlapping ranges, so it doesn't quite look like your example plot.

```<code>library(tidyr)
library(dplyr)
library(ggplot2)

conversion_factor <- mean(c(blast$V3, blast$V4)) / mean(c(blast$V1, blast$V2))
blast2 <- mutate(blast, V3 = V3 / conversion_factor, V4 = V4 / conversion_factor)

blast_long <- blast2 %>%
  gather(var, x, -id) %>%
  group_by(id) %>%
  mutate(y = c(0, 0, 1, 1),
         order = c(1, 2, 4, 3)) %>%
  arrange(order)

ggplot(blast_long, aes(x, y, group = id))+
  geom_polygon(alpha = 0.3) +
  scale_x_continuous(sec.axis = sec_axis(~ . * conversion_factor))
</code>```

Body:
I have a table with coordinate data that looks like this,

V1       V2      V3       V4
10253363 10273825 9982154 10003803
10265080 10285697 9993266 10015040
10250800 10271301 9979709 10001394
10254775 10275140 9983264 10004815
10268607 10288871 9995004 10016450
10263978 10284276 9992831 10014300

And I'd like to generate a plot similar to the one shown below,

I tried this,

blast <- fread("../plots/coords.tsv")
blast$id = as.numeric(rownames(blast))
ggplot(blast)+
  geom_rect(aes(xmin=V1,xmax=V2,ymin=V3,ymax=V4, group = id), alpha=0.2) +
  scale_y_continuous(position = "top")

and ended up with the plot below instead.

It seems like y axis position could only be flipped between right and left. Therefore, this isn't working for me.

How do I generate the intended plot in ggplot2? Or is there another way to get at that?

Body:
That's not so easy, as you need to reshape and then trick ggplot2 a little.

The conversion factor is needed, since ggplot doesn't really allow separate axes, only relabeling based on simple conversions.

Also see this related answer.

You have a bunch of overlapping ranges, so it doesn't quite look like your example plot.

library(tidyr)
library(dplyr)
library(ggplot2)

conversion_factor <- mean(c(blast$V3, blast$V4)) / mean(c(blast$V1, blast$V2))
blast2 <- mutate(blast, V3 = V3 / conversion_factor, V4 = V4 / conversion_factor)

blast_long <- blast2 %>%
  gather(var, x, -id) %>%
  group_by(id) %>%
  mutate(y = c(0, 0, 1, 1),
         order = c(1, 2, 4, 3)) %>%
  arrange(order)

ggplot(blast_long, aes(x, y, group = id))+
  geom_polygon(alpha = 0.3) +
  scale_x_continuous(sec.axis = sec_axis(~ . * conversion_factor))


问:
Razor link to read file path from Controller
I'm quite new to the concept of razor. Basically, I need to download .pdf files. The paths are stored in my database.

I need to have a hyperlink on my cshtml which will call a function inside my Controller.
Then, on my controller, it will fetch the path of my file, which will return to my cshtml and do a windows.open(path).

Please let me know how can this be possible or perhaps a better approach to perform what I need to do.

Thanks.

Example:

.cshtml

```<code>@Html.ActionLink (
linkText: "My Link",
actionName: "DownloadFiles",
controllerName: "Files",
routeValues: new
{
   fileId: id,
   fileType: "PDF"
},
htmlAttributes: null

windows.open(path);
</code>```

Controller

```<code>public ActionResult DownloadFiles(int fileId, string fileType)
{
   string FilePath = "";
   FilePath = service.GetFilePath(fileId,fileType);

   return FilePath;
}
</code>```

答:
You have to return fileresult which is a child class for ActionResult:

```<code>public FileResult DownloadFile()
{
   string FilePath = "";
   FilePath = service.GetFilePath(fileId,fileType);

   // add virtual file path only
   return File(FilePath, "application/pdf");
}
</code>```

Here virtual path can be "~/Uploadfile/mypdf.pdf"

Body:
I'm quite new to the concept of razor. Basically, I need to download .pdf files. The paths are stored in my database.

I need to have a hyperlink on my cshtml which will call a function inside my Controller.
Then, on my controller, it will fetch the path of my file, which will return to my cshtml and do a windows.open(path).

Please let me know how can this be possible or perhaps a better approach to perform what I need to do.

Thanks.

Example:

.cshtml

@Html.ActionLink (
linkText: "My Link",
actionName: "DownloadFiles",
controllerName: "Files",
routeValues: new
{
   fileId: id,
   fileType: "PDF"
},
htmlAttributes: null

windows.open(path);

Controller

public ActionResult DownloadFiles(int fileId, string fileType)
{
   string FilePath = "";
   FilePath = service.GetFilePath(fileId,fileType);

   return FilePath;
}

Body:
You have to return fileresult which is a child class for ActionResult:

public FileResult DownloadFile()
{
   string FilePath = "";
   FilePath = service.GetFilePath(fileId,fileType);

   // add virtual file path only
   return File(FilePath, "application/pdf");
}

Here virtual path can be "~/Uploadfile/mypdf.pdf"


问:
Override styles in a shadow-root element
Is there a way to change styles found in a shadow element? Specifically, extend/overwrite some properties found in a css class? I am using a chrome-extension called Beanote which hasn't been updated since April(2017) and there's a pesky bug I'd like to fix. I found that one line of css patches it up enough for me, but I am at a loss at applying it without going inside of the shadow element itself and directly editing those styles in the dev tools.

I'm looking for a way for this:

```<code>/*global css rule*/
.the-class-name { property-name: my-value; }
</code>```

to overwrite this:

```<code>/* style tag inside the shadow-root */
.the-class-name { property-name: bad-value; }
</code>```

Most of the resources I've found online with queries involving shadow-root override style or edit shadow-root styling had something to do with :host which, if its meant for this, doesn't work for my needs or deprecated functionality like ::shadow.

答:
Because of the isolation of styles, which is a feature of Shadow DOM, you cannot define a global CSS rule that will be applied in the Shadow DOM scope.

It could be possible with CSS variables but they should be implemented explicitly in the shadowed component (which is not the case with this 3rd party library).

A workaround is to inject the line of style in the shadow DOM directly.

```<code>//host is the element that holds the shadow root:
var style = document.createElement( 'style' )
style.innerHTML = '.the-class-name { property-name: my-value; }'
host.shadowRoot.appendChild( style )
</code>```

NB: it will work only if the Shadow DOM mode is set to 'open'.

2019 update for Chrome 73+ and Opera 60+

Now it is possible to instantiate a CSSStyleSheet object directly and to affect it to a Shadow DOM or a document:

```<code>var sheet = new CSSStyleSheet
sheet.replaceSync( `.color { color: pink }`)
host.shadowRoot.adoptedStyleSheets = [ sheet ]
</code>```

Body:
Is there a way to change styles found in a shadow element? Specifically, extend/overwrite some properties found in a css class? I am using a chrome-extension called Beanote which hasn't been updated since April(2017) and there's a pesky bug I'd like to fix. I found that one line of css patches it up enough for me, but I am at a loss at applying it without going inside of the shadow element itself and directly editing those styles in the dev tools.

I'm looking for a way for this:

/*global css rule*/
.the-class-name { property-name: my-value; }

to overwrite this:

/* style tag inside the shadow-root */
.the-class-name { property-name: bad-value; }

Most of the resources I've found online with queries involving shadow-root override style or edit shadow-root styling had something to do with :host which, if its meant for this, doesn't work for my needs or deprecated functionality like ::shadow.

Body:
Because of the isolation of styles, which is a feature of Shadow DOM, you cannot define a global CSS rule that will be applied in the Shadow DOM scope.

It could be possible with CSS variables but they should be implemented explicitly in the shadowed component (which is not the case with this 3rd party library).

A workaround is to inject the line of style in the shadow DOM directly.

//host is the element that holds the shadow root:
var style = document.createElement( 'style' )
style.innerHTML = '.the-class-name { property-name: my-value; }'
host.shadowRoot.appendChild( style )

NB: it will work only if the Shadow DOM mode is set to 'open'.

2019 update for Chrome 73+ and Opera 60+

Now it is possible to instantiate a CSSStyleSheet object directly and to affect it to a Shadow DOM or a document:

var sheet = new CSSStyleSheet
sheet.replaceSync( `.color { color: pink }`)
host.shadowRoot.adoptedStyleSheets = [ sheet ]

ContentLicense: CC BY-SA 4.0


问:
Why is my search form (supposed to hide on click of button) not hiding?
I coded a simple search form that is supposed to hide/show on button click. But it is not working. Here isthe JSFiddle.

HTML:-

```<code><form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">
  <div class="input-group">
    <input type="hidden" name="id" value="63">
    <input type="search" name="keywords" class="form-control" placeholder="Search..">
    <div class="input-group-btn">
      <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
        <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
      </button>
    </div>
  </div>
</form>
</code>```

Can you spot the problem in the JSFiddle?

答:
Simply Add a button below the form in HTML & use jQuery on it as -

$('#hide_form').on('click', function() {
 $('#hiddenSearchBox').toggle();    // toggle(false) will hide it permanently
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="POST">
    <div class="input-group">
        <input type="hidden" name="id" value="63">
        <input type="search" name="keywords" class="form-control" placeholder="Search..">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
                <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
            </button>
        </div>
    </div>
</form>
<button id="hide_form">
    Hide Form
</button></code>```

Body:
I coded a simple search form that is supposed to hide/show on button click. But it is not working. Here isthe JSFiddle.

HTML:-

<form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="get">

    <input type="hidden" name="id" value="63">
    <input type="search" name="keywords" class="form-control" placeholder="Search..">

      <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
         Submit
      </button>

</form>

Can you spot the problem in the JSFiddle?

Body:
Simply Add a button below the form in HTML & use jQuery on it as -

$('#hide_form').on('click', function() {
 $('#hiddenSearchBox').toggle();    // toggle(false) will hide it permanently
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="search-form searchbar" role="search" id="hiddenSearchBox" action="" method="POST">
    <div class="input-group">
        <input type="hidden" name="id" value="63">
        <input type="search" name="keywords" class="form-control" placeholder="Search..">
        <div class="input-group-btn">
            <button type="submit" class="btn btn-default" data-toggle="searchbar" data-target="#hiddenSearchBox">
                <span class="glyphicon glyphicon-search"></span> <span class="sr-only">Submit</span>
            </button>
        </div>
    </div>
</form>
<button id="hide_form">
    Hide Form
</button>


问:
How to pass variable value to HTA
The following code in a batch file which gets the password from user Thru a HTA dialog box. It works fine. I want to pass a variable value !user[%%a]! to be displayed inside the pop up HTA dialog box so I can see
Enter password for User ID: "BATCH FILE USER VARIABLE"
in this window :

How can I do that?

```<code><!-- :
@setlocal enableextensions enabledelayedexpansion
:: PasswordSubmitter.bat
@echo off
set user[1]=me1
set user[2]=me2
set user[3]=me3

for /l %%a in (1,1,3)  do (
    set counter=%%a
    for /f "tokens=* delims=" %%p in ('mshta.exe "%~f0"') do (
        set pass[!counter!]=%%p
    )
    echo Password for User-!user[%%a]! is "!pass[%%a]!"
)
endlocal
exit /b

<html>
<HEAD><title>Password submitter</title>
<HTA:APPLICATION INNERBORDER="no" SYSMENU="no" SCROLL="no" >
   <style type="text/css">
   body {
      color: white;
      background: black;
      font-family: "Calibri", monospace;
   }
   </style>
</HEAD>
<body>
    <p>Enter password for User ID</p>
    <script language='javascript' >
    window.resizeTo(400,200);
        function pipePass() {
            var pass=document.getElementById('pass').value;
            var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);
            close(fso.Write(pass));

    }
</script>

<input type='password' name='pass' size='16'></input>
<hr>
<button onclick='pipePass()'>Submit</button>

</body>

</html>
</code>```

答:
Here's a Microsoft example of using the commandline property of the hta application object.

```<code><HTML>
<HEAD>
   <TITLE>Scripting the HTA:APPLICATION Tag</TITLE>
   <HTA:APPLICATION
      ID="oHTA"
   >   <SCRIPT LANGUAGE="VBScript">
      Option Explicit      Dim cmdLineArray
      Dim strHello      ' This code assumes that you have no spaces in
      ' the path to Hello.hta.  (In other words, this code
      ' splits the command line by spaces and assumes
      ' that your name is the second word.)
      '
      cmdLineArray = Split(oHTA.commandLine)
      strHello = "Hello " & cmdLineArray(1) & ", " _
               & "How are you?"      MsgBox strHello
   </SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>
</code>```

Writing HTML Applications for Internet Explorer 5.0, Scott Roberts, MSDN Library 2001.

Title: How to pass variable value to HTA

Body:
Here's a Microsoft example of using the commandline property of the hta application object.

<HTML>
<HEAD>
   <TITLE>Scripting the HTA:APPLICATION Tag</TITLE>
   <HTA:APPLICATION
      ID="oHTA"
   >   <SCRIPT LANGUAGE="VBScript">
      Option Explicit      Dim cmdLineArray
      Dim strHello      ' This code assumes that you have no spaces in
      ' the path to Hello.hta.  (In other words, this code
      ' splits the command line by spaces and assumes
      ' that your name is the second word.)
      '
      cmdLineArray = Split(oHTA.commandLine)
      strHello = "Hello " & cmdLineArray(1) & ", " _
               & "How are you?"      MsgBox strHello
   </SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Writing HTML Applications for Internet Explorer 5.0, Scott Roberts, MSDN Library 2001.


问:
Shiny app with reactive data call from server
I'm trying to make a plot with reactive data from the server. Unfortunately I can't get the plot to work. I'm getting an error like: "Error:EXPR must be a length 1 vector". I tried different styles of plots and different libraries: Quantmod, ggplot, so on. Any suggestions?</p>

```<code>Server:
library(shiny)

Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  DatSv <- reactive({
    Value <- switch(input$Value,
                    "Failure"= Dat$Failure[1:10],
                    "Disbursement"=Dat$Disbursement[1:10],
                    "Disb$X$1000"=Dat$`Disb$X$1000`[1:10],
                    "Chgoff"=Dat$Chgoff[1:10])
    Brand<-Dat$Brand[1:10]
    Brand(input$Value)
  })

# Generate plot
  output$plot1 <- renderPlot({
    library("quantmod")
    hist(DatSv(),
         main=paste('r', Value, '(', Brand, ')', sep=''))
  })

  # Generate summary of data

  output$summary<-renderPrint({
    summary(Dat)
  })

})

UI:
library(shiny)
shinyUI(fluidPage(
  titlePanel("Plot Franchise Failure"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("n", "Chose output Y Axis:",
                   c("Failure" ,
                     "Disbursement",
                     "Disb$X$1000" ,
                     "Chgoff" )),

      checkboxInput("show_xlab", "Show/Hide X Axis Label", value=TRUE),
      checkboxInput("show_ylab", "Show/Hide Y Axis Label", value=TRUE),
      checkboxInput("show_title", "Show/Hide Title")
    ),
  mainPanel(
    tabsetPanel(
      type = "tabs",
      tabPanel("Plot", plotOutput("plot1")),
      tabPanel("Summary", verbatimTextOutput("summary"))
  )
  )
)
)
)
</code>```

答:
Hi the problem comes from connecting the inputs in the UI with the server. In the UI you have given the inputid = "n" for the radioButtons. That means we can get the Value of the Radiobuttons with input$n and not  input$Value. The later is always NULL since there is no input with inputid = "Value". I had some other small problems with your code but here is a working version of the server code. I didn't modify the UI

```<code>library(shiny)

Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  DatSv <- reactive({
    switch(input$n,
          "Failure"= gsub("%","",as.character(    Dat$Failure)),
          "Disbursement"=Dat$Disbursement,
          "Disb$X$1000"=gsub("\\$","",as.character(    Dat$`Disb$X$1000`)),
          "Chgoff"=gsub("%","",as.character(Dat$Chgoff)))

  })

  # Generate plot
  output$plot1 <- renderPlot({
    library("quantmod")
    hist(as.numeric(DatSv()),
         main=paste('Histogram of ',input$n, sep=''),
         xlab = input$n)
  })

  # Generate summary of data

  output$summary<-renderPrint({
    summary(Dat)
  })

})
</code>```

Body:
I'm trying to make a plot with reactive data from the server. Unfortunately I can't get the plot to work. I'm getting an error like: "Error:EXPR must be a length 1 vector". I tried different styles of plots and different libraries: Quantmod, ggplot, so on. Any suggestions?

Server:
library(shiny)

Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  DatSv <- reactive({
    Value <- switch(input$Value,
                    "Failure"= Dat$Failure[1:10],
                    "Disbursement"=Dat$Disbursement[1:10],
                    "Disb$X$1000"=Dat$`Disb$X$1000`[1:10],
                    "Chgoff"=Dat$Chgoff[1:10])
    Brand<-Dat$Brand[1:10]
    Brand(input$Value)
  })

# Generate plot
  output$plot1 <- renderPlot({
    library("quantmod")
    hist(DatSv(),
         main=paste('r', Value, '(', Brand, ')', sep=''))
  })

  # Generate summary of data

  output$summary<-renderPrint({
    summary(Dat)
  })

})

UI:
library(shiny)
shinyUI(fluidPage(
  titlePanel("Plot Franchise Failure"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("n", "Chose output Y Axis:",
                   c("Failure" ,
                     "Disbursement",
                     "Disb$X$1000" ,
                     "Chgoff" )),

      checkboxInput("show_xlab", "Show/Hide X Axis Label", value=TRUE),
      checkboxInput("show_ylab", "Show/Hide Y Axis Label", value=TRUE),
      checkboxInput("show_title", "Show/Hide Title")
    ),
  mainPanel(
    tabsetPanel(
      type = "tabs",
      tabPanel("Plot", plotOutput("plot1")),
      tabPanel("Summary", verbatimTextOutput("summary"))
  )
  )
)
)
)

Body:
Hi the problem comes from connecting the inputs in the UI with the server. In the UI you have given the inputid = "n" for the radioButtons. That means we can get the Value of the Radiobuttons with input$n and not  input$Value. The later is always NULL since there is no input with inputid = "Value". I had some other small problems with your code but here is a working version of the server code. I didn't modify the UI

library(shiny)

Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]

# Define server logic required to draw a histogram
shinyServer(function(input, output) {
  DatSv <- reactive({
    switch(input$n,
          "Failure"= gsub("%","",as.character(    Dat$Failure)),
          "Disbursement"=Dat$Disbursement,
          "Disb$X$1000"=gsub("\\$","",as.character(    Dat$`Disb$X$1000`)),
          "Chgoff"=gsub("%","",as.character(Dat$Chgoff)))

  })

  # Generate plot
  output$plot1 <- renderPlot({
    library("quantmod")
    hist(as.numeric(DatSv()),
         main=paste('Histogram of ',input$n, sep=''),
         xlab = input$n)
  })

  # Generate summary of data

  output$summary<-renderPrint({
    summary(Dat)
  })

})


问:
How to get the values of an asp.net user control with two textboxes with same id in javascript
searched a lot but couldn't get anywhere..My case : I have a UserControl called DateControl:

  <asp:TextBox ID="ValueDateTextBox" runat="server" CssClass="form-control input-sm nepali-datepicker ignore" data-inputmask="'alias': 'dd/mm/yyyy'" />

```

<p>It has got one textbox which i am using for datepicker. In my .aspx page i am used the control like this :</p>

<pre class="lang-html prettyprint-override"><code><div class="form-group">
  <label class="control-label col-sm-2">
                                From Date
                            </label>
  <div class="col-sm-3">
    <uc1:DateControl runat="server" ID="FromDateControl" />
  </div>

  <label class="control-label col-sm-2">
                                To Date
                            </label>
  <div class="col-sm-3">
    <uc1:DateControl runat="server" ID="ToDateControl" />
  </div>
</div>
<small class="col-sm-offset-2 text-warning pvInfo"></small>
</code>```

In my case i have to select two dates FROM and TO from the datepicker.There is no problem to access the dates from server side since i can access it like

var fromDate = FromDateControl.ValueDateAd;
var toDate = ToDateControl.ValueDateAd;
```

<p>And this gets me the selected date.But in my case again here i need to pass these two dates to an ajax call.And since both the datepicker id's is
<strong>ValueDateTextBox</strong>,i am getting both the selected date same.</p>

<p><strong>JS Code</strong></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).ready(function(){
        $('#ShowInGridButton').on('click',
            function () {

                var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();

                var fromDateCtrl = $('[id$="FromDateControl"]').find('[id$="ValueDateTextBox"]');
                alert(fromDateCtrl.val());
                var toDateCtrl = $('[id$="ToDateControl"]').find('[id$="ValueDateTextBox"]');
                alert(toDateCtrl.val());

                //var fromDate = $('#ValueDateTextBox').val();

                //var toDate = $('#ValueDateTextBox').val();
                var url = "/WebMethods/Deposit.asmx/GetDepositAccountStatement";
                var d = { accountNumberId: accountNumberId, fromDate: fromDate, toDate: toDate };
                var jqXhr = ajaxPost(url, d);
                jqXhr.done(function (data) {
                    console.log(data);
                    if (data) {
                        var div = $('#CfDataTable').empty();
                        div.append(
                           $("<tr class='success'><th>Tran Date</th><th>Value Date</th><th>Statement Reference</th><th>Check No.</th><th>Collector</th><th>Debit</th><th>Credit</th><th>Balance</th></tr>"));

                        $(data.d).each(function (index, item) {

                            div.append(
                                    $("<tr>")

                                    .append($("<td>").html(ToJavaScriptDate(item.TranDate)))
                                    .append($("<td>").html(ToJavaScriptDate(item.ValueDate)))
                                    //.append($("<td>").html(item.TranDate))
                                    //.append($("<td>").html(item.ValueDate))
                                    .append($("<td>").html(item.StatementReference))
                                    .append($("<td>").html(item.CheckNumber))
                                    .append($("<td>").html(item.Collector))
                                    .append($("<td>").html(item.Debit))
                                    .append($("<td>").html(item.Credit))
                                    .append($("<td>").html(item.Balance)));

                        });
                    }
                }).fail(function () {
                    console.log('Data Retrieve failed.');
                });
            });
    });</code>```

So its obvious here that being same ids the value would be same.I even tried doing this looking around here

var bothElements = document.querySelectorAll("[id='ValueDateTextBox']");
var first = bothElements[0];
alert(first);
```

<p>Still couldnt get the different date for the selected date from the date picker.Help appreciated.Thanks.It isnt that i didnt looked around for possible solutions,had to ask here.sorry if too vague a question for you expert devs.:)</p>

<p><strong>Edited</strong></p>

<p>Code behind of DateControl</p>

``` public partial class DateControl : System.Web.UI.UserControl
{
    public string ValueDateNp
    {
        get { return ValueDateTextBox.Text; }
        set { ValueDateTextBox.Text = value; }
    }
    public DateTime ValueDateAd
    {
        get { return DateConversion.GetEnglishDate(ValueDateTextBox.Text).ToDateTime(); }
        set
        {
            if (value == DateTime.MinValue)
            {
                ValueDateTextBox.Text = DateConversion.GetCurrentBSServerDate();
            }
            ValueDateTextBox.Text = DateConversion.GetNepaliDate(value);
        }
    }

    public bool IsDateDisabled { get; set; }

    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
        {
            ValueDateTextBox.Text = DateConversion.GetCurrentBSServerDate();
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        if (!IsPostBack)
        {
            ValueDateTextBox.Focus();
        }
        if (IsDateDisabled)
        {
            ValueDateTextBox.MakeReadOnly();
            ValueDateTextBox.CssClass.Remove(3);
        }
    }

    public void BindDataProperty<T>(Expression<Func<T, object>> property)
    {
        ValueDateTextBox.SetDataBindPropertyName(property);
    }

}
```

答:
Since you have a parent container with id(FromDateControl & ToDateControl), you can use them to find the inner child.

```<code>var fromDateCtrl = $('[id$="FromDateControl"]').find('[id$="ValueDateTextBox"]');
alert(fromDateCtrl.val());
</code>```

Body:
searched a lot but couldn't get anywhere..My case : I have a UserControl called DateControl:

  <asp:TextBox ID="ValueDateTextBox" runat="server" CssClass="form-control input-sm nepali-datepicker ignore" data-inputmask="'alias': 'dd/mm/yyyy'" />

It has got one textbox which i am using for datepicker. In my .aspx page i am used the control like this :

                                From Date

    <uc1:DateControl runat="server" ID="FromDateControl" />

                                To Date

    <uc1:DateControl runat="server" ID="ToDateControl" />

In my case i have to select two dates FROM and TO from the datepicker.There is no problem to access the dates from server side since i can access it like

var fromDate = FromDateControl.ValueDateAd;
var toDate = ToDateControl.ValueDateAd;

And this gets me the selected date.But in my case again here i need to pass these two dates to an ajax call.And since both the datepicker id's is
ValueDateTextBox,i am getting both the selected date same.

JS Code

 $(document).ready(function(){
        $('#ShowInGridButton').on('click',
            function () {

                var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();

                var fromDateCtrl = $('[id$="FromDateControl"]').find('[id$="ValueDateTextBox"]');
                alert(fromDateCtrl.val());
                var toDateCtrl = $('[id$="ToDateControl"]').find('[id$="ValueDateTextBox"]');
                alert(toDateCtrl.val());

                //var fromDate = $('#ValueDateTextBox').val();

                //var toDate = $('#ValueDateTextBox').val();
                var url = "/WebMethods/Deposit.asmx/GetDepositAccountStatement";
                var d = { accountNumberId: accountNumberId, fromDate: fromDate, toDate: toDate };
                var jqXhr = ajaxPost(url, d);
                jqXhr.done(function (data) {
                    console.log(data);
                    if (data) {
                        var div = $('#CfDataTable').empty();
                        div.append(
                           $("
Tran Date	Value Date	Statement Reference	Check No.	Collector	Debit	Credit	Balance
"));

                        $(data.d).each(function (index, item) {

                            div.append(
                                    $("
")

                                    .append($("").html(ToJavaScriptDate(item.TranDate)))
                                    .append($("").html(ToJavaScriptDate(item.ValueDate)))
                                    //.append($("").html(item.TranDate))
                                    //.append($("").html(item.ValueDate))
                                    .append($("").html(item.StatementReference))
                                    .append($("").html(item.CheckNumber))
                                    .append($("").html(item.Collector))
                                    .append($("").html(item.Debit))
                                    .append($("").html(item.Credit))
                                    .append($("").html(item.Balance)));

                        });
                    }
                }).fail(function () {
                    console.log('Data Retrieve failed.');
                });
            });
    });

So its obvious here that being same ids the value would be same.I even tried doing this looking around here

var bothElements = document.querySelectorAll("[id='ValueDateTextBox']");
var first = bothElements[0];
alert(first);

Still couldnt get the different date for the selected date from the date picker.Help appreciated.Thanks.It isnt that i didnt looked around for possible solutions,had to ask here.sorry if too vague a question for you expert devs.:)

Edited

Code behind of DateControl

 public partial class DateControl : System.Web.UI.UserControl
{
    public string ValueDateNp
    {
        get { return ValueDateTextBox.Text; }
        set { ValueDateTextBox.Text = value; }
    }
    public DateTime ValueDateAd
    {
        get { return DateConversion.GetEnglishDate(ValueDateTextBox.Text).ToDateTime(); }
        set
        {
            if (value == DateTime.MinValue)
            {
                ValueDateTextBox.Text = DateConversion.GetCurrentBSServerDate();
            }
            ValueDateTextBox.Text = DateConversion.GetNepaliDate(value);
        }
    }

    public bool IsDateDisabled { get; set; }

    protected override void OnInit(EventArgs e)
    {
        if (!IsPostBack)
        {
            ValueDateTextBox.Text = DateConversion.GetCurrentBSServerDate();
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        if (!IsPostBack)
        {
            ValueDateTextBox.Focus();
        }
        if (IsDateDisabled)
        {
            ValueDateTextBox.MakeReadOnly();
            ValueDateTextBox.CssClass.Remove(3);
        }
    }

    public void BindDataProperty<T>(Expression<Func<T, object>> property)
    {
        ValueDateTextBox.SetDataBindPropertyName(property);
    }

}

Body:
Since you have a parent container with id(FromDateControl & ToDateControl), you can use them to find the inner child.

var fromDateCtrl = $('[id$="FromDateControl"]').find('[id$="ValueDateTextBox"]');
alert(fromDateCtrl.val());


问:
How do I make Firefox console group repeat outputs?
I recently switched to Firefox Quantum Developer from Chrome and I notice that duplicate log messages aren't collapsed like they are in Chrome:

How would I make this all show as one, like this

Edit: It seems that it does this for some outputs but not others, which I find strange.

答:
The Firefox DevTools console generally groups output.

For example, executing the code of your screenshot shows this:

Though, when you output objects it may happen that they are not grouped. If that's the case, check if the data is really identical (incl. source links). It may be that your output refers to different objects. E.g.

```<code>for(let i=0;i<100;i++) { console.log(["test"]); }
</code>```

will output 100 times Array [ "test" ].

If you're sure your output refers to identical objects, ensure you have the latest version of Firefox installed. If it still occurs in the current version of Firefox, you should file a bug report.

Body:
The Firefox DevTools console generally groups output.

For example, executing the code of your screenshot shows this:

Though, when you output objects it may happen that they are not grouped. If that's the case, check if the data is really identical (incl. source links). It may be that your output refers to different objects. E.g.

for(let i=0;i<100;i++) { console.log(["test"]); }

will output 100 times Array [ "test" ].

If you're sure your output refers to identical objects, ensure you have the latest version of Firefox installed. If it still occurs in the current version of Firefox, you should file a bug report.


问:
How to use différents JS functions at the exact same time
I wish to launch multiples functions at the same time when clicking in a button.

The thing is sensitive since that's launch timers, and if they aren't synchronised the little difference is immediatly visible ...

Actually I use this code :

```<code><button class="btn btn-success startTimer" id="gobutton">Start</button>

    <script type="text/javascript">
        $(".startTimer").click(function() {
            var timeseconds = $("#MoneyTimer").TimeCircles().getTime();
            $("#timeseconds").val(timeseconds);
            $("#MoneyTimer").TimeCircles().start();
            $('#totaleuro.compteur1').timer1('start');
            $('#totaleuro.compteur2').timer2('start');
        });
    </script>
</code>```

答:
Regular in-browser Javascript is strictly single threaded, hence nothing here will start at the same time. In fact, one of the two functions will only start, if the other finished (or ran into a promise, or...)

You best and only bet is looking into web workers – whose Performance and possible multithreading may vary wildly from implementation to implentation. Still, it's more of a guess, complete parallelness is unguaranteeable. (Also, because processors might have other stuff to do right now...)

Possibly a better solution to your actual problem:

That said, both of your timers could relate to the same starttime, set once and shared in a global variable (or passed in an object).

The will still never run truly in parallel at the same time, but whenever it's their turn (to update display info, metrics, etc...) they will be calculating with relation to the exakt same start-time.

Body:
I wish to launch multiples functions at the same time when clicking in a button.

The thing is sensitive since that's launch timers, and if they aren't synchronised the little difference is immediatly visible ...

Actually I use this code :

<button class="btn btn-success startTimer" id="gobutton">Start</button>


问:
How to CREATE only 1 session with rc server when running PHPUnit selense HTML files
My website has a Login page, so it needs to login first to run each HTML selense test file. The way PHPUnit framework works is creating independent test cases by running each test independently, which means it calls the Setup() function on each test case --> then calls Selenium RC Server --> then creates session id. My code is below.

```<code>require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class SeleneseTests extends PHPUnit_Extensions_SeleniumTestCase
{
   protected static $seleneseDirectory = '/home/server/Web/phase-four/tests';

   protected function setUp()
  {
    $this->setBrowser("*firefox");
    $this->setBrowserUrl("http://mywebsite.com/");
  }
}
</code>```

答:
My selenium rc setup seems to keep the same session for each test by default, as long as I am setting the session (doing login) inside the setUp() function. </p>

<p>There is also a -browserSessionReuse flag you can specify when starting the rc server, in case this behavior is not enabled by default. </p>

Body:
My website has a Login page, so it needs to login first to run each HTML selense test file. The way PHPUnit framework works is creating independent test cases by running each test independently, which means it calls the Setup() function on each test case --> then calls Selenium RC Server --> then creates session id. My code is below.

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class SeleneseTests extends PHPUnit_Extensions_SeleniumTestCase
{
   protected static $seleneseDirectory = '/home/server/Web/phase-four/tests';

   protected function setUp()
  {
    $this->setBrowser("*firefox");
    $this->setBrowserUrl("http://mywebsite.com/");
  }
}

Body:
My selenium rc setup seems to keep the same session for each test by default, as long as I am setting the session (doing login) inside the setUp() function.

There is also a -browserSessionReuse flag you can specify when starting the rc server, in case this behavior is not enabled by default.


问:
Unable to resolve host "<URL here>" No address associated with host name
In my Android application for reading RSS links, I am getting this error:

java.net.UnknownHostException:
  Unable to resolve host "example.com";
  No address associated with hostname.

In my emulator I can connect to Google through a browser.
Please help me to resolve this issue.

答: In my case problem was with WIFI working with IPV6 and my domain did not have IPv6 adress</p>


问:
How to Customize bootstrap carousel using fade in effect
This is my html code for carousal

```<code>  <section id="showcase">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item carousel-image-1 active">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block text-right mb-5">
          <h1 class="display-3">Heading One</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-danger btn-lg">Sign Up Now</a>
        </div>
      </div>
    </div>

    <div class="carousel-item carousel-image-2">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block mb-5">
          <h1 class="display-3">Heading Two</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-primary btn-lg">Learn More</a>
        </div>
      </div>
    </div>

    <div class="carousel-item carousel-image-3">
      <div class="container">
        <div class="carousel-caption d-none d-sm-block text-right mb-5">
          <h1 class="display-3">Heading Three</h1>
          <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.</p>
          <a href="#" class="btn btn-success btn-lg">Learn More</a>
        </div>
      </div>
    </div>
  </div>

  <a href="#myCarousel" data-slide="prev" class="carousel-control-prev">
    <span class="carousel-control-prev-icon"></span>
  </a>
  <a href="#myCarousel" data-slide="next" class="carousel-control-next">
    <span class="carousel-control-next-icon"></span>
  </a>
</div>
</code>```

I want to style fade in effect for this slide. can anyone help me to make my css code.
i found some css code for carousel like this.

but it's not working properly.

```<code>     .carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
  transition-property: opacity;
 }
  .carousel-fade .carousel-inner .item,
 .carousel-fade .carousel-inner .active.left,
 .carousel-fade .carousel-inner .active.right {
   opacity: 0;
 }
 .carousel-fade .carousel-inner .active,
  .carousel-fade .carousel-inner .next.left,
 .carousel-fade .carousel-inner .prev.right {
  opacity: 1;
 }
 .carousel-fade .carousel-inner .next,
  .carousel-fade .carousel-inner .prev,
 .carousel-fade .carousel-inner .active.left,
  .carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
 }
 .carousel-fade .carousel-control {
  z-index: 2;
 }
  html,
  body,
 .carousel,
 .carousel-inner,
 .carousel-inner .item
{
  height: 100%;
  }
 .item:nth-child(1) {
    background: url("../img/img2.jpeg");
   background-size: cover;
  }
  }
 .item:nth-child(2) {
    background: url("../img/img2.jpeg");
    background-size: cover;
 }
 }
 .item:nth-child(3) {
   background: url("../img/img2.jpeg");
   background-size: cover;
  }
 }
</code>```

i want to edit this css code for my bootstrap carousal.

if anyone know another method for fade in effect please help me.

答:
This one works for me. Just add this CSS code in your style area.</p>

```<code>.carousel-fade .carousel-inner > .item {
    transition-property: opacity;
}
.carousel-fade .carousel-inner > .item,
.carousel-fade .carousel-inner > .item.active.left {
    opacity: 0;
}
.carousel-fade .carousel-inner > .item.active,
.carousel-fade .carousel-inner > .item.next.left {
    opacity: 1;
}
.carousel-fade .carousel-inner > .next,
.carousel-fade .carousel-inner > .prev,
.carousel-fade .carousel-inner > .active.left,
.carousel-fade .carousel-inner > .active.right {
    left: 0;
}
.carousel-fade .carousel-inner > .item.next,
.carousel-fade .carousel-inner > .item.active.right,
.carousel-fade .carousel-inner > .item.prev,
.carousel-fade .carousel-inner > .item.active.left {
    transform: translate3d(0, 0, 0);
}
</code>```

Body:
This is my html code for carousal

Heading One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Sign Up Now

Heading Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Learn More

Heading Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Natus illum commodi enim consequatur nesciunt voluptatum perspiciatis sint. Nemo, modi nulla.

          Learn More

I want to style fade in effect for this slide. can anyone help me to make my css code.
i found some css code for carousel like this.

but it's not working properly.

     .carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
  transition-property: opacity;
 }
  .carousel-fade .carousel-inner .item,
 .carousel-fade .carousel-inner .active.left,
 .carousel-fade .carousel-inner .active.right {
   opacity: 0;
 }
 .carousel-fade .carousel-inner .active,
  .carousel-fade .carousel-inner .next.left,
 .carousel-fade .carousel-inner .prev.right {
  opacity: 1;
 }
 .carousel-fade .carousel-inner .next,
  .carousel-fade .carousel-inner .prev,
 .carousel-fade .carousel-inner .active.left,
  .carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
 }
 .carousel-fade .carousel-control {
  z-index: 2;
 }
  html,
  body,
 .carousel,
 .carousel-inner,
 .carousel-inner .item
{
  height: 100%;
  }
 .item:nth-child(1) {
    background: url("../img/img2.jpeg");
   background-size: cover;
  }
  }
 .item:nth-child(2) {
    background: url("../img/img2.jpeg");
    background-size: cover;
 }
 }
 .item:nth-child(3) {
   background: url("../img/img2.jpeg");
   background-size: cover;
  }
 }

i want to edit this css code for my bootstrap carousal.

if anyone know another method for fade in effect please help me.

Body:
This one works for me. Just add this CSS code in your style area.

.carousel-fade .carousel-inner > .item {
    transition-property: opacity;
}
.carousel-fade .carousel-inner > .item,
.carousel-fade .carousel-inner > .item.active.left {
    opacity: 0;
}
.carousel-fade .carousel-inner > .item.active,
.carousel-fade .carousel-inner > .item.next.left {
    opacity: 1;
}
.carousel-fade .carousel-inner > .next,
.carousel-fade .carousel-inner > .prev,
.carousel-fade .carousel-inner > .active.left,
.carousel-fade .carousel-inner > .active.right {
    left: 0;
}
.carousel-fade .carousel-inner > .item.next,
.carousel-fade .carousel-inner > .item.active.right,
.carousel-fade .carousel-inner > .item.prev,
.carousel-fade .carousel-inner > .item.active.left {
    transform: translate3d(0, 0, 0);
}


问:
avrdude: error: buffered memory access not supported
I am trying to upload this firmware sck_beta_v0_8_6 via Arduino 1.0.5-r2.
I have chosen LilyPad Arduino USB as the board. The device is a Smart Citizen Kit Urban Shield v.1.1.
The upload fails with the following error message:

```<code>Found programmer: Id = "BÛR"; type =
   Software Version = . ; Hardware Version = .
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
</code>```

What am I doing wrong?

答:
I had the same issue when trying  to upload code into Arduino Micro ( Chinese clone ). Spending hours on Google, flashing new bootloader - still nothing. Physical reset and opening COM port with boundrate 1200 doesn't work. Why?

I HAVE ATMEGA168 INSTEAD OF ATMEGA32u4!

Google is telling, that Arduino Micro got Atmega32u4, but my clone got Atmega168! First of all, check what atmega type do you have by lookup on black soldered chip on Arduino.
So instead of choose "Arduino Micro" on "Board" menu, i choose Arduino Nano and everything works!

Body:
I am trying to upload this firmware sck_beta_v0_8_6 via Arduino 1.0.5-r2.
I have chosen LilyPad Arduino USB as the board. The device is a Smart Citizen Kit Urban Shield v.1.1.
The upload fails with the following error message:

Found programmer: Id = "BÛR"; type =
   Software Version = . ; Hardware Version = .
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

What am I doing wrong?


问:
datatable custom dropdown for sort
I have below dropdown.

```<code><select name="sortBy" id="sortBy">
    <option value="0_asc" selected="selected">Reference #</option>
    <option value="0_desc">Reference # (desc)</option>
    <option value="pe-sku-column_asc">Part # (asc)</option>
    <option value="pe-sku-column_desc">Part # (desc)</option>
    <option value="pe-title-column_asc">Description (asc)</option>
    <option value="pe-title-column_desc">Description (desc)</option>
    <option value="pe-price-column_asc">Price (asc)</option>
    <option value="pe-price-column_desc">Price (desc)</option>
</select>
</code>```

Now I want to sort my datatable according to the dropdown selection

I tried this

```<code>jQuery(document).ready(function ($) {
    var oTable = $('#super-product-table').DataTable({
        dom: 't'
    });

    $('#myInputTextField').keyup(function () {
        oTable.search($(this).val()).draw();
    })

    $("#sortBy").change(function () {

        oTable.fnSort([[1, 'asc']]);
    })
});
</code>```

But it gives me

TypeError: oTable.fnSort is not a function

I have search for fnsort in datatable.js and found it.

One more thing, when I change DataTable to dataTable sorting started working and custom search stop.

答:
Please see the answer provided by @davidkonrad about differences between dataTable() and DataTable().

If you want to use DataTable(), replace older API method fnSort with newer API method order(). For example:

```<code>oTable.order([1, 'asc']).draw();
</code>```

See conversion guide for DataTables 1.10 for more information.

Title: datatable custom dropdown for sort

Body:
I have below dropdown.

<select name="sortBy" id="sortBy">
    <option value="0_asc" selected="selected">Reference #</option>
    <option value="0_desc">Reference # (desc)</option>
    <option value="pe-sku-column_asc">Part # (asc)</option>
    <option value="pe-sku-column_desc">Part # (desc)</option>
    <option value="pe-title-column_asc">Description (asc)</option>
    <option value="pe-title-column_desc">Description (desc)</option>
    <option value="pe-price-column_asc">Price (asc)</option>
    <option value="pe-price-column_desc">Price (desc)</option>
</select>

Now I want to sort my datatable according to the dropdown selection

I tried this

jQuery(document).ready(function ($) {
    var oTable = $('#super-product-table').DataTable({
        dom: 't'
    });

    $('#myInputTextField').keyup(function () {
        oTable.search($(this).val()).draw();
    })

    $("#sortBy").change(function () {

        oTable.fnSort([[1, 'asc']]);
    })
});

But it gives me

TypeError: oTable.fnSort is not a function

I have search for fnsort in datatable.js and found it.

One more thing, when I change DataTable to dataTable sorting started working and custom search stop.

Body:
Please see the answer provided by @davidkonrad about differences between dataTable() and DataTable().

If you want to use DataTable(), replace older API method fnSort with newer API method order(). For example:

oTable.order([1, 'asc']).draw();

See conversion guide for DataTables 1.10 for more information.


问:
How to show an Alert Dialog for a background FCM message when notification is pressed
I would like some help to show an alert dialog when the I press the Firebase push notification shown in the top notification bar on the android device when you swipe downwards from the complete top.

I need it to open the activity and show the alert dialog with the notification message with an OK button after the notification in the notification bar is pressed.

May someone please help me to do so on Android Studio 3.0.1

答:
Try this hope so it will be helpful for you

```<code>Intent notifyIntent = new Intent(context,YourActivityClassHere.class);
notifyIntent.setFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
//UNIQUE_ID if you expect more than one notification to appear
PendingIntent intent = PendingIntent.getActivity(SimpleNotification.this, UNIQUE_ID,
            notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
</code>```

just make the PendingIntent open up one of your Activities and have your Activity be complete transparent and just open a Dialog.

Body:
Try this hope so it will be helpful for you

Intent notifyIntent = new Intent(context,YourActivityClassHere.class);
notifyIntent.setFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
//UNIQUE_ID if you expect more than one notification to appear
PendingIntent intent = PendingIntent.getActivity(SimpleNotification.this, UNIQUE_ID,
            notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

just make the PendingIntent open up one of your Activities and have your Activity be complete transparent and just open a Dialog.


问:
Only counting data that fits certain criteria in SQL on Microsoft Access
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have. </p>

```<code>SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;
</code>```

<p>I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them. </p>

答:
I'm not sure about ms-access capabilities so these possibilities may not all work for you but at least one should.</p>

```<code>-- Some sample data

create table StudDetails(sex char(1),currclass varchar(10));

insert into StudDetails values
('M','ClassA'), ('M','ClassA'), ('F','ClassA'),
('F','ClassB'), ('F','ClassB'), ('F','ClassB'), ('M','ClassB'), ('F','ClassB'),
('F','ClassC'), ('F','ClassC');

-- One method

select CurrClass as "class",
       sum(case when sex='M' then 1 else 0 end) as "malecount",
       sum(case when sex='F' then 1 else 0 end) as "femalecount"
  from StudDetails
 group by CurrClass;

-- Another method

with xxx(CurrClass,malecount,femalecount) as
  (
   select CurrClass,1,0 from StudDetails where sex = 'M'
   union all
   select CurrClass,0,1 from StudDetails where sex = 'F'
  )
  select CurrClass,sum(malecount) as malecount,sum(femalecount) as femalecount
    from xxx
    group by CurrClass;

-- Yet another method

select CurrClass,sum(malecount) as malecount,sum(femalecount) as femalecount
  from (
        select CurrClass,1 as malecount,0 as femalecount from StudDetails where sex = 'M'
        union all
        select CurrClass,0 as malecount,1 as femalecount from StudDetails where sex = 'F'
       ) xxx
  group by CurrClass;
</code>```

Body:
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have.

SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;

I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them.

Body:
I'm not sure about ms-access capabilities so these possibilities may not all work for you but at least one should.

-- Some sample data

create table StudDetails(sex char(1),currclass varchar(10));

insert into StudDetails values
('M','ClassA'), ('M','ClassA'), ('F','ClassA'),
('F','ClassB'), ('F','ClassB'), ('F','ClassB'), ('M','ClassB'), ('F','ClassB'),
('F','ClassC'), ('F','ClassC');

-- One method

select CurrClass as "class",
       sum(case when sex='M' then 1 else 0 end) as "malecount",
       sum(case when sex='F' then 1 else 0 end) as "femalecount"
  from StudDetails
 group by CurrClass;

-- Another method

with xxx(CurrClass,malecount,femalecount) as
  (
   select CurrClass,1,0 from StudDetails where sex = 'M'
   union all
   select CurrClass,0,1 from StudDetails where sex = 'F'
  )
  select CurrClass,sum(malecount) as malecount,sum(femalecount) as femalecount
    from xxx
    group by CurrClass;

-- Yet another method

select CurrClass,sum(malecount) as malecount,sum(femalecount) as femalecount
  from (
        select CurrClass,1 as malecount,0 as femalecount from StudDetails where sex = 'M'
        union all
        select CurrClass,0 as malecount,1 as femalecount from StudDetails where sex = 'F'
       ) xxx
  group by CurrClass;


问:
Angular Routing Params
I'd like to know if there is a way that the parameters, which a route possesses, will stay even if I route/go to another page?

For example:

localhost:4200/welcomepage?param=true => localhost:4200/secondpage?param=true

答:
Yes possible, you can try like this,

import { ModuleWithProviders }  from '@angular/core';
import { CanActivate, Routes, RouterModule } from '@angular/router';

/* Component */
import { welcomepage } from '../../modules/welcomepage/welcomepage.component';

const appRoutes: Routes = [
  {
    path: 'welcomepage/:param',
    component: welcomepage
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

And in HTML page

Welcome```

and in HTML page,

Title: Angular Routing Params

Body:
Yes possible, you can try like this,

import { ModuleWithProviders }  from '@angular/core';
import { CanActivate, Routes, RouterModule } from '@angular/router';

/* Component */
import { welcomepage } from '../../modules/welcomepage/welcomepage.component';

const appRoutes: Routes = [
  {
    path: 'welcomepage/:param',
    component: welcomepage
  }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

And in HTML page

<a [routerLink]="['/welcomepage', 'true']">Welcome</a>

and in HTML page,


问:
Why the error only be reported on the second element and how can I solve it?
I try to build a char array.

```<code>#include <iostream>
#include <vector>

using namespace std;

int main(){

    static const char array1[] = {"green", "red","red", "green", "green"};

}
</code>```

I would expect this to work, but I get the following error:

答:
This is not an array of chars. Its an Array of strings.

You could write

static const char* array1[] = {"green", "red","red", "green", "green"};

or

static const std::string array1[] = {"green", "red","red", "green", "green"};

Also the error is on the second entry because "green" is an array of chars.

Body:
I try to build a char array.

#include <iostream>
#include <vector>

using namespace std;

int main(){

    static const char array1[] = {"green", "red","red", "green", "green"};

}

I would expect this to work, but I get the following error:


问:
Floating label on icon
Is it possible to achieve something like facebook's notifications icon with Semantic UI? I.e. an icon with a red Label to show the number of notifications? Found this thread but no answers there.

I tried this:

```<code><Icon name='bell outline'>
  <Label color='red' floating>22</Label>
</Icon>
</code>```

But the label doesn't show up (syntax is semantic-ui-react).

答:
With Semantic UI you can make another icon float to the right upper corner:

```<code><i class="huge icons">
  <i class="puzzle icon"></i>
  <i class="top right corner add icon"></i>
</i>
</code>```

but it does't help in case you want to display some number in the corner- for intance, the number of followers or the number of messages. If you want to achieve it you have to use your own css styling.

In my project I do it in following way:

```<code><div class="ui top  dropdown item">
<i class="icon bell outline"></i>
<div id="live_message_badge_main_header" class="floating ui red label hidden" style="padding:2px 3px;top: 10px;left: 47px;">
  <span class='live_message_badge'> </span>
</div>
</div>
</code>```

Additionally, you need corresponding js which will fill the span.

Result:

Title: Floating label on icon

Body:
Is it possible to achieve something like facebook's notifications icon with Semantic UI? I.e. an icon with a red Label to show the number of notifications? Found this thread but no answers there.

I tried this:

<Icon name='bell outline'>
  22
</Icon>

But the label doesn't show up (syntax is semantic-ui-react).

Body:
With Semantic UI you can make another icon float to the right upper corner:

<i class="huge icons">
  <i class="puzzle icon"></i>
  <i class="top right corner add icon"></i>
</i>

but it does't help in case you want to display some number in the corner- for intance, the number of followers or the number of messages. If you want to achieve it you have to use your own css styling.

In my project I do it in following way:

<div class="ui top  dropdown item">
<i class="icon bell outline"></i>
<div id="live_message_badge_main_header" class="floating ui red label hidden" style="padding:2px 3px;top: 10px;left: 47px;">
  <span class='live_message_badge'>&nbsp;</span>
</div>
</div>

Additionally, you need corresponding js which will fill the span.

Result:


问:
beep in WinCE , it possible ?
is it possible to make beep in WinCE ?

i try and i get an error

答:
The .net framework methods for beeing are not available in the CF version of the framework.  The best way to get a beep sound is to PInvoke into the MessageBeep function.  The PInvoke signature for this method is pretty straight forward

```<code>[DllImport("CoreDll.dll")]
public static extern void MessageBeep(int code);

public static void MessageBeep() {
  MessageBeep(-1);  // Default beep code is -1
}
</code>```

This blog post has an excellent more thorough example: http://blog.digitforge.com/?p=4 (on archive.org)

OwnerDisplayName: Gold

Title: beep in WinCE , it possible ?

LastEditorDisplayName: ctacke

Body:
The .net framework methods for beeing are not available in the CF version of the framework.  The best way to get a beep sound is to PInvoke into the MessageBeep function.  The PInvoke signature for this method is pretty straight forward

[DllImport("CoreDll.dll")]
public static extern void MessageBeep(int code);

public static void MessageBeep() {
  MessageBeep(-1);  // Default beep code is -1
}

This blog post has an excellent more thorough example: http://blog.digitforge.com/?p=4 (on archive.org)

OwnerDisplayName: JaredPar


问:
How to examine the size of the Bundle object in onSaveInstanceState?
I am using Android Studio 3.0.1 which allows to inspect the Bundle object in onSaveInstanceState:

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}
</code>```

To do so add a breakpoint and once the debugger stops right click the Bundle object as shown in the screenshot and select "Show Bundle Objects..." from the context menu.

Then a window opens to list the Bundle objects as shown in this screenshot:

Is there a way to find out how much memory the whole Bundle and it's children occupy? I want to identify the bigger chunks to optimize and avoid TransactionTooLargeException to be thrown on Android >= 7.

Something like Ubuntu Disk Usage Analyzer would be helpful - see screeshot:

答:
You can also use this one :-

=> just pass the Bundle here

```<code>public int  getBundleSizeInBytes(Bundle bundle  ) {
            Parcel parcel = Parcel.obtain();
            parcel.writeValue(bundle);
            byte[] bytes = parcel.marshall();
            parcel.recycle();
            return bytes.length;
}
</code>```

Then use android.text.format.Formatter.formatFileSize(activityContext, bytes) to output nicely.

Body:
I am using Android Studio 3.0.1 which allows to inspect the Bundle object in onSaveInstanceState:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

To do so add a breakpoint and once the debugger stops right click the Bundle object as shown in the screenshot and select "Show Bundle Objects..." from the context menu.

Then a window opens to list the Bundle objects as shown in this screenshot:

Is there a way to find out how much memory the whole Bundle and it's children occupy? I want to identify the bigger chunks to optimize and avoid TransactionTooLargeException to be thrown on Android >= 7.

Something like Ubuntu Disk Usage Analyzer would be helpful - see screeshot:

Body:
You can also use this one :-

=> just pass the Bundle here

public int  getBundleSizeInBytes(Bundle bundle  ) {
            Parcel parcel = Parcel.obtain();
            parcel.writeValue(bundle);
            byte[] bytes = parcel.marshall();
            parcel.recycle();
            return bytes.length;
}

Then use android.text.format.Formatter.formatFileSize(activityContext, bytes) to output nicely.


问:
Javascript copy input value
Hello Guys I want to copy input value yeah on button click But nothing work. Please Help!!</p>

```<code><script>
  function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
  }
</script>

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

<button class="btn btn-primary btn-block" onclick="copyToClipboard('#myvalue')">Copy myvalue</button>
</code>```

答:
function copyToClipboard() {
    var textBox = document.getElementById("myvalue");
    textBox.select();
    document.execCommand("copy");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

     <button class="btn btn-primary btn-block" onclick="copyToClipboard()">Copy myvalue</button></code>```

Title: Javascript copy input value

Body:
Hello Guys I want to copy input value yeah on button click But nothing work. Please Help!!

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

<button class="btn btn-primary btn-block" onclick="copyToClipboard('#myvalue')">Copy myvalue</button>

Body:
function copyToClipboard() {
    var textBox = document.getElementById("myvalue");
    textBox.select();
    document.execCommand("copy");
}

<input type="text" class="form-control" name="myvalue"  id="myvalue" value="YEAH" readonly  />

     <button class="btn btn-primary btn-block" onclick="copyToClipboard()">Copy myvalue</button>


问:
With Amazon S3, can I prevent trolls/grievers from making millions of GET-requests with bots?
I'm working on a website that contains photo galleries, and these images are stored on Amazon S3. Since Amazon charges like $0.01 per 10k GET-requests, it seems that a potential troll could seriously drive up my costs with a bot that makes millions of page requests per day.

Is there an easy way to protect myself from this?

答:
The simplest strategy would be to create randomized URLs for your images.

You can serve these URLs with your page information. But they cannot be guessed by the bruteforcer and will usually lead to a 404.

so something like yoursite/images/long_random_string


问:
Multiple Line Scala List
When I input a single array into my function, I get the correct result.  Now, instead, I would like to feed into my function a multiple line List (or some other Type that I can make from a multiple line String).

```<code>val inputLine = "foo, bar, bar, foo".split(", ").toList
</code>```

That works.  But I want to pass multiple lines into my function.

```<code>val inputList = List("""foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""")
</code>```

Thank you!

答:
```<code>val inputList = """foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""".split(",\\s*").toList

println(inputList)
</code>```

The ,\s* regex means "comma and then 0 or more spaces" where space is a whitespace character (includes \r \n and space...).

Title: Multiple Line Scala List

Body:
When I input a single array into my function, I get the correct result.  Now, instead, I would like to feed into my function a multiple line List (or some other Type that I can make from a multiple line String).

val inputLine = "foo, bar, bar, foo".split(", ").toList

That works.  But I want to pass multiple lines into my function.

val inputList = List("""foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""")

Thank you!

Body:
val inputList = """foo, bar, bar, foo,
bar, foo, foo, bar,
foo, bar, bar, foo""".split(",\\s*").toList

println(inputList)

The ,\s* regex means "comma and then 0 or more spaces" where space is a whitespace character (includes \r \n and space...).


问:
Getting the text from a div to be an input value of a field
I have a telephone field <input id="phone" type="tel"> where the user can input his telephone number and this number together with the country code is displayed into a div
Result
. I am now in turn trying to get this number displayed into a div  to be the input value of a hidden field.

I have managed to get the telephone number however I am not able to get the country code into the hidden field as well.

var input = $("#phone"),
output = $("#output");

input.intlTelInput({
  nationalMode: true,
  utilsScript: "https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js" // just for formatting/placeholders etc
});

// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
  var intlNumber = input.intlTelInput("getNumber");
  if (intlNumber) {
    output.text("International: " + intlNumber);
  } else {
    output.text("Please enter a number below");
  }
});

$("#phone").change(function(){
  $("#field2").val(this.value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Result</h2>
<div id="result">
  <p id="output">Please enter a number below</p>
  <input id="phone" type="tel">
</div>
Hidden: <input id="field2"></code>```

Fiddle

答:
maybe using the plugin method will help ?!</p>

```<code>$("#phone").change(function(){
  $("#field2").val(input.intlTelInput("getNumber"));
});
</code>```

Body:
I have a telephone field <input id="phone" type="tel"> where the user can input his telephone number and this number together with the country code is displayed into a div
Result
. I am now in turn trying to get this number displayed into a div  to be the input value of a hidden field.

I have managed to get the telephone number however I am not able to get the country code into the hidden field as well.

var input = $("#phone"),
output = $("#output");

input.intlTelInput({
  nationalMode: true,
  utilsScript: "https://intl-tel-input.com/node_modules/intl-tel-input/build/js/utils.js" // just for formatting/placeholders etc
});

// listen to "keyup", but also "change" to update when the user selects a country
input.on("keyup change", function() {
  var intlNumber = input.intlTelInput("getNumber");
  if (intlNumber) {
    output.text("International: " + intlNumber);
  } else {
    output.text("Please enter a number below");
  }
});

$("#phone").change(function(){
  $("#field2").val(this.value);
});

Result

Please enter a number below

  <input id="phone" type="tel">

Hidden: <input id="field2">

Fiddle

Body:
maybe using the plugin method will help ?!

$("#phone").change(function(){
  $("#field2").val(input.intlTelInput("getNumber"));
});


问:
The fast efficient way to normalize each channel of an image with different value
I have to divide all the pixels of each channel by a value (normalization). What I do is split the image into three channels, divide all pixels and then merge back the three channels. Here is how I do it:

```<code>template <typename T, typename ... Ts>
void insert_all(std::vector<T> &vec, Ts ... ts)
{
    (vec.push_back(ts), ...);
}

std::vector<cv::Mat> rgb, rgbN;
cv::split(src, rgb); //src is my RGB image

rgbN.reserve(3);
insert_all(rgbN, cv::Mat_<float>(rgb[0])/A0,
                 cv::Mat_<float>(rgb[1])/A1,
                 cv::Mat_<float>(rgb[2])/A2);
cv::Mat srcN;
cv::merge(rgbN, srcN_gray);
</code>```

I think it is too much code for a simple normalization, is there a better way to do it, probably without spiting and merging?

答:
As I wrote in my comment you can try to do everything without separating it... with the least code as possible I think this is the way to go:

```<code>// dummy values, replace as needed
float A0 = 1.0, A1 = 2.0, A2 = 3.0;
// creates a copy to work in
cv::Mat srcN = src.clone();
// normalizes in one pass
std::transform(srcN.begin<cv::Vec3f>(), srcN.end<cv::Vec3f>(), srcN.begin<cv::Vec3f>(), [A0, A1, A2](const cv::Vec3f pixel){
  return cv::Vec3f(pixel[0]/A0, pixel[1]/A1, pixel[2]/A2);
});
</code>```

In a similar way you can try other approaches, e.g. OpenCV foreach  or the concurrency library.

EDIT:

Here is my try with the OpenCV foreach... I have not tested it, but should work

```<code>cv::Mat srcN = src.clone();
srcN.forEach<cv::Vec3f>
(
  [A0, A1, A2](cv::Vec3f &pixel, const int * position) -> void
  {
    pixel[0]/=A0;
    pixel[1]/=A1;
    pixel[2]/=A2;
  }
);
</code>```

Body:
I have to divide all the pixels of each channel by a value (normalization). What I do is split the image into three channels, divide all pixels and then merge back the three channels. Here is how I do it:

template <typename T, typename ... Ts>
void insert_all(std::vector<T> &vec, Ts ... ts)
{
    (vec.push_back(ts), ...);
}

std::vector<cv::Mat> rgb, rgbN;
cv::split(src, rgb); //src is my RGB image

rgbN.reserve(3);
insert_all(rgbN, cv::Mat_<float>(rgb[0])/A0,
                 cv::Mat_<float>(rgb[1])/A1,
                 cv::Mat_<float>(rgb[2])/A2);
cv::Mat srcN;
cv::merge(rgbN, srcN_gray);

I think it is too much code for a simple normalization, is there a better way to do it, probably without spiting and merging?

Body:
As I wrote in my comment you can try to do everything without separating it... with the least code as possible I think this is the way to go:

// dummy values, replace as needed
float A0 = 1.0, A1 = 2.0, A2 = 3.0;
// creates a copy to work in
cv::Mat srcN = src.clone();
// normalizes in one pass
std::transform(srcN.begin<cv::Vec3f>(), srcN.end<cv::Vec3f>(), srcN.begin<cv::Vec3f>(), [A0, A1, A2](const cv::Vec3f pixel){
  return cv::Vec3f(pixel[0]/A0, pixel[1]/A1, pixel[2]/A2);
});

In a similar way you can try other approaches, e.g. OpenCV foreach  or the concurrency library.

EDIT:

Here is my try with the OpenCV foreach... I have not tested it, but should work

cv::Mat srcN = src.clone();
srcN.forEach<cv::Vec3f>
(
  [A0, A1, A2](cv::Vec3f &pixel, const int * position) -> void
  {
    pixel[0]/=A0;
    pixel[1]/=A1;
    pixel[2]/=A2;
  }
);


问:
Return min/max number in nested list
I'm trying to find the min/max number within a nested list using Linq.

An example class would be:

```<code>public class ListA
{
    public HashSet<HashSet<int>> nestedList;

    public ListA()
    {
        nestedList = new HashSet<HashSet<int>>()
        {
            new HashSet<int> { 1, 3, 5, 7 },
            new HashSet<int> { 2, 12, 7, 19 },
            new HashSet<int> { 6, 9 , 3, 14 }
        };
    }

    public int MaxNumber
    {
        // return the highest number in list
    }
}
</code>```

In the example above, the minimum number would be 1 and the max number 19.

I'm struggling to get anything to get valid syntax. Anyone help?

答:
```<code>nestedList.SelectMany(item => item).Max();
</code>```

and

```<code>nestedList.SelectMany(item => item).Min();
</code>```

Title: Return min/max number in nested list

Body:
I'm trying to find the min/max number within a nested list using Linq.

An example class would be:

public class ListA
{
    public HashSet<HashSet<int>> nestedList;

    public ListA()
    {
        nestedList = new HashSet<HashSet<int>>()
        {
            new HashSet<int> { 1, 3, 5, 7 },
            new HashSet<int> { 2, 12, 7, 19 },
            new HashSet<int> { 6, 9 , 3, 14 }
        };
    }

    public int MaxNumber
    {
        // return the highest number in list
    }
}

In the example above, the minimum number would be 1 and the max number 19.

I'm struggling to get anything to get valid syntax. Anyone help?

Body:
nestedList.SelectMany(item => item).Max();

and

nestedList.SelectMany(item => item).Min();


问:
How do I convert an array of Strings to an Array of Int in Kotlin
I am looking to convert an List<String> to an List<Int> in Kotlin.

```<code>val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}
</code>```

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

答:
```<code>val intArray = stringArray.map(String::toInt)
</code>```

or with lambda

```<code>val intArray = stringArray.map { it.toInt() }
</code>```

Body:
I am looking to convert an List<String> to an List<Int> in Kotlin.

val stringArray = "1 2 3 4 5 6".split(" ")
val intArray = MutableList<Int>(0, {0})
for (item in stringArray) {
    intArray.add(item.toInt())
}

The above will do it, but it feels as if there is a better way of doing this (possible with lambdas and streams?).

Body:
val intArray = stringArray.map(String::toInt)

or with lambda

val intArray = stringArray.map { it.toInt() }