问:
"Export" x509 certificate in Ruby
I'm communicating with an API that has the following directions:

Install the issued x509 certificate onto the client server.

Export the x509 certificate using the supplied password and default Machine Key Set into memory.

Base64 encode the exported bytes of the x509 certificate.

Add ‘X509Certificate’ as an HTTP header and set its value to the result of step 3.

Step 1 and 4 are easy, but I have no idea on 2 or or the 'export' portion of 3. I have tried Googling for some time and I'm not sure exactly where to even really start.

Would someone point me in the right direction on how to "export" a certificate with "machine key set"?

Here is what I have so far

```<code>raw_data = File.read('cert.pfx')
pkcs = OpenSSL::PKCS12.new(raw_data, 'password')
cert = OpenSSL::X509::Certificate.new(pkcs.certificate.to_pem)
</code>```

Here is equivalent .NET code:

```<code>public string GetBase64Cert(string certificateThumbprint)
 {
 using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
 {
 store.Open(OpenFlags.ReadOnly);
 var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
 if (foundCertificates.Count != 1)
 {
 return null;
 }
 var certByteArray = foundCertificates[0].Export(X509ContentType.Cert);
 store.Close();
 return Convert.ToBase64String(certByteArray);
 }
}
</code>```

And equivalent PHP code:

```<code>public function setx509($x509file) {
  $cert = openssl_x509_parse($x509file);
  $base64cert = base64_encode($cert);
  return $base64cert;
}
</code>```

答:
Try

```<code>pkcs = OpenSSL::PKCS12.new(File.read('cert.pfx'), 'password')
str = Base64.urlsafe_encode64(pkcs.certificate.to_der)
</code>```

Probably also str.gsub(/=+$/, '') to cut off padding

Title: "Export" x509 certificate in Ruby

Body:
I'm communicating with an API that has the following directions:

Install the issued x509 certificate onto the client server.

Export the x509 certificate using the supplied password and default Machine Key Set into memory.

Base64 encode the exported bytes of the x509 certificate.

Add ‘X509Certificate’ as an HTTP header and set its value to the result of step 3.

Step 1 and 4 are easy, but I have no idea on 2 or or the 'export' portion of 3. I have tried Googling for some time and I'm not sure exactly where to even really start.

Would someone point me in the right direction on how to "export" a certificate with "machine key set"?

Here is what I have so far

raw_data = File.read('cert.pfx')
pkcs = OpenSSL::PKCS12.new(raw_data, 'password')
cert = OpenSSL::X509::Certificate.new(pkcs.certificate.to_pem)

Here is equivalent .NET code:

public string GetBase64Cert(string certificateThumbprint)
 {
 using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
 {
 store.Open(OpenFlags.ReadOnly);
 var foundCertificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
 if (foundCertificates.Count != 1)
 {
 return null;
 }
 var certByteArray = foundCertificates[0].Export(X509ContentType.Cert);
 store.Close();
 return Convert.ToBase64String(certByteArray);
 }
}

And equivalent PHP code:

public function setx509($x509file) {
  $cert = openssl_x509_parse($x509file);
  $base64cert = base64_encode($cert);
  return $base64cert;
}

Body:
Try

pkcs = OpenSSL::PKCS12.new(File.read('cert.pfx'), 'password')
str = Base64.urlsafe_encode64(pkcs.certificate.to_der)

Probably also str.gsub(/=+$/, '') to cut off padding


来源: stackexchange

问:
Comparing floating point numbers with tolerance fails assertion
I am using ScalaTest (3.0.4), and can't get any examples to work that I've found of comparing floating point numbers with a tolerance. Here's what I have:

```<code>import org.scalatest.{MustMatchers, WordSpec}

class DetectionClusteringSpec extends WordSpec with MustMatchers {

    "EmbeddingsGroup.vecdist" should {
        "correctly compute vector distance" in {
            val dist = EmbeddingsGroup.vecdist(TestDetections.emb1,TestDetections.emb4)
            // Note: The above method returns a Float.

            dist mustBe 3.058 +- 0.1
        }
    }
</code>```

The above compiles, but when I run the test, I get the following failure:

```<code>3.0579379 was not equal to 3.058 +- 0.1
Expected :3.058 +- 0.1
Actual   :3.0579379
</code>```

I also tied the following assertion instead:

```<code>assert(dist === 3.058)
</code>```

However, that does not work either, and gives the following failure:

```<code>3.0579379 did not equal 3.058
Expected :3.058
Actual   :3.0579379
</code>```

I've read numerous examples of comparing floating point numbers with both of the above syntaxes, and it seems like they should work. My first example is straight from the documentation.

What am I doing wrong?

答:
Since dist is a Float whilst other arguments are Doubles try converting dist to Double like so

```<code>dist.toDouble mustBe 3.058D +- 0.1
</code>```

or make other arguments floats like so

```<code>dist mustBe 3.058f +- 0.1f
</code>```

Possibly related to Comparison matchers fail on mixed numeric types

ContentLicense: CC BY-SA 4.0

Body:
I am using ScalaTest (3.0.4), and can't get any examples to work that I've found of comparing floating point numbers with a tolerance. Here's what I have:

import org.scalatest.{MustMatchers, WordSpec}

class DetectionClusteringSpec extends WordSpec with MustMatchers {

