问:
Make column content width, not width: 100%
I put flex-direction: column and flex-wrap: wrap for ul to achieve columns.

If ul splits elements into few columns, they have width of the widest li content in the column. But if there is only one column, it has 100% width.

What I want is to have this one column the size of its content.

/* boilerplate */

* {
  margin: 0;
  padding: 0;
}

div {
  max-height: 100px;
  background-color: #cacaca;
}

ul {
  list-style-type: none;
  height: 100px;
  background-color: #dadada;
}

li {
  margin-right: 10px;
  background-color: #eaeaea;
}

/* actual code */

div {}

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: center;
}

li {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <ul>
    <li>normal</li>
    <li>x</li>
    <li>y</li>
    <li>z</li>
    <li>short</li>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>wiiiiiiiiiiiiiiide</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>normal</li>
    <li>just two</li>
  </ul>
</div>

<div>
  <ul>
    <li>why</li>
    <li>full</li>
    <li>width?</li>
  </ul>
</div></code>```

https://codepen.io/anon/pen/eRYjLd

答:
Instead of display: flex use display: inline-flex.

This switches the container from block-level (which takes the full width of its parent) to inline-level (which takes the width of its content).

This sizing behavior is similar to display: block vs. display: inline-block.

OR

Make the parent div a flex container with justify-content: center.

This confines the ul flex container to the width of the flex item, whose default is flex-basis: auto (content width).

/* boilerplate */

* {
  margin: 0;
  padding: 0;
}

div {
  max-height: 100px;
  background-color: #cacaca;
}

ul {
  list-style-type: none;
  height: 100px;
  background-color: #dadada;
}

li {
  margin-right: 10px;
  background-color: #eaeaea;
}

/* actual code */

div {
  display: flex;             /* NEW */
  justify-content: center;   /* NEW */
}

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: center;
}

li {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <ul>
    <li>normal</li>
    <li>x</li>
    <li>y</li>
    <li>z</li>
    <li>short</li>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>wiiiiiiiiiiiiiiide</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>normal</li>
    <li>just two</li>
  </ul>
</div>

<div>
  <ul>
    <li>why</li>
    <li>full</li>
    <li>width?</li>
  </ul>
</div></code>```

Body:
I put flex-direction: column and flex-wrap: wrap for ul to achieve columns.

If ul splits elements into few columns, they have width of the widest li content in the column. But if there is only one column, it has 100% width.

What I want is to have this one column the size of its content.

/* boilerplate */

* {
  margin: 0;
  padding: 0;
}

div {
  max-height: 100px;
  background-color: #cacaca;
}

ul {
  list-style-type: none;
  height: 100px;
  background-color: #dadada;
}

li {
  margin-right: 10px;
  background-color: #eaeaea;
}

/* actual code */

div {}

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: center;
}

li {}

normal

x

y

z

short

a

b

c

wiiiiiiiiiiiiiiide

1

2

3

normal

just two

why

full

width?

https://codepen.io/anon/pen/eRYjLd

Body:
Instead of display: flex use display: inline-flex.

This switches the container from block-level (which takes the full width of its parent) to inline-level (which takes the width of its content).

This sizing behavior is similar to display: block vs. display: inline-block.

OR

Make the parent div a flex container with justify-content: center.

This confines the ul flex container to the width of the flex item, whose default is flex-basis: auto (content width).

/* boilerplate */

* {
  margin: 0;
  padding: 0;
}

div {
  max-height: 100px;
  background-color: #cacaca;
}

ul {
  list-style-type: none;
  height: 100px;
  background-color: #dadada;
}

li {
  margin-right: 10px;
  background-color: #eaeaea;
}

/* actual code */

div {
  display: flex;             /* NEW */
  justify-content: center;   /* NEW */
}

ul {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  align-content: center;
}

li {}

<div>
  <ul>
    <li>normal</li>
    <li>x</li>
    <li>y</li>
    <li>z</li>
    <li>short</li>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>wiiiiiiiiiiiiiiide</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>normal</li>
    <li>just two</li>
  </ul>
</div>

<div>
  <ul>
    <li>why</li>
    <li>full</li>
    <li>width?</li>
  </ul>
</div>


来源: stackexchange

问:
Trying to create two different account types in rails
I am trying to build a simple donation app in rails. In this application, patrons would give amounts of money to clients. Both the patron and the client share large amounts of the same functionality. They are both linked to a user and have a username. However, the client is also supposed to have a content_type and a content_list property. At first glance, my guess is that I want to have both my patron and client inherit from the account class. However, the client has additional functionality, which seems to preclude any STI-based implementation (though I will be the first to admit that my understanding of STI is shaky at best). As it stands, it seems to simply make more sense to write out two separate resources, but I would like to keep my code as DRY as humanly possible. Is there a simple way for me to create the behaviors I want through inheritance, or should I simply go with overlapping resources?

答:
Regarding my question: Will a patron ever be a client? Will a client ever be a patron?

If the answer is "yes", you should consider creating a separate entity/model for the resource they're relating to.

With model DonationCampaign (attributes client_id, among others):

```<code>has_one :client, :class_name => 'User'
has_many :patrons, :class_name => 'DonationCampaignPatron'
</code>```

DonationCampaignPatron (attributes patron_id, among others):

```<code>belongs_to :patron, :class_name => 'User'
</code>```

This allows you to keep the shared functionality of User and then extend functionality to specific campaigns, without having to make other models messy, and keeps things DRY.

If a DonationCampaign could then have multiple users (as administrators, per se), to extend, a DonationCampaignRole model would be required, donation_campaign_id, user_id, role

Say you're using CanCanCan,

if can? :manage, @campaign

if can? :contribute, @campaign

:contribute would have to be added to ability.rb and could simply be @campaign.client != User

Also, STI example (the good kind, at least):

```<code>class Animal < ActiveRecord::Base
  def says
    raise "Implement on subclass"
  end
end

class Cat < Animal
 # always has a type of 'Cat'
  def says
    "meow"
  end
end

class Dog < Animal
 # always has a type of 'Dog'
  def says
    "woof"
  end
end
</code>```

And there's only one table: animals

Edit: Based on your response: From what I can learn by briefly using Patreon they have a single User model (for authentication), and then they likely have a creator_page_id in the User column. They then have a separate model CreatorPage which has all the "Client" (in your terms) info associated with it.

Personally, I would stick with a single User model for authentication and then implement the aforementioned DonationCampaign/DonationCampaignPatreon business logic. It's the most extensible with the least amount of effort (both long and shot-term).

If, for whatever reason, a Client is restricted to contributing to other Clients once they are a Client, I would forego using STI on the User model.

ContentLicense: CC BY-SA 3.0

Body:
Regarding my question: Will a patron ever be a client? Will a client ever be a patron?

If the answer is "yes", you should consider creating a separate entity/model for the resource they're relating to.

With model DonationCampaign (attributes client_id, among others):

has_one :client, :class_name => 'User'
has_many :patrons, :class_name => 'DonationCampaignPatron'

DonationCampaignPatron (attributes patron_id, among others):

belongs_to :patron, :class_name => 'User'

This allows you to keep the shared functionality of User and then extend functionality to specific campaigns, without having to make other models messy, and keeps things DRY.

If a DonationCampaign could then have multiple users (as administrators, per se), to extend, a DonationCampaignRole model would be required, donation_campaign_id, user_id, role

Say you're using CanCanCan,

if can? :manage, @campaign

if can? :contribute, @campaign

:contribute would have to be added to ability.rb and could simply be @campaign.client != User

Also, STI example (the good kind, at least):

class Animal < ActiveRecord::Base
  def says
    raise "Implement on subclass"
  end
end

class Cat < Animal
 # always has a type of 'Cat'
  def says
    "meow"
  end
end

class Dog < Animal
 # always has a type of 'Dog'
  def says
    "woof"
  end
end

And there's only one table: animals

Edit: Based on your response: From what I can learn by briefly using Patreon they have a single User model (for authentication), and then they likely have a creator_page_id in the User column. They then have a separate model CreatorPage which has all the "Client" (in your terms) info associated with it.

Personally, I would stick with a single User model for authentication and then implement the aforementioned DonationCampaign/DonationCampaignPatreon business logic. It's the most extensible with the least amount of effort (both long and shot-term).

If, for whatever reason, a Client is restricted to contributing to other Clients once they are a Client, I would forego using STI on the User model.


问:
PHP MVC: Injecting utility/helper class instances into base classes as dependencies
In my HMVC project I've implemented an Arrays class. Its STATIC methods are used overall to handle various operations on multidimensional arrays. Beside this class I use similar ones too: Files, Images, Printer, Messages, Classes, etc. But I don't want any statics, or singletons in my project anymore.

I see them as helpers, final classes having methods used to just perform specific tasks on the project components or with them (merge arrays, resize images, upload/print files, etc). As such, I want to... minimize their distribution inside my project.

For example, I don't find it optimal to pass an Arrays object in each child controller, just because in the constructor of the base controller class some arrays must be merged.

I'd like to ask:

Is it wrong that I actually merge arrays inside the base controller class, or this situation can really arise?

If it's not wrong, then I have only the choice to pass the utility class Arrays as constructor dependency, and the static problem would be elegantly solved this way. Is this true, or is there a better alternative?

I'd appreciate any perspective of yours.

Thank you very much!

P.S:

Here is the Arrays class, if you need to take a look in it:

```<code><?php

namespace MYMVC\Utils;

/**
 * Arrays: utility class to handle operations on multidimensional arrays.
 */
class Arrays {

    /* ------------------------------------------------------------- */
    /* Keypath format: '{key0}/{key1}/{key2}/{key3}/{searched-key}'. */
    /* ------------------------------------------------------------- */

    /** Set the value in array at the specified keypath. [...] */

    public static function setArrayValue(&$array, $keypath, $value, $delimiter = '/') { ... }

    /** Get a tree structure from the specified keypath. [...] */

    public static function buildArrayTree($keypath, $value, $delimiter = '/') { ... }

    /** Check if the specified keypath exists in array. [...] */

    public static function arrayKeyExists(&$array, $keypath, $delimiter = '/') { ... }

    /** Get the array value from the specified keypath. [...] */

    public static function getArrayValue(&$array, $keypath, $delimiter = '/') { ... }

    /** Merge multiple multidimensional arrays. [...] */

    public static function mergeMultipleArrays(/* func_get_args */) { ... }

    /** Merge the top multidimensional array over the base multidimensional array. [...] */

    public static function mergeArrays($base, $top) { ... }

}
</code>```

答:
Something like Arrays::mergeArrays is not wrong. You don't mind call in_array or array_merge inside your classes, no? You can call Arrays an "utility" class if you want, but I don't think you can do the same for Files.

If your current problem is "I don't want pass the xyz object to each child controller", then usually you have schools of thought:

Just inject the DIC to your controllers. Then retrieve your dependency from it. That's what's called "Service Locator", and it's widely used by many frameworks. It has the advantage that you can require the dependency only where you need it, and when you need it. But it has a series of downside. Your object can't exists without it, and your classes can't be mocked easily. That's why it's considered an anti-pattern.

Inject your dependency (i.e: Files) explicitly in your controllers. Why you should want hide the fact that your controller depends on Files?  The only problem here is, especially with controllers, that many dependencies aren't always used by all the class's methods. That's more a performance problem, and you can think of solve it in many ways (example:
Action object).

Choose what works for you.

Body:
In my HMVC project I've implemented an Arrays class. Its STATIC methods are used overall to handle various operations on multidimensional arrays. Beside this class I use similar ones too: Files, Images, Printer, Messages, Classes, etc. But I don't want any statics, or singletons in my project anymore.

I see them as helpers, final classes having methods used to just perform specific tasks on the project components or with them (merge arrays, resize images, upload/print files, etc). As such, I want to... minimize their distribution inside my project.

For example, I don't find it optimal to pass an Arrays object in each child controller, just because in the constructor of the base controller class some arrays must be merged.

I'd like to ask:

Is it wrong that I actually merge arrays inside the base controller class, or this situation can really arise?

If it's not wrong, then I have only the choice to pass the utility class Arrays as constructor dependency, and the static problem would be elegantly solved this way. Is this true, or is there a better alternative?

I'd appreciate any perspective of yours.

Thank you very much!

P.S:

Here is the Arrays class, if you need to take a look in it:

<?php

namespace MYMVC\Utils;

/**
 * Arrays: utility class to handle operations on multidimensional arrays.
 */
class Arrays {

    /* ------------------------------------------------------------- */
    /* Keypath format: '{key0}/{key1}/{key2}/{key3}/{searched-key}'. */
    /* ------------------------------------------------------------- */

    /** Set the value in array at the specified keypath. [...] */

    public static function setArrayValue(&$array, $keypath, $value, $delimiter = '/') { ... }

    /** Get a tree structure from the specified keypath. [...] */

    public static function buildArrayTree($keypath, $value, $delimiter = '/') { ... }

    /** Check if the specified keypath exists in array. [...] */

    public static function arrayKeyExists(&$array, $keypath, $delimiter = '/') { ... }

    /** Get the array value from the specified keypath. [...] */

    public static function getArrayValue(&$array, $keypath, $delimiter = '/') { ... }

    /** Merge multiple multidimensional arrays. [...] */

    public static function mergeMultipleArrays(/* func_get_args */) { ... }

    /** Merge the top multidimensional array over the base multidimensional array. [...] */

    public static function mergeArrays($base, $top) { ... }

}


问:
how to activate the activity in android app in the right time that the app should be closed then
I am working on alarm clock android app.
my problem is to activate an ringing activity in the app at the right time that the app should be closed then..
how to do that??
I wish my idea is clear. thanks</p>

答: You can use AlarmManager to set the alarm. You just need to create a PendingIntent for the activity, and then pass in the parameters for either AlarmManager#set or AlarmManager#setExact, depending on your API version. If you are using API 21 or later, another option is AlarmManager#setAlarmClock.</p>


问:
Regex href match a number
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

```<code>/<a href=\"travis.php?theTaco=([0-9999999])\">(.*)</a>
</code>```

I basically want the number in this string:

```<code><a href="travis.php?theTaco=510973">510973</a>
</code>```

My regex is almost good? my original was:

```<code>"/<a href=\"travis.php?theTaco(.*)\">(.*)<\/a>/";
</code>```

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.

答:
Try using a HTML parser provided by the language you are using.

Reason why your first regex fails:

[0-9999999] is not what you think. It is same as [0-9] which matches one digit. To match a number you need [0-9]+. Also .* is greedy and will try to match as much as it can. You can use .*? to make it non-greedy. Since you are trying to match a number again, use [0-9]+ again instead of .*. Also if the two number you are capturing will be the same, you can just match the first and use a back reference \1 for 2nd one.

And there are a few regex meta-characters which you need to escape like ., ?.

Try:

```<code><a href=\"travis\.php\?theTaco=([0-9]+)\">\1<\/a>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Regex href match a number

Body:
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

/(.*)

I basically want the number in this string:

510973

My regex is almost good? my original was:

"/(.*)<\/a>/";

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.

Body:
Try using a HTML parser provided by the language you are using.

Reason why your first regex fails:

[0-9999999] is not what you think. It is same as [0-9] which matches one digit. To match a number you need [0-9]+. Also .* is greedy and will try to match as much as it can. You can use .*? to make it non-greedy. Since you are trying to match a number again, use [0-9]+ again instead of .*. Also if the two number you are capturing will be the same, you can just match the first and use a back reference \1 for 2nd one.

And there are a few regex meta-characters which you need to escape like ., ?.

Try:

<a href=\"travis\.php\?theTaco=([0-9]+)\">\1<\/a>


问:
Adding multiple youtube playlists to site just like youtube has em
this is desired output for site

this is how youtube displays multiple playlist...how can I add this just like they have it to my site AND to linkedin profile?

embedding the share html link just brings in playlist but it does not display properly....I need it to appear exactly like it does in attached pic???

答:
Linking to your LinkedIn profile, I have not tried. So perhaps someone else can tell you.

As to having a section like the one you showed to be on your own site is doable.

Firstly you will need to collect the playlist ID's that you are going to use.

Then you will need to get the video ID's from the video's in each Playlist.

This can be done with the API.

As to the displaying it like on youtube, you will need to do that yourself with one or more combination of table's, div's and CSS. Then With the information you grabbed in the APi, populate it.

Best to do it in a loop so as to be done all at the same time. Then put it to the page where you require it to be.


问:
How can i convert string to double ? I'm getting exception
```<code>for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }
</code>```

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

```<code>double b = Convert.ToDouble(secondNumber);
</code>```

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

```<code>private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

答:
Its doomed to fail.
I would use following regex:</p>

```<code>        string test = "matrix(0.1234,0.23233433,0.34,-3343,-3.33)";
        Regex reg = new Regex("[-]?[0-9]+(\\.[0-9]+)?");
        MatchCollection coll = reg.Matches(test);
</code>```

Body:
for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

double b = Convert.ToDouble(secondNumber);

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

Body:
Its doomed to fail.
I would use following regex:

        string test = "matrix(0.1234,0.23233433,0.34,-3343,-3.33)";
        Regex reg = new Regex("[-]?[0-9]+(\\.[0-9]+)?");
        MatchCollection coll = reg.Matches(test);


问:
SVG array not available to HTML page
I'm referencing a .js file from my .html file and trying to append my SVG charts into specific div's. However, I get the following message in the console when I open the html file:

```<code>TypeError: svg[0] is undefined
</code>```

