问:
Get a list of duplicates from list based on properties comparison
I have a List<Demo>

```<code>public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}
</code>```

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

```<code>List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});
</code>```

and then i am doing:

```<code>var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();
</code>```

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

答:
You were almost there.

Groupby divides a sequence into groups. Each group has something in common: the Key of the group. Each group is a sequence containing all elements in the original sequence that match the key.

Your key is new { t.Name, t.Title }. Your original sequence will be divided into groups of object that had the same name / title:

Group Demo / A contains three elements: Id = 1, Id = 2, Id = 3

Group Demo1 / A contains only element Id = 4

Group Demo2 / A contains only element Id = 5

The Where after you group returns a sequence of IGrouping. This sequence contains only one element: the only group that has more than one element. This is the group with key Demo/A.

Your specification was not a sequence of IGrouping (where each group is a sequence of Demo), but one list of Demo that contains all elements with duplicate Name/Title.

This means you have to take the elements from all groups after your Where (in your example this sequence contains only one group) and concatenate all these groups into one sequence. This is done by Enumerable.SelectMany

```<code>IEnumerable<Demo> duplicates = demo
    .GroupBy(demoElement => new {demoElement.Name, demoElement.Title})
    .Where(group => group.Skip(1).Any())
    .SelectMany(group => group);
</code>```

The SelectMany takes the sequence of each group and concatenates all sequences into one sequence.

By the way, did you notice that I didn't use Count() to detect if there are duplicates, but Skip(1).Any(). If one of your groups would have hundreds of elements, it would be enough to stop counting after the first element. It is a waste of computing power to count all elements to detect if there is more than one.

One final hint: don't use ToList() if you are not certain you need it. If the user of your piece of code only wants the first element, or the first few, it is a waste if you calculate all elements into a list. Keep it IEnumerable<Demo> as long as possible.

Body:
I have a List<Demo>