    "EmbeddingsGroup.vecdist" should {
        "correctly compute vector distance" in {
            val dist = EmbeddingsGroup.vecdist(TestDetections.emb1,TestDetections.emb4)
            // Note: The above method returns a Float.

            dist mustBe 3.058 +- 0.1
        }
    }

The above compiles, but when I run the test, I get the following failure:

3.0579379 was not equal to 3.058 +- 0.1
Expected :3.058 +- 0.1
Actual   :3.0579379

I also tied the following assertion instead:

assert(dist === 3.058)

However, that does not work either, and gives the following failure:

3.0579379 did not equal 3.058
Expected :3.058
Actual   :3.0579379

I've read numerous examples of comparing floating point numbers with both of the above syntaxes, and it seems like they should work. My first example is straight from the documentation.

What am I doing wrong?

Body:
Since dist is a Float whilst other arguments are Doubles try converting dist to Double like so

dist.toDouble mustBe 3.058D +- 0.1

or make other arguments floats like so

dist mustBe 3.058f +- 0.1f

Possibly related to Comparison matchers fail on mixed numeric types


问:
Workflow for creating new Maven project in Eclipse and bringing it to Github
I want to create a new Maven project in Eclipse and push it to a new repository on github. I am a bit stuck on the right order of steps to achieve this.

To use a Maven archetype, I cannot use a directory with files in it. So I cannot create a Maven project in a git local repository. So using the archetype should probably come first.

I also need to create a repository in my github account. If I do this through the github desktop app, this already creates a local repository for me.

Now I have an Eclipse project and a local repository, up to now unrelated. How should I "relate" them?

I found a lot of information about cloning from github, but my github repository does not have a Maven project yet, so I cannot import in Eclipse. If I use command line instead and an empty directory, I cannot apply Maven archetypes any more because the directory is not empty.

I am confused. Can somebody de-confuse me?

答:
Try this

Create a blank project in git hub

create a maven project in local

clone the git repo

this will not have any file

copy the maven project

add the files to git and push


问:
I am getting two errors in my CSS code, "Expected RBRACE", "Unexpected RBRACE", and "Expected LBRACE"
I am new to CSS and HTML as I am learning it in my free time for my livestreaming.
I am attempting to create a custom text animation of the text being cut in half, with the left half floating up and the right half floating down (possibly in future changing to where they both just swing and fall downwards).

I'm not fully sure what to try at this point, I have added, removed, and messed with the code in every way I can think of. I have scoured the internet and this forum and found nothing to help me.

```<code>#keyframes slideup {
    0% {
        top: 50%
    }
    30% {
        top: 50%;
    }
    90% {
        top 40%;
    }
    100%: {
        top: 40%;
}
</code>```

I expect the left half of the text to float upwards while the right side floats downwards, but that is not happening and I'm assuming its because of my code.

答:
p{
position:absolute;
top:50%;
left:50%;
animation:slideup 1s infinite;
}
@keyframes slideup {
    0% {
        transform:translateY(0);
    }
    100%{
      transform:translateY(-100px)
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>text<p></code>```

this is how u create animation!

Body:
I am new to CSS and HTML as I am learning it in my free time for my livestreaming.
I am attempting to create a custom text animation of the text being cut in half, with the left half floating up and the right half floating down (possibly in future changing to where they both just swing and fall downwards).

I'm not fully sure what to try at this point, I have added, removed, and messed with the code in every way I can think of. I have scoured the internet and this forum and found nothing to help me.

#keyframes slideup {
    0% {
        top: 50%
    }
    30% {
        top: 50%;
    }
    90% {
        top 40%;
    }
    100%: {
        top: 40%;
}

I expect the left half of the text to float upwards while the right side floats downwards, but that is not happening and I'm assuming its because of my code.

Body:
p{
position:absolute;
top:50%;
left:50%;
animation:slideup 1s infinite;
}
@keyframes slideup {
    0% {
        transform:translateY(0);
    }
    100%{
      transform:translateY(-100px)
}
}

<p>text<p>

this is how u create animation!


问:
How to make website look same on all browsers?
I am designing my site on a mac.  I used basic formatting and then when i want on to my pc, the wrapper width was too wide.  My question is what can i do so that my website looks the same on all browsers/os?</p>

答:
Autoprefixer uses data on the popularity of browsers and support for vendor prefixes by browsers. Based on this information, it arranges and deletes the prefixes. It can help you to get prefixes for: animations, transition, transform, grid, flex, flexbox and others. It is recommended by Google and used by Twitter and Alibaba.source

autoprefixer tag

autoprefixer GitHub – PostCSS plugin to parse CSS and add vendor prefixes to CSS rules using values from Can I Use

Autoprefixer CSS online – web repl for the original autorefixer.

ContentLicense: CC BY-SA 2.5


问:
Js regexp question match
I am just starting to learn js and I got stuck to regexp at a specific expression. Can you figure out what !![a-z]* will match ?
I can't seem to figure this one out.

ContentLicense: CC BY-SA 3.0

Title: Js regexp question match

Body:
'!!abcdefgh$asd124123'.match(/!![a-z]*/g)
return ["!!abcdefgh"]

'!!#abcdefgh$asd124123'.match(/!![a-z]*/g)

return ['!!']


问:
insert in std::map is throwing error. The key is a std::pair and the value is a short
```<code>#include <iostream>
#include <map>
#include <utility>
int main()
    {
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;
       // p = std::make_pair("A", "a1");
        m.insert(std::make_pair("A", "a1"), 10);
        return 0;
    }
</code>```

This code is throwing the following error

```<code>maptest.cpp: In function ‘int main()’:
maptest.cpp:9: error: no matching function for call to
‘std::map<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int,
std::less<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >, std::allocator<std::pair<const
std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int> > >::insert(std::pair<const char*,
const char*>, int)’
</code>```

I am trying to do a std map insertion. The kwy is a std pair and value is a short. But I am getting the above mentioned error.
What am I doing wrong here? Pleas help.

答:
The insert function takes a pair. You need

```<code> m.insert(std::make_pair(std::make_pair("A", "a1"), 10));
</code>```

Alternatively, you could use the emplace function:

```<code> m.emplace(std::make_pair("A", "a1"), 10);
</code>```

As a side note, in programmers' vernacular, the word "throw" has a specific meaning relating to exceptions. In your case you are just getting a compilation error.

Body:
#include <iostream>
#include <map>
#include <utility>
int main()
    {
        std::pair<std::string, std::string> p;
        std::map< std::pair<std::string, std::string>, short> m;
       // p = std::make_pair("A", "a1");
        m.insert(std::make_pair("A", "a1"), 10);
        return 0;
    }

This code is throwing the following error

maptest.cpp: In function ‘int main()’:
maptest.cpp:9: error: no matching function for call to
‘std::map<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int,
std::less<std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > > >, std::allocator<std::pair<const
std::pair<std::basic_string<char, std::char_traits<char>,
std::allocator<char> >, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, short int> > >::insert(std::pair<const char*,
const char*>, int)’

I am trying to do a std map insertion. The kwy is a std pair and value is a short. But I am getting the above mentioned error.
What am I doing wrong here? Pleas help.

Body:
The insert function takes a pair. You need

 m.insert(std::make_pair(std::make_pair("A", "a1"), 10));

Alternatively, you could use the emplace function:

 m.emplace(std::make_pair("A", "a1"), 10);

As a side note, in programmers' vernacular, the word "throw" has a specific meaning relating to exceptions. In your case you are just getting a compilation error.


问:
COLCOIN - Collecting Coins
I am solving this problem - COLCOIN - Collecting Coins on spoj.
link- https://www.spoj.com/problems/COLCOIN/

where for a given set of denominations, and money you want, the bank gives you the coins with highest denominations, until it can't anymore and then move to the next highest denomination. ex: if the denominations are [1,2,3,4,8], if you request 23 rupees, it gives you two 8 rupee coins first and as it can't give any more 8 rupee coins, moves to next denomination and gives you one 4 rupee and one 3 rupee.

The problem is to find the maximum of number of distinct denominations you can get given an input of denominations. money you request from bank is a variable, it actually shouldn't come into the picture if I am correct.

this is my idea:

try to sum up the value of lower denominations and see if they can add up to a bigger denominations,and if they are you'll never get all the smaller denominations.

ex: let's say there is 1, 2 and 5. 1+2< 5. so you can get all denominations. for 8 = 5+2+1

another: let's say there are denominations 3,4 and 5. so 3+4>5 so, we can never get all the denominations. because money will be given in denominations of 5 until the money that should be given is less than 5. and obviously you can't get 3+4= 7 rupees for something less than 5

One other idea which obviously is wrong is to start with 2nd highest denomination and find the coins which we will add upto that and return that solution+1(highest denomination).
it is not correct because, for example, [1,2,4,17,19], if we count 19 already in try to sum up others for 18, we get 1+17, only 2 denominations other than, where as 26 would have given 4 denominations 19+4+2+1

答:
I think you can use the following approach:

Start with the lowest denomination

Check if adding the next lowest denomination exceeds the denomination after that

If the sum is smaller, add the denomination to the sum

otherwise continue and check if the denomination one step further doesn't exceed the denomination after that.

Example: 1 3 6 8 15 20

different denominations d = 1, sum = 1

1 + 3 < 6: d = 2, sum = 4

4 + 6 >= 8: d = 2, sum = 4

4 + 8 < 15: d = 3, sum = 12

12 + 15 >= 20: d = 3, sum = 12

12 + 20 < infinity: d = 4, sum = 32

=> answer is 4 (and the amount to withdraw is 32).

Implementation:

// expects the denominations to be ordered from smallest to largest
// and also expects them to be unique
function findMaxDenominationsInSingleWithdrawal(denominations) {
    if (denominations.length <= 2)
        return denominations.length
    let sum = denominations[0], d = 1
    for (let index = 1; index + 1 < denominations.length; index++) {
        if (sum + denominations[index] < denominations[index + 1]) {
            d++
            sum += denominations[index]
        }
    }
    return d + 1
}

console.log(findMaxDenominationsInSingleWithdrawal([1, 3, 6, 8, 15, 20]))```

Title: COLCOIN - Collecting Coins


答:
Create a new Maven project (however you want to create it). This, of course, will create a new directory in the file system with all the resources.

Create a repository in Github.

From the command line (located inside the project directory) do git init. This will create the local repository inside that directory.

Next, add a remote to your local repository: $ git remote add origin https://github.com/user/repo.git (optionally replace origin for the name your remote repository is going to be called, also replace user for your github username and repo for the name of your github repository name)

Add all files to be commited in the local repository.

For example

```<code>$ git add .

# Adds the file to your local repository and stages it for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
</code>```

Commit changes.

For example:

```<code>$ git commit -m "Add existing file"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
</code>```

Push to remote.

Just be clear, taking the following structure as reference, What I propose is to have as git repositories any of the directories project1, project2, projectN, not the whole worspace (/roo_dir/workspace/ directory).

```<code>/roo_dir/workspace/
            - project1
            - project2
            - projectN
</code>```

Additional readings:

Considerations for Git Repositories to be used in Eclipse

Should I store git repository in Home or Eclipse Workspace?

Is it better to keep Git repository inside or outside of Eclipse workspace?

Title: Workflow for creating new Maven project in Eclipse and bringing it to Github

Body:
I want to create a new Maven project in Eclipse and push it to a new repository on github. I am a bit stuck on the right order of steps to achieve this.

To use a Maven archetype, I cannot use a directory with files in it. So I cannot create a Maven project in a git local repository. So using the archetype should probably come first.

I also need to create a repository in my github account. If I do this through the github desktop app, this already creates a local repository for me.

Now I have an Eclipse project and a local repository, up to now unrelated. How should I "relate" them?

I found a lot of information about cloning from github, but my github repository does not have a Maven project yet, so I cannot import in Eclipse. If I use command line instead and an empty directory, I cannot apply Maven archetypes any more because the directory is not empty.

I am confused. Can somebody de-confuse me?

Body:
Create a new Maven project (however you want to create it). This, of course, will create a new directory in the file system with all the resources.

Create a repository in Github.

From the command line (located inside the project directory) do git init. This will create the local repository inside that directory.

Next, add a remote to your local repository: $ git remote add origin https://github.com/user/repo.git (optionally replace origin for the name your remote repository is going to be called, also replace user for your github username and repo for the name of your github repository name)

Add all files to be commited in the local repository.

For example

$ git add .

# Adds the file to your local repository and stages it for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.

Commit changes.

For example:

$ git commit -m "Add existing file"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.

Push to remote.

Just be clear, taking the following structure as reference, What I propose is to have as git repositories any of the directories project1, project2, projectN, not the whole worspace (/roo_dir/workspace/ directory).

/roo_dir/workspace/
            - project1
            - project2
            - projectN

Additional readings:

Considerations for Git Repositories to be used in Eclipse

Should I store git repository in Home or Eclipse Workspace?

Is it better to keep Git repository inside or outside of Eclipse workspace?


问:
how to display mongodb date in symfony2 twig template?
I have a website listing products using symfony2 and mongodb

I added the items into mongodb with create date and need to display all items in my twig template.

For this

In my controller I passed the array itemlist  to twig template.

My twig template

```<code>{% for item in itemlist %}
<h4>{{item.name}}</h4>
<p>{{item.name}}</p>
{{item.createdate}}
{% endfor %}
</code>```

Here I am not getting the item.createdate

How to directly display the mongo date in twig template?

is there any twig extension for this?

答:
Th most simple way i found is : </p>

```<code>{{ event.begin.toDateTime()|date("d/m/Y H:i:s") }}
</code>```

Body:
I have a website listing products using symfony2 and mongodb

I added the items into mongodb with create date and need to display all items in my twig template.

For this

In my controller I passed the array itemlist  to twig template.

My twig template

{% for item in itemlist %}

{{item.name}}

{{item.name}}

{{item.createdate}}
{% endfor %}

Here I am not getting the item.createdate

How to directly display the mongo date in twig template?

is there any twig extension for this?

Body:
Th most simple way i found is :

{{ event.begin.toDateTime()|date("d/m/Y H:i:s") }}


问:
How do you decode info_hash information from tracker announce request?
I have the following tracker request:

```<code>"info_hash=%92%c345%c0%28%15%e4rr%b1y%17%b7%cbs%0a%ef%9a%fc&peer_id=-UT2210-%2abP%b2%c23~NaN7-%7c%0f%1f&port=56541&uploaded=0&downloaded=0&left=461680&corrupt=0&key=6AD19369&event=started&numwant=200&compact=1&no_peer_id=1"
</code>```

and I would like to decode the info_hash and peer_id fields in JavaScript.
I've tried the unescape(), decodeURI() and decodeURIComponent() functions but they didn't return the expected results.

答:
the method you use to 'decode' depends upon how it was 'encoded'.

When choosing the encoding method:

escape() will not encode: @*/+

encodeURI() will not encode: ~!@#$&*()=:/,;?+'

encodeURIComponent() will not encode: ~!*()'

you may be looking at some form of double encoding.

Body:
I have the following tracker request:

"info_hash=%92%c345%c0%28%15%e4rr%b1y%17%b7%cbs%0a%ef%9a%fc&peer_id=-UT2210-%2abP%b2%c23~NaN7-%7c%0f%1f&port=56541&uploaded=0&downloaded=0&left=461680&corrupt=0&key=6AD19369&event=started&numwant=200&compact=1&no_peer_id=1"

and I would like to decode the info_hash and peer_id fields in JavaScript.
I've tried the unescape(), decodeURI() and decodeURIComponent() functions but they didn't return the expected results.


问:
Is there any way to force the use of a class and not a subclass in a method?
I have a parent class called BasicUser and a subclass called User that inherits from BasicUser. When I try to add a basic user(BasicUser class) using a user(User class) it passes the whole User object instead of just the BasicUser.

Is there a way to avoid sending a subclass that conforms to a class in a method?

```<code>class BasicUser {}

class User: BasicUser {}

func addAttendingUser(_ newUser: BasicUser) {

}

let user = User()
addAttendingUser(user)
</code>```

EDIT:
Some logic behind ObjectMapper.
First of all, it maps a Festival and because Festival has a BasicUser array (attendingUsers) it calls mapping on BasicUser which it's a User.

User has a followedFestivals array and this is where it gets accessed from multiple threads.

On User class:

```<code>override func mapping(map: Map) {
    super.mapping(map: map)
    followedFestivals <- map["followed_festivals"]
}
</code>```

On Festival class:

```<code>override func mapping(map: Map) {
    super.mapping(map: map)
    attendingUsers <- map["attending_users_list"]
}
</code>```

答:
The easiest thing would be instantiate a new object.</p>

```<code>class BasicUser {

    init() {}

    init(fromOther other: BasicUser) {
        // basically copy the value from other to self
    }

}

class User: BasicUser {}

func addAttendingUser(_ newUser: BasicUser) {
    let newUser = BasicUser(fromOther: newUser)
    // do your stuff
}

let user = User()
addAttendingUser(user)
</code>```

Body:
I have a parent class called BasicUser and a subclass called User that inherits from BasicUser. When I try to add a basic user(BasicUser class) using a user(User class) it passes the whole User object instead of just the BasicUser.

Is there a way to avoid sending a subclass that conforms to a class in a method?

class BasicUser {}

class User: BasicUser {}

func addAttendingUser(_ newUser: BasicUser) {

}

let user = User()
addAttendingUser(user)

EDIT:
Some logic behind ObjectMapper.
First of all, it maps a Festival and because Festival has a BasicUser array (attendingUsers) it calls mapping on BasicUser which it's a User.

User has a followedFestivals array and this is where it gets accessed from multiple threads.

On User class:

override func mapping(map: Map) {
    super.mapping(map: map)
    followedFestivals <- map["followed_festivals"]
}

On Festival class:

override func mapping(map: Map) {
    super.mapping(map: map)
    attendingUsers <- map["attending_users_list"]
}

Body:
The easiest thing would be instantiate a new object.

class BasicUser {

    init() {}

    init(fromOther other: BasicUser) {
        // basically copy the value from other to self
    }

}

class User: BasicUser {}

func addAttendingUser(_ newUser: BasicUser) {
    let newUser = BasicUser(fromOther: newUser)
    // do your stuff
}

let user = User()
addAttendingUser(user)


问:
Filter then copy and paste values to new Excel tab
I'm trying to use an autofilter to filter unique values, then copy and paste these values to a new Excel tab.

The macro stops working at this line of code.

```<code>Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True
</code>```

```<code>Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

For Each x In Range([CA2], Cells(Rows.Count, "CA").End(xlUp))
    With rng
        .AutoFilter
        .AutoFilter Field:=1, Criteria1:=x.Value
        .SpecialCells(xlCellTypeVisible).Copy

        Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value
        ActiveSheet.Paste
        ActiveSheet.Range("A1").Select
        ActiveSheet.Columns("A:A").Select
        Selection.ColumnWidth = 15

    End With
Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False

With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

End Sub
</code>```

答:
it is Working !!  </p>

```<code>Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("CA1"), Unique:=True

End Sub
</code>```

Body:
I'm trying to use an autofilter to filter unique values, then copy and paste these values to a new Excel tab.

The macro stops working at this line of code.

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, _
  CopyToRange:=Range("CA1"), Unique:=True

For Each x In Range([CA2], Cells(Rows.Count, "CA").End(xlUp))
    With rng
        .AutoFilter
        .AutoFilter Field:=1, Criteria1:=x.Value
        .SpecialCells(xlCellTypeVisible).Copy

        Sheets.Add(After:=Sheets(Sheets.Count)).Name = x.Value
        ActiveSheet.Paste
        ActiveSheet.Range("A1").Select
        ActiveSheet.Columns("A:A").Select
        Selection.ColumnWidth = 15

    End With
Next x

' Turn off filter
Sheets(sht).AutoFilterMode = False

With Application
    .CutCopyMode = False
    .ScreenUpdating = True
End With

End Sub

Body:
it is Working !!

Private Sub CommandButton3_Click()

Application.ScreenUpdating = False
Dim x As Range
Dim rng As Range
Dim last As Long
Dim sht As String

'specify sheet name in which the data is stored
sht = "data"

'change filter column in the following code
last = Sheets(sht).Cells(Rows.Count, "B").End(xlUp).Row
Set rng = Sheets(sht).Range("A1:AY" & last)
'set last column

Sheets(sht).Range("A1:A" & last).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("CA1"), Unique:=True

End Sub


问:
PHP MySQL Insert not working without error
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

```<code><?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>
</code>```

答:
Did you try to put single quotes around description variable?

Change

```<code>VALUES('$name', '$price', '$type', $des, '$img')";
</code>```

To

```<code>VALUES('$name', '$price', '$type', '$des', '$img')";
</code>```

Cheers

Body:
i used this code and i didnt get any errors but when i check the phpadmin and my database its all empty no data added to the table what should i do ?
where is the problem?

i checked also my database and table values and my html names

<?php
    if(isset( $_POST['submit'] ) )
    {
        $name = $_POST['p_name'];
        $price = $_POST['p_price'];
        $type = $_POST['p_type'];
        $des = $_POST['p_desc'];
        $img = 'images/is7.jpeg';
        //***********************
        require_once 'setting.php';
        $dbc = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        mysqli_set_charset($dbc, 'utf8');
        $query = "INSERT INTO products(name, price, type, des, img)
                        VALUES('$name', '$price', '$type', $des, '$img')";
        mysqli_query($dbc, $query);
        mysqli_close($dbc);
        header('Location: success.php');
        exit;
    }
?>

Body:
Did you try to put single quotes around description variable?

Change

VALUES('$name', '$price', '$type', $des, '$img')";

To

VALUES('$name', '$price', '$type', '$des', '$img')";

Cheers


问:
What is the name of com.mysql's datasource implementation?
I just installed the official mysql jdbc driver, and I cannot find the class name for the datasource implementation.

I saw in a site that it was com.mysql.jdbc.jdbc2.optional.MysqlDataSource, but eclipse does not recognize it.  (trying to import it gives me an error)

I tried reading the documentation, but I only found the name for the Driver.
I know there is another thread asking the same question, but it does not answer my question.

Please help me.

Thank you for your time.

答:
With MySQL Connector/J 8.0 the import is</p>

```<code>import com.mysql.cj.jdbc.MysqlDataSource;
</code>```

Body:
With MySQL Connector/J 8.0 the import is

import com.mysql.cj.jdbc.MysqlDataSource;


问:
Press-and-hold button for "repeat fire"
I have referred to countless other questions about a press-and-hold button but there aren't many related to Swift. I have one function connected to a button using the touchUpInside event:

```<code>@IBAction func singleFire(sender: AnyObject){
    //code
}
</code>```

...and another function that is meant to call the function above repeatedly while the same button is held down, and stop when the button is no longer pressed:

```<code>@IBAction func speedFire(sender: AnyObject){

    button.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown)
    button.addTarget(self, action: "buttonUp:", forControlEvents: .TouchUpOutside)

    func buttonDown(sender: AnyObject){
        timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "singleFire", userInfo: nil, repeats: true)
    }

    func buttonUp(sender: AnyObject){
        timer.invalidate()
    }
}
</code>```

I'm not sure what I'm doing wrong, and I don't know how to setup touch events to the same button for a different function.

答:
I took a different approach when coming up with my own solution. I created a UIButton subclass and enclosed all the solution inside. The difference is that instead of using an IBAction for the handler I created a property in the UIButton

```<code>class RapidFireButton: UIButton {

    private var rapidFireTimer: Timer?
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    init() {
        super.init(frame: .zero)
        commonInit()
    }

    private func commonInit() {
        addTarget(self, action: #selector(touchDownHandler), for: .touchDown)
        addTarget(self, action: #selector(touchUpHandler), for: .touchUpOutside)
        addTarget(self, action: #selector(touchUpHandler), for: .touchUpInside)
    }

    @objc private func touchDownHandler() {
        rapidFireTimer?.invalidate()
        rapidFireTimer = nil
        tapHandler(self)
        rapidFireTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { [unowned self] (timer) in
            self.tapHandler(self)
        })
    }

    @objc private func touchUpHandler() {
        rapidFireTimer?.invalidate()
        rapidFireTimer = nil
    }

    var tapHandler: (RapidFireButton) -> Void = { button in

    }
}
</code>```

Usage is basically creating an outlet for the button and implementing the handler like so

```<code>rapidFireButton.tapHandler = { button in
    //do stuff
}
</code>```

Title: Press-and-hold button for "repeat fire"

Body:
I have referred to countless other questions about a press-and-hold button but there aren't many related to Swift. I have one function connected to a button using the touchUpInside event:

@IBAction func singleFire(sender: AnyObject){
    //code
}

...and another function that is meant to call the function above repeatedly while the same button is held down, and stop when the button is no longer pressed:

@IBAction func speedFire(sender: AnyObject){

    button.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown)
    button.addTarget(self, action: "buttonUp:", forControlEvents: .TouchUpOutside)

    func buttonDown(sender: AnyObject){
        timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "singleFire", userInfo: nil, repeats: true)
    }

    func buttonUp(sender: AnyObject){
        timer.invalidate()
    }
}

I'm not sure what I'm doing wrong, and I don't know how to setup touch events to the same button for a different function.

Body:
I took a different approach when coming up with my own solution. I created a UIButton subclass and enclosed all the solution inside. The difference is that instead of using an IBAction for the handler I created a property in the UIButton

class RapidFireButton: UIButton {