When I include the script tag in my html along with my script.js code, I can find the "svg" array (and expected pie chart's) from the console. [I used that data to build the forEach loop at the end of stack.js below.] I know that the stack.js code works because it's the same code from this question which I posted a few days ago.

I'm curious as to why I cannot get my .html file to "see" the array from my .js file. Is there a way to do this, or am I missing a best-practice with d3 which I should be using? Is it somehow related to d3 being asynchronous?

stack.html:

```<code><!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    <script src="stack.js"></script>
</head>

<body>
    <div id="pie1"></div>
    <div id="pie2"></div>
</body>
</html>
</code>```

stack.js

```<code>var data  = {
    "data":[
        {"pie_one": {
            "id": "pie1",
            "results": [
                {"ratio": 0.04, "total": 7, "failures": 1},
                {"ratio": 0.04, "total": 8, "failures": 0},
                {"ratio": 0.04, "total": 9001, "failures": 0}
            ]}
        },
        {"pie_two": {
            "id": "pie2",
            "results": [
                {"ratio": 0.04, "total": 10, "failures": 0},
                {"ratio": 0.04, "total": 11, "failures": 1},
                {"ratio": 0.04, "total": 12, "failures": 1}
            ]}
        }
    ]
};

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var arc = d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius - (radius / 2));

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.ratio; });

var svg = d3.select("body").selectAll("svg")
   .data(data.data)
   .enter()
   .append("svg")
   .attr("width", width)
   .attr("height", height)
   .append("g")
   .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg[0].forEach(function(pie) {
        var div = document.getElementById(pie.__data__.id);
        div.innerHTML = pie;
    });

var g = svg.selectAll(".arc")
    .data(function(d,i) { return pie(d["pie"+(i+1)].results) })
    .enter().append("g")
    .attr("class", "arc")

    g.append("path")
     .attr("d", arc)
     .style("fill", function(d) { return (d.data.failures > 0) ? "#d63535" : "#22c12d"; });

window.onload = function() {
    svg[0].forEach(function(pie) {
        var div = document.getElementById(pie.__data__.id);
        div.innerHTML = pie;
    });
};
</code>```

答:
The reason that you can't reference your svg[0] is-- as I mentioned in my comment-- because you are trying to do things before the DOM is loaded.  Moving your code into the window.onload would fix that particular error but you have additional problems with the way you're trying to do things.

Below is a working example and is more what you want to do.  You should be using d3's functionality to embed your charts where you want them.  Rather than sticking them in the body and then trying to move them around.

stack.js

```<code>var data  = {
    "data":[
        {
            "id": "pie1",
            "results": [
                {"ratio": 0.04, "total": 7, "failures": 1},
                {"ratio": 0.04, "total": 8, "failures": 0},
                {"ratio": 0.04, "total": 9001, "failures": 0}
            ]
        },
        {
            "id": "pie2",
            "results": [
                {"ratio": 0.04, "total": 10, "failures": 0},
                {"ratio": 0.04, "total": 11, "failures": 1},
                {"ratio": 0.04, "total": 12, "failures": 1}
            ]
        }
    ]
};

window.onload = function() {

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var arc = d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius - (radius / 2));

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.ratio; });

var svg = d3.select("body")
   .selectAll("div")
   .data(data.data, function(d) { return d ? d.id : this.id })
   .append("svg")
   .attr("width", width)
   .attr("height", height)
   .append("g")
   .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var g = svg.selectAll(".arc")
    .data(function(d) { return pie(d.results) })
    .enter().append("g")
    .attr("class", "arc")
    .append("path")
    .attr("d", arc)
    .style("fill", function(d) { return (d.data.failures > 0) ? "#d63535" : "#22c12d"; });

};
</code>```

The key to getting the charts where you want them is in the second parameter of the data binding call.

```<code>   .selectAll("div")
   .data(data.data, function(d) { return d ? d.id : this.id })
</code>```

The above generates a key value for both the elements and your data rows-- where those keys match, d3 binds that particular data row to the data element.

I also changed up your data structure a tiny bit because the way you're doing things with unique keys to identify your objects makes it difficult to work with d3's idea of data.  If you can't change up your data structure for some reason, then I'd suggest an intermediate function to reshape your data into something easier to work with.  The other poster in your previous question commented on your data structure as well.

Your stack.html is unchanged.

```<code><!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    <script src="stack.js"></script>
</head>

<body>
    <div id="pie1"></div>
    <div id="pie2"></div>
</body>
</html>
</code>```

Title: SVG array not available to HTML page

Body:
I'm referencing a .js file from my .html file and trying to append my SVG charts into specific div's. However, I get the following message in the console when I open the html file:

TypeError: svg[0] is undefined

When I include the script tag in my html along with my script.js code, I can find the "svg" array (and expected pie chart's) from the console. [I used that data to build the forEach loop at the end of stack.js below.] I know that the stack.js code works because it's the same code from this question which I posted a few days ago.

I'm curious as to why I cannot get my .html file to "see" the array from my .js file. Is there a way to do this, or am I missing a best-practice with d3 which I should be using? Is it somehow related to d3 being asynchronous?

stack.html:

<!doctype html>

    <meta charset="UTF-8">

stack.js

var data  = {
    "data":[
        {"pie_one": {
            "id": "pie1",
            "results": [
                {"ratio": 0.04, "total": 7, "failures": 1},
                {"ratio": 0.04, "total": 8, "failures": 0},
                {"ratio": 0.04, "total": 9001, "failures": 0}
            ]}
        },
        {"pie_two": {
            "id": "pie2",
            "results": [
                {"ratio": 0.04, "total": 10, "failures": 0},
                {"ratio": 0.04, "total": 11, "failures": 1},
                {"ratio": 0.04, "total": 12, "failures": 1}
            ]}
        }
    ]
};

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var arc = d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius - (radius / 2));

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.ratio; });

var svg = d3.select("body").selectAll("svg")
   .data(data.data)
   .enter()
   .append("svg")
   .attr("width", width)
   .attr("height", height)
   .append("g")
   .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg[0].forEach(function(pie) {
        var div = document.getElementById(pie.__data__.id);
        div.innerHTML = pie;
    });

var g = svg.selectAll(".arc")
    .data(function(d,i) { return pie(d["pie"+(i+1)].results) })
    .enter().append("g")
    .attr("class", "arc")

    g.append("path")
     .attr("d", arc)
     .style("fill", function(d) { return (d.data.failures > 0) ? "#d63535" : "#22c12d"; });

window.onload = function() {
    svg[0].forEach(function(pie) {
        var div = document.getElementById(pie.__data__.id);
        div.innerHTML = pie;
    });
};

Body:
The reason that you can't reference your svg[0] is-- as I mentioned in my comment-- because you are trying to do things before the DOM is loaded.  Moving your code into the window.onload would fix that particular error but you have additional problems with the way you're trying to do things.

Below is a working example and is more what you want to do.  You should be using d3's functionality to embed your charts where you want them.  Rather than sticking them in the body and then trying to move them around.

stack.js

var data  = {
    "data":[
        {
            "id": "pie1",
            "results": [
                {"ratio": 0.04, "total": 7, "failures": 1},
                {"ratio": 0.04, "total": 8, "failures": 0},
                {"ratio": 0.04, "total": 9001, "failures": 0}
            ]
        },
        {
            "id": "pie2",
            "results": [
                {"ratio": 0.04, "total": 10, "failures": 0},
                {"ratio": 0.04, "total": 11, "failures": 1},
                {"ratio": 0.04, "total": 12, "failures": 1}
            ]
        }
    ]
};

window.onload = function() {

var width = 300,
    height = 300,
    radius = Math.min(width, height) / 2;

var arc = d3.svg.arc()
    .outerRadius(radius)
    .innerRadius(radius - (radius / 2));

var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) { return d.ratio; });

var svg = d3.select("body")
   .selectAll("div")
   .data(data.data, function(d) { return d ? d.id : this.id })
   .append("svg")
   .attr("width", width)
   .attr("height", height)
   .append("g")
   .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

var g = svg.selectAll(".arc")
    .data(function(d) { return pie(d.results) })
    .enter().append("g")
    .attr("class", "arc")
    .append("path")
    .attr("d", arc)
    .style("fill", function(d) { return (d.data.failures > 0) ? "#d63535" : "#22c12d"; });

};

The key to getting the charts where you want them is in the second parameter of the data binding call.

   .selectAll("div")
   .data(data.data, function(d) { return d ? d.id : this.id })

The above generates a key value for both the elements and your data rows-- where those keys match, d3 binds that particular data row to the data element.

I also changed up your data structure a tiny bit because the way you're doing things with unique keys to identify your objects makes it difficult to work with d3's idea of data.  If you can't change up your data structure for some reason, then I'd suggest an intermediate function to reshape your data into something easier to work with.  The other poster in your previous question commented on your data structure as well.

Your stack.html is unchanged.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
    <script src="stack.js"></script>
</head>

<body>
    <div id="pie1"></div>
    <div id="pie2"></div>
</body>
</html>


问:
read.WSdata Error in data.frame
I am trying to do the Landsat 8 example at https://cran.r-project.org/web/packages/water/vignettes/Landsat8.html example. I get stuck at the read.WSdata example where I get the error Error in data.frame(date = unique(WSdata$date), radiation_sum = tapply(WSdata$radiation,  :
  arguments imply differing number of rows: 1, 0 I am using my own data - NOT the data provided in the example.

My csv file has been organized exactly as the example dataset ("INTA.csv"). The only difference I have noticed between the datasets is that mine has a datetime every 15min and the example dataset has datetime every hour.

Here is my code.

```<code>`rm(list=ls())
library(water)
aoi<-createAoi(topleft=c(385387,4776577),
bottomright=c(414825,4749526), EPSG = 32612)
raw_data_folder <- system.file("rossfrk072616", package="water")
image <- loadImage(path=raw_data_folder, aoi=aoi, sat="L8")
image.SR <- loadImageSR(path=raw_data_folder, aoi=aoi)
plot(image)
plot(image.SR)
csvfile<-system.file("rossfrk072616","FTHI_L8_1.csv",package="water")`
</code>```

I am also assuming we use the original MTL file and NOT the surface reflectance MTL file, which when you download from the ESPA gives the same name of the mtl file as the original?

MTLfile <- system.file("rossfrk072616",
   "LC08_L1TP_039030_20160726_20170221_01_T1_MTL.txt", package="water")
   WeatherStation <- read.WSdata(WSdata = csvfile,datetime.format =  "%Y/%m/%d
    %H:%M",columns = c("datetime", "temp","RH", "pp", "radiation",
    "wind"),lat=43.07138, long= -112.4311, elev=1354.5, height= 2.5, MTL =
    MTLfile)

After I run the read.WSdata I get the error

```<code>Error in data.frame(date = unique(WSdata$date), radiation_sum =
tapply(WSdata$radiation,: arguments imply differing number of rows: 1, 0
</code>```

答:
For some reason I was not able to get the code from the website to function with my dataset. However, I was able to read my weather station data with the following code. WeatherStation <- read.WSdata(WSdata = csvfile, date.format = "%d/%m/%Y",
                  lat=43.07138, long= -112.4311, elev=1354.5, height= 2.5,
                  MTL = MTLfile)

