问:
Divide a Set into Subsets of objects having equal field?
I am currently trying to implement a data structure in java, and would like to divide a set of input objects, into different subsets of objects having an equal field.

An example use case:

We want to divide a list of persons to sub list of persons being born a certain date.

Input: person1 born 1990, person2 born 2000, person3 born 1990.

Output:

1 -> person1, person3

2 -> person2

```<code>public Map<Integer, List<Foo>> getIntToFooMap(List<Foo> foos) {
    Map<Integer, List<Foo>> map = new TreeMap<>(); // need keys to be automatically ordered.
    List<Foo> foosWithSameSetId = new ArrayList<>();
    if (!foos.isEmpty) {
       for (Foo foo: foos) {
           for (Foo foo2: foos) {
               if (foo.getSetId().equals(foo2.getSetId())) {
                   foosWithSameSetId.add(foo2);
               }
           }
        map.put(foo.getSetId(), foosWithSameSetId);
        foosWithSameSetId.clear();
       }
    }
  return map;
 }
</code>```

The code above is not optimal, the time complexity is quadratic, and also not thread safe.
Can someone tell me of a better way to divide a List or a Set into subsets of objects having an equal field, in this case the setId.

答:
The Answer by ernest_k is correct and clear. Here is more code, a full example.

First, define a class for Person.

```<code>package work.basil.example;

import java.time.LocalDate;
import java.util.Objects;

public class Person
{
    // ----------|  Member fields  |----------------------
    public String name;
    public LocalDate birthdate;

    // ----------|  Constructor  |----------------------
    public Person ( String name , LocalDate birthdate )
    {
        this.name = Objects.requireNonNull( name );
        this.birthdate = Objects.requireNonNull( birthdate );
    }

    // ----------|  Object  |----------------------

    @Override
    public String toString ( )
    {
        return "Person{ " +
                "name='" + name + '\'' +
                " | birthdate=" + birthdate +
                " }";
    }

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        Person person = ( Person ) o;
        return name.equals( person.name ) &&
                birthdate.equals( person.birthdate );
    }

    @Override
    public int hashCode ( )
    {
        return Objects.hash( name , birthdate );
    }
}
</code>```

Populate some sample data. The Set.of syntax added to Java 9 gives us simple literals syntax.

```<code>Set < Person > persons = Set.of(
        new Person( "Alice" , LocalDate.of( 1990 , Month.JANUARY , 23 ) ) ,
        new Person( "Bob" , LocalDate.of( 2000 , Month.FEBRUARY , 24 ) ) ,
        new Person( "Carol" , LocalDate.of( 1990 , Month.MARCH , 25 ) )
);
</code>```

Concurrency

Define the Map we want to populate. You mentioned concurrency as an issue, that is, sharing this map across threads. So we should use one of the two classes bundled with Java that implement the ConcurrentMap interface.

Here is a graphic table I made showing the attributes of the various Map implementations bundled with Java.

Here we choose to use ConcurrentHashMap. The alternative, ConcurrentSkipListMap might be better if you had large numbers of objects, or if you wanted to maintain the keys (Year in our case) in a certain order.

```<code>Map < Year, List < Person > > yearToListOfPersonsMap = new ConcurrentHashMap <>();
</code>```

Data types

Notice the appropriate use of data types. Java offers a Year class to represent an entire year. So we should use it. Doing so makes our code more self-documenting.

On the Person class, we represent a birth date using LocalDate. That class is for a date-only value without time-of-day and without time zone.

Multimap

We will extract the year from each person’s birthdate as the key to our map. The value is a List of Person objects, to which we add the person object in question.

If you wanted to eliminate any possible duplicate Person objects from being collected, you could use a Set here rather than a List.

The Map::computeIfAbsent method added in Java 8 does the work of what is known as a multimap, a map where a key leads to a collection of values rather than a single value. Alternatively, you could use a multipmap implementation from a third-party such as the Google Guava library.

```<code>for ( Person person : persons )
{
    yearToListOfPersonsMap.computeIfAbsent(
            Year.from( person.birthdate ) ,
            ( ( Year key ) -> new ArrayList <>() )
    ).add( person )
    ;
}
</code>```

Dump to console.

```<code>System.out.println( "yearToListOfPersonsMap = " + yearToListOfPersonsMap );
</code>```

yearToListOfPersonsMap = {2000=[Person{ name='Bob' | birthdate=2000-02-24 }], 1990=[Person{ name='Alice' | birthdate=1990-01-23 }, Person{ name='Carol' | birthdate=1990-03-25 }]}

Body:
I am currently trying to implement a data structure in java, and would like to divide a set of input objects, into different subsets of objects having an equal field.

An example use case:

We want to divide a list of persons to sub list of persons being born a certain date.

Input: person1 born 1990, person2 born 2000, person3 born 1990.

Output:

1 -> person1, person3

2 -> person2

public Map<Integer, List<Foo>> getIntToFooMap(List<Foo> foos) {
    Map<Integer, List<Foo>> map = new TreeMap<>(); // need keys to be automatically ordered.
    List<Foo> foosWithSameSetId = new ArrayList<>();
    if (!foos.isEmpty) {
       for (Foo foo: foos) {
           for (Foo foo2: foos) {
               if (foo.getSetId().equals(foo2.getSetId())) {
                   foosWithSameSetId.add(foo2);
               }
           }
        map.put(foo.getSetId(), foosWithSameSetId);
        foosWithSameSetId.clear();
       }
    }
  return map;
 }

The code above is not optimal, the time complexity is quadratic, and also not thread safe.
Can someone tell me of a better way to divide a List or a Set into subsets of objects having an equal field, in this case the setId.

Body:
The Answer by ernest_k is correct and clear. Here is more code, a full example.

First, define a class for Person.

package work.basil.example;

import java.time.LocalDate;
import java.util.Objects;

public class Person
{
    // ----------|  Member fields  |----------------------
    public String name;
    public LocalDate birthdate;

    // ----------|  Constructor  |----------------------
    public Person ( String name , LocalDate birthdate )
    {
        this.name = Objects.requireNonNull( name );
        this.birthdate = Objects.requireNonNull( birthdate );
    }

    // ----------|  Object  |----------------------

    @Override
    public String toString ( )
    {
        return "Person{ " +
                "name='" + name + '\'' +
                " | birthdate=" + birthdate +
                " }";
    }

    @Override
    public boolean equals ( Object o )
    {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;
        Person person = ( Person ) o;
        return name.equals( person.name ) &&
                birthdate.equals( person.birthdate );
    }

    @Override
    public int hashCode ( )
    {
        return Objects.hash( name , birthdate );
    }
}

Populate some sample data. The Set.of syntax added to Java 9 gives us simple literals syntax.

Set < Person > persons = Set.of(
        new Person( "Alice" , LocalDate.of( 1990 , Month.JANUARY , 23 ) ) ,
        new Person( "Bob" , LocalDate.of( 2000 , Month.FEBRUARY , 24 ) ) ,
        new Person( "Carol" , LocalDate.of( 1990 , Month.MARCH , 25 ) )
);

Concurrency

Define the Map we want to populate. You mentioned concurrency as an issue, that is, sharing this map across threads. So we should use one of the two classes bundled with Java that implement the ConcurrentMap interface.

Here is a graphic table I made showing the attributes of the various Map implementations bundled with Java.

Here we choose to use ConcurrentHashMap. The alternative, ConcurrentSkipListMap might be better if you had large numbers of objects, or if you wanted to maintain the keys (Year in our case) in a certain order.

Map < Year, List < Person > > yearToListOfPersonsMap = new ConcurrentHashMap <>();

Data types

Notice the appropriate use of data types. Java offers a Year class to represent an entire year. So we should use it. Doing so makes our code more self-documenting.

On the Person class, we represent a birth date using LocalDate. That class is for a date-only value without time-of-day and without time zone.

Multimap

We will extract the year from each person’s birthdate as the key to our map. The value is a List of Person objects, to which we add the person object in question.

If you wanted to eliminate any possible duplicate Person objects from being collected, you could use a Set here rather than a List.

The Map::computeIfAbsent method added in Java 8 does the work of what is known as a multimap, a map where a key leads to a collection of values rather than a single value. Alternatively, you could use a multipmap implementation from a third-party such as the Google Guava library.

for ( Person person : persons )
{
    yearToListOfPersonsMap.computeIfAbsent(
            Year.from( person.birthdate ) ,
            ( ( Year key ) -> new ArrayList <>() )
    ).add( person )
    ;
}

Dump to console.

System.out.println( "yearToListOfPersonsMap = " + yearToListOfPersonsMap );

yearToListOfPersonsMap = {2000=[Person{ name='Bob' | birthdate=2000-02-24 }], 1990=[Person{ name='Alice' | birthdate=1990-01-23 }, Person{ name='Carol' | birthdate=1990-03-25 }]}


来源: stackexchange

问:
Why use static_cast rather than dynamic_cast in here?
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