public class Demo
{
    public Demo()
    {

    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
}

The Id property is unique for every record in the list.

How can I get a List<Demo> from the original List<Demo> with all the duplicates where the Name and Title are same.

What I did so far but what I get is one single record:

List<Demo> demo = new List<Demo>();

demo.Add(new Demo()
{
    Id = 1,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 2,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 3,
    Name = "Demo",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 4,
    Name = "Demo1",
    Title = "A"
});

demo.Add(new Demo()
{
    Id = 5,
    Name = "Demo2",
    Title = "A"
});

and then i am doing:

var duplicates = demo.GroupBy(t => new { t.Name, t.Title })
                     .Where(t => t.Count() > 1)
                     .Select(g => g.Key).ToList();

From the example above I should get a List<Demo> with the first 3 items where the ids are:1,2,3 because Name and Title are same.

Body:
You were almost there.

Groupby divides a sequence into groups. Each group has something in common: the Key of the group. Each group is a sequence containing all elements in the original sequence that match the key.

Your key is new { t.Name, t.Title }. Your original sequence will be divided into groups of object that had the same name / title:

Group Demo / A contains three elements: Id = 1, Id = 2, Id = 3

Group Demo1 / A contains only element Id = 4

Group Demo2 / A contains only element Id = 5

The Where after you group returns a sequence of IGrouping. This sequence contains only one element: the only group that has more than one element. This is the group with key Demo/A.

Your specification was not a sequence of IGrouping (where each group is a sequence of Demo), but one list of Demo that contains all elements with duplicate Name/Title.

This means you have to take the elements from all groups after your Where (in your example this sequence contains only one group) and concatenate all these groups into one sequence. This is done by Enumerable.SelectMany

IEnumerable<Demo> duplicates = demo
    .GroupBy(demoElement => new {demoElement.Name, demoElement.Title})
    .Where(group => group.Skip(1).Any())
    .SelectMany(group => group);

The SelectMany takes the sequence of each group and concatenates all sequences into one sequence.

By the way, did you notice that I didn't use Count() to detect if there are duplicates, but Skip(1).Any(). If one of your groups would have hundreds of elements, it would be enough to stop counting after the first element. It is a waste of computing power to count all elements to detect if there is more than one.

One final hint: don't use ToList() if you are not certain you need it. If the user of your piece of code only wants the first element, or the first few, it is a waste if you calculate all elements into a list. Keep it IEnumerable<Demo> as long as possible.


来源: stackexchange

问:
How to make refresh function in VBA
I am using Access Database to make a program.

Here is the problem:

After I enter the data in textbox, which is in a blue boxes, and click 'Add Data' button, data move to the ListBox, which is marked with orange box. But I should press 'F5' button(refresh) to see the data. I want to see the data immediately after I click 'Add Data' button. Is there any way to do that?
Any comments would be greatly thankful(It would be nice if you can share your code)

答: requerying the form is the simplest way probably, but with no idea of what the button does, how your data is structured, how the form is structured, i.e. is the listbox bound or unbound, so cant really say, if F5, is doing it, then just look for the VBA method for refreshing the form.</p>

ContentLicense: CC BY-SA 3.0

Title: How to make refresh function in VBA


问:
Chartist import graph data from database in laravel
i have data in sql database, how to get them and place in the chartist as line graph data?

so far, i've passed the data through controller into blade in a parameter, and i don't know how to implement it in chartist. Thanks!

答:
According to Chart.js you can easily make a static line chart it. Look here

```<code><canvas id="myChart" width="400" height="400"></canvas>
<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
</code>```

But if you have to make a dynamic chart according to your database then what you have to do? Here, if you can change the data array then you will be able to prepare your own chart. I have asked a same question once in stackoverflow, finally I got a solution by myself.

So what you need to do? I hope you are familiar with laravel blade. I mean how to write a laravel variable inside a JS file. So you need to make a string of you dataset. You must make a string like this data set from your controller and pass it to the view, this way

```<code>$points = "[12, 19, 3, 5, 2, 3]"
</code>```

Later will put the variable in the position of the data array inside the javascript in blade. Like

```<code>data: {! $points !},
</code>```

If you do this I hope your chart will definitely appear. In this case you can take the help from my previous question. Otherwise you will face same parsing problem like I had faced.

Additionally you can change the labels here by applying same procedure

Body:
According to Chart.js you can easily make a static line chart it. Look here

<canvas id="myChart" width="400" height="400"></canvas>
<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.js"></script>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>

But if you have to make a dynamic chart according to your database then what you have to do? Here, if you can change the data array then you will be able to prepare your own chart. I have asked a same question once in stackoverflow, finally I got a solution by myself.

So what you need to do? I hope you are familiar with laravel blade. I mean how to write a laravel variable inside a JS file. So you need to make a string of you dataset. You must make a string like this data set from your controller and pass it to the view, this way

$points = "[12, 19, 3, 5, 2, 3]"

Later will put the variable in the position of the data array inside the javascript in blade. Like

data: {! $points !},

If you do this I hope your chart will definitely appear. In this case you can take the help from my previous question. Otherwise you will face same parsing problem like I had faced.

Additionally you can change the labels here by applying same procedure


问:
How to prevent unauthorized spidering
I want to prevent automated html scraping from one of our sites while not affecting legitimate spidering (googlebot, etc.). Is there something that already exists to accomplish this? Am I even using the correct terminology?

EDIT: I'm mainly looking to prevent people that would be doing this maliciously. I.e. they aren't going to abide by robots.txt

EDIT2: What about preventing use by "rate of use" ... i.e. captcha to continue browsing if automation is detected and the traffic isn't from a legitimate (google, yahoo, msn, etc.) IP.

答:
One approach is to set up an HTTP tar pit; embed a link that will only be visible to automated crawlers. The link should go to a page stuffed with random text and links to itself (but with additional page info: /tarpit/foo.html , /tarpit/bar.html , /tarpit/baz.html - but have the script at /tarpit/ handle all requests with the 200 result).

To keep the good guys out of the pit,  generate a 302 redirect to your home page if the user agent is google or yahoo.

It isn't perfect, but it will at least slow down the naive ones.

EDIT: As suggested by Constantin, you could mark the tar pit as offlimits in robots.txt. The good guys use web spiders that honor this protocol will stay out of the tar pit. This would probably get rid of the requirement to generate redirects for known good people.

OwnerDisplayName: Kyle West

Title: How to prevent unauthorized spidering

LastEditorDisplayName: Kyle West

OwnerDisplayName: Tim Howland

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tim Howland


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答:
I have to disagree with Matt Greer about any assumption for MVC that you are already versed in ASP.NET.   Nearly all of the tutorials and/or books that I've come across definitely do not start from an assumed ASP.NET knowledge base. In fact, for a junior developer, I'd think that knowledge of ASP.NET would be detrimental and confusing, as ASP.NET adds a whole bunch of stuff (designers, viewstate, abstractions, etc)  that really is sort of the antithesis of ASP.NET MVC development.

ASP.NET MVC, however, is a framework that definitely requires knowledge of C# or VB to implement properly.  In the end, any of the code that drives the site will be written in C#.  The ability to properly write .net code is a definite requirement.

I'm personally very partial to Apress books, so I'd recommend the following:

Apress Beginning C# 2010:
http://www.apress.com/book/view/9781430231714

I'd also recommend from experience

Apress Pro ASP.NET MVC 2:
http://www.apress.com/book/view/1430228865

Another really great series for learning ASP.NET MVC 2 is the screencast series available from tekpub at:

http://www.tekpub.com.


问:
centering text positioning using flexbox
Trying to do a simple website recreation using flexbox. Here is the final goal (for this step):

Pretty simple. But I am struggling with aligning the text. I am able to get the header to center just fine. It's mainly the paragraph underneath that I am having trouble centering. Is there a way to center that paragraph vertically and horizontally to its outer container? New to flexbox and would like any tips! Here is a link to my codepen and relevant code: https://codepen.io/gkunthara/pen/qjympg

HTML

```<code> <div class = "content-container">
<h1 class = "main-header"> Connect with Subscribers Effortlessly </h1>
 <p class = "sub-header"> Email Marketing Platform for Bloggers &
Authors. </p>
 </div>
</code>```

CSS

```<code> .content-container  .main-header{

  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height:75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;

}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
  margin-top: 150px;
}
</code>```

答:
You just need to do two things.

1. Add

```<code>flex-direction: column;
align-items: center;
</code>```

to your .content-container class.

2. Remove margin-top: 150px from .content-container .sub-header and it should be it.

* {
  box-sizing: border-box;
}

.content-container {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  border-style: solid;
  margin-top: 15px;
  flex-direction: column;
  align-items: center;
}

.content-container .main-header {
  box-sizing: border-box;
  font-weight: 600;
  font-size: 30px;
  height: 75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;
}

.content-container .sub-header {
  border-style: solid;
  height: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content-container">
  <h1 class="main-header"> Connect with Subscribers Effortlessly </h1>
  <p class="sub-header"> Email Marketing Platform for Bloggers & Authors. </p>
</div></code>```

Here is the fiddle to play with.

Hope this helps.

Body:
Trying to do a simple website recreation using flexbox. Here is the final goal (for this step):

Pretty simple. But I am struggling with aligning the text. I am able to get the header to center just fine. It's mainly the paragraph underneath that I am having trouble centering. Is there a way to center that paragraph vertically and horizontally to its outer container? New to flexbox and would like any tips! Here is a link to my codepen and relevant code: https://codepen.io/gkunthara/pen/qjympg

HTML

 Connect with Subscribers Effortlessly

 Email Marketing Platform for Bloggers &
Authors.

CSS

 .content-container  .main-header{

  box-sizing: border-box;
  font-weight: 600;
  font-size: 45px;
  height:75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;

}

.content-container .sub-header {
  border-style: solid;
  display: flex;
  height: 25px;
  margin-top: 150px;
}

Body:
You just need to do two things.

1. Add

flex-direction: column;
align-items: center;

to your .content-container class.

2. Remove margin-top: 150px from .content-container .sub-header and it should be it.

* {
  box-sizing: border-box;
}

.content-container {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  border-style: solid;
  margin-top: 15px;
  flex-direction: column;
  align-items: center;
}

.content-container .main-header {
  box-sizing: border-box;
  font-weight: 600;
  font-size: 30px;
  height: 75px;
  padding-left: 5px;
  padding-right: 5px;
  color: rgb(51, 51, 51);
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  border-style: solid;
}

.content-container .sub-header {
  border-style: solid;
  height: 25px;
}

<div class="content-container">
  <h1 class="main-header"> Connect with Subscribers Effortlessly </h1>
  <p class="sub-header"> Email Marketing Platform for Bloggers & Authors. </p>
</div>

Here is the fiddle to play with.

Hope this helps.


问:
Give a custom file name to each file being zipped
I am downloading multiple files from S3 and zipping them. How do I give a custom name to each file being zipped?</p>

```<code>def download_all_files
   folder_path = "#{Rails.root}/public/downloads/"
   zipfile_name = "#{Rails.root}/public/archive.zip"

   FileUtils.remove_dir(folder_path) if Dir.exist?(folder_path)
   FileUtils.remove_entry(zipfile_name) if File.exist?(zipfile_name)
   Dir.mkdir("#{Rails.root}/public/downloads")

   @model_object.each do |attachment|
      open(folder_path + "#{attachment.avatar.file.filename}", 'wb') do |file|
         file << open("#{attachment.avatar.url}").read
      end
   end

   input_filenames = Dir.entries(folder_path).select {|f| !File.directory? f}

   Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      input_filenames.each do |attachment|
         zipfile.add(attachment,File.join(folder_path,attachment))
      end
   end

   send_file(File.join("#{Rails.root}/public/", 'archive.zip'), :type => 'application/zip', :filename => "#{Time.now.to_date}.zip")

end
</code>```

答:
Looks like you have 2 ways you can accomplish this. To the end user, both of these should yield the same result, just depends how you want them on your server.

1. Change it while zipping the files together

This will leave the files as they are currently named on your system and only change them in the output archive.zip

Looking at this gem it looks like

```<code>Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
  input_filenames.each do |filename|
    # Two arguments:
    # - The name of the file as it will appear in the archive
    # - The original file, including the path to find it
    zipfile.add(filename, folder + '/' + filename)
  end
  zipfile.get_output_stream("myFile") { |os| os.write "myFile contains just this" }
end
</code>```

So, in your code just change the first occurrence of 'attachment' on

```<code>zipfile.add(attachment, File.join(folder_path, attachment))
</code>```

to whatever you want the name to be.

2. Change it while writing the file to your server

Since you are writing the file just a few lines above there

```<code>open(folder_path + "#{attachment.avatar.file.filename}", 'wb') do |file|
</code>```

you could change the file name on this line as well. This would change the filename on your server and in the archive.zip

Body:
I am downloading multiple files from S3 and zipping them. How do I give a custom name to each file being zipped?

def download_all_files
   folder_path = "#{Rails.root}/public/downloads/"
   zipfile_name = "#{Rails.root}/public/archive.zip"

   FileUtils.remove_dir(folder_path) if Dir.exist?(folder_path)
   FileUtils.remove_entry(zipfile_name) if File.exist?(zipfile_name)
   Dir.mkdir("#{Rails.root}/public/downloads")

   @model_object.each do |attachment|
      open(folder_path + "#{attachment.avatar.file.filename}", 'wb') do |file|
         file << open("#{attachment.avatar.url}").read
      end
   end

   input_filenames = Dir.entries(folder_path).select {|f| !File.directory? f}

   Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
      input_filenames.each do |attachment|
         zipfile.add(attachment,File.join(folder_path,attachment))
      end
   end

   send_file(File.join("#{Rails.root}/public/", 'archive.zip'), :type => 'application/zip', :filename => "#{Time.now.to_date}.zip")

end

Body:
Looks like you have 2 ways you can accomplish this. To the end user, both of these should yield the same result, just depends how you want them on your server.

1. Change it while zipping the files together

This will leave the files as they are currently named on your system and only change them in the output archive.zip

Looking at this gem it looks like

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
  input_filenames.each do |filename|
    # Two arguments:
    # - The name of the file as it will appear in the archive
    # - The original file, including the path to find it
    zipfile.add(filename, folder + '/' + filename)
  end
  zipfile.get_output_stream("myFile") { |os| os.write "myFile contains just this" }
end

So, in your code just change the first occurrence of 'attachment' on

zipfile.add(attachment, File.join(folder_path, attachment))

to whatever you want the name to be.

2. Change it while writing the file to your server

Since you are writing the file just a few lines above there

open(folder_path + "#{attachment.avatar.file.filename}", 'wb') do |file|

you could change the file name on this line as well. This would change the filename on your server and in the archive.zip


问:
Ionic Cordova app crashes at launch in ipad
I checked it in many devices, in almost all it is working without any issue. But when checked in iPad with OS version 9.3.5, first time launch causes crash. i have no idea why it is crashing. I have checked a lot for the solution, but couldn't find any. The log from XCode when running is

2017-07-03 11:58:12.334 [10543:4215404] DiskCookieStorage changing
  policy from 2 to 0, cookie file:
  file:///private/var/mobile/Containers/Data/Application/C264816D-2744-4D26-BC6A-46B3BEF8DA46/Library/Cookies/Cookies.binarycookies

2017-07-03 11:58:12.498[10543:4215404] Apache Cordova native platform
  version 4.0.0 is starting.

2017-07-03 11:58:12.501[10543:4215404] Multi-tasking -> Device: YES,
  App: YES

2017-07-03 11:58:12.676[10543:4215404] Using UIWebView

2017-07-03 11:58:12.684[10543:4215404] [CDVTimer][handleopenurl]
  0.398993ms

2017-07-03 11:58:12.692[10543:4215404]
  [CDVTimer][intentandnavigationfilter] 8.102000ms

2017-07-03 11:58:12.693[10543:4215404] [CDVTimer][gesturehandler]
  0.422001ms

2017-07-03 11:58:12.736[10543:4215404] [CDVTimer][splashscreen]
  42.403996ms

2017-07-03 11:58:12.764[10543:4215404] [CDVTimer][statusbar]
  27.370989ms

2017-07-03 11:58:12.769[10543:4215404] [CDVTimer][keyboard] 3.852963ms

2017-07-03 11:58:12.772[10543:4215404] [CDVTimer][localnotification]
  2.893984ms

2017-07-03 11:58:12.773[10543:4215404] [CDVTimer][localnotification]
  0.070989ms

2017-07-03 11:58:12.773[10543:4215404] [CDVTimer][TotalPluginStartup]
  89.882970ms

2017-07-03 11:58:13.556[10543:4215404] Resetting plugins due to page
  load.

2017-07-03 11:58:15.216[10543:4215404] Finished load of:
  file:///var/containers/Bundle/Application/D2B7D0DC-8697-4605-B0FC-B72CA832E4F3/appName.app/www/index.html

2017-07-03 11:58:16.653[10543:4215404] THREAD WARNING: ['Device'] took
  '15.490967' ms. Plugin should use a background thread.

I know it shows a thread warning, but they say it can be neglected here

I tried this stack overflow answer also to remove the warning. But that too couldn't fix the issue. My Cordova version is 6.5.0.

答: Thanks to this post, at last I solved it. Removed old ios platform & updated it with the new. Now its working without any issue </p>


问:
Why does "const extern" give an error?
The following piece of code working fine:

```<code>#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}
</code>```

But, the following piece of code give an error:

```<code>#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}
</code>```

So, why does const extern give an error?

答:
You say foo is const and then try to change its constness with the other declaration.
Do this and you should be fine.

```<code>  const extern int foo; // With constant
  const int foo = 42;
</code>```

Title: Why does "const extern" give an error?

Body:
The following piece of code working fine:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

But, the following piece of code give an error:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

So, why does const extern give an error?

Body:
You say foo is const and then try to change its constness with the other declaration.
Do this and you should be fine.

  const extern int foo; // With constant
  const int foo = 42;


问:
Best Way to Store Time in Format HH:MM in MySQL for Performance
I am storing departure and arrival times as minutes(int) in database.

```<code>id, transport_date, departure_time, arrival_time
'3','2017-08-01',        '620',       '650'
</code>```

and convert the minutes to time in JS:
e.g:

```<code>public String getDepartureTime() {
    return minuteToTime(departureTime);
}

public static String minuteToTime(int minute) {
  int hour = minute / 60;
  minute %= 60;
  String p = "AM";
  if (hour >= 12) {
    hour %= 12;
    p = "PM";
  }
  if (hour == 0) {
    hour = 12;
  }
  return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}
</code>```

and this returns 620 to "10:20 AM". Is this a good approach to store time in database? or should I just change column datatype as varchar and save time as 10:20 AM? Which way is faster, or has better performance?

答:
Instead of storing times in INT type or Varchar, you should use "datetime" data type for those columns and while retrieving we can extract time from these column with functions.

Ex :  Assuming that you have altered the datatypes to 'datetime' and your query will be

SELECT id, transport_date, Time(departure_time) As DepartureTime , Time(arrival_time) As ArrivalTime
FROM Transport_TABLE;

Body:
I am storing departure and arrival times as minutes(int) in database.

id, transport_date, departure_time, arrival_time
'3','2017-08-01',        '620',       '650'

and convert the minutes to time in JS:
e.g:

public String getDepartureTime() {
    return minuteToTime(departureTime);
}

public static String minuteToTime(int minute) {
  int hour = minute / 60;
  minute %= 60;
  String p = "AM";
  if (hour >= 12) {
    hour %= 12;
    p = "PM";
  }
  if (hour == 0) {
    hour = 12;
  }
  return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute) + " " + p;
}

and this returns 620 to "10:20 AM". Is this a good approach to store time in database? or should I just change column datatype as varchar and save time as 10:20 AM? Which way is faster, or has better performance?


问:
How to use the same name classes but in separate styles
see the example to understand:

```<code>    <!--Standard Bootstrap -->
    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <!-- Material Design Bootstrap -->
    <link href="/build/css/site/mdb.min.css" rel="stylesheet">
</code>```

so i want a thing like it:

```<code>    <div class="btn btn-danger" >Standard Bootstrap Button</div>
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</code>```

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

答:
If using SCSS is an option, you could create a file that imports the two files but wraps each in its own namespace. Something like:

```<code>.bootstrap {
    @import 'bootstrap.min.css';
}

.mdb {
    @import 'mdb.min.css';
}
</code>```

This file should go in the same directory as bootstrap.min.css and mdb.min.css and should have a .scss extension. After running the above through an SCSS compiler, you will have one CSS file that you can link to in your HTML file instead of bootstrap.min.css and mdb.min.css. For example, if your new compiled file is named combined.css, then you would replace the link tags in your question with this:

```<code><link href="/build/css/site/combined.css" rel="stylesheet">
</code>```

You could then use the styles in your HTML like so:

```<code><div class="bootstrap">
    <div class="btn btn-danger" >Standard Bootstrap Button</div>
</div>
<div class="mdb">
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</div>
</code>```

Note that you must wrap your elements in a DIV (or other element) with a class of bootstrap or mdb to get the intended styling.

ContentLicense: CC BY-SA 4.0

Body:
see the example to understand:

    <link href="/build/css/site/bootstrap.min.css" rel="stylesheet">

    <link href="/build/css/site/mdb.min.css" rel="stylesheet">

so i want a thing like it:

Standard Bootstrap Button

Material Design Bootstrap Button

The name of the classes are the same. But they are in two separate styles.
How can I use the two styles as I said?

Forgive me for the bad English.

Body:
If using SCSS is an option, you could create a file that imports the two files but wraps each in its own namespace. Something like:

.bootstrap {
    @import 'bootstrap.min.css';
}

.mdb {
    @import 'mdb.min.css';
}

This file should go in the same directory as bootstrap.min.css and mdb.min.css and should have a .scss extension. After running the above through an SCSS compiler, you will have one CSS file that you can link to in your HTML file instead of bootstrap.min.css and mdb.min.css. For example, if your new compiled file is named combined.css, then you would replace the link tags in your question with this:

<link href="/build/css/site/combined.css" rel="stylesheet">

You could then use the styles in your HTML like so:

<div class="bootstrap">
    <div class="btn btn-danger" >Standard Bootstrap Button</div>
</div>
<div class="mdb">
    <div class="btn btn-danger" >Material Design Bootstrap Button</div>
</div>

Note that you must wrap your elements in a DIV (or other element) with a class of bootstrap or mdb to get the intended styling.


问:
Custom file format in Impala
We have a custom internal data format. I'd like to use Impala with this format, just for reading. I want to write the binding for this format. But there is no reason to contribute this back, as nobody else uses this format.

Does Impala support file format plugins in some way?

From hdfs-scan-node.cc it looks like the list of file formats is hardcoded unfortunately. If this is the case, is there a plan to change this? Or is this not a common problem for some reason?

答:
No, as stated in How Impala Works with Hadoop File Formats:

Impala can only query the file formats listed in the preceding table. In particular, Impala does not support the ORC file format.

The reasons for this are probably related to the run-time code generation which would be harder to optimize if Impala didn't constrain file formats.
However, Impala is an open source project and there is no reason why you cannot suggest this by filing a JIRA.

http://blog.cloudera.com/blog/2013/02/inside-cloudera-impala-runtime-code-generation/
https://issues.apache.org/jira/projects/IMPALA/issues
https://www.cloudera.com/documentation/enterprise/latest/topics/impala_file_formats.html

Title: Custom file format in Impala


问:
Making Transaction from remote device (e.g. Mobile) to make Transaction or call data from Blockain
I was thinking of developing a mobile application which can make transaction in private network nodes of which are located at a server.
How this objective can be achieved?
What should be the technologies I should learn to implement?</p>

答:
I understand that you are talking about developing a permissioned Blockchain, i.e. a private network where everyone can't access. So, if I were you, I'd learn about the Fabric project by Hyperledger, which is an implementation of Blockchain for permissioned networks. You have more information about it here

Fabric allows you to create a permissioned Blockchain. Then, you will develop the clients that will call the Blockchain. In the Blockchain, you deploy your smartcontract, i.e. the code that you want to be executed.


问:
STL container leak
I'm using a vector container to hold instances of an object which contain 3 ints and 2 std::strings, this is created on the stack and populated from a function in another class but running the app through deleaker shows that the std::strings from the object are all leaked. Here's the code:

```<code>// Populator function:
void PopulatorClass::populate(std::vector<MyClass>& list) {
    // m_MainList contains a list of pointers to the master objects
    for( std::vector<MyClass*>::iterator it = m_MainList.begin(); it != m_MainList.end(); it++ ) {
        list.push_back(**it);
    }
}

// Class definition
class MyClass {
private:
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Code causing the problem:
std::vector<MyClass> list;
PopulatorClass.populate(list);
</code>```

When this is run through deleaker the leaked memory is in the allocator for the std::string classes.

I'm using Visual Studio 2010 (CRT).

Is there anything special I need to do to make the strings delete properly when unwinding the stack and deleting the vector?

Thanks,
J

答:
Every time you got a problem with the STL implementation doing something strange or wrong like a memory leak, try this :

Reproduce the most basic example of what you try to achieve. If it runs without a leak, then the problem is in the way you fill the data. It's the most probable source of problem (I mean your own code).

Not tested simple on-the-fly example for your specific problem :

```<code>#include <string>
#include <sstream>

// Class definition
struct MyClass  { // struct for convenience
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Prototype of populator function:
void populate(std::vector<MyClass>& list)
{
    const int MAX_TYPE_IDX = 4;
    const int MAX_CATEGORY_IDX = 8;
    const int MAX_SUB_CATEGORY_IDX = 6;

    for( int type_idx = 0; type_idx < MAX_TYPE_IDX ; ++type_idx)
        for( int category_idx = 0; category_idx < MAX_CATEGORY_IDX ; ++category_idx)
             for( int sub_category_idx = 0; sub_category_idx < MAX_SUB_CATEGORY_IDX ; ++sub_category_idx)
             {
                   std::stringstream name_stream;
                   name_stream << "object_" << type_idx << "_" << category_idx << "_" << sub_category_idx ;
                   std::stringstream desc_stream;
                   desc_stream << "This is an object of the type N°" << type_idx << ".\n";
                   desc_stream << "It is of category N°" << category_idx << ",\n";
                   desc_stream << "and of sub-category N°" << category_idx << "!\n";

                   MyClass object;
                   object.m_Name = name_stream.str();
                   object.m_Description = desc_stream.str();
                   object.m_nType = type_idx;
                   m_nCategory =
                   m_nSubCategory =
                   list.push_back( object );
             }
}

int main()
{
    // Code causing the problem:
    std::vector<MyClass> list;
    populate(list);

    // memory leak check?
    return 0;
 }
</code>```

If you still got the memory leak, first check that it's not a false-positive from your leak detection software.

Then if it's not, google for memory leak problems with your STL implementation (most of the time on the compiler developer website). The implementor might provide a bug tracking tool where you could search in for the same problem and potential solution.

If you still can't find the source of the leak, maybe try to build your project with a different compiler (if you can) and see if it have the same effect. Again if the leak still occurs, the problem have a lot of chances to come from your code.

Title: STL container leak

Body:
I'm using a vector container to hold instances of an object which contain 3 ints and 2 std::strings, this is created on the stack and populated from a function in another class but running the app through deleaker shows that the std::strings from the object are all leaked. Here's the code:

// Populator function:
void PopulatorClass::populate(std::vector<MyClass>& list) {
    // m_MainList contains a list of pointers to the master objects
    for( std::vector<MyClass*>::iterator it = m_MainList.begin(); it != m_MainList.end(); it++ ) {
        list.push_back(**it);
    }
}

// Class definition
class MyClass {
private:
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Code causing the problem:
std::vector<MyClass> list;
PopulatorClass.populate(list);

When this is run through deleaker the leaked memory is in the allocator for the std::string classes.

I'm using Visual Studio 2010 (CRT).

Is there anything special I need to do to make the strings delete properly when unwinding the stack and deleting the vector?

Thanks,
J

Body:
Every time you got a problem with the STL implementation doing something strange or wrong like a memory leak, try this :

Reproduce the most basic example of what you try to achieve. If it runs without a leak, then the problem is in the way you fill the data. It's the most probable source of problem (I mean your own code).

Not tested simple on-the-fly example for your specific problem :

#include <string>
#include <sstream>

// Class definition
struct MyClass  { // struct for convenience
    std::string m_Name;
    std::string m_Description;
    int m_nType;
    int m_nCategory;
    int m_nSubCategory;
};

// Prototype of populator function:
void populate(std::vector<MyClass>& list)
{
    const int MAX_TYPE_IDX = 4;
    const int MAX_CATEGORY_IDX = 8;
    const int MAX_SUB_CATEGORY_IDX = 6;

    for( int type_idx = 0; type_idx < MAX_TYPE_IDX ; ++type_idx)
        for( int category_idx = 0; category_idx < MAX_CATEGORY_IDX ; ++category_idx)
             for( int sub_category_idx = 0; sub_category_idx < MAX_SUB_CATEGORY_IDX ; ++sub_category_idx)
             {
                   std::stringstream name_stream;
                   name_stream << "object_" << type_idx << "_" << category_idx << "_" << sub_category_idx ;
                   std::stringstream desc_stream;
                   desc_stream << "This is an object of the type N°" << type_idx << ".\n";
                   desc_stream << "It is of category N°" << category_idx << ",\n";
                   desc_stream << "and of sub-category N°" << category_idx << "!\n";

                   MyClass object;
                   object.m_Name = name_stream.str();
                   object.m_Description = desc_stream.str();
                   object.m_nType = type_idx;
                   m_nCategory =
                   m_nSubCategory =
                   list.push_back( object );
             }
}

int main()
{
    // Code causing the problem:
    std::vector<MyClass> list;
    populate(list);

    // memory leak check?
    return 0;
 }

If you still got the memory leak, first check that it's not a false-positive from your leak detection software.

Then if it's not, google for memory leak problems with your STL implementation (most of the time on the compiler developer website). The implementor might provide a bug tracking tool where you could search in for the same problem and potential solution.

If you still can't find the source of the leak, maybe try to build your project with a different compiler (if you can) and see if it have the same effect. Again if the leak still occurs, the problem have a lot of chances to come from your code.


问:
Add protocol to href value
I have added an editor and user can enter anything they want, then I show that entered text under message card, so if user has entered a link like Click here & its HTML part is Click here so when show this under message card and click on click here then its not redirecting to google.com it goes to http://my-website.com/google.com, its because href value don't have any protocol, so how I can add protocol to its value and there could be multiple links in single message, some could have protocol and some not.

答:
You just need to loop over the  links after you have added the HTML from editor to your message card and check the protocol of each anchor link. If there is no protocol then add one to them.

```<code>$('#messageCard').find('a').each(function() {
    //get the href value of each anchor element
    var hrefValue = $(this).attr('href');
    //use regular expression to check if the href contain http:// or
    //https://. If not then add http://
    if (!hrefValue.match(/^[a-zA-Z]+:\/\//))
       {
          $(this).attr('href','http://' + hrefValue);
       }
});
</code>```

Title: Add protocol to href value

Body:
You just need to loop over the <a> links after you have added the HTML from editor to your message card and check the protocol of each anchor link. If there is no protocol then add one to them.

$('#messageCard').find('a').each(function() {
    //get the href value of each anchor element
    var hrefValue = $(this).attr('href');
    //use regular expression to check if the href contain http:// or
    //https://. If not then add http://
    if (!hrefValue.match(/^[a-zA-Z]+:\/\//))
       {
          $(this).attr('href','http://' + hrefValue);
       }
});


问:
Scipy-interp2d returned function sorts input argument automatically and undesirably
Following the documentation:

```<code>import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx+yy)
f = interpolate.interp2d(x, y, z, kind='cubic')
</code>```

I proceed to evaluate f:

```<code>xnew = np.arange(-5.01, 5.01, 1e-2)
f(xnew, 0)
</code>```

Output:

```<code>array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])
</code>```

Reversing the argument gives the same result! I was expecting to get the reversed one:

```<code>xnewrev=np.array(list(reversed(np.arange(-5.01, 5.01, 1e-2))))
f(xnewrev, 0)
</code>```

Output:

```<code>array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])
</code>```

Expected:

```<code>array([-0.96171273, -0.96171273, -0.96443103, ...,  0.96176018,
    0.9589498 ,  0.95603946])
</code>```

I get the same result also after shuffling xnew. It seems the interpolated function f sorts xnew before evaluation. How can I make f return values in the same order as given in the input list?

Somehow this is not an issue with interp1d.

I'm using Jupyter notebook, Python 2.7.12 |Anaconda 4.1.1 (64-bit)

答:
Your f callable takes an assume_sorted parameter:

```<code>assume_sorted : bool, optional
    If False, values of `x` and `y` can be in any order and they are
    sorted first.
    If True, `x` and `y` have to be arrays of monotonically
    increasing values.
</code>```

So, yes, the inputs are sorted internally if you haven't sorted them before hand.  I don't see a way of getting the sorted coordinates back.

The x,y inputs to interp2d are also sorted before use.  Apparently the interpolation calculations require sorted arrays.

You can recover a pre-sort order with a double argsort index

Make an array and shuffle it:

```<code>In [415]: xnew = np.arange(-10,11,2)
In [416]: xnew
Out[416]: array([-10,  -8,  -6,  -4,  -2,   0,   2,   4,   6,   8,  10])
In [417]: np.random.shuffle(xnew)
In [418]: xnew
Out[418]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])
</code>```

Get the recovery index:

```<code>In [419]: idx = np.argsort(np.argsort(xnew))
In [420]: idx
Out[420]: array([ 5,  6,  8,  4, 10,  3,  9,  1,  0,  2,  7], dtype=int32)
</code>```

test it:

```<code>In [421]: np.sort(xnew)[idx]
Out[421]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])
</code>```

Body:
Following the documentation:

import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(-5.01, 5.01, 0.25)
y = np.arange(-5.01, 5.01, 0.25)
xx, yy = np.meshgrid(x, y)
z = np.sin(xx+yy)
f = interpolate.interp2d(x, y, z, kind='cubic')

I proceed to evaluate f:

xnew = np.arange(-5.01, 5.01, 1e-2)
f(xnew, 0)

Output:

array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])

Reversing the argument gives the same result! I was expecting to get the reversed one:

xnewrev=np.array(list(reversed(np.arange(-5.01, 5.01, 1e-2))))
f(xnewrev, 0)

Output:

array([ 0.95603946,  0.9589498 ,  0.96176018, ..., -0.96443103,
   -0.96171273, -0.96171273])

Expected:

array([-0.96171273, -0.96171273, -0.96443103, ...,  0.96176018,
    0.9589498 ,  0.95603946])

I get the same result also after shuffling xnew. It seems the interpolated function f sorts xnew before evaluation. How can I make f return values in the same order as given in the input list?

Somehow this is not an issue with interp1d.

I'm using Jupyter notebook, Python 2.7.12 |Anaconda 4.1.1 (64-bit)

Body:
Your f callable takes an assume_sorted parameter:

assume_sorted : bool, optional
    If False, values of `x` and `y` can be in any order and they are
    sorted first.
    If True, `x` and `y` have to be arrays of monotonically
    increasing values.

So, yes, the inputs are sorted internally if you haven't sorted them before hand.  I don't see a way of getting the sorted coordinates back.

The x,y inputs to interp2d are also sorted before use.  Apparently the interpolation calculations require sorted arrays.

You can recover a pre-sort order with a double argsort index

Make an array and shuffle it:

In [415]: xnew = np.arange(-10,11,2)
In [416]: xnew
Out[416]: array([-10,  -8,  -6,  -4,  -2,   0,   2,   4,   6,   8,  10])
In [417]: np.random.shuffle(xnew)
In [418]: xnew
Out[418]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])

Get the recovery index:

In [419]: idx = np.argsort(np.argsort(xnew))
In [420]: idx
Out[420]: array([ 5,  6,  8,  4, 10,  3,  9,  1,  0,  2,  7], dtype=int32)

test it:

In [421]: np.sort(xnew)[idx]
Out[421]: array([  0,   2,   6,  -2,  10,  -4,   8,  -8, -10,  -6,   4])


问:
Icons appear too small on Bootstrap navbar
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

```<code><header>
  <nav class = "navbar navbar-default navbar-fixed-top">
    <div class = "container">
      <div class = "navbar-header">
        <a class = "navbar-brand" href = "#">
          BRAND
        </a>
      </div>
      <ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><i class = "fa fa-facebook"></i><li/>
        <li><i class = "fa fa-twitter"> </i><li/>
        <li><i class = "fa fa-instagram"> </i><li/>
      </ul>
    </div>
  </nav>