Title: read.WSdata Error in data.frame

Body:
I am trying to do the Landsat 8 example at https://cran.r-project.org/web/packages/water/vignettes/Landsat8.html example. I get stuck at the read.WSdata example where I get the error Error in data.frame(date = unique(WSdata$date), radiation_sum = tapply(WSdata$radiation,  :
  arguments imply differing number of rows: 1, 0 I am using my own data - NOT the data provided in the example.

My csv file has been organized exactly as the example dataset ("INTA.csv"). The only difference I have noticed between the datasets is that mine has a datetime every 15min and the example dataset has datetime every hour.

Here is my code.

`rm(list=ls())
library(water)
aoi<-createAoi(topleft=c(385387,4776577),
bottomright=c(414825,4749526), EPSG = 32612)
raw_data_folder <- system.file("rossfrk072616", package="water")
image <- loadImage(path=raw_data_folder, aoi=aoi, sat="L8")
image.SR <- loadImageSR(path=raw_data_folder, aoi=aoi)
plot(image)
plot(image.SR)
csvfile<-system.file("rossfrk072616","FTHI_L8_1.csv",package="water")`

I am also assuming we use the original MTL file and NOT the surface reflectance MTL file, which when you download from the ESPA gives the same name of the mtl file as the original?

MTLfile <- system.file("rossfrk072616",
   "LC08_L1TP_039030_20160726_20170221_01_T1_MTL.txt", package="water")
   WeatherStation <- read.WSdata(WSdata = csvfile,datetime.format =  "%Y/%m/%d
    %H:%M",columns = c("datetime", "temp","RH", "pp", "radiation",
    "wind"),lat=43.07138, long= -112.4311, elev=1354.5, height= 2.5, MTL =
    MTLfile)

After I run the read.WSdata I get the error