```<code>class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
</code>```

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}
</code>```

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

```<code>class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
</code>```

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

答: This seems like a pretty solid answer.  Basically static cast is faster but doesn't do runtime type checking.</p>

ContentLicense: CC BY-SA 3.0

Body:
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?


问:
Finding most common occurrence of a character that follows another
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to (because I cannot, for the life of me, figure it out) find the most common occurrence of a character that follows a specific character or string?

For example, say I have the following sentence:

```<code>"this is a test sentence that happens to be short"
</code>```

How would could I determine, for example, the most common character that occurs after the letter h?

In this specific example, doing it by hand, I get something like this:

{"i": 1, "a": 2, "o": 1}

I'd then like to be able to get the key of the highest value--in this case, a.

Using Counter from collections, I've been able to find the most common occurrence of a specific word or character, but I'm not sure how to do this specific implementation of doing the most common occurrence after. Any help would be greatly appreciated, thanks!

(The code I wrote to find the most common occurrence of a letter in a file:
 Counter(text).most_common(1), which does include white spaces )

EDIT:

How would this be done with words? For example, if I had the sentence: "whales are super neat, but whales don't make good pets. whales are cool."
How would I find the most common character that occurs after the words whales?
In this instance, removing white spaces, the most common character would be a

答:
Using the Counter class we can try:

```<code>import collections
s = "this is a test sentence that happens to be short"
s = re.sub(r'^.*n|\s*', '', s)
print(collections.Counter(s).most_common(1)[0])
</code>```

The above would print o as it is the most frequent character occurring after the last n.  Note that we also strip off whitespace before calling collections count.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently working on a small piece of code and I seem to have run into a roadblock. I was wondering if it's possible to (because I cannot, for the life of me, figure it out) find the most common occurrence of a character that follows a specific character or string?

For example, say I have the following sentence:

"this is a test sentence that happens to be short"

How would could I determine, for example, the most common character that occurs after the letter h?

In this specific example, doing it by hand, I get something like this:

{"i": 1, "a": 2, "o": 1}

I'd then like to be able to get the key of the highest value--in this case, a.

Using Counter from collections, I've been able to find the most common occurrence of a specific word or character, but I'm not sure how to do this specific implementation of doing the most common occurrence after. Any help would be greatly appreciated, thanks!

(The code I wrote to find the most common occurrence of a letter in a file:
 Counter(text).most_common(1), which does include white spaces )

EDIT:

How would this be done with words? For example, if I had the sentence: "whales are super neat, but whales don't make good pets. whales are cool."
How would I find the most common character that occurs after the words whales?
In this instance, removing white spaces, the most common character would be a

Body:
Using the Counter class we can try:

import collections
s = "this is a test sentence that happens to be short"
s = re.sub(r'^.*n|\s*', '', s)
print(collections.Counter(s).most_common(1)[0])

The above would print o as it is the most frequent character occurring after the last n.  Note that we also strip off whitespace before calling collections count.


问:
Dropping Unused Indexes
I am referring the Unused Index Script blog.

I got to know that if Seek = 0, Scan = 0, Lookup = 0, User Update = 0 then we should delete index as it is not needed.

The unused script gives me many indexes but should I delete all those indexes? Can you please help me to understand to identify actual unused index from the given script.

I would like to know the importance between UserSeek, UserScans, UserLookups, UserUpdates column before I delete.

答:
The seeks, scans and lookups are read operations which are beneficial to query performance. The updates are inserts into or updates to the index. These updates are considered a negative side affect of indexing.

The first and only rule in the black art of indexing is: take a backup of the indexes before you change them. Just script them out and save them for later. Be sure to date the file so you can correlate any database performance degradation.

A few things to understand:

The columns you are referencing (UserSeeks, etc.) are coming from a MSSQL DMV (Dynamic Management View). These metrics are ephemeral, meaning they are reset every time the service is restarted (such as a server reboot). So keep in mind that the seeks, scans, etc will not reflect historical activity.

Even is an index has a lot of updates and few beneficial operations - the beneficial operations may be very important. They (for example) may be responsible for making a query that would otherwise run for an hour execute in a second or so.

Even if you don't see beneficial activity on an index for months, it may still be used by some rarely accessed part of the software that uses the software - like some kind of monthly or yearly maintenance.

So again, backup the indexes before you remove anything.

Title: Dropping Unused Indexes


问:
Image disappear when use NavigationPage inside TabbedPage Xamarin
I tried to make NavigationPage inside my tabbed page For first i used this code in my app.xaml.cs

```<code>    var tabbedPage = new Xamarin.Forms.TabbedPage();
    tabbedPage.On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
    tabbedPage.BarBackgroundColor = Color.White;
    tabbedPage.Children.Add(new MainPage()  { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    MainPage = tabbedPage;
</code>```

Ok it works perfect.But when i tried with this -

```<code>tabbedPage.Children.Add(new NavigationPage(new MainPage()  { Title = "myTabName", Icon = "Icon.png" }));
</code>```

My Icon and title disappear.I dont know how to fix it

答:
You should add the icon and title on the NavigationPage:

```<code>tabbedPage.Children.Add(new NavigationPage(new MainPage()) { Title = "myTabName", Icon = "Icon.png" });
</code>```

Body:
I tried to make NavigationPage inside my tabbed page For first i used this code in my app.xaml.cs

    var tabbedPage = new Xamarin.Forms.TabbedPage();
    tabbedPage.On<Android>().SetToolbarPlacement(ToolbarPlacement.Bottom);
    tabbedPage.BarBackgroundColor = Color.White;
    tabbedPage.Children.Add(new MainPage()  { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    tabbedPage.Children.Add(new MainPage() { Title = "myTabName", Icon = "Icon.png" });
    MainPage = tabbedPage;

Ok it works perfect.But when i tried with this -

tabbedPage.Children.Add(new NavigationPage(new MainPage()  { Title = "myTabName", Icon = "Icon.png" }));

My Icon and title disappear.I dont know how to fix it

Body:
You should add the icon and title on the NavigationPage:

tabbedPage.Children.Add(new NavigationPage(new MainPage()) { Title = "myTabName", Icon = "Icon.png" });


问:
add two lists then sort = None(?)
Second list squared each item on list, xs. Running the code below, python gives me 'None'

```<code>xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')
</code>```

Same list but different code--

```<code>xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, end=', ')
</code>```

...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

Thanks!

答:
Generally speaking, anything that operates on something in-place will return None, by convention. (This convention is not necessarily always followed, however.)  somelist.sort() will sort the list in-place.

If you'd rather have a sorted copy, you can just call c = sorted(a + xs).  sorted operates on a copy of the original, and therefore returns the copy.

There's a much more through explanation here: http://wiki.python.org/moin/HowTo/Sorting/

Title: add two lists then sort = None(?)

Body:
Second list squared each item on list, xs. Running the code below, python gives me 'None'

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')

Same list but different code--

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, end=', ')

...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

Thanks!


问:
passing multiple arguments in rename_all()
To tidy up column names, is there a way to pass multiple arguments in rename_all()?

Example: I'd like to cleaning up the following column names by changing them all to lower, removing the ., and replacing the spaces with _ using rename_all()

```<code>> colnames(tibble("COLUMN 1." = (1:3), "column 2." = (1:3)))
[1] "COLUMN 1." "column 2."
</code>```

And I can do it as follows:

```<code>> tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
+     rename_all(tolower) %>%
+     rename_all(~gsub("\\ ", "_", .x)) %>%
+     rename_all(~gsub("\\.", "", .x))
# A tibble: 3 x 2
  column_1 column_2
     <int>    <int>
1        1        1
2        2        2
3        3        3
</code>```

But is there a way to do this with one call of rename_all() instead of 3?

答:
You can combine gsub with chartr

```<code>tibble::tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
       dplyr::rename_all(~gsub("\\.", "", chartr(" ", "_", tolower(.x))))

#  column_1 column_2
#     <int>    <int>
#1        1        1
#2        2        2
#3        3        3
</code>```

Or we can use mgsub which as the name suggests uses multiple gsub

```<code>tibble::tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
   dplyr::rename_all(~mgsub::mgsub(tolower(.), c('\\.', ' '), c('', '_')))
</code>```

Body:
To tidy up column names, is there a way to pass multiple arguments in rename_all()?

Example: I'd like to cleaning up the following column names by changing them all to lower, removing the ., and replacing the spaces with _ using rename_all()

> colnames(tibble("COLUMN 1." = (1:3), "column 2." = (1:3)))
[1] "COLUMN 1." "column 2."

And I can do it as follows:

> tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
+     rename_all(tolower) %>%
+     rename_all(~gsub("\\ ", "_", .x)) %>%
+     rename_all(~gsub("\\.", "", .x))
# A tibble: 3 x 2
  column_1 column_2
     <int>    <int>
1        1        1
2        2        2
3        3        3

But is there a way to do this with one call of rename_all() instead of 3?

Body:
You can combine gsub with chartr

tibble::tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
       dplyr::rename_all(~gsub("\\.", "", chartr(" ", "_", tolower(.x))))

#  column_1 column_2
#     <int>    <int>
#1        1        1
#2        2        2
#3        3        3

Or we can use mgsub which as the name suggests uses multiple gsub

tibble::tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
   dplyr::rename_all(~mgsub::mgsub(tolower(.), c('\\.', ' '), c('', '_')))


问:
What is _md5.md5 and why is hashlib.md5 so much slower?
Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation.

On a macbook:

```<code>>>> timeit hashlib.md5(b"hello world")
597 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"hello world")
224 ns ± 3.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_md5.cpython-37m-darwin.so'>
</code>```

On a Windows box:

```<code>>>> timeit hashlib.md5(b"stonk overflow")
328 ns ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"stonk overflow")
110 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' (built-in)>
</code>```

On a Linux box:

```<code>>>> timeit hashlib.md5(b"https://adventofcode.com/2016/day/5")
259 ns ± 1.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"https://adventofcode.com/2016/day/5")
102 ns ± 0.0576 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/lib/python3.8/lib-dynload/_md5.cpython-38-x86_64-linux-gnu.so'>
</code>```

For hashing short messages, it's way faster. For long messages, similar performance.

Why is it hidden away in an underscore extension module, and why isn't this faster implementation used by default in hashlib?  What is the _md5 module and why doesn't it have public API?

答:
My theory from looking around on bugs.python.org and reading the cpython git commit history:

cpython switched to openssl md5 in 2005 because it was faster than the built-in implementation. They added a new built-in implementation in 2007 that is faster than openssl but never switched back.  Both of these changes were done by Gregory P. Smith.

Here's my evidence.

In 2005, Greg created the bpo issue "sha and md5 modules should use OpenSSL when possible". This change made in this commit.

In 2007, Greg added the new, fast md5 module in this commit.

The _md5 implementation appears to be essentially the same in Python 3.8 (I'm looking at commit ea316fd21527)

I think the cpython maintainers would probably be open to switching back to _md5 when it is available, since it's no longer true that the openssl implementation is faster (and may have been untrue for the last 13 years).

Body:
Found this undocumented _md5 when getting frustrated with the slow stdlib hashlib.md5 implementation.

On a macbook:

>>> timeit hashlib.md5(b"hello world")
597 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"hello world")
224 ns ± 3.18 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/Cellar/python/3.7.6_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_md5.cpython-37m-darwin.so'>

On a Windows box:

>>> timeit hashlib.md5(b"stonk overflow")
328 ns ± 21.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"stonk overflow")
110 ns ± 12.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' (built-in)>

On a Linux box:

>>> timeit hashlib.md5(b"https://adventofcode.com/2016/day/5")
259 ns ± 1.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit _md5.md5(b"https://adventofcode.com/2016/day/5")
102 ns ± 0.0576 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> _md5
<module '_md5' from '/usr/local/lib/python3.8/lib-dynload/_md5.cpython-38-x86_64-linux-gnu.so'>

For hashing short messages, it's way faster. For long messages, similar performance.

Why is it hidden away in an underscore extension module, and why isn't this faster implementation used by default in hashlib?  What is the _md5 module and why doesn't it have public API?


问:
Why can't I return the string person into main? It gives me a error saying that the string "person" is not in the context even though I returned it?
It gives me this error even though the function should have returned the value person? Is it because I can't return strings? if that's so, then is there a way around it?

main.cs(7,23): error CS0103: The name `person' does not exist in the current context.