</header>
</code>```

答:
Wrap your icons with anchor tags so that they use the styling of the anchor tags just like the menu items.

```<code><ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><a href="#"><i class = "fa fa-facebook"></i></a><li/>
        <li><a href="#"><i class = "fa fa-twitter"> </i></a><li/>
        <li><a href="#"><i class = "fa fa-instagram"> </i></a><li/>
      </ul>
</code>```

Also if you want to add additional styles use

```<code>.navbar-nav .fa{ //your styles}
</code>```

Body:
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

          BRAND

ABCD

EFGH

IJKL

MNOP

Body:
Wrap your icons with anchor tags so that they use the styling of the anchor tags just like the menu items.

<ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><a href="#"><i class = "fa fa-facebook"></i></a><li/>
        <li><a href="#"><i class = "fa fa-twitter"> </i></a><li/>
        <li><a href="#"><i class = "fa fa-instagram"> </i></a><li/>
      </ul>

Also if you want to add additional styles use

.navbar-nav .fa{ //your styles}


问:
Validation of radiobuttonlist using javascript
I want to validate radiobuttonlist if user is not checked any item. If not checked whole list should be highlighted. Following is my code:

```<code>var userImpect = document.getElementById("<%=userImpect.ClientID%>");
for (var i = 0; i < userImpect.length; i++) {
    if (userImpect[i].checked) {
        userImpect.style.backgroundColor = "Yellow";
        validate = false;
    }
}
return validate;
</code>```

Please tell me how to do it.
Here is my asp code

```<code><asp:RadioButtonList ID="userImpect" runat="server" ForeColor="Black" RepeatDirection="Horizontal">
     <asp:ListItem Text="Just me" Value="Just me"></asp:ListItem>
     <asp:ListItem Text="Multiple Users" Value="Multiple Users"></asp:ListItem>
     <asp:ListItem Text="Everyone" Value="Everyone"></asp:ListItem>
</asp:RadioButtonList>
</code>```

Button code

```<code><asp:Button Text="Save" runat="server" ID="btnTest" OnClick="btnTest_Click" OnClientClick="return ValidateForm();" />
</code>```

html generated

答:
You can use a CustomValidator to check if a value has been selected and color the html table accordingly.

```<code><asp:RadioButtonList ID="userImpect" runat="server" ForeColor="Black" RepeatDirection="Horizontal">
    <asp:ListItem Text="Just me" Value="Just me"></asp:ListItem>
    <asp:ListItem Text="Multiple Users" Value="Multiple Users"></asp:ListItem>
    <asp:ListItem Text="Everyone" Value="Everyone"></asp:ListItem>
</asp:RadioButtonList>

<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="Required" ClientValidationFunction="checkRadioList"></asp:CustomValidator>

<script type="text/javascript">
    function checkRadioList(oSrc, args) {
        var a = document.getElementById('<%=userImpect.ClientID %>').style;
        if ($("input[name='<%= userImpect.UniqueID %>']:checked").val() == null) {
            args.IsValid = false;
            a.backgroundColor = "#ffff00";
        } else {
            args.IsValid = true;
            a.backgroundColor = "#ffffff";
        }
    }
</script>
</code>```

Body:
I want to validate radiobuttonlist if user is not checked any item. If not checked whole list should be highlighted. Following is my code:

var userImpect = document.getElementById("<%=userImpect.ClientID%>");
for (var i = 0; i < userImpect.length; i++) {
    if (userImpect[i].checked) {
        userImpect.style.backgroundColor = "Yellow";
        validate = false;
    }
}
return validate;

Please tell me how to do it.
Here is my asp code

<asp:RadioButtonList ID="userImpect" runat="server" ForeColor="Black" RepeatDirection="Horizontal">
     <asp:ListItem Text="Just me" Value="Just me"></asp:ListItem>
     <asp:ListItem Text="Multiple Users" Value="Multiple Users"></asp:ListItem>
     <asp:ListItem Text="Everyone" Value="Everyone"></asp:ListItem>
</asp:RadioButtonList>

Button code

<asp:Button Text="Save" runat="server" ID="btnTest" OnClick="btnTest_Click" OnClientClick="return ValidateForm();" />

html generated

Body:
You can use a CustomValidator to check if a value has been selected and color the html table accordingly.

<asp:RadioButtonList ID="userImpect" runat="server" ForeColor="Black" RepeatDirection="Horizontal">
    <asp:ListItem Text="Just me" Value="Just me"></asp:ListItem>
    <asp:ListItem Text="Multiple Users" Value="Multiple Users"></asp:ListItem>
    <asp:ListItem Text="Everyone" Value="Everyone"></asp:ListItem>
</asp:RadioButtonList>

<asp:CustomValidator ID="CustomValidator2" runat="server" ErrorMessage="Required" ClientValidationFunction="checkRadioList"></asp:CustomValidator>

<script type="text/javascript">
    function checkRadioList(oSrc, args) {
        var a = document.getElementById('<%=userImpect.ClientID %>').style;
        if ($("input[name='<%= userImpect.UniqueID %>']:checked").val() == null) {
            args.IsValid = false;
            a.backgroundColor = "#ffff00";
        } else {
            args.IsValid = true;
            a.backgroundColor = "#ffffff";
        }
    }
</script>


问:
Python sort and sorted -- How are lists of lists sorted precisely?
What is the precise rule used in Python in order to sort lists where
the elements are lists? Can this be expressed as a 'key' or 'cmp'
function? The problems comes from the fact that there are two things
to consider: length and values at their position.

```<code>sorted([
   [ 0, 1, 2, 3 ],  # 1st line: longer list
   [ 0, 1 ],        # 2nd line: shorter list
   [ 0, 2 ]         # 3rd line: suspected last
])
</code>```

Is it safe to assume that the second line will sort before the first?
Is it safe to assume that the third line will sort always last?

Note, this is not about stability! The specific case above behaves
that way as described. But, can the rules there be considered to
be general? What are the precise rules which python applies here?

Relying on the following definition Lexicographical Order (Thanks to Ashniwi):

To compare sequences of different lengths, the shorter sequence is
  usually padded at the end with enough "blanks" (a special symbol that
  is treated as smaller than every element of A). This way of comparing
  sequences of different lengths is always used in dictionaries.
  However, in combinatorics, another convention is frequently used,
  whereby a shorter sequence is always smaller than a longer sequence.
  This variant of the lexicographical order is sometimes called shortlex
  order.

Is Python using 'shortlex order'. Where is proof for that assumption,
beyond practical examples?

答: By default, sorted uses the __lt__ method of the items that are compared. And lists with comparable elements are compared lexicographically, according to the Python documentation. So yes, the language guarantees that in the shorter string will be sorted before the longer string.

Body:
What is the precise rule used in Python in order to sort lists where
the elements are lists? Can this be expressed as a 'key' or 'cmp'
function? The problems comes from the fact that there are two things
to consider: length and values at their position.

sorted([
   [ 0, 1, 2, 3 ],  # 1st line: longer list
   [ 0, 1 ],        # 2nd line: shorter list
   [ 0, 2 ]         # 3rd line: suspected last
])

Is it safe to assume that the second line will sort before the first?
Is it safe to assume that the third line will sort always last?

Note, this is not about stability! The specific case above behaves
that way as described. But, can the rules there be considered to
be general? What are the precise rules which python applies here?

Relying on the following definition Lexicographical Order (Thanks to Ashniwi):

To compare sequences of different lengths, the shorter sequence is
  usually padded at the end with enough "blanks" (a special symbol that
  is treated as smaller than every element of A). This way of comparing
  sequences of different lengths is always used in dictionaries.
  However, in combinatorics, another convention is frequently used,
  whereby a shorter sequence is always smaller than a longer sequence.
  This variant of the lexicographical order is sometimes called shortlex
  order.

Is Python using 'shortlex order'. Where is proof for that assumption,
beyond practical examples?


问:
Mutual Auth between API gateway and API microservice?
I'm writing an API gateway which will expose a single point of entry to various other APIs which can only be accessed via this API gateway.

This API gateway will be serve requests from various frontends such as a website, a mobile app, a desktop app, whatever...

I want to be able to verify that requests to my API Gateway have come from one of these sources and haven't just come from anyone doing a Curl request. To this end I've been looking for a way to authorise these requests. I've looked at implementing JWTs to verify where these requests have come from, with this frontend services would have to share a secret with the API gateway so they could create tokens to send which the API gateway could then verify. I guess the problem comes in the fact that these secrets would have to be securely stored in the frontend apps.

I was wondering if there was a better way of verifying that requests have come from where I expect them to come from?

Has anyone got any ideas?

Thanks in advance :)

答:
Well you can make your own algorithm that generates a unique time dependent access token. The algorithm should be implemented on both the API gateway and the frontends.

The benefit of using JSON web tokens is that JWT is a popular authentication protocol. Open source libraries for most popular programming languages are provided so you dont have to write your own code. Using a standard authentication library will also make it easier for third party apps to access your API.


问:
How to detect that the HTML element has text by clicking on text content area?
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

```<code><div>
some text
<span class="box"></span>
</div>

<div>
some text
</div>

<div><span class="box"></span></div>
</code>```

JS:

```<code>$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('<span>You clicked on a text</span>');
    }

});
</code>```

答:
As long as you have id's and classes you can try comparing ids or classes

```<code>$(document).on('click','div', function(e){
if (e.target.id.toString() == "box" || $(e.target).hasClass("box")) {
    $(this).append('<span>foo</span>');
} else {
    $(this).append('<span>You clicked on a text</span>');
}
</code>```

https://jsfiddle.net/q6vbohxm/

Body:
I have text content and a boxed element in a div but still changes happen when I click on boxed element while I need to make changes only when I click on text content.

Here is the code:https://jsfiddle.net/Issact/u0g8LLLo/

some text

some text

JS:

$(document).on('click','div', function(){
    if (!$(this).text().trim().length > 0) {
        $(this).text("foo");
    } else {
    $(this).append('You clicked on a text');
    }

});

Body:
As long as you have id's and classes you can try comparing ids or classes

$(document).on('click','div', function(e){
if (e.target.id.toString() == "box" || $(e.target).hasClass("box")) {
    $(this).append('<span>foo</span>');
} else {
    $(this).append('<span>You clicked on a text</span>');
}

https://jsfiddle.net/q6vbohxm/


问:
View to Show Third Party Licenses in Android App
I'm new to Android App Development and was studying about various views. There was a particular view which caught my attention and is used in Google Play Music Android App

I think it is a PopUpWindow but not fully sure. How can we achieve this kind of View and customize the text inside it?

答:
Your question is pretty ambiguous. The actual view where the licenses are displayed, it's usually an android view called Dialog, there is a 3rd party library that simplifies the work with dialogs: Material Dialogs.
Regarding licenses, there is a good library that retrieves info about the libraries used in your project: 3rd party licenses</p>


问:
How do I get argument values inferred from usage?
So I'm following through some code snippets for AutoInjector and Automapper online, and noticed something that I don't really understand.

In the code, AutoInjector is Registering Automapper for use in this line.

container.Register(() => config.CreateMapper(container.GetInstance));

I noticed that container.GetInstance isn't having anything passed into it.

After some tinkering, I tried to do var instance = container.GetInstance(); in a console app, but it gives the error The type arguments for method 'Container.GetInstance<TService>() cannot be inferred from the usage. Try specifying the type arguments explicitly.

Obviously, the arguments being passed are inferred from the outer method config.CreateMapper()

I was wondering if there was a way to step through the code so I can see what is being passed into container.GetInstance(). When I step through the code, it just steps over the line and doesn't show me what's being passed into the method.

答:
I noticed that container.GetInstance isn't having anything passed into it.

Because nothing is. The argument of CreateMapper is a delegate, more specifically a Func<Type, object>; So config.CreateMapper(container.GetInstance)  is exactly the same as if you'd written:

```<code>config.CreateMapper(type => GetInstance(type));
</code>```

You are not passing in any concrete arguments at that point in time, you are simply "informing" container how to create a mapper for any given type,

Its the same as the following LINQ usage in this trivial code snippet (hence the possible duplicate comment):

```<code>public static string ToString<T>(T arg) => arg.ToString();

var ints = Enumerable.Empty<int>();
var strs = ints.Select(ToString); //or ints.Select(i => ToString(i))
</code>```

What arguments are passed into ToString in the Select call? Well, none, you are only informing Select how to map an int to a string, you are not processing any integers yet (you wouldn't be able to anyways, the enumeration is empty!). The arguments will be passed into the delegate (or not) when the enumeration is enumerated.

Your code is the same, an argument typed Type (if any) will be passed into GetInstance whenever a mapper needs to be created for any given type. The code you've posted is irrelevant as to when and for what specific type that happens, thats why while debugging you simply step over that line.

Body:
I noticed that container.GetInstance isn't having anything passed into it.

Because nothing is. The argument of CreateMapper is a delegate, more specifically a Func<Type, object>; So config.CreateMapper(container.GetInstance)  is exactly the same as if you'd written:

config.CreateMapper(type => GetInstance(type));

You are not passing in any concrete arguments at that point in time, you are simply "informing" container how to create a mapper for any given type,

Its the same as the following LINQ usage in this trivial code snippet (hence the possible duplicate comment):

public static string ToString<T>(T arg) => arg.ToString();

var ints = Enumerable.Empty<int>();
var strs = ints.Select(ToString); //or ints.Select(i => ToString(i))

What arguments are passed into ToString in the Select call? Well, none, you are only informing Select how to map an int to a string, you are not processing any integers yet (you wouldn't be able to anyways, the enumeration is empty!). The arguments will be passed into the delegate (or not) when the enumeration is enumerated.

Your code is the same, an argument typed Type (if any) will be passed into GetInstance whenever a mapper needs to be created for any given type. The code you've posted is irrelevant as to when and for what specific type that happens, thats why while debugging you simply step over that line.


问:
Ionic 3 slide not working with autoplay
I am using ionic 3.

Here is my template

```<code> <ion-slides autoplay="5000" loop="true" speed="500" class="slides" pager="true">
      <ion-slide *ngFor="let Image of PImage">
         <img src="{{Image.URL}}" alt="Product Image">
      </ion-slide>
 </ion-slides>
</code>```

But I am getting this error

```<code>TypeError: Cannot read property 'hasAttribute' of undefined
</code>```

How can I fix this issue?

Kindly advice me,

Thanks

答:
There seems to be an issue when trying to create the slides elements, when the data is not ready yet. To fix it, use an *ngIf to create the slides only when the data is ready:

```<code><ion-slides *ngIf="PImage && PImage.length"  autoplay="5000" loop="true" speed="500" class="slides" pager="true">
      <ion-slide *ngFor="let Image of PImage">
         <img src="{{Image.URL}}" alt="Product Image">
      </ion-slide>
 </ion-slides>
</code>```

Title: Ionic 3 slide not working with autoplay

Body:
I am using ionic 3.

Here is my template

 <ion-slides autoplay="5000" loop="true" speed="500" class="slides" pager="true">
      <ion-slide *ngFor="let Image of PImage">

      </ion-slide>
 </ion-slides>

But I am getting this error

TypeError: Cannot read property 'hasAttribute' of undefined

How can I fix this issue?

Kindly advice me,

Thanks

Body:
There seems to be an issue when trying to create the slides elements, when the data is not ready yet. To fix it, use an *ngIf to create the slides only when the data is ready:

<ion-slides *ngIf="PImage && PImage.length"  autoplay="5000" loop="true" speed="500" class="slides" pager="true">
      <ion-slide *ngFor="let Image of PImage">
         <img src="{{Image.URL}}" alt="Product Image">
      </ion-slide>
 </ion-slides>


问:
How does one test item membership in an unordered sequence (C++)?
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

```<code>a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"
</code>```

it's much more efficient than doing this:

```<code>a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"
</code>```

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?

答: Get to know the C++ Standard Template Library.  The set class (and others) has a find() method that will return an iterator to an item in the set if it exists.

Body:
I've used python for a long time, and I'm just beginning to use C++

In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword.
i.e.

a = set(2,4,3)
if 4 in a
print "yes, 4 is in a, thank you for asking!"

it's much more efficient than doing this:

a = [2,3,4]
for number in a
>if number == 4
>>return "yes, 4 is in a, thank you for asking!"

is there a way to do make a membership test simple and efficient in cpp or do you always have to iterate through some ordered sequence?


问:
How to Compress the IMAGE size in Titanium Appcelerator
i am using titanium 2.0.1, i need to compress the size of a image taken by camera and then upload it. Right now the image size is 800kb+, which takes a lot of time to upload. i need to compress the size. can anyone tell me the way how to do that.</p>

答:
The upvoted answer seems to be outdated.

https://github.com/appcelerator-modules/ti.imagefactory is an up-to-date module that runs on iOS and Android and allows for image manipulation with Appcelerator/Axway/Titanium.

Some example from https://github.com/appcelerator-modules/ti.imagefactory/blob/stable/ios/example/app.js

```<code>btnSave.addEventListener('click', function (e) {
newBlob = ImageFactory.compress(blob, 0.25);
var filename = Titanium.Filesystem.applicationDataDirectory + "/newflower.jpg";
f = Titanium.Filesystem.getFile(filename);
f.write(newBlob);
var alert = Ti.UI.createAlertDialog({
    title:'Image Factory',
    message:'Compressed image saved to newflower.jpg with compression quality of 25%'
});
alert.show();
</code>```

});

Body:
The upvoted answer seems to be outdated.

https://github.com/appcelerator-modules/ti.imagefactory is an up-to-date module that runs on iOS and Android and allows for image manipulation with Appcelerator/Axway/Titanium.

Some example from https://github.com/appcelerator-modules/ti.imagefactory/blob/stable/ios/example/app.js

btnSave.addEventListener('click', function (e) {
newBlob = ImageFactory.compress(blob, 0.25);
var filename = Titanium.Filesystem.applicationDataDirectory + "/newflower.jpg";
f = Titanium.Filesystem.getFile(filename);
f.write(newBlob);
var alert = Ti.UI.createAlertDialog({
    title:'Image Factory',
    message:'Compressed image saved to newflower.jpg with compression quality of 25%'
});
alert.show();

});


答:
why don't you wrap the icons in anchor tag

```<code><li><a href=""><i class = "fa fa-facebook"></i></a><li/>
<li><a href=""><i class = "fa fa-twitter"> </i></a><li/>
<li><a href=""><i class = "fa fa-instagram"> </i></a><li/>
</code>```

and give a try.

Title: Icons appear too small on Bootstrap navbar

Body:
why don't you wrap the icons in anchor tag

<li><a href=""><i class = "fa fa-facebook"></i></a><li/>
<li><a href=""><i class = "fa fa-twitter"> </i></a><li/>
<li><a href=""><i class = "fa fa-instagram"> </i></a><li/>

and give a try.


问:
How can I use http request headers for content negotiation in a Mashaller?
My app supports protobuf and JSON serialzation. For JSON serialization I use com.trueaccord.scalapb.json.JsonFormat, my dtos are generated from proto definitions.

The com.trueaccord serializer wraps option types to JSON objects which is causing issues for some clients so I want to be able to support org.json4s without braking the existing clients.

I would like to be able to pick a serializer based on a custom http header called JFORMAT. The idea is that if this header is sent I will use json4s otherwise I will use the trueaccord serializer.

I managed to create a Unmarshaller which can pick a request serializer based on a header value:

```<code>Unmarshaller.withMaterializer[HttpRequest, T](_ => implicit mat => {
  case request: HttpRequest =>
    val entity = request.entity
    entity.dataBytes.runFold(ByteString.empty)(_ ++ _).map(data => {
      entity.contentType match {
        case `applicationJsonContentType` =>
          val jsFormat = {
            val header = request.headers.find(h => h.name() == jsonFormatHeaderName)
            if (header.isEmpty) "1.0" else header.get.value()
          }

          val charBuffer = Unmarshaller.bestUnmarshallingCharsetFor(entity)
          val jsonText = data.decodeString(charBuffer.nioCharset().name())
          val dto = if(jsFormat == "2.0") {
            write[T](value)(formats) // New Formatter
          } else {
            JsonFormat.fromJsonString[T](jsonText) // Old Formatter
          }
          dto
        case `protobufContentType` =>
          companion.parseFrom(CodedInputStream.newInstance(data.asByteBuffer)) // Proto Formatter
        case _ =>
          throw UnsupportedContentTypeException(applicationJsonContentType, protobufContentType)
      }
    })
</code>```

I want to do the same with my Marshaller which I use with Marshaller.oneOf and the JSON handling one looks like:

```<code>  Marshaller.withFixedContentType(contentType) { value =>
    val jsonText = JsonSerializer.toJsonString[T](value)
    HttpEntity(contentType, jsonText)
  }
</code>```

Is there a way to construct a Mashaller which is aware of the request http headers? The Akka HTTP docs don't have any examples and I cannot make sense of the PredefinedToRequestMarshallers.

Do I need to combine multiple marshallers somehow or can I append some metadata to a context during the request serialization I can use later in the Marshaller? I want to avoid appending meta to my dto if possible or using a custom content type like application/vnd.api+json

There are lots of other useful info I could use from the request when I format the response like Accept-Encoding, custom headers like unique request id to create a correlation id, I could add JSONP support by reading the callback query parmeter, etc.

To clarify: I need a solution to use the Mashaller, subclass of it or a custom version created by a factory method or maybe multiple Marshallers chained together. Marshaller.withFixedContentType already using the Accept header so there must be a way. I added added bounty to reward a solution to a specific challenge. I am ware of hacks and workarounds and I asked the question because I need a clean solution solving a specific scenario.

答:
Custom Marshallers section mentions Marshaller.oneOf overloaded methods, that seems to be what you want:

Helper for creating a "super-marshaller" from a number of
  "sub-marshallers". Content-negotiation determines, which
  "sub-marshaller" eventually gets to do the job.

The Marshaller companion object has many methods that receive a Seq[HttpHeader]. You can look into their implementations as well.

I don't have the time to look into the source code myself, but if this is not enough to put you on the right path, let me know.

Edit:

How about?

```<code>get {
  optionalHeaderValueByName("JFORMAT") { format =>
    complete {
      format match {
        case Some(f) => "Complete with json4s"
        case _ => "Complete with trueaccord"
      }
    }
  }
}
</code>```

Body:
My app supports protobuf and JSON serialzation. For JSON serialization I use com.trueaccord.scalapb.json.JsonFormat, my dtos are generated from proto definitions.

The com.trueaccord serializer wraps option types to JSON objects which is causing issues for some clients so I want to be able to support org.json4s without braking the existing clients.

I would like to be able to pick a serializer based on a custom http header called JFORMAT. The idea is that if this header is sent I will use json4s otherwise I will use the trueaccord serializer.

I managed to create a Unmarshaller which can pick a request serializer based on a header value:

Unmarshaller.withMaterializer[HttpRequest, T](_ => implicit mat => {
  case request: HttpRequest =>
    val entity = request.entity
    entity.dataBytes.runFold(ByteString.empty)(_ ++ _).map(data => {
      entity.contentType match {
        case `applicationJsonContentType` =>
          val jsFormat = {
            val header = request.headers.find(h => h.name() == jsonFormatHeaderName)
            if (header.isEmpty) "1.0" else header.get.value()
          }

          val charBuffer = Unmarshaller.bestUnmarshallingCharsetFor(entity)
          val jsonText = data.decodeString(charBuffer.nioCharset().name())
          val dto = if(jsFormat == "2.0") {
            write[T](value)(formats) // New Formatter
          } else {
            JsonFormat.fromJsonString[T](jsonText) // Old Formatter
          }
          dto
        case `protobufContentType` =>
          companion.parseFrom(CodedInputStream.newInstance(data.asByteBuffer)) // Proto Formatter
        case _ =>
          throw UnsupportedContentTypeException(applicationJsonContentType, protobufContentType)
      }
    })

I want to do the same with my Marshaller which I use with Marshaller.oneOf and the JSON handling one looks like:

  Marshaller.withFixedContentType(contentType) { value =>
    val jsonText = JsonSerializer.toJsonString[T](value)
    HttpEntity(contentType, jsonText)
  }

Is there a way to construct a Mashaller which is aware of the request http headers? The Akka HTTP docs don't have any examples and I cannot make sense of the PredefinedToRequestMarshallers.

Do I need to combine multiple marshallers somehow or can I append some metadata to a context during the request serialization I can use later in the Marshaller? I want to avoid appending meta to my dto if possible or using a custom content type like application/vnd.api+json

There are lots of other useful info I could use from the request when I format the response like Accept-Encoding, custom headers like unique request id to create a correlation id, I could add JSONP support by reading the callback query parmeter, etc.

To clarify: I need a solution to use the Mashaller, subclass of it or a custom version created by a factory method or maybe multiple Marshallers chained together. Marshaller.withFixedContentType already using the Accept header so there must be a way. I added added bounty to reward a solution to a specific challenge. I am ware of hacks and workarounds and I asked the question because I need a clean solution solving a specific scenario.

Body:
Custom Marshallers section mentions Marshaller.oneOf overloaded methods, that seems to be what you want:

Helper for creating a "super-marshaller" from a number of
  "sub-marshallers". Content-negotiation determines, which
  "sub-marshaller" eventually gets to do the job.

The Marshaller companion object has many methods that receive a Seq[HttpHeader]. You can look into their implementations as well.

I don't have the time to look into the source code myself, but if this is not enough to put you on the right path, let me know.

Edit:

How about?

get {
  optionalHeaderValueByName("JFORMAT") { format =>
    complete {
      format match {
        case Some(f) => "Complete with json4s"
        case _ => "Complete with trueaccord"
      }
    }
  }
}


问:
Skype URI doesn't work on new version Skype in iOS
I have developed one application which use Skype URI for dial the tel number.

```<code>NSString* stringURL = [NSString stringWithFormat:@"skype:%@", strTel];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringURL]];
</code>```

But the Skype URI doesn't work.

I remembered it worked before.

Now, it only opened Skype, and nothing happens (It used to dial the tel number before).

I checked the skype document, but seems nothing change.

Did I miss anything?

Please help me to solve this issue.

PS: I already added the key LSApplicationQueriesSchemes in Info.plist file for skype

答:
Firsly check skype is in your device or not. You can use below code for Skype and check real device.

```<code> BOOL skypeInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
if(skypeInstalled){

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];

} else {

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/in/app/skype/id304878510?mt=8"]];
}
</code>```

Or Use as this

```<code> NSString* urlString = [NSString stringWithFormat:@"skype:USER_NAME?call"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlString]];
</code>```

Body:
I have developed one application which use Skype URI for dial the tel number.

NSString* stringURL = [NSString stringWithFormat:@"skype:%@", strTel];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:stringURL]];

But the Skype URI doesn't work.

I remembered it worked before.

Now, it only opened Skype, and nothing happens (It used to dial the tel number before).

I checked the skype document, but seems nothing change.

Did I miss anything?

Please help me to solve this issue.

PS: I already added the key LSApplicationQueriesSchemes in Info.plist file for skype

Body:
Firsly check skype is in your device or not. You can use below code for Skype and check real device.

 BOOL skypeInstalled = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"skype:"]];
if(skypeInstalled){

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"skype:echo123?call"]];

} else {

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/in/app/skype/id304878510?mt=8"]];
}

Or Use as this

 NSString* urlString = [NSString stringWithFormat:@"skype:USER_NAME?call"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: urlString]];


问:
How to show timezone abbreviation with the date
I am getting a time in UTC and want to append timezone abbreviation with it. I have the below code to get the timezone abbreviation but it is giving as GMT +5.30. I want as IST.

For America it is giving as EDT, I need for all the timezones to give 3 letter abbreviation.

Is that possible?

Please check the below code:

```<code>NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate* sourceDate = [dateFormatter dateFromString:@"2015-03-16T13:08:17.989Z"];
NSTimeZone* destinationTimeZone = [NSTimeZone defaultTimeZone];
NSString *str =[destinationTimeZone abbreviation];

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"MMMM dd yyyy, HH:mm "];
NSString* localTime = [dateFormat stringFromDate:sourceDate];
NSString* str1 = [NSString stringWithFormat:@"%@, %@",localTime, str];
NSLog(@"localTime:%@", str1);
</code>```

The output is:

```localTime:March 16 2015, 18:38 , GMT+5:30```

I need it as

```localTime:March 16 2015, 18:38 , IST```

Please help!

答:
You can get the time zone abbreviation when you have the timezone name using this.</p>

```<code>+ (NSString *)getAbbriviationByTimeZone:(NSString *)timeZone {
    if ([timeZone isEqualToString:@"America/Halifax"])
        return @"ADT";
    if ([timeZone isEqualToString:@"America/Juneau"])
        return @"AKDT";
    if ([timeZone isEqualToString:@"America/Argentina/Buenos_Aires"])
        return @"ART";
    if ([timeZone isEqualToString:@"America/Halifax"])
        return @"AST";
    if ([timeZone isEqualToString:@"Asia/Dhaka"])
        return @"BDT";
    if ([timeZone isEqualToString:@"America/Sao_Paulo"])
        return @"BRST";
    if ([timeZone isEqualToString:@"America/Sao_Paulo"])
        return @"BRT";
    if ([timeZone isEqualToString:@"Europe/London"])
        return @"BST";
    if ([timeZone isEqualToString:@"Africa/Harare"])
        return @"CAT";
    if ([timeZone isEqualToString:@"America/Chicago"])
        return @"CDT";
    if ([timeZone isEqualToString:@"Europe/Paris"])
        return @"CEST";
    if ([timeZone isEqualToString:@"Europe/Paris"])
        return @"CET";
    if ([timeZone isEqualToString:@"America/Santiago"])
        return @"CLST";
    if ([timeZone isEqualToString:@"America/Santiago"])
        return @"CLT";
    if ([timeZone isEqualToString:@"America/Bogota"])
        return @"COT";
    if ([timeZone isEqualToString:@"America/Chicago"])
        return @"CST";
    if ([timeZone isEqualToString:@"Africa/Addis_Ababa"])
        return @"EAT";
    if ([timeZone isEqualToString:@"America/New_York"])
        return @"EDT";
    if ([timeZone isEqualToString:@"Europe/Istanbul"])
        return @"EEST";
    if ([timeZone isEqualToString:@"Europe/Istanbul"])
        return @"EET";
    if ([timeZone isEqualToString:@"America/New_York"])
        return @"EST";
    if ([timeZone isEqualToString:@"Asia/Dubai"])
        return @"GST";
    if ([timeZone isEqualToString:@"Asia/Hong_Kong"])
        return @"HKT";
    if ([timeZone isEqualToString:@"Pacific/Honolulu"])
        return @"HST";
    if ([timeZone isEqualToString:@"Asia/Bangkok"])
        return @"ICT";
    if ([timeZone isEqualToString:@"Asia/Tehran"])
        return @"IRST";
    if ([timeZone isEqualToString:@"Asia/Calcutta"])
        return @"IST";
    if ([timeZone isEqualToString:@"Asia/Tokyo"])
        return @"JST";
    if ([timeZone isEqualToString:@"Asia/Seoul"])
        return @"KST";
    if ([timeZone isEqualToString:@"Asia/Hong_Kong"])
        return @"HKT";
    if ([timeZone isEqualToString:@"Europe/Moscow"])
        return @"MSD";
    if ([timeZone isEqualToString:@"Europe/Moscow"])
        return @"MSK";
    if ([timeZone isEqualToString:@"America/Denver"])
        return @"MST";
    if ([timeZone isEqualToString:@"Pacific/Auckland"])
        return @"NZDT";
    if ([timeZone isEqualToString:@"Pacific/Auckland"])
        return @"NZST";
    if ([timeZone isEqualToString:@"America/Los_Angeles"])
        return @"PDT";
    if ([timeZone isEqualToString:@"America/Lima"])
        return @"PET";
    if ([timeZone isEqualToString:@"Asia/Manila"])
        return @"PHT";
    if ([timeZone isEqualToString:@"Asia/Karachi"])
        return @"PKT";
    if ([timeZone isEqualToString:@"America/Los_Angeles"])
        return @"PST";
    if ([timeZone isEqualToString:@"Asia/Singapore"])
        return @"SGT";
    if ([timeZone isEqualToString:@"Africa/Lagos"])
        return @"WAT";
    if ([timeZone isEqualToString:@"Europe/Lisbon"])
        return @"WEST";
    if ([timeZone isEqualToString:@"Europe/Lisbon"])
        return @"WET";
    if ([timeZone isEqualToString:@"Asia/Jakarta"])
        return @"WIT";
    return nil;
}
</code>```

Body:
I am getting a time in UTC and want to append timezone abbreviation with it. I have the below code to get the timezone abbreviation but it is giving as GMT +5.30. I want as IST.

For America it is giving as EDT, I need for all the timezones to give 3 letter abbreviation.

Is that possible?

Please check the below code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate* sourceDate = [dateFormatter dateFromString:@"2015-03-16T13:08:17.989Z"];
NSTimeZone* destinationTimeZone = [NSTimeZone defaultTimeZone];
NSString *str =[destinationTimeZone abbreviation];

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"MMMM dd yyyy, HH:mm "];
NSString* localTime = [dateFormat stringFromDate:sourceDate];
NSString* str1 = [NSString stringWithFormat:@"%@, %@",localTime, str];
NSLog(@"localTime:%@", str1);

The output is:

localTime:March 16 2015, 18:38 , GMT+5:30

I need it as

localTime:March 16 2015, 18:38 , IST

Please help!

Body:
You can get the time zone abbreviation when you have the timezone name using this.

+ (NSString *)getAbbriviationByTimeZone:(NSString *)timeZone {
    if ([timeZone isEqualToString:@"America/Halifax"])
        return @"ADT";
    if ([timeZone isEqualToString:@"America/Juneau"])
        return @"AKDT";
    if ([timeZone isEqualToString:@"America/Argentina/Buenos_Aires"])
        return @"ART";
    if ([timeZone isEqualToString:@"America/Halifax"])
        return @"AST";
    if ([timeZone isEqualToString:@"Asia/Dhaka"])
        return @"BDT";
    if ([timeZone isEqualToString:@"America/Sao_Paulo"])
        return @"BRST";
    if ([timeZone isEqualToString:@"America/Sao_Paulo"])
        return @"BRT";
    if ([timeZone isEqualToString:@"Europe/London"])
        return @"BST";
    if ([timeZone isEqualToString:@"Africa/Harare"])
        return @"CAT";
    if ([timeZone isEqualToString:@"America/Chicago"])
        return @"CDT";
    if ([timeZone isEqualToString:@"Europe/Paris"])
        return @"CEST";
    if ([timeZone isEqualToString:@"Europe/Paris"])
        return @"CET";
    if ([timeZone isEqualToString:@"America/Santiago"])
        return @"CLST";
    if ([timeZone isEqualToString:@"America/Santiago"])
        return @"CLT";
    if ([timeZone isEqualToString:@"America/Bogota"])
        return @"COT";
    if ([timeZone isEqualToString:@"America/Chicago"])
        return @"CST";
    if ([timeZone isEqualToString:@"Africa/Addis_Ababa"])
        return @"EAT";
    if ([timeZone isEqualToString:@"America/New_York"])
        return @"EDT";
    if ([timeZone isEqualToString:@"Europe/Istanbul"])
        return @"EEST";
    if ([timeZone isEqualToString:@"Europe/Istanbul"])
        return @"EET";
    if ([timeZone isEqualToString:@"America/New_York"])
        return @"EST";
    if ([timeZone isEqualToString:@"Asia/Dubai"])
        return @"GST";
    if ([timeZone isEqualToString:@"Asia/Hong_Kong"])
        return @"HKT";
    if ([timeZone isEqualToString:@"Pacific/Honolulu"])
        return @"HST";
    if ([timeZone isEqualToString:@"Asia/Bangkok"])
        return @"ICT";
    if ([timeZone isEqualToString:@"Asia/Tehran"])
        return @"IRST";
    if ([timeZone isEqualToString:@"Asia/Calcutta"])
        return @"IST";
    if ([timeZone isEqualToString:@"Asia/Tokyo"])
        return @"JST";
    if ([timeZone isEqualToString:@"Asia/Seoul"])
        return @"KST";
    if ([timeZone isEqualToString:@"Asia/Hong_Kong"])
        return @"HKT";
    if ([timeZone isEqualToString:@"Europe/Moscow"])
        return @"MSD";
    if ([timeZone isEqualToString:@"Europe/Moscow"])
        return @"MSK";
    if ([timeZone isEqualToString:@"America/Denver"])
        return @"MST";
    if ([timeZone isEqualToString:@"Pacific/Auckland"])
        return @"NZDT";
    if ([timeZone isEqualToString:@"Pacific/Auckland"])
        return @"NZST";
    if ([timeZone isEqualToString:@"America/Los_Angeles"])
        return @"PDT";
    if ([timeZone isEqualToString:@"America/Lima"])
        return @"PET";
    if ([timeZone isEqualToString:@"Asia/Manila"])
        return @"PHT";
    if ([timeZone isEqualToString:@"Asia/Karachi"])
        return @"PKT";
    if ([timeZone isEqualToString:@"America/Los_Angeles"])
        return @"PST";
    if ([timeZone isEqualToString:@"Asia/Singapore"])
        return @"SGT";
    if ([timeZone isEqualToString:@"Africa/Lagos"])
        return @"WAT";
    if ([timeZone isEqualToString:@"Europe/Lisbon"])
        return @"WEST";
    if ([timeZone isEqualToString:@"Europe/Lisbon"])
        return @"WET";
    if ([timeZone isEqualToString:@"Asia/Jakarta"])
        return @"WIT";
    return nil;
}


问:
Gradle task doLast if task fails
I want a clean build, where you can see exactly what happened, but all information is preserved - so essentially for every task, I want it to write the output to a file, and only display it if the task fails.

I've tried to achieve this in gradle - but am being defeated because doLast doesn't run if the task fails.  Here's my "almost" working pattern:

```<code>task fakeTask( type: Exec ) {

    standardOutput = new ByteArrayOutputStream()
    commandLine 'cmd', '/c', 'silly'
    doLast {
        new File("build.log") << standardOutput.toString()
        if (execResult.exitValue != 0) println standardOutput.toString()
    }
}
</code>```

is there any alternative to doLast that will run any time?  Any other way of doing this? - especially as I want to do this for every single task I have?

答:
You can use the task graph as documented at https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:task_execution to execute code after a task has run.</p>

```<code>gradle.taskGraph.afterTask { task, state ->
    if (task instanceof ExecTask && state.failure) {
        file('gradle.log') << standardOutput.toString()
    }
}
</code>```

Title: Gradle task doLast if task fails

Body:
I want a clean build, where you can see exactly what happened, but all information is preserved - so essentially for every task, I want it to write the output to a file, and only display it if the task fails.

I've tried to achieve this in gradle - but am being defeated because doLast doesn't run if the task fails.  Here's my "almost" working pattern:

task fakeTask( type: Exec ) {

    standardOutput = new ByteArrayOutputStream()
    commandLine 'cmd', '/c', 'silly'
    doLast {
        new File("build.log") << standardOutput.toString()
        if (execResult.exitValue != 0) println standardOutput.toString()
    }
}

is there any alternative to doLast that will run any time?  Any other way of doing this? - especially as I want to do this for every single task I have?

Body:
You can use the task graph as documented at https://docs.gradle.org/current/userguide/build_lifecycle.html#sec:task_execution to execute code after a task has run.

gradle.taskGraph.afterTask { task, state ->
    if (task instanceof ExecTask && state.failure) {
        file('gradle.log') << standardOutput.toString()
    }
}


问:
Multi-Line select with Alt
How can I select multi-line with vscode?

On Visual Studio you can press left alt key and select multi-lines, but it is not working with vscode.

答:
As of May 2017, it is possible. Read the release notes:

We have introduced a new setting, editor.multiCursorModifier, to
  change the modifier key for applying multiple cursors to Cmd+Click on
  macOS and Ctrl+Click on Windows and Linux. This lets users coming from
  other editors such as Sublime Text or Atom continue to use the
  keyboard modifier they are familiar with.

The setting can be set to:

ctrlCmd - Maps to Ctrl on Windows and Cmd on macOS.

alt - The existing default Alt.

Title: Multi-Line select with Alt


问:
External memory management and COM
Having trouble with memory management of a third party library. I have the source but it's very complex (COM stuff), full of macros and those annoying Microsoft annotations, etc, and interacts with another library the source of which I don't have to boot. Now some quick debug runtimes have shown that it's leaking memory and in a pretty big way. I make extensive use of self-releasing pointers like unique_ptr and know that I released everything that I created. Is it my only option to try and clean up (and understand) the source?

In addition, is it safe to allocate COM objects with operator new, or do they have to go in the COM heap?

答:
COM is quite agnostic about how you allocate your own COM objects.  They get created by the class factory and your IUnknown::AddRef and Release methods keep the reference count.  Using operator new in the class factory and delete this in Release is fine.

You do have to be careful about any pointers you return in your interface methods.  Typical Automation objects like BSTR and SAFEARRAY do indeed need to be allocated in the COM heap so that the client code can release them.  Pretty hard to mess that up, the API does the work.

The client code can be responsible for the leak, fumbling the reference count is a pretty standard COM bug.  Usually easy to diagnose when you have access to the AddRef/Release implementations.  Debugging this in Vista or Win7 is also strongly recommended, they have a much better heap manager that doesn't silently ignore attempts to free memory from the wrong heap.

If you're pretty sure it is the COM server that leaks then isolate the problem with the <crtdbg.h> header and unit tests to exercise the interface methods.

Title: External memory management and COM