Error in data.frame(date = unique(WSdata$date), radiation_sum =
tapply(WSdata$radiation,: arguments imply differing number of rows: 1, 0


问:
Ionic 2 data reload when network isn't present
I just want to know if this is possible and how it could be done.

Let's say an Android user has a network connection and makes a change that then updates the database. Then the user loses network connection but still makes changes on their device. They can't obviously send data to the database without a connection.

But when they receive a connection again, the changes they made when there wasn't a connection are automatically updated and sent to the database. How would I go about doing such a thing with Ionic 2 framework? Please point me in the right direction.

Thanks!

答:
Yes it's possible.

For that you need SQLite. It is best to make a SQLite service.

In the first phase the most important thing is to save data to offline/local database. In this case this is SQlite.

When there is no network connection and user make some action save data to table created in your SQlite database.

```<code> finishFunction(){
   if(this._connectivityService.isOnline()){
     //Send data directly to external database
      this._api.sendData(this.parameters).subscribe(res => {
    });
   } else {
    //Store data in offline SQLite database
    this._database.myOfflineTable(this.parameters);
   }
 }
</code>```

After that, in app home page check when network connection is available and call function that sends local/offline data through API to external database. When API return success message you can empty offline table.

```<code>sendMyOfflineData(){
     this._database.getOfflineTable().then((result) => {
            this.OfflineTableList = <Array<Object>> result;
            if(this.OfflineTable.length != 0){
            for(var i = 0; i < this.OfflineTable.length; i++){
              this._api.sendData(this.OfflineTable[i]).subscribe(res => {
              if(res.status == true){
                 this._database.deleteOfflineTable();
              }
         });
            }}
        }, (error) => {
            console.log("ERROR: ", error);
        });
   }
</code>```

If you need more details, I'm here.

Body:
Yes it's possible.

For that you need SQLite. It is best to make a SQLite service.

In the first phase the most important thing is to save data to offline/local database. In this case this is SQlite.

When there is no network connection and user make some action save data to table created in your SQlite database.

 finishFunction(){
   if(this._connectivityService.isOnline()){
     //Send data directly to external database
      this._api.sendData(this.parameters).subscribe(res => {
    });
   } else {
    //Store data in offline SQLite database
    this._database.myOfflineTable(this.parameters);
   }
 }

After that, in app home page check when network connection is available and call function that sends local/offline data through API to external database. When API return success message you can empty offline table.

sendMyOfflineData(){
     this._database.getOfflineTable().then((result) => {
            this.OfflineTableList = <Array<Object>> result;
            if(this.OfflineTable.length != 0){
            for(var i = 0; i < this.OfflineTable.length; i++){
              this._api.sendData(this.OfflineTable[i]).subscribe(res => {
              if(res.status == true){
                 this._database.deleteOfflineTable();
              }
         });
            }}
        }, (error) => {
            console.log("ERROR: ", error);
        });
   }

If you need more details, I'm here.


问:
std::thread.join() deadlock
I don't understand why this simple snippet has a dead lock:

```<code>#include <atomic>
#include <thread>
#include <memory>

using namespace std;
class Test {
public:

    Test() : mExit( false )
    {
        mThread = thread( bind( &Test::func, this ) );
    }

    ~Test()
    {
        if ( mThread.joinable() )
        {
            mExit = true;
            mThread.join();
        }
    }

private:
    void func()
    {
        while ( !mExit )
        {
            // do something
        }
    }

private:
    atomic< bool > mExit;
    thread mThread;
};

typedef unique_ptr< Test > TestPtr;
TestPtr gTest;

int main()
{
    gTest = TestPtr( new Test );
    return 0;
}
</code>```

 Edit
I typed wrong the contstructor set mExit = true

 Edit 2
I'm using msvc2012 with v110_xp toolset.

 Edit 3
The issue disappear if I explicity call gTest.release() inside main

答:
Changing code from

gTest = TestPtr( new Test );

to

auto gTest = std::make_unique();

eliminate the problem.

the problem as point above with global object.

Title: std::thread.join() deadlock

Body:
I don't understand why this simple snippet has a dead lock:

#include <atomic>
#include <thread>
#include <memory>

using namespace std;
class Test {
public:

    Test() : mExit( false )
    {
        mThread = thread( bind( &Test::func, this ) );
    }

    ~Test()
    {
        if ( mThread.joinable() )
        {
            mExit = true;
            mThread.join();
        }
    }

private:
    void func()
    {
        while ( !mExit )
        {
            // do something
        }
    }

private:
    atomic< bool > mExit;
    thread mThread;
};

typedef unique_ptr< Test > TestPtr;
TestPtr gTest;

int main()
{
    gTest = TestPtr( new Test );
    return 0;
}

 Edit
I typed wrong the contstructor set mExit = true

 Edit 2
I'm using msvc2012 with v110_xp toolset.

 Edit 3
The issue disappear if I explicity call gTest.release() inside main


问:
How to access the member of a template parameter's? "Member access to incomplete type"
I'm trying to declare a class "Lambdas" that would provide lambdas (and their type information) to another class "Test". Lambdas also is holding the "this" reference to concrete Test instance for access of Test public members, inside the lambdas.
I do it to define the lambdas once and then to deduce types anywhere else through decltype()
But I get error: Member access to incomplete type:

```<code>template <typename T>
struct LambdasInstances {
    T * self;
    explicit LambdasInstances(T * p) : self(p) {} // CAPTURE Test "this"

    auto genLambda1() {
        return [=](int x){
            self->testVar; // ERROR: Member access to incomplete type
        };
    }
};

class Test3 {
public:
    LambdasInstances<Test3> instances;
    int testVar;

    Test3() : instances(this) {}

    decltype(instances.genLambda1()) varLambda = instances.genLambda1();

    void useLambda() { varLambda(123); }
};
</code>```

BUT IF I would make genLambda() externally defined, then I would run to another problem - ERROR: genLambda() with deduced type cannot be used before its defined!:

```<code>template <typename T>
struct LambdasInstances {
    T * self;
    explicit LambdasInstances(T * p) : self(p) {}
    auto genLambda1(); // would be defined after Test3 declaration
};

class Test3 {
public:
    int testVar;
    LambdasInstances<Test3> instances;
    Test3() : instances(this) {}
    decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};

// IF WE DEFINE AFTER :: ^ genLambda() with deduced type cannot be used before its defined!
template< typename T>
auto LambdasInstances<T>::genLambda1() {
    return [=](int x){
        self->testVar;
    };
}
</code>```

答:
The compiler might require the definition of the whole type available to be able to know the offset of the members (e.g. in the expression self->testVar, the compiler has to know the offset of testVar), but it might not be able to know the offset of a particular member until it will get the whole definition, because the compiler must know the alignment of your structure/class (I would even guess that some not straight forward logic might be involved when computing the padding between members) that comes after the knowledge of all members, see this, that is totally compiler and platform specific.

So back to your problem. You tell the compiler to define Test3 with genLambda1 as a member, that is a lambda that has to know the offset of member testVar. Seems easy, right? But the offset of testVar depends on the definition of the whole Test3 (see the paragraph above) - here we are in the loop.

You would say: "Hey stupid compiler, I give only a pointer to the lambda, not a copy by value where you have to know the whole size of the `Test3, why would you stop me from doing that?". Quite a legit question because theoretically compiler can resolve offset later, but seems like the compilers are not smart enough. And the standard says:

The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator ...

That basically says that the lambda body is the function body, but in the function body you cannot have incomplete types right? Lambdas are relatively new to C++ and not all corner cases are elaborated, so let's hope that in some future this will be resolved, of course the compilers will be more complicated as well as the standard.

For you problem I see the following resolution:

```<code>template <typename T>
struct LambdasInstances {
  explicit LambdasInstances(T* p) : _lambda([=](int x) { return p->testVar; }) {}

  auto genLambda1() { return _lambda; }

private:
  std::function<void(int)> _lambda;
};

class Test3 {
public:
  int testVar;
  LambdasInstances<Test3> instances;

  Test3() : instances(this) {}

  decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};

int main() {
  Test3 test3;
  Test3* test3_ptr;
  LambdasInstances<Test3> instances(&test3);
  auto lambda = [=](int x) { return test3_ptr->testVar; };
  std::function<void(int)> functor = lambda;
  cerr << sizeof(Test3) << endl;
  cerr << sizeof(LambdasInstances<Test3>) << endl;
  cerr << sizeof(lambda) << endl;
  cerr << sizeof(functor) << endl;
  return 0;
}
</code>```

The difference is that std::function gives you a level of abstraction that protects the type LambdasInstances::genLambda1 from the definition of Test3. Unfortunately, as you will see from the main output the function takes more memory than the lambda. If this does not satisfy your needs I recommend to revise the design and may be you will find something in the old good techniques before the era of lambdas.

Body:
I'm trying to declare a class "Lambdas" that would provide lambdas (and their type information) to another class "Test". Lambdas also is holding the "this" reference to concrete Test instance for access of Test public members, inside the lambdas.
I do it to define the lambdas once and then to deduce types anywhere else through decltype()
But I get error: Member access to incomplete type:

template <typename T>
struct LambdasInstances {
    T * self;
    explicit LambdasInstances(T * p) : self(p) {} // CAPTURE Test "this"

    auto genLambda1() {
        return [=](int x){
            self->testVar; // ERROR: Member access to incomplete type
        };
    }
};

class Test3 {
public:
    LambdasInstances<Test3> instances;
    int testVar;

    Test3() : instances(this) {}

    decltype(instances.genLambda1()) varLambda = instances.genLambda1();

    void useLambda() { varLambda(123); }
};

BUT IF I would make genLambda() externally defined, then I would run to another problem - ERROR: genLambda() with deduced type cannot be used before its defined!:

template <typename T>
struct LambdasInstances {
    T * self;
    explicit LambdasInstances(T * p) : self(p) {}
    auto genLambda1(); // would be defined after Test3 declaration
};

class Test3 {
public:
    int testVar;
    LambdasInstances<Test3> instances;
    Test3() : instances(this) {}
    decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};

// IF WE DEFINE AFTER :: ^ genLambda() with deduced type cannot be used before its defined!
template< typename T>
auto LambdasInstances<T>::genLambda1() {
    return [=](int x){
        self->testVar;
    };
}

Body:
The compiler might require the definition of the whole type available to be able to know the offset of the members (e.g. in the expression self->testVar, the compiler has to know the offset of testVar), but it might not be able to know the offset of a particular member until it will get the whole definition, because the compiler must know the alignment of your structure/class (I would even guess that some not straight forward logic might be involved when computing the padding between members) that comes after the knowledge of all members, see this, that is totally compiler and platform specific.

So back to your problem. You tell the compiler to define Test3 with genLambda1 as a member, that is a lambda that has to know the offset of member testVar. Seems easy, right? But the offset of testVar depends on the definition of the whole Test3 (see the paragraph above) - here we are in the loop.

You would say: "Hey stupid compiler, I give only a pointer to the lambda, not a copy by value where you have to know the whole size of the `Test3, why would you stop me from doing that?". Quite a legit question because theoretically compiler can resolve offset later, but seems like the compilers are not smart enough. And the standard says:

The lambda-expression’s compound-statement yields the function-body (8.4) of the function call operator ...

That basically says that the lambda body is the function body, but in the function body you cannot have incomplete types right? Lambdas are relatively new to C++ and not all corner cases are elaborated, so let's hope that in some future this will be resolved, of course the compilers will be more complicated as well as the standard.

For you problem I see the following resolution:

template <typename T>
struct LambdasInstances {
  explicit LambdasInstances(T* p) : _lambda([=](int x) { return p->testVar; }) {}

  auto genLambda1() { return _lambda; }

private:
  std::function<void(int)> _lambda;
};

class Test3 {
public:
  int testVar;
  LambdasInstances<Test3> instances;

  Test3() : instances(this) {}

  decltype(instances.genLambda1()) varLambda = instances.genLambda1();
};

int main() {
  Test3 test3;
  Test3* test3_ptr;
  LambdasInstances<Test3> instances(&test3);
  auto lambda = [=](int x) { return test3_ptr->testVar; };
  std::function<void(int)> functor = lambda;
  cerr << sizeof(Test3) << endl;
  cerr << sizeof(LambdasInstances<Test3>) << endl;
  cerr << sizeof(lambda) << endl;
  cerr << sizeof(functor) << endl;
  return 0;
}

The difference is that std::function gives you a level of abstraction that protects the type LambdasInstances::genLambda1 from the definition of Test3. Unfortunately, as you will see from the main output the function takes more memory than the lambda. If this does not satisfy your needs I recommend to revise the design and may be you will find something in the old good techniques before the era of lambdas.


问:
Tables: How to achieve “normal” td widths, but 100% table width?
On our site we have tables containing data. We like the column widths we get with a normal table, but we like the border-bottom of tds to stretch the entire width of the page like we get with CSS: table { width:100% }, as can be seen on a demo table widths page, which renders like this:

Is it possible to achieve the same column widths as with a normal (non-width-100%) table in a table where the border-bottom stretches the entire width?

And no, td { white-space: nowrap } in combination with an extra width: 100% td (see the link above) is not good, as sometimes the tds are long and so we want the tds to wrap exactly like in a normal table.

We need a solution that works in at least IE6-8 + FF.

Btw, is there a better way (tm) of showing HTML snippets than linking to an external page? I can show just source, but having HTML rendered too is very illustrative.

This was originally posted on Webmasters, but following a suggestion there, I now (re)post it here.

答:
This is pretty ugly and not exactly what you asked for, but it works in Firefox and appears to get the same gist...</p>

```<code><html>
<head>
<style type="text/css">
td{background-color:blue;}
div{border:1px solid red;position:absolute;width:100%;}
</style>
</head>
<body>

<table>
<tr>
<td>asdf<div></div></td><td>hello blah blah</td>
</tr>
<tr>
<td>lorem ipsum dolor si amet</td><td>testing</td>
</tr>

</body>
</html>
</code>```

Body:
This is pretty ugly and not exactly what you asked for, but it works in Firefox and appears to get the same gist...

<html>
<head>
<style type="text/css">
td{background-color:blue;}
div{border:1px solid red;position:absolute;width:100%;}
</style>
</head>
<body>

<table>
<tr>
<td>asdf<div></div></td><td>hello blah blah</td>
</tr>
<tr>
<td>lorem ipsum dolor si amet</td><td>testing</td>
</tr>

</body>
</html>


问:
Single Background for Multiple Divs
Is there a way of having one image (PNG or SVG) as a background for multiple divs? Please see the images below as to how it would work. Also when the screen width becomes smaller and the divs line up below each other, would there be a way of changing the background to match that aswell?

DIVs without background:

The background:

DIVs with background:

答:
You might be looking for background-attachment: fixed:

If a background-image is specified, the background-attachment CSS
  property determines whether that image's position is fixed within the
  viewport, or scrolls along with its containing block.

.container {
  background-color: gray;
}

.window {
  background-image: url("https://i.stack.imgur.com/RPBBs.jpg");
  background-attachment: fixed;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="window" style="width: 100px; height: 50px; margin: 20px;"></div>
  <div class="window" style="width: 200px; height: 50px; margin: 20px;"></div>
  <div class="window" style="width: 500px; height: 50px; margin: 20px;"></div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Single Background for Multiple Divs

Body:
You might be looking for background-attachment: fixed:

If a background-image is specified, the background-attachment CSS
  property determines whether that image's position is fixed within the
  viewport, or scrolls along with its containing block.

.container {
  background-color: gray;
}

.window {
  background-image: url("https://i.stack.imgur.com/RPBBs.jpg");
  background-attachment: fixed;
  display: inline-block;
}

<div class="container">
  <div class="window" style="width: 100px; height: 50px; margin: 20px;"></div>
  <div class="window" style="width: 200px; height: 50px; margin: 20px;"></div>
  <div class="window" style="width: 500px; height: 50px; margin: 20px;"></div>
</div>


问:
Firebase uid returning nil after authentication (Swift)
In my app, as soon as it opens I check to see if the user is already authenticated in the viewdidload of the initial view. If they are already authenticated, I perform a segue to the main view. I'm even printing the uid to the log at this time and it's printing correctly.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    if ref.authData != nil {
        let uid = ref.authData.uid
        print(uid)
</code>```

I then do the same later in the app to get some of the user's info when they click on their profile settings. I write the exact same code to fetch their uid, but this time the uid is returning nil and is crashing with the error

"fatal error: unexpectedly found nil while unwrapping an Optional value"

Is this a firebase or simulator issue?

Edit: This issue has only occurred twice. Otherwise, the code itself works as intended, which makes me wonder whether it is a firebase or simulator issue.

答:
I was having this problem and it took me hours. Then I realized that I'd just forgotten to do this:

```<code>ref = FIRDatabase.database().reference()
</code>```

before

```<code>var ref: FIRDatabaseReference!
</code>```

Body:
In my app, as soon as it opens I check to see if the user is already authenticated in the viewdidload of the initial view. If they are already authenticated, I perform a segue to the main view. I'm even printing the uid to the log at this time and it's printing correctly.

override func viewDidLoad() {
    super.viewDidLoad()

    if ref.authData != nil {
        let uid = ref.authData.uid
        print(uid)

I then do the same later in the app to get some of the user's info when they click on their profile settings. I write the exact same code to fetch their uid, but this time the uid is returning nil and is crashing with the error

"fatal error: unexpectedly found nil while unwrapping an Optional value"

Is this a firebase or simulator issue?

Edit: This issue has only occurred twice. Otherwise, the code itself works as intended, which makes me wonder whether it is a firebase or simulator issue.

Body:
I was having this problem and it took me hours. Then I realized that I'd just forgotten to do this:

ref = FIRDatabase.database().reference()

before

var ref: FIRDatabaseReference!


问:
Fail to retrieve data from jquery datatables
My snippets below shows a datatables example that has 3 rows, I have added an extra column in column definition "action" and I m setting its display/data via default content and render functions respectively.

every time I try to build an JSON data containing the column "action" val i fail. I added the cell click listener (disabled in this action) just to make sure that the data is stored in the API data collection and it is indeed, yet it fails to show up after building the values.

if you click "build vals" you will see how the "action" data is not included in JSON. if you click "Mark for delete" and then "build vals" the "action" data will show up.

any idea how to make it work?

var tablenest = $('#RegSrc').DataTable({
  select: true,
  "bPaginate": false,
  "bFilter": false,
  responsive: true,
  deferRender: true,
  "processing": true,
  "serverSide": false,
  bAutoWidth: true,
  data: [{
    "RecID": 2383,
    "PtFilenum": 15090248,
    "PrtFilenum": 13090701,
    "Fullname": "Salem",
    "PrtStatus": 1
  }, {
    "RecID": 2384,
    "PtFilenum": 15090248,
    "PrtFilenum": 15120996,
    "Fullname": "Tony",
    "PrtStatus": 1
  }, {
    "RecID": 2385,
    "PtFilenum": 15090248,
    "PrtFilenum": 170227111,
    "Fullname": "Jorge",
    "PrtStatus": 1
  }],
  order: [2, 'asc'],
  keys: {
    columns: ':not(:first-child)',
    keys: [9]
  },
  columns: [
  { // Checkbox select column
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false,
      "width": "1%"
    },
    {
      "width": "50%",
      data: "RecID",
      "visible": false
    },
    {
      "width": "50%",
      data: "PtFilenum",
      "visible": false
    },
    {
      "width": "10%",
      data: "PrtFilenum"
    },
    {
      "width": "40%",
      data: "Fullname"
    },
    {
      "width": "10%",
      data: "PrtStatus",
      render: function(data, type, row) {
        if (type === 'display') {
          if (data == 1) {
            return 'Partners';
          } else {
            return 'Not Partners';
          }
        }
        return data;
      },
      className: "dt-body-center"
    },
    {
      "width": "10%",
      data: 'action',
      defaultContent: 'update',
      orderable: false,
      className: "dt-body-center",
      "visible": true,
      render: function(data, type, row) {
        if (data == null) {
          return 'update';
        } else {
          return data;
        }
      }
    },
  ],

});
  /* $('#RegSrc tbody').on('click', 'td', function () {
                        console.log(tablenest.cell(this).data());
                    });*/
$("#btn1").click(function() {
  tablenest.rows({
    selected: true
  }).every(function(rowIdx, tableLoop, rowLoop) {
    tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
    var row = tablenest.row(this).node();
    $(row).css('color', 'red').animate({
      color: 'black'
    });
  });
  return false;
})
$("#btn2").click(function() {
  var tbldta = $.map(tablenest.rows().data(), function(d, i) {
    var myObject = new Object();
    myObject = {
      action: d.action,
      RecID: d.RecID,
      PrtStatus: d.PrtStatus,
      ptfilenum: d.PtFilenum,
      PrtFilenum: d.PrtFilenum
    }
    return myObject
  });
  var DtaObj = {}
  DtaObj.Data = tbldta
  console.log(JSON.stringify(DtaObj))
  return false;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/moment-2.18.1/dt-1.10.15/b-1.3.1/se-1.2.2/datatables.min.js"></script>

<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>
<table id="RegSrc" class="table table-bordered table-striped table-condensed mb-none display responsive nowrap" cellspacing="0" width="100%">
  <thead>
    <tr>
    <th>click here to select</th>
      <th><b>RecID</b></th>
      <th><b>Patient File Number</b></th>
      <th><b>Partner File Number</b></th>
      <th><b>Patient Name</b></th>
      <th><b>Status</b></th>
      <th><b>action</b></th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table></code>```

答:
Include "action":"update" to your data source in constructor.

columns.defaultContent is static and therefore cannot possibly access
  the data.

Also you can remove render from "action" column.

var tablenest = $('#RegSrc').DataTable({
  select: true,
  "bPaginate": false,
  "bFilter": false,
  responsive: true,
  deferRender: true,
  "processing": true,
  "serverSide": false,
  bAutoWidth: true,
  data: [{
    "RecID": 2383,
    "PtFilenum": 15090248,
    "PrtFilenum": 13090701,
    "Fullname": "Salem",
    "PrtStatus": 1,
    "action": "update"
  }, {
    "RecID": 2384,
    "PtFilenum": 15090248,
    "PrtFilenum": 15120996,
    "Fullname": "Tony",
    "PrtStatus": 1,
    "action": "update"
  }, {
    "RecID": 2385,
    "PtFilenum": 15090248,
    "PrtFilenum": 170227111,
    "Fullname": "Jorge",
    "PrtStatus": 1,
    "action": "update"
  }],
  order: [2, 'asc'],
  keys: {
    columns: ':not(:first-child)',
    keys: [9]
  },
  columns: [
  { // Checkbox select column
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false,
      "width": "1%"
    },
    {
      "width": "50%",
      data: "RecID",
      "visible": false
    },
    {
      "width": "50%",
      data: "PtFilenum",
      "visible": false
    },
    {
      "width": "10%",
      data: "PrtFilenum"
    },
    {
      "width": "40%",
      data: "Fullname"
    },
    {
      "width": "10%",
      data: "PrtStatus",
      render: function(data, type, row) {
        if (type === 'display') {
          if (data == 1) {
            return 'Partners';
          } else {
            return 'Not Partners';
          }
        }
        return data;
      },
      className: "dt-body-center"
    },
    {
      "width": "10%",
      data: 'action',
      orderable: false,
      className: "dt-body-center",
      "visible": true
    },
  ],

});
  /* $('#RegSrc tbody').on('click', 'td', function () {
                        console.log(tablenest.cell(this).data());
                    });*/
$("#btn1").click(function() {
  tablenest.rows({
    selected: true
  }).every(function(rowIdx, tableLoop, rowLoop) {
    tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
    var row = tablenest.row(this).node();
    $(row).css('color', 'red').animate({
      color: 'black'
    });
  });
  return false;
})
$("#btn2").click(function() {
  var tbldta = $.map(tablenest.rows().data(), function(d, i) {
    var myObject = new Object();
    console.log(d);
    myObject = {
      action: d.action,
      RecID: d.RecID,
      PrtStatus: d.PrtStatus,
      ptfilenum: d.PtFilenum,
      PrtFilenum: d.PrtFilenum
    }
    return myObject
  });
  var DtaObj = {}
  DtaObj.Data = tbldta
  console.log(JSON.stringify(DtaObj))
  return false;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/moment-2.18.1/dt-1.10.15/b-1.3.1/se-1.2.2/datatables.min.js"></script>

<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>
<table id="RegSrc" class="table table-bordered table-striped table-condensed mb-none display responsive nowrap" cellspacing="0" width="100%">
  <thead>
    <tr>
    <th>click here to select</th>
      <th><b>RecID</b></th>
      <th><b>Patient File Number</b></th>
      <th><b>Partner File Number</b></th>
      <th><b>Patient Name</b></th>
      <th><b>Status</b></th>
      <th><b>action</b></th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table></code>```

Body:
My snippets below shows a datatables example that has 3 rows, I have added an extra column in column definition "action" and I m setting its display/data via default content and render functions respectively.

every time I try to build an JSON data containing the column "action" val i fail. I added the cell click listener (disabled in this action) just to make sure that the data is stored in the API data collection and it is indeed, yet it fails to show up after building the values.

if you click "build vals" you will see how the "action" data is not included in JSON. if you click "Mark for delete" and then "build vals" the "action" data will show up.

any idea how to make it work?

var tablenest = $('#RegSrc').DataTable({
  select: true,
  "bPaginate": false,
  "bFilter": false,
  responsive: true,
  deferRender: true,
  "processing": true,
  "serverSide": false,
  bAutoWidth: true,
  data: [{
    "RecID": 2383,
    "PtFilenum": 15090248,
    "PrtFilenum": 13090701,
    "Fullname": "Salem",
    "PrtStatus": 1
  }, {
    "RecID": 2384,
    "PtFilenum": 15090248,
    "PrtFilenum": 15120996,
    "Fullname": "Tony",
    "PrtStatus": 1
  }, {
    "RecID": 2385,
    "PtFilenum": 15090248,
    "PrtFilenum": 170227111,
    "Fullname": "Jorge",
    "PrtStatus": 1
  }],
  order: [2, 'asc'],
  keys: {
    columns: ':not(:first-child)',
    keys: [9]
  },
  columns: [
  { // Checkbox select column
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false,
      "width": "1%"
    },
    {
      "width": "50%",
      data: "RecID",
      "visible": false
    },
    {
      "width": "50%",
      data: "PtFilenum",
      "visible": false
    },
    {
      "width": "10%",
      data: "PrtFilenum"
    },
    {
      "width": "40%",
      data: "Fullname"
    },
    {
      "width": "10%",
      data: "PrtStatus",
      render: function(data, type, row) {
        if (type === 'display') {
          if (data == 1) {
            return 'Partners';
          } else {
            return 'Not Partners';
          }
        }
        return data;
      },
      className: "dt-body-center"
    },
    {
      "width": "10%",
      data: 'action',
      defaultContent: 'update',
      orderable: false,
      className: "dt-body-center",
      "visible": true,
      render: function(data, type, row) {
        if (data == null) {
          return 'update';
        } else {
          return data;
        }
      }
    },
  ],

});
  /* $('#RegSrc tbody').on('click', 'td', function () {
                        console.log(tablenest.cell(this).data());
                    });*/
$("#btn1").click(function() {
  tablenest.rows({
    selected: true
  }).every(function(rowIdx, tableLoop, rowLoop) {
    tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
    var row = tablenest.row(this).node();
    $(row).css('color', 'red').animate({
      color: 'black'
    });
  });
  return false;
})
$("#btn2").click(function() {
  var tbldta = $.map(tablenest.rows().data(), function(d, i) {
    var myObject = new Object();
    myObject = {
      action: d.action,
      RecID: d.RecID,
      PrtStatus: d.PrtStatus,
      ptfilenum: d.PtFilenum,
      PrtFilenum: d.PrtFilenum
    }
    return myObject
  });
  var DtaObj = {}
  DtaObj.Data = tbldta
  console.log(JSON.stringify(DtaObj))
  return false;
})

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>

    click here to select
      RecID
      Patient File Number
      Partner File Number
      Patient Name
      Status
      action

Body:
Include "action":"update" to your data source in constructor.

columns.defaultContent is static and therefore cannot possibly access
  the data.

Also you can remove render from "action" column.

var tablenest = $('#RegSrc').DataTable({
  select: true,
  "bPaginate": false,
  "bFilter": false,
  responsive: true,
  deferRender: true,
  "processing": true,
  "serverSide": false,
  bAutoWidth: true,
  data: [{
    "RecID": 2383,
    "PtFilenum": 15090248,
    "PrtFilenum": 13090701,
    "Fullname": "Salem",
    "PrtStatus": 1,
    "action": "update"
  }, {
    "RecID": 2384,
    "PtFilenum": 15090248,
    "PrtFilenum": 15120996,
    "Fullname": "Tony",
    "PrtStatus": 1,
    "action": "update"
  }, {
    "RecID": 2385,
    "PtFilenum": 15090248,
    "PrtFilenum": 170227111,
    "Fullname": "Jorge",
    "PrtStatus": 1,
    "action": "update"
  }],
  order: [2, 'asc'],
  keys: {
    columns: ':not(:first-child)',
    keys: [9]
  },
  columns: [
  { // Checkbox select column
      data: null,
      defaultContent: '',
      className: 'select-checkbox',
      orderable: false,
      "width": "1%"
    },
    {
      "width": "50%",
      data: "RecID",
      "visible": false
    },
    {
      "width": "50%",
      data: "PtFilenum",
      "visible": false
    },
    {
      "width": "10%",
      data: "PrtFilenum"
    },
    {
      "width": "40%",
      data: "Fullname"
    },
    {
      "width": "10%",
      data: "PrtStatus",
      render: function(data, type, row) {
        if (type === 'display') {
          if (data == 1) {
            return 'Partners';
          } else {
            return 'Not Partners';
          }
        }
        return data;
      },
      className: "dt-body-center"
    },
    {
      "width": "10%",
      data: 'action',
      orderable: false,
      className: "dt-body-center",
      "visible": true
    },
  ],

});
  /* $('#RegSrc tbody').on('click', 'td', function () {
                        console.log(tablenest.cell(this).data());
                    });*/
$("#btn1").click(function() {
  tablenest.rows({
    selected: true
  }).every(function(rowIdx, tableLoop, rowLoop) {
    tablenest.row(this).cell(rowIdx, 6).data('delete').draw()
    var row = tablenest.row(this).node();
    $(row).css('color', 'red').animate({
      color: 'black'
    });
  });
  return false;
})
$("#btn2").click(function() {
  var tbldta = $.map(tablenest.rows().data(), function(d, i) {
    var myObject = new Object();
    console.log(d);
    myObject = {
      action: d.action,
      RecID: d.RecID,
      PrtStatus: d.PrtStatus,
      ptfilenum: d.PtFilenum,
      PrtFilenum: d.PrtFilenum
    }
    return myObject
  });
  var DtaObj = {}
  DtaObj.Data = tbldta
  console.log(JSON.stringify(DtaObj))
  return false;
})

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<script src="https://cdn.datatables.net/1.10.15/js/dataTables.bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://cdn.datatables.net/v/dt/jqc-1.12.4/moment-2.18.1/dt-1.10.15/b-1.3.1/se-1.2.2/datatables.min.js"></script>

<button id="btn2" class="btn btn-primary">build vals</button>
<button id="btn1" class="btn btn-primary">Mark For Delete</button>
<table id="RegSrc" class="table table-bordered table-striped table-condensed mb-none display responsive nowrap" cellspacing="0" width="100%">
  <thead>
    <tr>
    <th>click here to select</th>
      <th><b>RecID</b></th>
      <th><b>Patient File Number</b></th>
      <th><b>Partner File Number</b></th>
      <th><b>Patient Name</b></th>
      <th><b>Status</b></th>
      <th><b>action</b></th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>


问:
When I call the function it shows nothing?
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

This is my script in python 3.5:

```<code>def plin1():
    for i in range(1000,1):
        for j in range(1000,1):
            if str(i*j)==str(i*j)[::-1]:
                break
            return i*j
        print(i,'*',j,'=',i*j)
</code>```

But when I call this function, nothing is printed. What's wrong?

答:
range with two arguments i, j generates the range from i to j. If i > j then there is no range to generate, and when iterating over that range nothing happens.

Range also takes a "step" parameter, allowing you to set the increment of the range. Perhaps you meant to use that. It would look like this:

```<code>for i in range(1, 1000, 1):
    # loop body
</code>```

Note that specifying a step of 1 is redundant, as 1 is the default value for that parameter.

If you want to generate a "do the right thing" range to generate the range from the lesser of (i, j) to the greater, you might write a function like the following:

```<code>def dwim_range(i,j):
    return range(*sorted((i,j)))
</code>```

Here you're sorting the tuple (i, j) and then unpacking it with the * operator so that range gets the two items of the tuple, in sorted order.

Body:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

This is my script in python 3.5:

def plin1():
    for i in range(1000,1):
        for j in range(1000,1):
            if str(i*j)==str(i*j)[::-1]:
                break
            return i*j
        print(i,'*',j,'=',i*j)

But when I call this function, nothing is printed. What's wrong?

Body:
range with two arguments i, j generates the range from i to j. If i > j then there is no range to generate, and when iterating over that range nothing happens.

Range also takes a "step" parameter, allowing you to set the increment of the range. Perhaps you meant to use that. It would look like this:

for i in range(1, 1000, 1):
    # loop body

Note that specifying a step of 1 is redundant, as 1 is the default value for that parameter.

If you want to generate a "do the right thing" range to generate the range from the lesser of (i, j) to the greater, you might write a function like the following:

def dwim_range(i,j):
    return range(*sorted((i,j)))

Here you're sorting the tuple (i, j) and then unpacking it with the * operator so that range gets the two items of the tuple, in sorted order.


问:
MYSQL InnoDB: LOAD DATA INFILE issue with Unique key
Does the performance of LOAD DATA LOCAL INFILE will come down when we use UNIQUE Key Column as to avoid the duplicates?

When i test a .csv file import with Unique and without Unique Key columns, I have following observations:

I see 1 Million records stores/inserts into the table without having any issue without using the Unique key constraint, So it takes duplicates.

With Unique Key constraint on a column to avoid duplicates, I tested with 70k records, it stored well in a minutes time where as for half million records are not inserting/storing into the table and it is running hours of hours through web or MySQL Workbench.  Some times i see following issue:

Error Code: 1205. Lock wait timeout exceeded; try restarting transaction
Query Used:

```<code>LOAD DATA LOCAL INFILE 'file.csv' ignore
    INTO TABLE table1
    CHARACTER SET UTF8mb4 FIELDS
    TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n';`
</code>```

Table structure:

CREATE TABLE table1 (
  Idint(11) NOT NULL AUTO_INCREMENT,
  cUrlvarchar(255) DEFAULT NULL,
  SUrlvarchar(255) DEFAULT NULL,
  FirstNamevarchar(100) DEFAULT NULL,
  LastNamevarchar(100) DEFAULT NULL,
  EmailIdvarchar(150) NOT NULL,
  Filtervarchar(55) DEFAULT NULL,
  Designationvarchar(255) DEFAULT NULL,
  Companyvarchar(255) DEFAULT NULL,
  WebSitevarchar(255) DEFAULT NULL,
  sizevarchar(25) DEFAULT NULL,
  Industryvarchar(255) DEFAULT NULL,
  Typevarchar(25) DEFAULT NULL,
  Foundedvarchar(5) DEFAULT NULL,
  datevarchar(55) NOT NULL,
    PRIMARY KEY (Id),
    UNIQUE KEYEmailId(EmailId`)
  ) ENGINE=InnoDB AUTO_INCREMENT=16812 DEFAULT CHARSET=UTF8mb4;

Applied following steps too:

```<code>set names utf8mb4;
set unique_checks = 0;
set foreign_key_checks = 0;
set sql_log_bin=0;

mysqld select version();
+------------+
| version()  |
+------------+
| 5.7.18-log |
+------------+
1 row in set (0.00 sec)

SELECT @@innodb_buffer_pool_size;
+---------------------------+
| @@innodb_buffer_pool_size |
+---------------------------+
|                   8388608 |
+---------------------------+
1 row in set (0.00 sec)
</code>```

I fixed the UTF8mb4 issue but with Unique key constraint i am failing to import the csv file of half million in the test. I have to work with 40 million records but ofcourse in chucks i will do.

Is it not efficient to use LOAD DATA LOCAL INFILE to import a large csv and with Unique Key constraint.

Suggestions and guidance will be appreciable.

答:
Does the performance of LOAD DATA LOCAL INFILE will come down when we
  use UNIQUE Key Column as to avoid the duplicates?

Yes, LOAD DATA creates non unique indexes in batches to increase performance. Updating the index for each CREATE/DELETE/UPDATE operation on a table adds an extra overhead to those operations. That's why you find your inserts really slow when you have two many indexes.

Index updates for each row cannot be avoided for unique indexes because the next row you insert might be a duplicate.

Still you have no choice here. Loading data by switching off the unique index and then deleting duplicates afterwards will be much much much slower. However there are things you can do to speed things up

Reduce size on disk

You have lot's of varchar columns. I have a feeling that founded, date  and size are integer columns. If yes, they should be created as integer columns. They take up a lot less space. The biggest bottleneck in the LOAD DATA is IO ops. Why make things harder.

Is emailId an email address or a numeric id? if it's an numeric. It two should be marked as integer

Drop the primary key!

It seems redundant to have the emailId as unique while having that auto increment primary key. Drop it and make emailId the primary key. More so if emailid is numeric.

Normalize your Data

Your fundamental problem seems to be that your data isn't normalized. If you normalize it the CSV dump could be much smaller and the data on disk also could be much smaller giving you  big boost.

Body:
Does the performance of LOAD DATA LOCAL INFILE will come down when we use UNIQUE Key Column as to avoid the duplicates?

When i test a .csv file import with Unique and without Unique Key columns, I have following observations:

I see 1 Million records stores/inserts into the table without having any issue without using the Unique key constraint, So it takes duplicates.

With Unique Key constraint on a column to avoid duplicates, I tested with 70k records, it stored well in a minutes time where as for half million records are not inserting/storing into the table and it is running hours of hours through web or MySQL Workbench.  Some times i see following issue:

Error Code: 1205. Lock wait timeout exceeded; try restarting transaction
Query Used:

LOAD DATA LOCAL INFILE 'file.csv' ignore
    INTO TABLE table1
    CHARACTER SET UTF8mb4 FIELDS
    TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n';`

Table structure:

CREATE TABLE table1 (
  Idint(11) NOT NULL AUTO_INCREMENT,
  cUrlvarchar(255) DEFAULT NULL,
  SUrlvarchar(255) DEFAULT NULL,
  FirstNamevarchar(100) DEFAULT NULL,
  LastNamevarchar(100) DEFAULT NULL,
  EmailIdvarchar(150) NOT NULL,
  Filtervarchar(55) DEFAULT NULL,
  Designationvarchar(255) DEFAULT NULL,
  Companyvarchar(255) DEFAULT NULL,
  WebSitevarchar(255) DEFAULT NULL,
  sizevarchar(25) DEFAULT NULL,
  Industryvarchar(255) DEFAULT NULL,
  Typevarchar(25) DEFAULT NULL,
  Foundedvarchar(5) DEFAULT NULL,
  datevarchar(55) NOT NULL,
    PRIMARY KEY (Id),
    UNIQUE KEYEmailId(EmailId`)
  ) ENGINE=InnoDB AUTO_INCREMENT=16812 DEFAULT CHARSET=UTF8mb4;

Applied following steps too:

set names utf8mb4;
set unique_checks = 0;
set foreign_key_checks = 0;
set sql_log_bin=0;

mysqld select version();
+------------+
| version()  |
+------------+
| 5.7.18-log |
+------------+
1 row in set (0.00 sec)

SELECT @@innodb_buffer_pool_size;
+---------------------------+
| @@innodb_buffer_pool_size |
+---------------------------+
|                   8388608 |
+---------------------------+
1 row in set (0.00 sec)

I fixed the UTF8mb4 issue but with Unique key constraint i am failing to import the csv file of half million in the test. I have to work with 40 million records but ofcourse in chucks i will do.

Is it not efficient to use LOAD DATA LOCAL INFILE to import a large csv and with Unique Key constraint.

Suggestions and guidance will be appreciable.


问:
Visual studio view (.cshtml) crashed and cannot recover
My view file(.cshtml) crashed and turned into as shown in image below. Actually, it happened right after the system was unexpectedly shut down. I tried other solutions like clearing temp files from bin. I tried to open it with notepad++ but it didn't work.
Any help will be appreciated.

答:
If you have published your content, then in visual studio you can right click on the specific file and choose 'replace [fileName] from server'. This will download an uncorrupted version of your content from the published site.

Hope this helps.


问:
In Complexity Analysis why is ++ considered to be 2 operations?
In my Computer Science II class, the professor considers ++,--,*=, etc. to be 2 operations. However, at the Assembly level this is not really two operations. Can someone explain or is this just for the sake of simplicity?</p>

答:
Why bother when doing complexity analysis? It is just O(1) :-)

EDIT: Please let me know why when you vote it down. Since the question is tagged complexity, I assume big O notion is the most important, rather than the actual constants. Besides, as already mentioned in other answers, how many operations this is depends on a lot of factors: the way you count operations, platform, compiler, etc.

OwnerDisplayName: PolyThinker

LastEditorDisplayName: PolyThinker


问:
Is there a better way to write this navigation statement?
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!</p>

```<code>$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});
</code>```

答:
You have a lot of code which can be condensed. Try this:</p>

```<code>$('.nav li a').click(function()
{
  $('.nav li a').removeClass('active');
  $(this).addClass('active');
});
</code>```

Body:
I know this is a redundant way to write these rules so I'm wondering if anyone knows a better way to write it. Thanks!

$('.nav li a').eq(0).click(function() {

    $('.nav li a').eq(0).addClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(1).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).addClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(2).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).addClass("active");
    $('.nav li a').eq(3).removeClass("active");

});
$('.nav li a').eq(3).click(function() {

    $('.nav li a').eq(0).removeClass("active");
    $('.nav li a').eq(1).removeClass("active");
    $('.nav li a').eq(2).removeClass("active");
    $('.nav li a').eq(3).addClass("active");

});

Body:
You have a lot of code which can be condensed. Try this:

$('.nav li a').click(function()
{
  $('.nav li a').removeClass('active');
  $(this).addClass('active');
});


问:
Defer Node.js HTTP requests if similar work already being done
I'm making a service which retrieves a photograph from a remote host and does some processing before passing it on to the client. It caches the retrieved source photo locally to avoid retrieving it again later on.

However, if there are several requests in rapid succession, the source image will not yet have been saved locally, and unnecessary retrievals are performed.

What is a nice approach to defer the incoming requests until the source image is cached, provided it's already currently being retrieved?

I'm currently using Node.js streams all the way from the inbound request stream, passing it through my caching and transformation logic, passing it to the outbound stream.

答:
You can cache the promise so all incoming requests to the same resource will only require one trip, avoiding flooding the database or some API.

```<code>const Cache = {};

function getPhoto(photoId) {

    let cacheKey = `photo-${photoId}`;
    let photoCache = Cache[cacheKey];

    if (photoCache instanceof Promise)
        return photoCache; //Return the promise from the cache

    let promise = new Promise((resolve, reject) => {

        if (photoCache) //Return the photo if exists in cache.
            return resolve(photoCache);

        return processPhoto(photoId).then(response => {
            //Override the promise with the actual response
            Cache[cacheKey] = response;
            resolve(response);

        }).catch(err => {
            Cache[cacheKey] = null; //We don't want the rejected promise in cache!
            reject();
        });

    });

    if (!photoCache)
        Cache[cacheKey] = promise; //Save the promise

    return promise;
}

function processPhoto(photoId){

 return new Promise((resolve, reject) => {

      // Get the image from somewhere...
      // Process it or whatever you need

      //...
      resolve('someResponse');
 });

}
</code>```

First request to a specific photo will perform the lookup, and will store the promise in the cache.

Second request comes in and if the photo from first request hasn't yet been retrieved, getPhoto will return the same promise, when the promise is resolved, both requests will get the same response.

Third request comes after the photo has been already retrieved, since the photo is cached it will just return the response.

Body:
You can cache the promise so all incoming requests to the same resource will only require one trip, avoiding flooding the database or some API.

const Cache = {};

function getPhoto(photoId) {

    let cacheKey = `photo-${photoId}`;
    let photoCache = Cache[cacheKey];

    if (photoCache instanceof Promise)
        return photoCache; //Return the promise from the cache

    let promise = new Promise((resolve, reject) => {

        if (photoCache) //Return the photo if exists in cache.
            return resolve(photoCache);

        return processPhoto(photoId).then(response => {
            //Override the promise with the actual response
            Cache[cacheKey] = response;
            resolve(response);

        }).catch(err => {
            Cache[cacheKey] = null; //We don't want the rejected promise in cache!
            reject();
        });

    });

    if (!photoCache)
        Cache[cacheKey] = promise; //Save the promise

    return promise;
}

function processPhoto(photoId){

 return new Promise((resolve, reject) => {

      // Get the image from somewhere...
      // Process it or whatever you need

      //...
      resolve('someResponse');
 });

}

First request to a specific photo will perform the lookup, and will store the promise in the cache.

Second request comes in and if the photo from first request hasn't yet been retrieved, getPhoto will return the same promise, when the promise is resolved, both requests will get the same response.

Third request comes after the photo has been already retrieved, since the photo is cached it will just return the response.