```<code>
class MainClass {
  public static void Main (string[] args)
  {
    CreateName();
    Console.WriteLine(person);
  }
  static string CreateName(){
    Console.Write("Enter a name: ");
    string person = Console.ReadLine();
    return person;
  }
}
</code>```

答:
your not catching the call. you need to do this</p>

```<code>var person = CreateName();
</code>```

Body:
It gives me this error even though the function should have returned the value person? Is it because I can't return strings? if that's so, then is there a way around it?

main.cs(7,23): error CS0103: The name `person' does not exist in the current context.

class MainClass {
  public static void Main (string[] args)
  {
    CreateName();
    Console.WriteLine(person);
  }
  static string CreateName(){
    Console.Write("Enter a name: ");
    string person = Console.ReadLine();
    return person;
  }
}

Body:
your not catching the call. you need to do this

var person = CreateName();


问:
problem with passing datetime to reporting service from asp.net
i'm using SSRS2008 and asp.net on VS2008 SP1.

i have found a problem when i tried to pass parameter from asp.net to reporting service.

in my c# code, i added report parameter with date value of "05/01/2011" ( 1 May 2011 ) but it became "5 Jan 2011" in rdl file instead.

is it possible that this problem might come from different regional/system locale setting in server?
because i did not found this problem on my development computer which was set to US location.

Please give me any suggestion on this issue.

Thanks in adv.

vcha

答: It looks like you are passing the date as a string? In that case I have had most success bypassing date format internationalisation problems by using a military style date format of "YYYY-MM-DD". In your example, your date would be "2011-05-01". Reporting Services always decodes this date format correctly.</p>


问:
Add auto generated field and value to database
I am working on a program whereby I need to add an auto generated field and value to my database. So to put it in context, I have a program where I can do normal CRUD operations and this is connected using swagger. I have a vouchers table where I want an auto generated text field which I have code for and I want to be able to enter an amount and it auto populates the fields in the database. The code is as follows:

My Voucher controller:

```<code>    [Route("[controller]")]
[ApiController]
public class VouchersController : ControllerBase
{
    private readonly ComicStockContext _context;

    private IVoucherService _voucherService;

    public VouchersController(ComicStockContext context, IVoucherService voucherService)
    {
        _context = context;
        _voucherService = voucherService;
    }

    // GET: api/Vouchers
    [HttpGet]
    public IEnumerable<Vouchers> GetAllVouchers([FromQuery] int page)
    {
        return _voucherService.GetAllVouchers(page);
    }