    private var rapidFireTimer: Timer?
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    init() {
        super.init(frame: .zero)
        commonInit()
    }

    private func commonInit() {
        addTarget(self, action: #selector(touchDownHandler), for: .touchDown)
        addTarget(self, action: #selector(touchUpHandler), for: .touchUpOutside)
        addTarget(self, action: #selector(touchUpHandler), for: .touchUpInside)
    }

    @objc private func touchDownHandler() {
        rapidFireTimer?.invalidate()
        rapidFireTimer = nil
        tapHandler(self)
        rapidFireTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { [unowned self] (timer) in
            self.tapHandler(self)
        })
    }

    @objc private func touchUpHandler() {
        rapidFireTimer?.invalidate()
        rapidFireTimer = nil
    }

    var tapHandler: (RapidFireButton) -> Void = { button in

    }
}

Usage is basically creating an outlet for the button and implementing the handler like so

rapidFireButton.tapHandler = { button in
    //do stuff
}


问:
No way to make Work persistent across reboots?
So I know WorkManager utilizes JobScheduler on supported APIs but there doesnt seem to be any way to make WorkManager work persistent across reboots? Is the only option to request the BOOT_COMPLETED permission and reschedule jobs?

答:
To answer your question: You don't need to do anything if the device is rebooted. WorkManager keeps scheduling your Work without any additional requirement from your side.

WorkManager persists Work requests in its internal Room database. This allows it to guarantee Work execution across device restart.

The documentation covers this as this blog "Introducing WorkManager" that the team wrote last year.


问:
How to call a function and then navigate to a route when click on a button?
Here is my code.

```<code><button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>
</code>```

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"

答:
Try

```<code>return <Redirect to='/proceedToCheckout'/>;
</code>```

Instead of

```<code><Link to="/proceedToCheckout">Buy Now</Link>
</code>```

Please import Redirect from your router library.

Body:
Here is my code.

<button type="button" className="btn btn-outline-secondary" onClick={this.addToCart.bind(
    this,
    this.state.itemDetails.product.images[0].path,
    this.state.itemDetails.name,
    this.state.itemDetails.id,
    this.state.itemDetails.unitPrice,
    this.state.quantity
)} >
    <Link to="/proceedToCheckout">
    Buy Now
    </Link>
</button>

Here I want to call the event onClick and with that I want to direct page to the link "/proceedToCheckout" when I click on the button. I want to do both of this with a single button click.
In the above code, when I click on the button area it calls the addToCart function. But route is not working. If I click on the word "Buy Now" (the link) then it directs to the route. But I want to do is with a single button click I need to call the function "addToCart" and then to direct to the route "/proceedToCheckout"

Body:
Try

return <Redirect to='/proceedToCheckout'/>;

Instead of

<Link to="/proceedToCheckout">Buy Now</Link>

Please import Redirect from your router library.


问:
Best practice for instantiating and initialising a Model in ASP.NET Core MVC
I have a method that returns a view, and in that view I want to display a list of something. In order to do this, I'll need a model with houses the list.

Microsoft's documentation (https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.2) says that it is the responsibility of the controller to select and work with the model(s) and that the responsibility of the model is to encapsulate business logic. This being said, I'm unsure of the best practice:

Logic in the controller:

Model:

```<code>public class DepartmentViewModel
{
    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}
</code>```

Controller:

```<code>public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index(DepartmentViewModel viewmodel)
    {
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        viewmodel.lstDepartments = lstDepartmentsForViewmodel;
        return View(viewmodel);
    }
}
</code>```

Logic in the model:

Model:

```<code>public class DepartmentViewModel
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentViewModel(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        lstDepartments = lstDepartmentsForViewmodel;
    }

    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}
</code>```

Controller:

```<code>public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index()
    {
        DepartmentViewModel viewmodel = new DepartmentViewModel(_work, _mapper);
        return View(viewmodel);
    }
}
</code>```

Guidance of any kind would be most appreciated.

答:
I would recommend you go for the first approach

Logic in the controller:

Model:

```<code>public class DepartmentViewModel
{
    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}
</code>```

Controller:

```<code>public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index(DepartmentViewModel viewmodel)
    {
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        viewmodel.lstDepartments = lstDepartmentsForViewmodel;
        return View(viewmodel);
    }
}
</code>```

Best practise is using DI to init services or dependency value in your constructor. If you go for second approach you have to send the data to the constructor like this

```<code>DepartmentViewModel viewmodel = new DepartmentViewModel(_work, _mapper);
</code>```

And that is not ideally what if you have a lot of model ?

Body:
I have a method that returns a view, and in that view I want to display a list of something. In order to do this, I'll need a model with houses the list.

Microsoft's documentation (https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.2) says that it is the responsibility of the controller to select and work with the model(s) and that the responsibility of the model is to encapsulate business logic. This being said, I'm unsure of the best practice:

Logic in the controller:

Model:

public class DepartmentViewModel
{
    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}

Controller:

public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index(DepartmentViewModel viewmodel)
    {
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        viewmodel.lstDepartments = lstDepartmentsForViewmodel;
        return View(viewmodel);
    }
}

Logic in the model:

Model:

public class DepartmentViewModel
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentViewModel(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        lstDepartments = lstDepartmentsForViewmodel;
    }

    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}

Controller:

public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index()
    {
        DepartmentViewModel viewmodel = new DepartmentViewModel(_work, _mapper);
        return View(viewmodel);
    }
}