    [HttpGet("generate")]
    // code to insert amount and generated string needs to go here
</code>```

My interface for vouchers service:

```<code>    namespace BusinessLogic.ServicesInterfaces
{
    public  interface IVoucherService
    {
        IEnumerable<Vouchers> GetAllVouchers(int page);

        Vouchers FindVoucherByID(int voucherID);

        void InsertVoucher(Vouchers vouchers);

    }
}
</code>```

My Vouchers Service

```<code>    public class VoucherService: IVoucherService
{
    private IVoucherRepository _voucherRepository;

    public VoucherService(IVoucherRepository voucherRepository)
    {
        _voucherRepository = voucherRepository;
    }

    public IEnumerable<Vouchers> GetAllVouchers(int page)
    {
        return _voucherRepository.GetAllVouchers(page);
    }

    public Vouchers FindVoucherByID(int voucherID)
    {
        return _voucherRepository.FindVoucherByID(voucherID);
    }

    public void InsertVoucher(Vouchers vouchers)
    {
        _voucherRepository.InsertVoucher(vouchers);
    }

    public void InsertGeneratedVoucher(string vouchercode, int amount)
    {
         String GetVoucherNumber()
        {
            int size = 20;
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }
        vouchercode = GetVoucherNumber();
        //_voucherRepository.InsertGeneratedVoucher(vouchercode, amount);
    }
}
</code>```

My Vouchers Repository

```<code>    public class VoucherRepository: GenericRepository<Vouchers>, IVoucherRepository
{
    public VoucherRepository(): base()
    {
    }

    public VoucherRepository(ComicStockContext comicStockContext) : base(comicStockContext)
    {
    }

    public Vouchers FindVoucherByID(int voucherID)
    {
        return GetById(voucherID);
    }

    public IEnumerable<Vouchers> GetAllVouchers(int page)
    {
        return GetAll(page);
    }

    public void InsertVoucher(Vouchers vouchers)
    {
        Insert(vouchers);
    }
}
}
</code>```

My Interface for voucher repository

```<code>{
public interface IVoucherRepository
{
    IEnumerable<Vouchers> GetAllVouchers(int page);

    Vouchers FindVoucherByID(int voucherID);

    void InsertVoucher(Vouchers vouchers);
</code>```

And my generic base repository

```<code>{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    protected ComicStockContext _context = null;
    protected DbSet<T> table = null;

    public GenericRepository()
    {
        this._context = new ComicStockContext();
        table = _context.Set<T>();
    }

    public GenericRepository(ComicStockContext context)
    {
        _context = context;
        table = _context.Set<T>();
    }

    public IEnumerable<T> GetAll(int page)
    {
        return table.ToList().Skip(25 * page).Take(25);
    }
    public T GetById(object id)
    {
        return table.Find(id);
    }
    public void Insert(T obj)
    {
        table.Add(obj);
        Save();
    }
    public void Update(T obj)
    {
        table.Attach(obj);
        _context.Entry(obj).State = EntityState.Modified;
        Save();
    }
    public void Delete(object id)
    {
        T existing = table.Find(id);
        table.Remove(existing);
    }
    public void Save()
    {
        _context.SaveChanges();
    }

}
}
</code>```

As well as the interface for the generic repository

```<code>    public interface IGenericRepository<T> where T : class
{
    IEnumerable<T> GetAll(int page);
    T GetById(object id);
    void Insert(T obj);
    void Update(T obj);
    void Delete(object id);
    void Save();
}
</code>```

So basically the code which I am trying to achieve is, I must be able to insert an amount using swagger, for example $100 and it must insert the $100 in my vouchers table along with an auto generated string, and the rest of the fields should just populate as Null.

答:
You've got the method to generate your voucher code, good or bad, so where is the problem? Is this a framework that someone else laid out that you don't quite understand yet because while generic repository patterns like this are rather anemic, from what I can see your code is 90% there:

```<code>public void InsertGeneratedVoucher(int amount)
{
    // TODO: Assert that your Amount is valid.. For instance can it be 0? <0??

    string GetVoucherNumber()
    {
        int size = 20;
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        // TODO: Check for duplicates?
        return builder.ToString();
    }
    var voucher = new Vouchers
    {
        Vouchercode = GetVoucherNumber();
        Amount = amount;
    };
    _voucherRepository.Insert(voucher);
}
</code>```

There is no point accepting a VoucherCode if you want this method to generate a new one. If you want to return it, use a return value on the method. If you can accept a voucher code from the caller then it should be validated to check for duplicates and that it is valid etc. All arguments to a method should be asserted/validated. The method to build a voucher number should probably be moved out to a separate utility method, and you should consider adding a check for duplicate voucher numbers once one is generated. A simpler alternative would be Guid.New().ToString("N") will provide a effective "random" 32 character code. Truncating it to 20 characters will weaken it but it avoids easily confused letters (0 vs O).

The only other thing is that your service should ensure that all required fields (non-null-able) for this new voucher are either provided as parameters or generated within this method.

Body:
I am working on a program whereby I need to add an auto generated field and value to my database. So to put it in context, I have a program where I can do normal CRUD operations and this is connected using swagger. I have a vouchers table where I want an auto generated text field which I have code for and I want to be able to enter an amount and it auto populates the fields in the database. The code is as follows:

My Voucher controller:

    [Route("[controller]")]
[ApiController]
public class VouchersController : ControllerBase
{
    private readonly ComicStockContext _context;

    private IVoucherService _voucherService;

    public VouchersController(ComicStockContext context, IVoucherService voucherService)
    {
        _context = context;
        _voucherService = voucherService;
    }

    // GET: api/Vouchers
    [HttpGet]
    public IEnumerable<Vouchers> GetAllVouchers([FromQuery] int page)
    {
        return _voucherService.GetAllVouchers(page);
    }

    [HttpGet("generate")]
    // code to insert amount and generated string needs to go here

My interface for vouchers service:

    namespace BusinessLogic.ServicesInterfaces
{
    public  interface IVoucherService
    {
        IEnumerable<Vouchers> GetAllVouchers(int page);

        Vouchers FindVoucherByID(int voucherID);

        void InsertVoucher(Vouchers vouchers);

    }
}

My Vouchers Service

    public class VoucherService: IVoucherService
{
    private IVoucherRepository _voucherRepository;

    public VoucherService(IVoucherRepository voucherRepository)
    {
        _voucherRepository = voucherRepository;
    }

    public IEnumerable<Vouchers> GetAllVouchers(int page)
    {
        return _voucherRepository.GetAllVouchers(page);
    }

    public Vouchers FindVoucherByID(int voucherID)
    {
        return _voucherRepository.FindVoucherByID(voucherID);
    }

    public void InsertVoucher(Vouchers vouchers)
    {
        _voucherRepository.InsertVoucher(vouchers);
    }

    public void InsertGeneratedVoucher(string vouchercode, int amount)
    {
         String GetVoucherNumber()
        {
            int size = 20;
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }
        vouchercode = GetVoucherNumber();
        //_voucherRepository.InsertGeneratedVoucher(vouchercode, amount);
    }
}

My Vouchers Repository

    public class VoucherRepository: GenericRepository<Vouchers>, IVoucherRepository
{
    public VoucherRepository(): base()
    {
    }

    public VoucherRepository(ComicStockContext comicStockContext) : base(comicStockContext)
    {
    }

    public Vouchers FindVoucherByID(int voucherID)
    {
        return GetById(voucherID);
    }

    public IEnumerable<Vouchers> GetAllVouchers(int page)
    {
        return GetAll(page);
    }

    public void InsertVoucher(Vouchers vouchers)
    {
        Insert(vouchers);
    }
}
}

My Interface for voucher repository

{
public interface IVoucherRepository
{
    IEnumerable<Vouchers> GetAllVouchers(int page);

    Vouchers FindVoucherByID(int voucherID);

    void InsertVoucher(Vouchers vouchers);

And my generic base repository

{
public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    protected ComicStockContext _context = null;
    protected DbSet<T> table = null;

    public GenericRepository()
    {
        this._context = new ComicStockContext();
        table = _context.Set<T>();
    }

    public GenericRepository(ComicStockContext context)
    {
        _context = context;
        table = _context.Set<T>();
    }

    public IEnumerable<T> GetAll(int page)
    {
        return table.ToList().Skip(25 * page).Take(25);
    }
    public T GetById(object id)
    {
        return table.Find(id);
    }
    public void Insert(T obj)
    {
        table.Add(obj);
        Save();
    }
    public void Update(T obj)
    {
        table.Attach(obj);
        _context.Entry(obj).State = EntityState.Modified;
        Save();
    }
    public void Delete(object id)
    {
        T existing = table.Find(id);
        table.Remove(existing);
    }
    public void Save()
    {
        _context.SaveChanges();
    }

}
}

As well as the interface for the generic repository

    public interface IGenericRepository<T> where T : class
{
    IEnumerable<T> GetAll(int page);
    T GetById(object id);
    void Insert(T obj);
    void Update(T obj);
    void Delete(object id);
    void Save();
}

So basically the code which I am trying to achieve is, I must be able to insert an amount using swagger, for example $100 and it must insert the $100 in my vouchers table along with an auto generated string, and the rest of the fields should just populate as Null.

Body:
You've got the method to generate your voucher code, good or bad, so where is the problem? Is this a framework that someone else laid out that you don't quite understand yet because while generic repository patterns like this are rather anemic, from what I can see your code is 90% there:

public void InsertGeneratedVoucher(int amount)
{
    // TODO: Assert that your Amount is valid.. For instance can it be 0? <0??

    string GetVoucherNumber()
    {
        int size = 20;
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        // TODO: Check for duplicates?
        return builder.ToString();
    }
    var voucher = new Vouchers
    {
        Vouchercode = GetVoucherNumber();
        Amount = amount;
    };
    _voucherRepository.Insert(voucher);
}

There is no point accepting a VoucherCode if you want this method to generate a new one. If you want to return it, use a return value on the method. If you can accept a voucher code from the caller then it should be validated to check for duplicates and that it is valid etc. All arguments to a method should be asserted/validated. The method to build a voucher number should probably be moved out to a separate utility method, and you should consider adding a check for duplicate voucher numbers once one is generated. A simpler alternative would be Guid.New().ToString("N") will provide a effective "random" 32 character code. Truncating it to 20 characters will weaken it but it avoids easily confused letters (0 vs O).

The only other thing is that your service should ensure that all required fields (non-null-able) for this new voucher are either provided as parameters or generated within this method.


答:
If you want a solution without using regex:

import collections
sentence = "this is a test sentence that happens to be short"
characters = [sentence[i] for i in range(1,len(sentence)) if sentence[i-1] == 'h']

most_common_char = collections.Counter(characters).most_common(1)
```

Title: Finding most common occurrence of a character that follows another


问:
Ansible privilege escalation prompt problem
```<code>---
- name: Transfer and execute a script.
  hosts: jumpbox
  remote_user: pppruser
  any_errors_fatal: true
  gather_facts: no
  become: true
  become_method: su
  become_user: splunk
  become_flags: '-s /bin/sh'
  tasks:
     - name: Transfer the script
       copy: src=test.sh dest=/home/splunk/ mode=0777
     - name: Execute the script
       command: sh /export/home/splunk/test.sh
</code>```

```<code>[splunk@ansible playbooks]$ cat test.sh
#!/bin/bash
cat /etc/passwd > /tmp/test
</code>```

With above main.yml script and used below playbook command

```<code>$ansible-playbook /etc/ansible/playbooks/main.yml --extra-vars "host=jumpbox" --ask-become-pass
SUDO password:
PLAY [Transfer and execute a script.] **********************************************************************************
TASK [Transfer the script] *********************************************************************************************
fatal: [192.168.1.20]: FAILED! => {"msg": "Timeout (12s) waiting for privilege escalation prompt: "}
NO MORE HOSTS LEFT *****************************************************************************************************
        to retry, use: --limit @/etc/ansible/playbooks/main.retry
PLAY RECAP *********************************************************************************************************
192.168.1.20               : ok=0    changed=0    unreachable=0    failed=1
</code>```

It is failing with error. I tried with different options and different suggestions from multiple forums. But nothing works. On the destination server(192.168.1.20) I have remote_user(pppruser) and service account(splunk). pppruser has sudo privileges to splunk. Here is the sudo list for pppruser account

```<code>$sudo -l
User pppruser may run the following commands on this host:
    (root) /bin/su - splunk
$sudo su - splunk
</code>```

Can anyone suggest me where I need configuration change in order to run my playbook execution as splunk user without problem.

答:
Adding below sudo privileges in my target serve fixed this problem.

pppruser       ALL=(root)      /bin/su - splunk
pppruser       ALL=(splunk) /bin/sh

Body:
---
- name: Transfer and execute a script.
  hosts: jumpbox
  remote_user: pppruser
  any_errors_fatal: true
  gather_facts: no
  become: true
  become_method: su
  become_user: splunk
  become_flags: '-s /bin/sh'
  tasks:
     - name: Transfer the script
       copy: src=test.sh dest=/home/splunk/ mode=0777
     - name: Execute the script
       command: sh /export/home/splunk/test.sh

[splunk@ansible playbooks]$ cat test.sh
#!/bin/bash
cat /etc/passwd > /tmp/test

With above main.yml script and used below playbook command

$ansible-playbook /etc/ansible/playbooks/main.yml --extra-vars "host=jumpbox" --ask-become-pass
SUDO password:
PLAY [Transfer and execute a script.] **********************************************************************************
TASK [Transfer the script] *********************************************************************************************
fatal: [192.168.1.20]: FAILED! => {"msg": "Timeout (12s) waiting for privilege escalation prompt: "}
NO MORE HOSTS LEFT *****************************************************************************************************
        to retry, use: --limit @/etc/ansible/playbooks/main.retry
PLAY RECAP *********************************************************************************************************
192.168.1.20               : ok=0    changed=0    unreachable=0    failed=1

It is failing with error. I tried with different options and different suggestions from multiple forums. But nothing works. On the destination server(192.168.1.20) I have remote_user(pppruser) and service account(splunk). pppruser has sudo privileges to splunk. Here is the sudo list for pppruser account

$sudo -l
User pppruser may run the following commands on this host:
    (root) /bin/su - splunk
$sudo su - splunk

Can anyone suggest me where I need configuration change in order to run my playbook execution as splunk user without problem.


问:
How likely are two blocks of data likely to produce the same CRC64 value?
I have an caching application that uses a CRC64 value to ensure data integrity.
I'm thinking about putting an extra field, a timestamp to be passed around with the data
between the various cache servers and compared to see if data has changed.

However, this requires protocol changes.  While that's not a huge deal,  I already have
a CRC64 that could be used as an indicator that something has changed.

Does anyone know the stats around two blocks of data producing the same CRC64? If not, how could I compute it or estimate it's likelyhood?

答:
If you assume that crc64 is 'perfect', then the numbers are pretty reasonable:

For a 1% probability of collision, you need 6.1 × 10^8 entries. For a 50% probability of collision, you need 5.1 × 10^9 entries.

Of course, if the data is potentially supplied by malicious sources, then collisions in a hash as simple as crc64 can be generated easily, and collisions could be rampant. So whether or not you go this route depends on the source of input data and the potential ramifications of collisions.


问:
How to pass a view id in Kotlin?
I’m trying to use Kotlin on Android. I need to pass a viewId to a function, so that the function can display a text view.

So, I tried to create a function with inputs: string (to be displayed), and the id (for the location of where it will be displayed):

Calling:

```<code>ShowHello("Hello world", textView.id)
</code>```

The function:

```<code>    fun ShowHello(toshow:String, thisId:id ){ textView.text=toshow }
</code>```

But, the thisId:id is failing with “Unresolved reference: id”?

Any help would be really appreciated.

答:
If you want to pass a resource ID (like a view ID), you can use an Int with the @IdRes annotation to clarify that only resource (res) ID's should be passed in that position:

```<code>fun showHello(displayText: String, @IdRes viewId: Int)
</code>```

To understand why this works, look into how resources are referenced. Each resource ID is mapped to a constant. When you call an ID in the format R.id.some_view_id, you get back an integer that references that resource.

Title: How to pass a view id in Kotlin?

Body:
I’m trying to use Kotlin on Android. I need to pass a viewId to a function, so that the function can display a text view.

So, I tried to create a function with inputs: string (to be displayed), and the id (for the location of where it will be displayed):

Calling:

ShowHello("Hello world", textView.id)

The function:

    fun ShowHello(toshow:String, thisId:id ){ textView.text=toshow }

But, the thisId:id is failing with “Unresolved reference: id”?

Any help would be really appreciated.

Body:
If you want to pass a resource ID (like a view ID), you can use an Int with the @IdRes annotation to clarify that only resource (res) ID's should be passed in that position:

fun showHello(displayText: String, @IdRes viewId: Int)

To understand why this works, look into how resources are referenced. Each resource ID is mapped to a constant. When you call an ID in the format R.id.some_view_id, you get back an integer that references that resource.


问:
React card icon display
a bit of help here if possible. I am creating a team card let's call it. I have a .jsonfile with data. Problem is, what shall I do if one of the team members doesn't have a facebook account let's say...then I don't want the font awesome to be shown. Thoughts?
Thanks in advance!

import React, { Component } from 'react';
import teamData from '../components/data/teamInfo.json';

const TeamCard =({data})=>{
  const imgStyles = {
    width: "200px",
    height: "250px",
    borderRadius: "20px"
  }

  return (

{data.name}
{data.title}

{data.hobbies}

  )
};

const TeamCards =()=>{

  return (

Meet the team

        {teamData && teamData.map((e, key) => {
          return (
            <TeamCard
              data={e}
              key={key}
            />
          );
        })}

  )
}

export default TeamCards;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

答:
You can use a ternary function condition ? value_if_true : value_if_false that only renders the component if data.facebookId is true in state

```<code>const component = ({ data.facebookId.state }) => (
  <div>
    {isTrue ?
      (
           <a href={data.linkedIn}><i className="fab fa-linkedin"></i></a>
         <a href={data.facebookId}><i className="fab fa-github-square"></i></a>

      ) : (

         <a href={data.facebookId}><i className="fab fa-github-square"></i></a>
      )}

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

Title: React card icon display

Body:
You can use a ternary function condition ? value_if_true : value_if_false that only renders the component if data.facebookId is true in state

const component = ({ data.facebookId.state }) => (
  <div>
    {isTrue ?
      (
           <a href={data.linkedIn}><i className="fab fa-linkedin"></i></a>
         <a href={data.facebookId}><i className="fab fa-github-square"></i></a>

      ) : (

         <a href={data.facebookId}><i className="fab fa-github-square"></i></a>
      )}

  </div>
)


问:
Unable to connect Dongle K5150 to iot core
I'm trying to connect Dongle K5150 with Emnify SIM to raspberry Pi3 with iot core 17763 version.
I followed these steps:
USB Mobile Broadband Modem on Windows 10 IoT?
but at the end I had an error:
Connect Failure: error 0x139f.

Can someone help me?

答:
You may get error 0x139f (ERROR_INVALID_STATE) in the case when the device is roaming but the roaming policy disallows data roaming - error on a connect request sent to wwansvc. You can try to toubleshoot this issue with this article.

https://learn.microsoft.com/en-us/windows/iot-core/troubleshooting#issue-when-connecting-a-mbm-device-when-roaming


问:
Cannot access php stdClass property on std class object
I'm passing an ACF std class object of values to a function as a value and when trying to read it in the function, it shows up as an object but when I try to access a property Notice: Trying to get property "type" of non-object</p>

```<code>function createACFProductLicenses($acfData, $propertyString){
    $newData = array();
    if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {

            print_r($value);
            // prints out
            // stdClass Object
            // (
            //   [type] => standard
            //   [item_id] => 727
            // )

            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}
// example of how I'm calling it:
// $product['acf'] is an stdClass of acf properties
createACFProductLicenses($product['acf'], 'product_licenses');
</code>```

答:
The "foreach" set the data structure to $key=>$value or [type] is a $key and "standard" is a $value so you can't print $value->type because the object is actually 'type' => 'standard'.
Also, know that the "foreach" will run your code for each item on the object like for ana array, so you can't just print a specific value when you have different $key.

If you want to display all the items use this:

```<code>print_r($key.':'.$value) // this will print:  type : standard
</code>```

Or if you want to only print the [Type] item Try this out:
insted of this

```<code> if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {
            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}
</code>```

Try this

```<code>if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        print_r($data['type']);
    }
}
</code>```

I hope this will help, let me know if it didn't work.

Body:
I'm passing an ACF std class object of values to a function as a value and when trying to read it in the function, it shows up as an object but when I try to access a property Notice: Trying to get property "type" of non-object

function createACFProductLicenses($acfData, $propertyString){
    $newData = array();
    if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {

            print_r($value);
            // prints out
            // stdClass Object
            // (
            //   [type] => standard
            //   [item_id] => 727
            // )

            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}
// example of how I'm calling it:
// $product['acf'] is an stdClass of acf properties
createACFProductLicenses($product['acf'], 'product_licenses');

Body:
The "foreach" set the data structure to $key=>$value or [type] is a $key and "standard" is a $value so you can't print $value->type because the object is actually 'type' => 'standard'.
Also, know that the "foreach" will run your code for each item on the object like for ana array, so you can't just print a specific value when you have different $key.

If you want to display all the items use this:

print_r($key.':'.$value) // this will print:  type : standard

Or if you want to only print the [Type] item Try this out:
insted of this

 if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        foreach ($data as $key => $value) {
            print_r($value->type); // errors out -> Notice: Trying to get property 'type' of non-object
        }
    }
}

Try this

if(isset($acfData->{$propertyString})){
        $data = (array)$acfData->{$propertyString};
        print_r($data['type']);
    }
}

I hope this will help, let me know if it didn't work.


答:
The value is indeed returned from the method.  But the variable you're looking for was declared only within that method and exists only within that method.

The returned value is then ignored:

```<code>CreateName();
</code>```

You can store that value in its own variable:

```<code>var result = CreateName();
Console.WriteLine(result);
</code>```

Or just use it directly for the purpose you want:

```<code>Console.WriteLine(CreateName());
</code>```

Another option might be to use a class-level member instead of local variables.  For example:

```<code>class MainClass
{
    private static string person;

    public static void Main (string[] args)
    {
        CreateName();
        Console.WriteLine(person);
    }

    static void CreateName()
    {
        Console.Write("Enter a name: ");
        person = Console.ReadLine();
    }
}
</code>```

In this case the methods are both using the same variable that's in a scope shared by both methods, so nothing needs to be returned or re-stored in a new local variable.

There are a variety of options for passing data around your application.  But "variables" aren't passed around or returned, they exist only within the scope in which they're declared.

Title: Why can't I return the string person into main? It gives me a error saying that the string "person" is not in the context even though I returned it?

Body:
The value is indeed returned from the method.  But the variable you're looking for was declared only within that method and exists only within that method.

The returned value is then ignored:

CreateName();

You can store that value in its own variable:

var result = CreateName();
Console.WriteLine(result);

Or just use it directly for the purpose you want:

Console.WriteLine(CreateName());

Another option might be to use a class-level member instead of local variables.  For example:

class MainClass
{
    private static string person;

    public static void Main (string[] args)
    {
        CreateName();
        Console.WriteLine(person);
    }

    static void CreateName()
    {
        Console.Write("Enter a name: ");
        person = Console.ReadLine();
    }
}

In this case the methods are both using the same variable that's in a scope shared by both methods, so nothing needs to be returned or re-stored in a new local variable.

There are a variety of options for passing data around your application.  But "variables" aren't passed around or returned, they exist only within the scope in which they're declared.


问:
Aligning chart title with left side of numbers on the y axis
I am trying to make an Altair theme that conforms with our internal guidelines. I found this excellent article that solved most of my issues. However, neither the article nor a search of the documentation has solved the problem of aligning the chart title with the left side of the numbers on the y axis.
See the dotted line in Urban institute's theme for visual explanation.
The problem is that I do not know the width of the longest number on the y axis. The solutions I have found just hard code an offset for the expected width of the number. However, I have to make a theme that automatically conforms to the standard in all cases.
Hints to possible solutions are welcome. I will try them out and post results.</p>

答:
I'm not sure if this exactly what you're looking for since you mentioned wanting to create a theme, but you can recreate the look of the UI theme by adding text to your chart via mark_text().

Here's an example:

```<code>df = pd.DataFrame({'col1':[0,1,2,3,4,5], 'col2':[0,1,2,3,4,5]})
text_df = pd.DataFrame({'col1':[0], 'col2':[0], 'col3':['title']})

line = alt.Chart(df).mark_line().encode(x='col1', y='col2')
text = alt.Chart(text_df.query('col1 == 0')).mark_text(dx=-60, dy=-400, fontSize=24, font='Lato').encode(x='col1', y='col2', text='col3')
line + text
</code>```

This is the resulting chart:

Body:
I'm not sure if this exactly what you're looking for since you mentioned wanting to create a theme, but you can recreate the look of the UI theme by adding text to your chart via mark_text().

Here's an example:

df = pd.DataFrame({'col1':[0,1,2,3,4,5], 'col2':[0,1,2,3,4,5]})
text_df = pd.DataFrame({'col1':[0], 'col2':[0], 'col3':['title']})

line = alt.Chart(df).mark_line().encode(x='col1', y='col2')
text = alt.Chart(text_df.query('col1 == 0')).mark_text(dx=-60, dy=-400, fontSize=24, font='Lato').encode(x='col1', y='col2', text='col3')
line + text

This is the resulting chart:


问:
JavaScript: add alert message if name or password less than 6
try to add function in JS where alert box will show message Password or Username must be more than 6 :

Password :

Password must have atleast 6 characters

Username :

Username must have atleast 6 characters

So far I got function show alert if Pass or Username is NULL

JaveScript Code :

```<code>    function validateForm() {
  var x = document.forms["myForm"]["namapengguna"].value;
  if (x == "" || x == null) {
    alert("Nama must be filled out");
    return false;
  }
  var x = document.forms["myForm"]["username"].value;
  if (x == "" || x == null) {
    alert("User must be filled out");
    return false;
  }
  var x = document.forms["myForm"]["password"].value;
  if (x == "" || x == null) {
    alert("Pass must be filled out");
    return false;
  }
    var x = document.forms["myForm"]["confirm_password"].value;
  if (x == "" || x == null) {
    alert("Confirm Pass must be filled out");
    return false;
  }
  else {
        alert('Application Has Been Registered');
        location.assign("homeA.php");
        }
}
</code>```

but I couldn't figure out how can add alert message if name or password less than 6.

Any idea or solution are really appreatiate.

p/s: if my question is not good enough for you to understand, please tell me so I can improve it.

答:
You can check string length by doing x.length. So:

```<code>if (x.length <= 6) {
    // Do what you want
}
</code>```

You may also want to make sure the user hasn't inputted any spaces at the start or end of the field.

Body:
try to add function in JS where alert box will show message Password or Username must be more than 6 :

Password :

Password must have atleast 6 characters

Username :

Username must have atleast 6 characters

So far I got function show alert if Pass or Username is NULL

JaveScript Code :

    function validateForm() {
  var x = document.forms["myForm"]["namapengguna"].value;
  if (x == "" || x == null) {
    alert("Nama must be filled out");
    return false;
  }
  var x = document.forms["myForm"]["username"].value;
  if (x == "" || x == null) {
    alert("User must be filled out");
    return false;
  }
  var x = document.forms["myForm"]["password"].value;
  if (x == "" || x == null) {
    alert("Pass must be filled out");
    return false;
  }
    var x = document.forms["myForm"]["confirm_password"].value;
  if (x == "" || x == null) {
    alert("Confirm Pass must be filled out");
    return false;
  }
  else {
        alert('Application Has Been Registered');
        location.assign("homeA.php");
        }
}

but I couldn't figure out how can add alert message if name or password less than 6.

Any idea or solution are really appreatiate.

p/s: if my question is not good enough for you to understand, please tell me so I can improve it.

Body:
You can check string length by doing x.length. So:

if (x.length <= 6) {
    // Do what you want
}

You may also want to make sure the user hasn't inputted any spaces at the start or end of the field.


答:
You should also be able to do it with pipe within the rename_all() call:

```<code>library(tidyverse)

tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
  rename_all(~ tolower(.) %>% str_remove(., '\\.') %>% str_replace(., ' ', '_'))

</code>```

Title: passing multiple arguments in rename_all()

Body:
To tidy up column names, is there a way to pass multiple arguments in rename_all()?

Example: I'd like to cleaning up the following column names by changing them all to lower, removing the ., and replacing the spaces with _ using rename_all()

> colnames(tibble("COLUMN 1." = (1:3), "column 2." = (1:3)))
[1] "COLUMN 1." "column 2."

And I can do it as follows:

> tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
+     rename_all(tolower) %>%
+     rename_all(~gsub("\\ ", "_", .x)) %>%
+     rename_all(~gsub("\\.", "", .x))
# A tibble: 3 x 2
  column_1 column_2
     <int>    <int>
1        1        1
2        2        2
3        3        3

But is there a way to do this with one call of rename_all() instead of 3?

Body:
You should also be able to do it with pipe within the rename_all() call:

library(tidyverse)

tibble("COLUMN 1." = (1:3), "column 2." = (1:3)) %>%
  rename_all(~ tolower(.) %>% str_remove(., '\\.') %>% str_replace(., ' ', '_'))


问:
Upgrading Global Ruby Version on macOS
I am trying to update Ruby on my computer to version 2.7.0 as that is the latest stable version.

Running macOS Catalina Version 10.15.3

Have tried the top two solutions from this StackOverflow post.

1. Using just brew

brew upgrade ruby

just confirms that "ruby 2.6.5 already installed"

2. Using rbenv

rbenv install 2.7.0

rbenv global 2.7.0

After installation I get confirmation that ruby 2.7.0 is installed, but when I close terminal, and check version, 2.6.5 is still the current version.

Initially when I tried this, I got an error BUILD FAILED (OS X 10.15.3 using ruby-build 20200115). Based on advise in this github issue I found that Xcode was not installed (it was installed, but something removed it in the last few months). I re-installed it, but still got the same issue.

3. Also tried RVM based on answer 3 from this post.

rvm upgrade 2.7.0

But I am prompted if I want to use ruby-2.6.3
I did said yes by accident. So now I am back down to 2.6.3

Do I need to do something more to change the global environment settings for Ruby? It seemed that rbenv global 2.7.0 would do this.

答:
As per advice from anothermh, uninstalled rbenv and brew versions of Ruby

Uninstallation

brew uninstall ruby for removing brew version

Use accepted answer on this SO article for removing rbenv

Install Ruby via RVM

Install RVM as per instructions || as per this

rvm install (ruby version)

rvm --default use (ruby version)

can use rvm list to see available ruby versions.

Title: Upgrading Global Ruby Version on macOS


问:
How can I call a function on a button being enabled in Angular 8?
Below is a snippet of my sign-in.component.html file. I have a function within the corresponding sign-in.component.ts file which I would like to call on the button below becoming enabled. An example of what I hope to achieve:</p>

```<code><div class="button-container">
    <button mat-raised-button [disabled]="!signInForm.valid" (enabled)="callAFunction()" type="submit">Sign in</button>