Guidance of any kind would be most appreciated.

Body:
I would recommend you go for the first approach

Logic in the controller:

Model:

public class DepartmentViewModel
{
    public IEnumerable<DepartmentDto> lstDepartments { get; set; }
}

Controller:

public class DepartmentController : Controller
{
    private readonly IUnitOfWork _work;
    private readonly IMapper _mapper;

    public DepartmentController(IUnitOfWork work, IMapper mapper)
    {
        _work = work;
        _mapper = mapper;
    }

    public async Task<IActionResult> Index(DepartmentViewModel viewmodel)
    {
        var lstAllDepartments = _work.DepartmentRepository.GetAll(); // All departments from the database.
        var lstDepartmentsForViewmodel = _mapper.Map<IEnumerable<Core.Entities.Department>, IEnumerable<DepartmentDto>>(lstAllDepartments); // Map to DTO.
        viewmodel.lstDepartments = lstDepartmentsForViewmodel;
        return View(viewmodel);
    }
}

Best practise is using DI to init services or dependency value in your constructor. If you go for second approach you have to send the data to the constructor like this

DepartmentViewModel viewmodel = new DepartmentViewModel(_work, _mapper);

And that is not ideally what if you have a lot of model ?


问:
favicon doesn't show up unless its name is "favicon.ico" - Local Apache2 Server
I am trying to add a favicon to my web page.

It works fine if the icon name is favicon.ico. But what if I don't want it to be named like that ?

What if I want to add more icons with different sizes. Like a 192x192 for Android Chrome ?

My website isn't live. It's local. It's on Apache2. I have it on a Raspberry Pi and on my Linux PC. Both servers have identical settings/configurations.
It behaves exactly the same on both servers.

All files(html,php,png,ico, etc) are inside one directory: /var/www/mysite. I've changed DocumentRoot to DocumentRoot /var/www/mysite inside etc/apache2/sites-enabled/000-default.conf

I am using Chrome. I cleared the cache. I'm refreshing the page using SHIFT + F5, CTRL + F5 or F5; all with similar results.

Note that it's index.php not index.html.
Here is what I've written inside the head tag inside index.php:

```<code><head>
    <meta charset = "utf-8">
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0">

    <!-- Chrome, Firefox OS and Opera -->
    <meta name="theme-color" content="#e11422">
    <!-- Windows Phone -->
    <meta name="msapplication-navbutton-color" content="#e11422">
    <!-- iOS Safari -->
    <meta name="apple-mobile-web-app-status-bar-style" content="#e11422">

    <link rel="shortcut icon" href="/favicon16x16.ico?v=3" type="image/x-icon">
    <link rel="icon" sizes="192x192" href="favicon-192x192.png">

    <link rel = "stylesheet" type = "text/css" href = "master.css">
    <title>Home Page</title>
    <script type="text/javascript" src="jquery-1.12.4.min.js"></script>

<!-- <script>
    $(document).ready( function(){
    $('.text-box').load('events_placeholder.html');
    refresh();
    });

    function refresh(){
        setTimeout( function() {
            $('.text-box').load('events_placeholder.html');
            refresh();
        }, 1000);
    }
</script> -->

<script>
    /* When the user clicks on the button,toggle between hiding and showing the dropdown content */
    function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
    }

    /* Close the dropdown menu if the user clicks outside of it */
    window.onclick = function(event) {
    if (!event.target.matches('.dropbtn') && !event.target.matches("#text-input") && !event.target.matches("#button")) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if (openDropdown.classList.contains('show')) {
            openDropdown.classList.remove('show');
        }
        }
    }
    }
</script>

<script>
$(document).ready(function() {
    $('.URR').change(function() {
        var n = $('.URR').val();
        if (n < 1)
            $('.URR').val(1);
        if (n > 10)
            $('.URR').val(10);
    });
    $('.Brightness').change(function() {
        var m = $('.Brightness').val();
        if (m < 2)
            $('.Brightness').val(2);
        if (m > 99)
            $('.Brightness').val(99);
    });
});
</script>

</head>
</code>```

I've read all that I could find on SO and on Google.
The only thing that came close to answering my questions is this SO question. But, the question being 8 years old, I really hope that something has changed since then.

Fix:

The fix I found was to actually include a favicon.ico.

Also, thanks to @Punit Gajjar I was able to find one of the best favicon tools online: Real Favicon Generator.

I recommend it to everyone who's trying to make a favicon.
After using the Favicon Generator I've added all the files generated (png, ico) to where index.php is located and also the following code inside the head tag:

```<code>    <!-- iOS App Icon-->
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=476mA4zprB">
    <!-- Chrome, Firefox OS and Opera -->
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png?v=476mA4zprB">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png?v=476mA4zprB">
    <link rel="manifest" href="/site.webmanifest?v=476mA4zprB">
    <link rel="mask-icon" href="/safari-pinned-tab.svg?v=476mA4zprB" color="#e11422">
    <link rel="shortcut icon" href="/favicon.ico?v=476mA4zprB">
    <!-- Tab Color iOS Safari -->
    <meta name="apple-mobile-web-app-title" content="#e11422">
    <meta name="application-name" content="#e11422">
    <!-- Tile Color Microsoft Windows Shortcut -->
    <meta name="msapplication-TileColor" content="#b91d47">
    <!-- Tab Color Android Chrome -->
    <meta name="theme-color" content="#e11422">
</code>```

答:
In order to use the .png file you must use the type="image/png" attributes, like below.

```<code><link rel="icon" type="image/png" href="http://example.com/image.png" />
</code>```

Make sure that the path you have given is the absolute.

Body:
I am trying to add a favicon to my web page.

It works fine if the icon name is favicon.ico. But what if I don't want it to be named like that ?

What if I want to add more icons with different sizes. Like a 192x192 for Android Chrome ?

My website isn't live. It's local. It's on Apache2. I have it on a Raspberry Pi and on my Linux PC. Both servers have identical settings/configurations.
It behaves exactly the same on both servers.

All files(html,php,png,ico, etc) are inside one directory: /var/www/mysite. I've changed DocumentRoot to DocumentRoot /var/www/mysite inside etc/apache2/sites-enabled/000-default.conf

I am using Chrome. I cleared the cache. I'm refreshing the page using SHIFT + F5, CTRL + F5 or F5; all with similar results.

Note that it's index.php not index.html.
Here is what I've written inside the head tag inside index.php:

    <meta charset = "utf-8">
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0">

    <meta name="theme-color" content="#e11422">

    <meta name="msapplication-navbutton-color" content="#e11422">

    <meta name="apple-mobile-web-app-status-bar-style" content="#e11422">

    <link rel="shortcut icon" href="/favicon16x16.ico?v=3" type="image/x-icon">
    <link rel="icon" sizes="192x192" href="favicon-192x192.png">

    <link rel = "stylesheet" type = "text/css" href = "master.css">
    <title>Home Page</title>

I've read all that I could find on SO and on Google.
The only thing that came close to answering my questions is this SO question. But, the question being 8 years old, I really hope that something has changed since then.

Fix:

The fix I found was to actually include a favicon.ico.

Also, thanks to @Punit Gajjar I was able to find one of the best favicon tools online: Real Favicon Generator.

I recommend it to everyone who's trying to make a favicon.
After using the Favicon Generator I've added all the files generated (png, ico) to where index.php is located and also the following code inside the head tag:

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=476mA4zprB">

    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png?v=476mA4zprB">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png?v=476mA4zprB">
    <link rel="manifest" href="/site.webmanifest?v=476mA4zprB">
    <link rel="mask-icon" href="/safari-pinned-tab.svg?v=476mA4zprB" color="#e11422">
    <link rel="shortcut icon" href="/favicon.ico?v=476mA4zprB">

    <meta name="apple-mobile-web-app-title" content="#e11422">
    <meta name="application-name" content="#e11422">

    <meta name="msapplication-TileColor" content="#b91d47">

    <meta name="theme-color" content="#e11422">

Body:
In order to use the .png file you must use the type="image/png" attributes, like below.

<link rel="icon" type="image/png" href="http://example.com/image.png" />

Make sure that the path you have given is the absolute.


问:
matplotlib.pyplot: set distance for axis units
```<code>import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1))
plt.show()
</code>```

shows

But if I set unit to 0.5:
plt.xticks(np.arange(min(x), max(x)+1, 0.5)) shows

x-axis is hardly readable.

Is there a way to set distance for every x-axis unit so it could extend the plot automatically (on x direction)?

答:
This works:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.figure(figsize=(20,10))
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 0.5))
plt.show()
</code>```

Operating on size of the figure does the job. Play with it, find your desired size/ratio etc.

Body:
import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1))
plt.show()

shows

But if I set unit to 0.5:
plt.xticks(np.arange(min(x), max(x)+1, 0.5)) shows

x-axis is hardly readable.

Is there a way to set distance for every x-axis unit so it could extend the plot automatically (on x direction)?

Body:
This works:

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.figure(figsize=(20,10))
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 0.5))
plt.show()

Operating on size of the figure does the job. Play with it, find your desired size/ratio etc.


问:
How do I check if sum of any N numbers of items in a list equals or greater than a value in Kotlin
Is it possible to check if any combination of n numbers of Items in a list is greater than or equal to a number? and how?</p>

答:
You should probably try this:

```<code>private fun hasLargerSum(compareTo: Int, n: Int, list: List<Int>): Boolean =
        list.sorted()
            .takeLast(n)
            .sum() >= compareTo
</code>```

in this case it will take N elements of the list sorted ascending, sum it and compare to the number you need.

Cheers!

Body:
You should probably try this:

private fun hasLargerSum(compareTo: Int, n: Int, list: List<Int>): Boolean =
        list.sorted()
            .takeLast(n)
            .sum() >= compareTo

in this case it will take N elements of the list sorted ascending, sum it and compare to the number you need.

Cheers!


问:
How to search and replace a word/text in word document using python-docx
For example:
Please find below paragraphs in a word document. The paragraphs are inside a table.

Ok Guys Please get up

Ok Guys Please getting up.

I'm trying to replace "get" with "wake". I am looking for "get" to replace with "wake" only in the case of paragraph 1. But in the below-given code, its getting replaced in both paragraph as shown in below result. This behavior is same for all paragraphs in a word document.
Please suggest working as per the above requirement.

Actual Result:
1. Ok Guys Please wake up.
2. Ok Guys Please waketing up.

```<code>doc = docx.Document("path/docss.docx")
def Search_replace_text():
 for table in doc.tables:
  for row in table.rows:
   for cell in row.cells:
    for paragraph in cell.paragraphs:
     for run in paragraph.runs:
       if str(word.get()) in run.text:
         text = run.text.split(str(word.get())) # Gets input from GUI
         if text[1] == " ":
            run.text = text[0] + str(replace.get()) # Gets input from GUI
            print(run.text)
        else:
            run.text = text[0] + str(replace.get()) + text[1]
     else: break
     doc.save("docss.docx")
</code>```

I want the result as shown below:

Ok Guys Please wake up.

Ok Guys Please getting up.

Actual Result:

Ok Guys Please wake up.

Ok Guys Please waketing up.

答:
replace

```<code>if str(word.get()) in run.text:
</code>```

with little formating

```<code>if ' {} '.format(str(word.get())) in run.text:
</code>```

to search separeted word(with two spaces).

Body:
For example:
Please find below paragraphs in a word document. The paragraphs are inside a table.

Ok Guys Please get up

Ok Guys Please getting up.

I'm trying to replace "get" with "wake". I am looking for "get" to replace with "wake" only in the case of paragraph 1. But in the below-given code, its getting replaced in both paragraph as shown in below result. This behavior is same for all paragraphs in a word document.
Please suggest working as per the above requirement.

Actual Result:
1. Ok Guys Please wake up.
2. Ok Guys Please waketing up.

doc = docx.Document("path/docss.docx")
def Search_replace_text():
 for table in doc.tables:
  for row in table.rows:
   for cell in row.cells:
    for paragraph in cell.paragraphs:
     for run in paragraph.runs:
       if str(word.get()) in run.text:
         text = run.text.split(str(word.get())) # Gets input from GUI
         if text[1] == " ":
            run.text = text[0] + str(replace.get()) # Gets input from GUI
            print(run.text)
        else:
            run.text = text[0] + str(replace.get()) + text[1]
     else: break
     doc.save("docss.docx")

I want the result as shown below:

Ok Guys Please wake up.

Ok Guys Please getting up.

Actual Result:

Ok Guys Please wake up.

Ok Guys Please waketing up.

Body:
replace

if str(word.get()) in run.text:

with little formating

if ' {} '.format(str(word.get())) in run.text:

to search separeted word(with two spaces).


问:
Using "umlauts" in C++ code

Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

```<code>string überwachung;
</code>```

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles

答:
See section E/2 of the C++03 standard:

1 This clause lists the complete set of hexadecimal code values that are valid in universal-character-names in C++ identifiers (2.10).

…

Latin: 00c0–00d6, 00d8–00f6, 00f8–01f5, 01fa–0217, 0250–02a8, 1e00–1e9a, 1ea0–1ef9

This includes most accented letters.

The problem is that C++03 didn't specify UTF-8 as the input format. Even C++11 maintains compatibility with EBCDIC.

So, you can certainly create an identifier with an umlaut; the problem is getting a text editor that will interpret the universal-character-name and display it properly. Otherwise you're stuck inputting Unicode directly in hexadecimal format \uXXXX, e.g. \u00FC for ü.

A compiler which accepts UTF-8 in string constants but not in identifiers suffers from shortsighted implementation. Clang, at least, properly translates UTF-8 to universal-character-names in Phase 1.

Title: Using "umlauts" in C++ code

Body:
Possible Duplicate:

  C++ source in unicode

I just discovered this line of code in a project:

string überwachung;

I was surprised, because actually I thought you are not allowed to use umlauts like 'äöü' in C++ code other than in strings and so on, and it would result in a compiler error. But this compiles just fine with visual studio 2008.

Is this a special microsoft feature, or are umlauts allowed with other compilers too?

Are there any potential problems with that (portability,system language settings..)?

I can clearly remember this was not allowed. When did it change?

Kind regards for any clarification

P.S.: the tool cppcheck will even mark this usage as an error, even though it compiles


问:
Compiler Warning (level 2) CS0618 how to fix this
In my Xamarin forms project, It gives me this kind of obsolete warning how to fix this

here my code

```<code>         public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty =

        BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));

    public string Uri
    {
        get => (string) GetValue(UriProperty);
        set => SetValue(UriProperty, value);
    }
}
</code>```

how to fix this

答:
The docs for the BindableProperty.Create method show that the generic version of this method has been deprecated since version 2.1.0 meaning you shouldn't be using it. Instead you should use the non-generic overload, so your code should look like this:

```<code>BindableProperty.Create("Uri", typeof(string), typeof(CustomWebView), default(string));
</code>```

Body:
In my Xamarin forms project, It gives me this kind of obsolete warning how to fix this

here my code

         public class CustomWebView : WebView
{
    public static readonly BindableProperty UriProperty =

        BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));

    public string Uri
    {
        get => (string) GetValue(UriProperty);
        set => SetValue(UriProperty, value);
    }
}

how to fix this

Body:
The docs for the BindableProperty.Create method show that the <a href="https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.bindableproperty.create?view=xamarin-forms#Xamarin_Forms_BindableProperty_Create__2_System_Linq_Expressions_Expression_System_Func___0___1_____1_Xamarin_Forms_BindingMode_Xamarin_Forms_BindableProperty_ValidateValueDelegate___1__Xamarin_Forms_BindableProperty_BindingPropertyChangedDelegate___1__Xamarin_Forms_BindableProperty_BindingPropertyChangingDelegate___1__Xamarin_Forms_BindableProperty_CoerceValueDelegate___1__Xamarin_Forms_BindableProperty_CreateDefaultValueDelegate___0___1__" rel="nofollow noreferrer">generic version of this method has been deprecated since version 2.1.0 meaning you shouldn't be using it. Instead you should use the <a href="https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.bindableproperty.create?view=xamarin-forms#Xamarin_Forms_BindableProperty_Create_System_String_System_Type_System_Type_System_Object_Xamarin_Forms_BindingMode_Xamarin_Forms_BindableProperty_ValidateValueDelegate_Xamarin_Forms_BindableProperty_BindingPropertyChangedDelegate_Xamarin_Forms_BindableProperty_BindingPropertyChangingDelegate_Xamarin_Forms_BindableProperty_CoerceValueDelegate_Xamarin_Forms_BindableProperty_CreateDefaultValueDelegate_" rel="nofollow noreferrer">non-generic overload, so your code should look like this:

BindableProperty.Create("Uri", typeof(string), typeof(CustomWebView), default(string));


问:
how could i get date from varchar column in mysql
I want to get date from VARCHAR column.

(eg: 4/14/2018 12:00:00 AM)

How do I display only date

(eg: 4/14/2018)?

```<code>SELECT date(created_at) from self_balance
</code>```

here created_at(varchar)

this returns NULL value

答:
You can run this query to get your output,

```<code>SELECT DATE_FORMAT(STR_TO_DATE(created_at, "%Y-%m-%d"), "%Y-%m-%d") FROM
self_balance
</code>```

First I am matching date format and converting it to date and then formatting.

Body:
I want to get date from VARCHAR column.

(eg: 4/14/2018 12:00:00 AM)

How do I display only date

(eg: 4/14/2018)?

SELECT date(created_at) from self_balance

here created_at(varchar)

this returns NULL value

Body:
You can run this query to get your output,

SELECT DATE_FORMAT(STR_TO_DATE(created_at, "%Y-%m-%d"), "%Y-%m-%d") FROM
self_balance

First I am matching date format and converting it to date and then formatting.


问:
Need JS to keep the hover link active
I have a dropdown menu and i need help getting the hover link to stay active when i hover over it so it blends with the dropdown.

I have put the code on JSF

http://jsfiddle.net/JmR87/2/

Thanks

答:
Add a class to the element you are hovering over in the hover function and then remove it when you exit. The class should have the same style has the hover style:

```<code>$(function () {
  $('.dropdown, .dropdown2, .dropdown3').each(function () {
    $(this).parent().eq(0).hover(function () {
      $('.dropdown, .dropdown2, .dropdown3:eq(0)', this).show();
      $(this).addClass("hoverstyle");
    }, function () {
      $('.dropdown, .dropdown2, .dropdown3:eq(0)', this).hide();
      $(this).removeClass("hoverstyle");
    });
  });
});
</code>```

Then define .hoverstyle.

Title: Need JS to keep the hover link active

Body:
Add a class to the element you are hovering over in the hover function and then remove it when you exit. The class should have the same style has the hover style:

$(function () {
  $('.dropdown, .dropdown2, .dropdown3').each(function () {
    $(this).parent().eq(0).hover(function () {
      $('.dropdown, .dropdown2, .dropdown3:eq(0)', this).show();
      $(this).addClass("hoverstyle");
    }, function () {
      $('.dropdown, .dropdown2, .dropdown3:eq(0)', this).hide();
      $(this).removeClass("hoverstyle");
    });
  });
});

Then define .hoverstyle.


问:
Get topic id from Google Trends for a topic name using Python
Using Python, I am attempting to scrape data from Google Trends for "topics" (as opposed to "search terms").

I am currently using the pytrends module, but it appears it's not (currently) possible to scrape topics rather than search terms, unless you know the topic_id.

E.g. if you wanted to scrape the data for the topic_name "Holiday", you could search using the topic_id /m/03gkl, but only if you knew that that was the topic_id.

I have a list of topic names. I would like a corresponding list of topic ids. How can I achieve this?

答:
It looks like I didn't read the pytrends documentation properly and it is possible to get the topic id:

```<code>from pytrends.request import TrendReq
pytrends = TrendReq(hl='en-US', tz=360)
suggs = pytrends.suggestions("iron")
print(suggs)

[{'mid': '/m/025rw19', 'title': 'Iron', 'type': 'Chemical element'},
 {'mid': '/m/04jphh9', 'title': 'Clothes iron', 'type': 'Topic'},
 {'mid': '/m/0b6l369', 'title': 'Loha', 'type': '1987 film'},
 {'mid': '/m/03cld36', 'title': 'Iron', 'type': 'Golf'},
 {'mid': '/m/0281ql7', 'title': 'Ferric', 'type': 'III'}]
</code>```

From the above, it is easy to extract the topic id.

Body:
It looks like I didn't read the pytrends documentation properly and it is possible to get the topic id:

from pytrends.request import TrendReq
pytrends = TrendReq(hl='en-US', tz=360)
suggs = pytrends.suggestions("iron")
print(suggs)

[{'mid': '/m/025rw19', 'title': 'Iron', 'type': 'Chemical element'},
 {'mid': '/m/04jphh9', 'title': 'Clothes iron', 'type': 'Topic'},
 {'mid': '/m/0b6l369', 'title': 'Loha', 'type': '1987 film'},
 {'mid': '/m/03cld36', 'title': 'Iron', 'type': 'Golf'},
 {'mid': '/m/0281ql7', 'title': 'Ferric', 'type': 'III'}]

From the above, it is easy to extract the topic id.


问:
Can I create Dataset in power BI Using Power Shell
Actually I want to create dataset by using PowerShell, suppose I don't want to use power BI desktop to create Dataset and data source.</p>

答:
Yes, you can create a dataset either using Power BI REST API's PostDatasetInGroup (using it with Invoke-RestMethod) or using Microsoft's official Power BI Management module and Add-PowerBIDataset cmdlet in particular.

For example, something like that:

```<code>Login-PowerBI