</div>
</code>```

答:
The condition for the button to be enabled is by:

```<code>signInForm.valid
</code>```

So I guess you could add a

```<code><input type="text" (ngModelChange)="theFunctionYouWantToCallWhenSignInFormIsValid()"/>
</code>```

With this, as soon as your form is valid, the function that you want to call will get triggered.

Body:
Below is a snippet of my sign-in.component.html file. I have a function within the corresponding sign-in.component.ts file which I would like to call on the button below becoming enabled. An example of what I hope to achieve:

    <button mat-raised-button [disabled]="!signInForm.valid" (enabled)="callAFunction()" type="submit">Sign in</button>

Body:
The condition for the button to be enabled is by:

signInForm.valid

So I guess you could add a

<input type="text" (ngModelChange)="theFunctionYouWantToCallWhenSignInFormIsValid()"/>

With this, as soon as your form is valid, the function that you want to call will get triggered.


问:
Why use static_cast rather than dynamic_cast in here?
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

```<code>class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };
</code>```

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

```<code>void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}
</code>```

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

```<code>class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);
</code>```

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?

答: You've already verified the types yourself, so you don't need to use dynamic_cast.  Dynamic_cast will check the types for you automatically.</p>

Body:
I copy the following text from the book More Effective C++.

Item 31:  Making functions virtual with respect to more than one object.

class GameObject { ... };
class SpaceShip: public GameObject { ... };
class SpaceStation: public GameObject { ... };
class Asteroid: public GameObject { ... };

The most common approach to double-dispatching returns us to the unforgiving world of virtual function emulation via chains of if-then-elses. In this harsh world, we first discover the real type of otherObject, then we test it against all the possibilities:

void SpaceShip::collide(GameObject& otherObject)
{
  const type_info& objectType = typeid(otherObject);

  if (objectType == typeid(SpaceShip)) {
    SpaceShip& ss = static_cast<SpaceShip&>(otherObject);

    process a SpaceShip-SpaceShip collision;

  }
  else if (objectType == typeid(SpaceStation)) {
    SpaceStation& ss =
      static_cast<SpaceStation&>(otherObject);

    process a SpaceShip-SpaceStation collision;

  }
...
}

Here is the question:

Q1> Why we use static_cast here rather than obvious dynamic_cast?

Q2>　Are they same in this case?

thank you

// updated //

In fact, I am more interested in question 2.

For example,

class base {};
class subclass : public base {};

base *pSubClass = new subclass;

subclass *pSubClass1 = static_cast<subClass*> (pSubClass);

// does the static_cast do the job correctly in this case although I know we should use dynamic_cast here?


问:
GameObject.name vs new GameObject(name)
Is there a difference performance-wise between using

Example 1

```<code>var myObject = new GameObject();
myObject.name = "myObjectName";
</code>```

And

Example 2

```<code>var myObject = new GameObject("myObjectName");
</code>```

Some articles like this suggest avoiding Example 1 because native code is called, hurting performance.

Out of curiosity, I checked the documentation of the GameObject class and there are no remarks indicating how any of the constructors might affect performance.

My current theory is that Example 2 is similar to instantiating an object and immediately specifying a parent as that is supposedly better than instantiating an object and specifying the parent later.

答:
I have answered my own question.

The second example runs 0.41 milliseconds faster, but allocates the same amount of memory as the first.

Title: GameObject.name vs new GameObject(name)

Body:
Is there a difference performance-wise between using

Example 1

var myObject = new GameObject();
myObject.name = "myObjectName";

And

Example 2

var myObject = new GameObject("myObjectName");

Some articles like this suggest avoiding Example 1 because native code is called, hurting performance.

Out of curiosity, I checked the documentation of the GameObject class and there are no remarks indicating how any of the constructors might affect performance.

My current theory is that Example 2 is similar to instantiating an object and immediately specifying a parent as that is supposedly better than instantiating an object and specifying the parent later.


问:
AngularJS 1.2 $injector:modulerr
When using angular 1.2 instead of 1.07 the following piece of code is not valid anymore, why?

```<code>'use strict';

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
        when('/', {
            templateUrl: 'part.html',
            controller: 'MyCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);
</code>```

the issue is in the injector configuration part (app.config):

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.0rc1/$injector/modulerr?p0=muninn&p1=Error%…eapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.0rc1%2Fangular.min.js%3A31%3A252)
</code>```

If I remember correctly this issue started with angular 1.1.6.

答:
I had this problem and after check my code line by line i saw this

```<code> <textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"/>
</code>```

i just changed it to

```<code>     <textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"></textarea>
</code>```

and it's worked.
so check your tags.

Title: AngularJS 1.2 $injector:modulerr

Body:
When using angular 1.2 instead of 1.07 the following piece of code is not valid anymore, why?

'use strict';

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
        when('/', {
            templateUrl: 'part.html',
            controller: 'MyCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);

the issue is in the injector configuration part (app.config):

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.0rc1/$injector/modulerr?p0=muninn&p1=Error%…eapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.0rc1%2Fangular.min.js%3A31%3A252)

If I remember correctly this issue started with angular 1.1.6.

Body:
I had this problem and after check my code line by line i saw this

 <textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"/>

i just changed it to

     <textarea class="form-control" type="text" ng-model="WallDesc" placeholder="Enter Your Description"></textarea>

and it's worked.
so check your tags.


问:
Creating pointers inside a for loop results in pointing to same memory address
I have an object that I am trying to duplicate for any number of times with some minor changes to that object. I want to store pointers to those duplicated objects in a std::vector. I am using a for loop to try and achieve the result. However, what I notice is that the std::vector<T *> is pointing to the same address after the loop exits. I tried this attempt to duplicate objects with std::string and I see the same effects. Here's my code snippet.

```<code>int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> names;
  names.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(&n);
  }

  // nothing from this loop prints out
  for (auto n : names) {
    std::cout << *n << std::endl;
  }

  return 0;
}
</code>```

When I place the code in a debugger, I see that names is storing pointers all to the same memory address: 0x7ffffffeead0. Any ideas on what I am doing wrong here?

I modified the code to store a vector of strings, and then to loop through each string, creating a pointer to each string's address as follows. This approach also does not work. The vector of pointers all still point to the same address; although this time, they all point to the address of the last string.

```<code>int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> pointers;
  std::vector<std::string> names;

  names.reserve(size);
  pointers.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(n);
  }

  for (int i = 0; i < size; i++) {
    auto n = names.at(i);
    auto p = &n;
    pointers.push_back(p);
  }

  for (auto n : names) {
    std::cout << n << std::endl;
  }

  for (auto n : pointers) {
    std::cout << *n << std::endl;
  }

  return 0;
}
</code>```

Yet, in a third attempt, I modify the code as follows. Note that I use the & operator against where I access the element by index. Here, I do get a std::vector<std::string *> that points to different addresses (corresponding correctly to the vector of strings).

```<code>int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> pointers;
  std::vector<std::string> names;

  names.reserve(size);
  pointers.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(n);
  }

  for (int i = 0; i < size; i++) {
    auto p = &names.at(i); // using address operator like this "works"
    pointers.push_back(p);
  }

  for (auto n : names) {
    std::cout << n << std::endl;
  }

  for (auto n : pointers) {
    std::cout << *n << std::endl;
  }

  return 0;
}
</code>```

Lastly, I finally get this more concise example to work. Here, I create a new pointer on every loop.

```<code>int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> names;
  names.reserve(size);

  for (int i = 0; i < size; i++) {
    auto x = new std::string(*name + " " + std::to_string(i));
    names.push_back(x);
  }

  for (auto n : names) {
    std::cout << *n << std::endl;
  }

  return 0;
}
</code>```

Is there something on for-loops and pointers that I am missing here? Any pointers (no pun intended) to scoping rules for C++ would be appreciated.

答:
However, what I notice is that the std::vector is pointing to the same address after the loop exits.

Any ideas on what I am doing wrong here?

```<code>for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
</code>```

Here, n is an automatic variable. n - like all objects with automatic storage, will be destroyed at the end of the scope, i.e. at the end of the iteration.

```<code>    names.push_back(&n);
</code>```

Here, you take the address of the automatic object and store it inside a vector.

```<code>}
</code>```

Here, the iteration ends and the next one begins. n has been destroyed and the pointer in the vector is invalid. In the next iteration, a new n object is created. Since the previous n was destroyed, the same memory can be used for the next object.

```<code>for (auto n : pointers) {
    std::cout << *n << std::endl;
</code>```

On this line, you attempt to access non-existing string through an invalid pointer and the behaviour of the program is undefined.

The same pattern persists through your second and third attempt.

In all your examples including the fourth one, you leak memory.

I have an object that I am trying to duplicate for any number of times

You can store strings in std::vector<std::string>. You can duplicate such vector like this:

```<code>std::vector<std::string> names;
// insert names here

std::vector<std::string> duplicates = names;
</code>```

Body:
I have an object that I am trying to duplicate for any number of times with some minor changes to that object. I want to store pointers to those duplicated objects in a std::vector. I am using a for loop to try and achieve the result. However, what I notice is that the std::vector<T *> is pointing to the same address after the loop exits. I tried this attempt to duplicate objects with std::string and I see the same effects. Here's my code snippet.

int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> names;
  names.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(&n);
  }

  // nothing from this loop prints out
  for (auto n : names) {
    std::cout << *n << std::endl;
  }

  return 0;
}

When I place the code in a debugger, I see that names is storing pointers all to the same memory address: 0x7ffffffeead0. Any ideas on what I am doing wrong here?

I modified the code to store a vector of strings, and then to loop through each string, creating a pointer to each string's address as follows. This approach also does not work. The vector of pointers all still point to the same address; although this time, they all point to the address of the last string.

int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> pointers;
  std::vector<std::string> names;

  names.reserve(size);
  pointers.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(n);
  }

  for (int i = 0; i < size; i++) {
    auto n = names.at(i);
    auto p = &n;
    pointers.push_back(p);
  }

  for (auto n : names) {
    std::cout << n << std::endl;
  }

  for (auto n : pointers) {
    std::cout << *n << std::endl;
  }

  return 0;
}