$col1 = New-PowerBIColumn -Name ID -DataType Int64
$col2 = New-PowerBIColumn -Name Data -DataType String
$table1 = New-PowerBITable -Name SampleTable1 -Columns $col1,$col2

$col3 = New-PowerBIColumn -Name ID -DataType Int64
$col4 = New-PowerBIColumn -Name Date -DataType DateTime
$col5 = New-PowerBIColumn -Name Detail -DataType String
$col6 = New-PowerBIColumn -Name Result -DataType Double
$table2 = New-PowerBITable -Name SampleTable2 -Columns $col3,$col4,$col5,$col6

$dataset = New-PowerBIDataSet -Name SampleDataSet -Tables $table1,$table2

Add-PowerBIDataSet -DataSet $dataset
</code>```

Body:
Yes, you can create a dataset either using Power BI REST API's PostDatasetInGroup (using it with Invoke-RestMethod) or using Microsoft's official Power BI Management module and Add-PowerBIDataset cmdlet in particular.

For example, something like that:

Login-PowerBI

$col1 = New-PowerBIColumn -Name ID -DataType Int64
$col2 = New-PowerBIColumn -Name Data -DataType String
$table1 = New-PowerBITable -Name SampleTable1 -Columns $col1,$col2

$col3 = New-PowerBIColumn -Name ID -DataType Int64
$col4 = New-PowerBIColumn -Name Date -DataType DateTime
$col5 = New-PowerBIColumn -Name Detail -DataType String
$col6 = New-PowerBIColumn -Name Result -DataType Double
$table2 = New-PowerBITable -Name SampleTable2 -Columns $col3,$col4,$col5,$col6

$dataset = New-PowerBIDataSet -Name SampleDataSet -Tables $table1,$table2

Add-PowerBIDataSet -DataSet $dataset


问:
"Cannot read property" error while clicking Start Recording Button
I get a console error while clicking a record Button.

I worked with the Code From RTCMulticonnection to establish a connection and now want to have the ability to record the stream. I used this demo to record the stream:

RecordRTC-and-RTCMultiConnection
 https://github.com/muaz-khan/WebRTC-Experiment/blob/d1040f7dcd47c290f99ad51f9b3d57aa40c847c4/RTCMultiConnection/v2.2.2/demos/RecordRTC-and-RTCMultiConnection.html

The Console Message

```<code>Uncaught TypeError: Cannot read property 'YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r' of undefined
    at HTMLButtonElement.button.onclick (index.html:108)
</code>```

What I see is that in the demo version all streamid's have a short ID like
id="1mnvuzts2dm". My Version sets the streamid's to longer random strings like the one above in the Error id="YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r"

```<code>//RECORD THE CONVERSATION AUDIO + VIDEO
  connection.onstream = function(e) {
            appendVideo(e.mediaElement, e.streamid);
        };

        function appendVideo(video, streamid) {
            video.width = 600;
            video = getVideo(video, streamid);
            videosContainer.appendChild(video);
            rotateVideo(video);
            scaleVideos();
        }

        function getVideo(video, streamid) {
            var div = document.createElement('div');
            div.className = 'video-container';

            var button = document.createElement('button');
            button.id = streamid;
            button.innerHTML = 'Start Recording';
            button.onclick = function() {
                this.disabled = true;
                if (this.innerHTML == 'Start Recording') {
                    this.innerHTML = 'Stop Recording';
                    connection.streams[this.id].startRecording({
                        audio: true,
                        video: true
                    });
                } else {
                    this.innerHTML = 'Start Recording';
                    var stream = connection.streams[this.id];
                    stream.stopRecording(function(blob) {
                        var h2;

                        if (blob.audio && !(connection.UA.Chrome && stream.type == 'remote')) {
                            h2 = document.createElement('h2');
                            h2.innerHTML = '<a href="' + URL.createObjectURL(blob.audio) + '" target="_blank">Open recorded ' + blob.audio.type + '</a>';
                            div.appendChild(h2);
                        }

                        if (blob.video) {
                            h2 = document.createElement('h2');
                            h2.innerHTML = '<a href="' + URL.createObjectURL(blob.video) + '" target="_blank">Open recorded ' + blob.video.type + '</a>';
                            div.appendChild(h2);
                        }
                    });
                }
                setTimeout(function() {
                    button.disabled = false;
                }, 3000);
            };
            div.appendChild(button);
            div.appendChild(video);
            return div;
        }

        function rotateVideo(mediaElement) {
            mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(0deg)';
            setTimeout(function() {
                mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(360deg)';
            }, 1000);
        }

        connection.onstreamended = function(e) {
            var div = e.mediaElement.parentNode;
            div.style.opacity = 0;
            rotateVideo(div);
            setTimeout(function() {
                if (div.parentNode) {
                    div.parentNode.removeChild(div);
                }
                scaleVideos();
            }, 1000);
        };

      function scaleVideos() {
            var videos = document.querySelectorAll('video'),
                length = videos.length,
                video;

            var minus = 130;
            var windowHeight = 700;
            var windowWidth = 600;
            var windowAspectRatio = windowWidth / windowHeight;
            var videoAspectRatio = 4 / 3;
            var blockAspectRatio;
            var tempVideoWidth = 0;
            var maxVideoWidth = 0;

            for (var i = length; i > 0; i--) {
                blockAspectRatio = i * videoAspectRatio / Math.ceil(length / i);
                if (blockAspectRatio <= windowAspectRatio) {
                    tempVideoWidth = videoAspectRatio * windowHeight / Math.ceil(length / i);
                } else {
                    tempVideoWidth = windowWidth / i;
                }
                if (tempVideoWidth > maxVideoWidth)
                    maxVideoWidth = tempVideoWidth;
            }
            for (var i = 0; i < length; i++) {
                video = videos[i];
                if (video)
                    video.width = maxVideoWidth - minus;
            }
        }