Yet, in a third attempt, I modify the code as follows. Note that I use the & operator against where I access the element by index. Here, I do get a std::vector<std::string *> that points to different addresses (corresponding correctly to the vector of strings).

int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> pointers;
  std::vector<std::string> names;

  names.reserve(size);
  pointers.reserve(size);

  for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);
    names.push_back(n);
  }

  for (int i = 0; i < size; i++) {
    auto p = &names.at(i); // using address operator like this "works"
    pointers.push_back(p);
  }

  for (auto n : names) {
    std::cout << n << std::endl;
  }

  for (auto n : pointers) {
    std::cout << *n << std::endl;
  }

  return 0;
}

Lastly, I finally get this more concise example to work. Here, I create a new pointer on every loop.

int main() {
  auto name = new std::string("fido");

  const int size = 3;
  std::vector<std::string *> names;
  names.reserve(size);

  for (int i = 0; i < size; i++) {
    auto x = new std::string(*name + " " + std::to_string(i));
    names.push_back(x);
  }

  for (auto n : names) {
    std::cout << *n << std::endl;
  }

  return 0;
}

Is there something on for-loops and pointers that I am missing here? Any pointers (no pun intended) to scoping rules for C++ would be appreciated.

Body:
However, what I notice is that the std::vector is pointing to the same address after the loop exits.

Any ideas on what I am doing wrong here?

for (int i = 0; i < size; i++) {
    std::string n = *name + " " + std::to_string(i);

Here, n is an automatic variable. n - like all objects with automatic storage, will be destroyed at the end of the scope, i.e. at the end of the iteration.

    names.push_back(&n);

Here, you take the address of the automatic object and store it inside a vector.

}

Here, the iteration ends and the next one begins. n has been destroyed and the pointer in the vector is invalid. In the next iteration, a new n object is created. Since the previous n was destroyed, the same memory can be used for the next object.

for (auto n : pointers) {
    std::cout << *n << std::endl;

On this line, you attempt to access non-existing string through an invalid pointer and the behaviour of the program is undefined.

The same pattern persists through your second and third attempt.

In all your examples including the fourth one, you leak memory.

I have an object that I am trying to duplicate for any number of times

You can store strings in std::vector<std::string>. You can duplicate such vector like this:

std::vector<std::string> names;
// insert names here

std::vector<std::string> duplicates = names;


问:
How to use tabIndex with jsx?
According to the react docs, this should work.

But when I try this, it doesn't work
  and my input is actually being skipped now!

What am I doing wrong here?

```<code><input
tabIndex='0'/>
<input
tabIndex='1'/>
<input
tabIndex='2'/>
</code>```

答:
You have typed tabIndex twice without the n, it should be:

```<code><CustomRadio
tabIndex='0'/>
<CustomCheckbox
tabIndex='1'/>
<input
tabIndex='2'/>
</code>```

I think you may also need to pass these props into your components, to the underlying element

Title: How to use tabIndex with jsx?

Body:
According to the react docs, this should work.

But when I try this, it doesn't work
  and my input is actually being skipped now!

What am I doing wrong here?

<input
tabIndex='0'/>
<input
tabIndex='1'/>
<input
tabIndex='2'/>

Body:
You have typed tabIndex twice without the n, it should be:

<CustomRadio
tabIndex='0'/>
<CustomCheckbox
tabIndex='1'/>
<input
tabIndex='2'/>

I think you may also need to pass these props into your components, to the underlying element


问:
How remove item by ID from localStorage?
Greeting. Do I need
Example:

```<code>items: [{id:1 , name: test} , {id: 2 , name: test2} , {id:3 , name: test3}];
</code>```

I want to delete example item where id 3?

答:
First, fetch the array from local storage.

```<code>const items = JSON.parse(localStorage.getItem('items'));
</code>```

Then, delete the item from the array.

```<code>const filtered = items.filter(item => item.id !== 3);
</code>```

Last, put the array back in local storage.

```<code>localStorage.setItem('items', JSON.stringify(filtered));
</code>```

Body:
Greeting. Do I need
Example:

items: [{id:1 , name: test} , {id: 2 , name: test2} , {id:3 , name: test3}];

I want to delete example item where id 3?

Body:
First, fetch the array from local storage.

const items = JSON.parse(localStorage.getItem('items'));

Then, delete the item from the array.

const filtered = items.filter(item => item.id !== 3);

Last, put the array back in local storage.

localStorage.setItem('items', JSON.stringify(filtered));


问:
Jupyter Notebook / Python
I am having trouble to why I am getting this error. I would like to have any assistance with this issue.

happyList = []
sadList = []

exclude = string.punctuation

happy_file = open("happy.txt", "r")
for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())
happy_file.close()
```

<p>The error:</p>

```    happyList.append(word.strip().lower())
            ^
SyntaxError: invalid syntax
```

答:
```<code>for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())
</code>```

Try putting an else case result as well when you are assigning it to 'word'. I don't remember exactly when, but I had faced a similar issue, when I forgot to give the else case for a similar assignment.

Let me know if it works.

Title: Jupyter Notebook / Python

Body:
I am having trouble to why I am getting this error. I would like to have any assistance with this issue.

happyList = []
sadList = []

exclude = string.punctuation

happy_file = open("happy.txt", "r")
for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())
happy_file.close()

The error:

    happyList.append(word.strip().lower())
            ^
SyntaxError: invalid syntax

Body:
for word in happy_file:
    word = ''.join(ch for ch in word if ch not in exclude)
    happyList.append(word.strip().lower())

Try putting an else case result as well when you are assigning it to 'word'. I don't remember exactly when, but I had faced a similar issue, when I forgot to give the else case for a similar assignment.

Let me know if it works.


问:
How to add optional claims to Azure Active Directory
We are working on authenticating a C# MVC Web API, following the "Daemon or Server Application to Web API" model and we would like to add some custom claims to the token issued by Azure Active Directory to be validated in the Web API side.

Our initial thought is to 'add' these optional claims to the Daemon application by editing the manifest, but we could not find a good exemple and we get errors when saving it.

Is there anyone that could provide us a good example of how to add this custom claims?

Or even better, Is there any other idea about how to add these custom claims?

答:
Please see the documentation on optional claims here - https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims

You can use the UX or manifest editing to add claims that are not usually included in tokens.

Please consider having the rest of the answers on this page erased as they are incorrect and give false information.


问:
can't download stock data using getSymbols() from quantmod, get SSL error with curl
I am trying to use quantmod's getSymbols. getSymbols("AAPL", src = "yahoo", from = start, to = end)
I am getting this error:

"Error in curl::curl_download(cu, tmp, handle = h) :
  SSL certificate problem: unable to get local issuer certificate"

I have uninstalled quantmod and curl, ignored SSL errors (httr::set_config(config(ssl_verifypeer = FALSE))) and reinstalled quantmod and curl.  I also ran this code: brew install libcurl4-openssl-dev.

I still get the error.

答: Turns out my internet connection was the problem. I switched to my mobile data and the code worked fine. </p>