</code>```

The ERROR Line is

```<code>connection.streams[this.id].startRecording({
</code>```

答:
You can use RecordRTC library to record the streams.
You just need to use this code in your primary page

and attach recordRTC library to your page.

```<code>  recorder = connection.recorder;
        if(!recorder)
        {
            recorder = RecordRTC([event.stream], {
                type: 'video'
            });
            connection.recorder = recorder;
        }
        else {
            recorder.getInternalRecorder().addStreams([event.stream]);
        }

        recorder.videoWidth  = 500;
        recorder.videoHeight = 500;

        if(!connection.recorder.streams) {
            connection.recorder.streams = [];
        }

        connection.recorder.streams.push(event.stream);

        var length = connection.recorder.streams.length;

        if(length > 2){
            length = 2;
        }
        recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';
</code>```

Or you can use this code

```<code>connection.onstream = function(event) {

    var video = document.createElement('video');

    try {
        video.setAttributeNode(document.createAttribute('autoplay'));
        video.setAttributeNode(document.createAttribute('playsinline'));
    } catch (e) {
        video.setAttribute('autoplay', true);
        video.setAttribute('playsinline', true);
    }

    if(event.type === 'local') {
      video.volume = 0;
      try {
          video.setAttributeNode(document.createAttribute('muted'));
      } catch (e) {
          video.setAttribute('muted', true);
      }
    }
    video.srcObject = event.stream;

    var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
    var mediaElement = getHTMLMediaElement(video, {
        title: event.userid,
        buttons: ['full-screen'],
        width: width,
        showOnMouseEnter: false
    });

    connection.videosContainer.appendChild(mediaElement);

    setTimeout(function() {
        mediaElement.media.play();
    }, 5000);

    mediaElement.id = event.streamid;
    // to keep room-id in cache
    localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
    if(chkRecordConference.checked === true) {
        chkRecordConference.parentNode.style.display = 'none';
        btnStopRecording.style.display = 'inline-block';
        recordingStatus.style.display = 'inline-block';
        recorder = connection.recorder;
        if(!recorder)
        {
            recorder = RecordRTC([event.stream], {
                type: 'video'
            });
            connection.recorder = recorder;
        }
        else {
            recorder.getInternalRecorder().addStreams([event.stream]);
        }

        recorder.videoWidth  = 500;
        recorder.videoHeight = 500;

        if(!connection.recorder.streams) {
            connection.recorder.streams = [];
        }

        connection.recorder.streams.push(event.stream);

        var length = connection.recorder.streams.length;

        if(length > 2){
            length = 2;
        }
        recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';
    }
</code>```

Body:
I get a console error while clicking a record Button.

I worked with the Code From RTCMulticonnection to establish a connection and now want to have the ability to record the stream. I used this demo to record the stream:

RecordRTC-and-RTCMultiConnection
 https://github.com/muaz-khan/WebRTC-Experiment/blob/d1040f7dcd47c290f99ad51f9b3d57aa40c847c4/RTCMultiConnection/v2.2.2/demos/RecordRTC-and-RTCMultiConnection.html

The Console Message

Uncaught TypeError: Cannot read property 'YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r' of undefined
    at HTMLButtonElement.button.onclick (index.html:108)

What I see is that in the demo version all streamid's have a short ID like
id="1mnvuzts2dm". My Version sets the streamid's to longer random strings like the one above in the Error id="YvuytsjuZSjrg1Wp9xa4jAXrEC783kpnW74r"

//RECORD THE CONVERSATION AUDIO + VIDEO
  connection.onstream = function(e) {
            appendVideo(e.mediaElement, e.streamid);
        };

        function appendVideo(video, streamid) {
            video.width = 600;
            video = getVideo(video, streamid);
            videosContainer.appendChild(video);
            rotateVideo(video);
            scaleVideos();
        }

        function getVideo(video, streamid) {
            var div = document.createElement('div');
            div.className = 'video-container';

            var button = document.createElement('button');
            button.id = streamid;
            button.innerHTML = 'Start Recording';
            button.onclick = function() {
                this.disabled = true;
                if (this.innerHTML == 'Start Recording') {
                    this.innerHTML = 'Stop Recording';
                    connection.streams[this.id].startRecording({
                        audio: true,
                        video: true
                    });
                } else {
                    this.innerHTML = 'Start Recording';
                    var stream = connection.streams[this.id];
                    stream.stopRecording(function(blob) {
                        var h2;

                        if (blob.audio && !(connection.UA.Chrome && stream.type == 'remote')) {
                            h2 = document.createElement('h2');
                            h2.innerHTML = 'Open recorded ' + blob.audio.type + '';
                            div.appendChild(h2);
                        }

                        if (blob.video) {
                            h2 = document.createElement('h2');
                            h2.innerHTML = 'Open recorded ' + blob.video.type + '';
                            div.appendChild(h2);
                        }
                    });
                }
                setTimeout(function() {
                    button.disabled = false;
                }, 3000);
            };
            div.appendChild(button);
            div.appendChild(video);
            return div;
        }

        function rotateVideo(mediaElement) {
            mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(0deg)';
            setTimeout(function() {
                mediaElement.style[navigator.mozGetUserMedia ? 'transform' : '-webkit-transform'] = 'rotate(360deg)';
            }, 1000);
        }

        connection.onstreamended = function(e) {
            var div = e.mediaElement.parentNode;
            div.style.opacity = 0;
            rotateVideo(div);
            setTimeout(function() {
                if (div.parentNode) {
                    div.parentNode.removeChild(div);
                }
                scaleVideos();
            }, 1000);
        };

      function scaleVideos() {
            var videos = document.querySelectorAll('video'),
                length = videos.length,
                video;

            var minus = 130;
            var windowHeight = 700;
            var windowWidth = 600;
            var windowAspectRatio = windowWidth / windowHeight;
            var videoAspectRatio = 4 / 3;
            var blockAspectRatio;
            var tempVideoWidth = 0;
            var maxVideoWidth = 0;

            for (var i = length; i > 0; i--) {
                blockAspectRatio = i * videoAspectRatio / Math.ceil(length / i);
                if (blockAspectRatio <= windowAspectRatio) {
                    tempVideoWidth = videoAspectRatio * windowHeight / Math.ceil(length / i);
                } else {
                    tempVideoWidth = windowWidth / i;
                }
                if (tempVideoWidth > maxVideoWidth)
                    maxVideoWidth = tempVideoWidth;
            }
            for (var i = 0; i < length; i++) {
                video = videos[i];
                if (video)
                    video.width = maxVideoWidth - minus;
            }
        }

The ERROR Line is

connection.streams[this.id].startRecording({

Body:
You can use RecordRTC library to record the streams.
You just need to use this code in your primary page

and attach recordRTC library to your page.

  recorder = connection.recorder;
        if(!recorder)
        {
            recorder = RecordRTC([event.stream], {
                type: 'video'
            });
            connection.recorder = recorder;
        }
        else {
            recorder.getInternalRecorder().addStreams([event.stream]);
        }

        recorder.videoWidth  = 500;
        recorder.videoHeight = 500;

        if(!connection.recorder.streams) {
            connection.recorder.streams = [];
        }

        connection.recorder.streams.push(event.stream);

        var length = connection.recorder.streams.length;

        if(length > 2){
            length = 2;
        }
        recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';

Or you can use this code

connection.onstream = function(event) {

    var video = document.createElement('video');

    try {
        video.setAttributeNode(document.createAttribute('autoplay'));
        video.setAttributeNode(document.createAttribute('playsinline'));
    } catch (e) {
        video.setAttribute('autoplay', true);
        video.setAttribute('playsinline', true);
    }

    if(event.type === 'local') {
      video.volume = 0;
      try {
          video.setAttributeNode(document.createAttribute('muted'));
      } catch (e) {
          video.setAttribute('muted', true);
      }
    }
    video.srcObject = event.stream;

    var width = parseInt(connection.videosContainer.clientWidth / 3) - 20;
    var mediaElement = getHTMLMediaElement(video, {
        title: event.userid,
        buttons: ['full-screen'],
        width: width,
        showOnMouseEnter: false
    });

    connection.videosContainer.appendChild(mediaElement);

    setTimeout(function() {
        mediaElement.media.play();
    }, 5000);

    mediaElement.id = event.streamid;
    // to keep room-id in cache
    localStorage.setItem(connection.socketMessageEvent, connection.sessionid);
    if(chkRecordConference.checked === true) {
        chkRecordConference.parentNode.style.display = 'none';
        btnStopRecording.style.display = 'inline-block';
        recordingStatus.style.display = 'inline-block';
        recorder = connection.recorder;
        if(!recorder)
        {
            recorder = RecordRTC([event.stream], {
                type: 'video'
            });
            connection.recorder = recorder;
        }
        else {
            recorder.getInternalRecorder().addStreams([event.stream]);
        }

        recorder.videoWidth  = 500;
        recorder.videoHeight = 500;

        if(!connection.recorder.streams) {
            connection.recorder.streams = [];
        }

        connection.recorder.streams.push(event.stream);

        var length = connection.recorder.streams.length;

        if(length > 2){
            length = 2;
        }
        recordingStatus.innerHTML = 'Recording Started ' + length + ' streams';
    }


问:
How to show ProgressBar in centre of screen regardless layout types
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

```<code>Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
</code>```

答:
```<code>public static void showProgressDialog(Context context) {
    if (mDialog != null && mDialog.isShowing()) {
        mDialog.dismiss();
        mDialog = null;
    }

    try {
        mDialog = new ProgressDialog(context, R.style.MyAlertDialogStyle);
        mDialog.show();
        mDialog.setCancelable(false);
        if (mDialog.getWindow() != null)
            mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        mDialog.setContentView(R.layout.progress_layout);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();

        layoutParams.copyFrom(mDialog.getWindow().getAttributes());

        int dialogWindowWidth = Validator.DtP(200,context);
        int dialogWindowHeight = Validator.DtP(150,context);

        layoutParams.width = dialogWindowWidth;
        layoutParams.height = dialogWindowHeight;

        // Apply the newly created layout parameters to the alert dialog window
        mDialog.getWindow().setAttributes(layoutParams);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // dialog.setMessage(Message);

}

public static void hideProgressDialog(Context context) {
    ((Activity)context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
        }
    });

}

 public static int DtP(float dp, Context context) {
        return (int) (dp * (context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT));
    }
</code>```

Body:
I wonder if there is any way to show a ProgressBar at the middle of the screen programatically regardless the type of layout of the current Activity like a toast can be shown like,

Toast toast = Toast.makeText(Activity.this,"Sample toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();


问:
How to get the sum of child component state value in parent component on first load?
I've tried to have a Parent component with state attribute 'sum'.
There are 2 Child components with state attribute 'value' with values 1 and 2 respectively.

On the load of application I want Parent to show '3'.
Currently I'm calling Parent method from Child using componentDidMount(), but in parent after this.setState() the values aren't updating!

```<code>Child:
componentDidMount() {
    this.props.calculateTotal(this.state.value);
  }

Parent:
class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      total: 0
    };
  }

calculateTotal = value => {
    console.log("value ", value);
    const calculatedTotal = this.state.total + value;
    console.log("calculatedTotal ", calculatedTotal);
   this.setState({
      total: calculatedTotal
    });
    console.log(
      "total after setting state",
      this.state.total
    );
  };
}
</code>```

In Parent I expected 'totalValue' to get sum but it is not happening.

Any assistance in this regard will be helpful.

答:
You can try the same in the callback of setState, and new value will reflect. Since setState doesn't happen synchronously, your immediate console.log after setState is ignored.

Check the following, this should do what you're trying to do, I'm using prevState param to access the current state instead of doing this.state.total + value:

```<code>calculateTotal = value => {
   this.setState(prevState => ({
      total: prevState.total + value;
    }, () => {
      console.log("total after setting state", this.state.total);
      console.log("This callback will show the new value");
    }));
    console.log("This will NOT show the new value", this.state.total);
  };
}
</code>```

Hope this is helpful!

Body:
I've tried to have a Parent component with state attribute 'sum'.
There are 2 Child components with state attribute 'value' with values 1 and 2 respectively.

On the load of application I want Parent to show '3'.
Currently I'm calling Parent method from Child using componentDidMount(), but in parent after this.setState() the values aren't updating!

Child:
componentDidMount() {
    this.props.calculateTotal(this.state.value);
  }

Parent:
class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      total: 0
    };
  }

calculateTotal = value => {
    console.log("value ", value);
    const calculatedTotal = this.state.total + value;
    console.log("calculatedTotal ", calculatedTotal);
   this.setState({
      total: calculatedTotal
    });
    console.log(
      "total after setting state",
      this.state.total
    );
  };
}

In Parent I expected 'totalValue' to get sum but it is not happening.

Any assistance in this regard will be helpful.

Body:
You can try the same in the callback of setState, and new value will reflect. Since setState doesn't happen synchronously, your immediate console.log after setState is ignored.

Check the following, this should do what you're trying to do, I'm using prevState param to access the current state instead of doing this.state.total + value:

calculateTotal = value => {
   this.setState(prevState => ({
      total: prevState.total + value;
    }, () => {
      console.log("total after setting state", this.state.total);
      console.log("This callback will show the new value");
    }));
    console.log("This will NOT show the new value", this.state.total);
  };
}

Hope this is helpful!