问:
Suggestions for implementing "inverse document frequency" on GAE?
I need to implement "inverse document frequency" in Google app engine. I'm looking for suggestions to improve efficiency. Now I take the basic routine as,

when parsing a webpage I save each  pair to datastore, like,

```<code>for(String phrase : phrase_collection){
  dataStore.put(phrase, domain);
}
</code>```

when computing the IDF later I fetch the occurrence of the phrase from datastore, like,

```<code>for(String phrase : phrase_collection){
  long count = dataStore.get(phrase).size();
}
</code>```

However the speed is not satisfying and results in 30sec timeout often. In this scenario I have additional challenges,

-Multi language input(webpages). So the phrases are also in different languages, which makes it hard to cache.

-Parsing webpages and ranking phrases take much time as well. The whole process is like charset_detect -> language_detect -> parse according to different languages -> ranking.

Always on enabled in GAE.

I'm looking forward to any suggestions! Thanks in advance!

答:
You're doing an individual get (and put) for each phrase. This is naturally going to be very slow, as you're doing a great many roundtrips to the datastore. Instead, you should use the variants of put and get that accept an iterable of entities or keys, and execute them all in a single transaction.

You should also do this work 'offline' - as Stefan suggests, using backends or task queues. Task queues would likely be a better match here.

Body:
I need to implement "inverse document frequency" in Google app engine. I'm looking for suggestions to improve efficiency. Now I take the basic routine as,

when parsing a webpage I save each  pair to datastore, like,

for(String phrase : phrase_collection){
  dataStore.put(phrase, domain);
}

when computing the IDF later I fetch the occurrence of the phrase from datastore, like,

for(String phrase : phrase_collection){
  long count = dataStore.get(phrase).size();
}

However the speed is not satisfying and results in 30sec timeout often. In this scenario I have additional challenges,

-Multi language input(webpages). So the phrases are also in different languages, which makes it hard to cache.

-Parsing webpages and ranking phrases take much time as well. The whole process is like charset_detect -> language_detect -> parse according to different languages -> ranking.

Always on enabled in GAE.

I'm looking forward to any suggestions! Thanks in advance!


来源: stackexchange

问:
Rearrange two columns so that the first column values are always larger in R
I have two columns that holds integers. I need to rearrange the columns so that the first column values are always larger

The example input:

```<code>     co1 co2
[1,]  15  25
[2,]  35  55
[3,]  65  45
[4,]  40  50
</code>```

The desired output:

```<code>     co1 co2
[1,]  25  15
[2,]  55  35
[3,]  65  45
[4,]  50  40
</code>```

Any help will be appreciated.

ContentLicense: CC BY-SA 4.0

Body:
I have two columns that holds integers. I need to rearrange the columns so that the first column values are always larger

The example input:

     co1 co2
[1,]  15  25
[2,]  35  55
[3,]  65  45
[4,]  40  50

The desired output:

     co1 co2
[1,]  25  15
[2,]  55  35
[3,]  65  45
[4,]  50  40

Any help will be appreciated.

Body:
We can also use pmin/pmax from base R

cbind(pmax(mat[,1], mat[,2]), pmin(mat[,1], mat[,2]))
#     [,1] [,2]
#[1,]   25   15
#[2,]   55   35
#[3,]   65   45
#[4,]   50   40

data

mat <- structure(c(25L, 55L, 65L, 50L, 15L, 35L, 45L, 40L), .Dim = c(4L,
2L), .Dimnames = list(NULL, c("co1", "co2")))


问:
create-react-app and relative subpaths in development
We are having a big environment where we have several applications under the same domain eg:

```<code>foo.org/a
foo.org/b
</code>```

We have set up IIS to act in the same way on localhost, so we can type:

```<code>localhost/a
localhost/b
</code>```

to reach the applications. The setup is done so to avoid CORS problems.

We are now trying to create a new application with "create-react-app" (https://github.com/facebook/create-react-app).

To add relative paths when you build for production is no problem, the problems occur when you try to run this with react-scripts start on localhost.
It seems it doesn't support relative paths so it always try to fetch build.js and other resources from /and there is not possible to set this without ejecting webpack.

So my question is, do you have any good ways of sorting this out? Ejecting webpack is not a good solution for us.

答: "homepage": "/subfolder/path", in package json file should help</p>

Body:
We are having a big environment where we have several applications under the same domain eg:

foo.org/a
foo.org/b

We have set up IIS to act in the same way on localhost, so we can type:

localhost/a
localhost/b

to reach the applications. The setup is done so to avoid CORS problems.

We are now trying to create a new application with "create-react-app" (https://github.com/facebook/create-react-app).

To add relative paths when you build for production is no problem, the problems occur when you try to run this with react-scripts start on localhost.
It seems it doesn't support relative paths so it always try to fetch build.js and other resources from /and there is not possible to set this without ejecting webpack.

So my question is, do you have any good ways of sorting this out? Ejecting webpack is not a good solution for us.


问:
python 3.6 bug or i am nuts
checks if items in a list are consecutive.

```<code>[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]
</code>```

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)
</code>```

What am i missing here?

答:
I don't think your code is doing what you think it's doing.

I tweaked it a bit and here's what happened:

>>> [[x, y] for x in lst[:-1] for y in lst[1:]]
[[1, 2], [1, 3], [1, 4], [1, 4], [2, 2], [2, 3], [2, 4], [2, 4], [3, 2], [3, 3], [3, 4], [3, 4], [4, 2], [4, 3], [4, 4], [4, 4]]
```

<p>Your list comprehension is actually a 2D loop and you're just filtering all the combinations for a semi-random number of <code>True</code>'s back.</p>

<p>In your case, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, and <code>[3, 4]</code> are satisfying the condition <code>x + 1 == y</code>.</p>

<p>Consider rewriting <code>consecutive</code>, here's a quick idea for example:</p>

<pre class="lang-py prettyprint-override"><code>def consecutive(lst):
    return [lst[i] + 1 == lst[i + 1] for i in range(len(lst) - 1)]
    # implicitly does the same thing as return [True if lst[i] + 1 == lst[i + 1] else False for i in range(len(lst) - 1)]
</code>```

Title: python 3.6 bug or i am nuts

Body:
checks if items in a list are consecutive.

[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)

What am i missing here?

Body:
I don't think your code is doing what you think it's doing.

I tweaked it a bit and here's what happened:

>>> [[x, y] for x in lst[:-1] for y in lst[1:]]
[[1, 2], [1, 3], [1, 4], [1, 4], [2, 2], [2, 3], [2, 4], [2, 4], [3, 2], [3, 3], [3, 4], [3, 4], [4, 2], [4, 3], [4, 4], [4, 4]]

Your list comprehension is actually a 2D loop and you're just filtering all the combinations for a semi-random number of True's back.

In your case, [1, 2], [2, 3], [3, 4], and [3, 4] are satisfying the condition x + 1 == y.

Consider rewriting consecutive, here's a quick idea for example:

def consecutive(lst):
    return [lst[i] + 1 == lst[i + 1] for i in range(len(lst) - 1)]
    # implicitly does the same thing as return [True if lst[i] + 1 == lst[i + 1] else False for i in range(len(lst) - 1)]


问:
Swift 5: AVPlayer layers multiple audio files on each other
I'm building a Swift 5 music app where a table view loads and lists multiple objects from a JSON API. After clicking on an entry, the navigator calls the detail view for the selected item.

Below, you can see my detail view controller, called BroadcastDetailViewController. As you can see there is a playBroadcastButton which'll play the audio file and setup the AVAudioSession.

So far so good. But after I've implemented the possibility to scrub through the audio file via control center scrubber (commandCenter.changePlaybackPositionCommand.addTarget) and go back to my table view controller and select another item to play it's audio file, the AVPlayer layers multiple audio files on each other and plays them simultaneously. This is a behavior I don't want. Before I implemented the control buttons, the whole audio file replacement process worked fine.

My question is, why does the player suddenly play another file on top of the other, instead of muting/ducking the old one and replace it with the new one?

```<code>class BroadcastDetailViewController: UIViewController {

    var player = AVPlayer()
    var playerItem: AVPlayerItem!

    var broadcast:Broadcasts?

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    @IBAction func playBroadcastButton(_ sender: Any) {
        player.play()
        setupAVAudioSession()
    }

    private func setupAVAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try AVAudioSession.sharedInstance().setActive(true)
            debugPrint("AVAudioSession is Active and Category Playback is set")
            UIApplication.shared.beginReceivingRemoteControlEvents()
            setupCommandCenter()
        } catch {
            debugPrint("Error: \(error)")
        }
    }

    private func setupCommandCenter() {

        // Meta
        var nowPlayingInfo = [String : Any]()

        nowPlayingInfo[MPMediaItemPropertyTitle] = broadcast?.title ?? "Radio Bass"
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Radio Bass"
        nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = "Radio Bass."
        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate

        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo

        let commandCenter = MPRemoteCommandCenter.shared()
        commandCenter.playCommand.isEnabled = true
        commandCenter.pauseCommand.isEnabled = true
        commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
            self?.player.play()
            return .success
        }
        commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
            self?.player.pause()
            return .success
        }

        // Scrubber
        commandCenter.changePlaybackPositionCommand.addTarget { event in
            let seconds = (event as? MPChangePlaybackPositionCommandEvent)?.positionTime ?? 0
            let time = CMTime(seconds: seconds, preferredTimescale: 1)
            self.player.seek(to: time)
            return .success
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let urlAudioString = broadcast?.audio

        playerItem = AVPlayerItem(url: URL(string: urlAudioString!)!)
        player = AVPlayer(playerItem: playerItem)

        title = broadcast?.title

        let urlImageString = broadcast?.image
        let urlImage = URL(string: urlImageString!)

        titleLabel.text = broadcast?.title
        imageView.load(url: urlImage!)
    }
}
</code>```

答:
Release/free and stop AVPlayer and AVPlayerItem before going back to your table view controller

```<code>avPlayer.pause()
avPlayer.cancelPendingPrerolls() // stops network requests
avPlayer.replaceCurrentItem(with: nil)
</code>```

Body:
I'm building a Swift 5 music app where a table view loads and lists multiple objects from a JSON API. After clicking on an entry, the navigator calls the detail view for the selected item.

Below, you can see my detail view controller, called BroadcastDetailViewController. As you can see there is a playBroadcastButton which'll play the audio file and setup the AVAudioSession.

So far so good. But after I've implemented the possibility to scrub through the audio file via control center scrubber (commandCenter.changePlaybackPositionCommand.addTarget) and go back to my table view controller and select another item to play it's audio file, the AVPlayer layers multiple audio files on each other and plays them simultaneously. This is a behavior I don't want. Before I implemented the control buttons, the whole audio file replacement process worked fine.

My question is, why does the player suddenly play another file on top of the other, instead of muting/ducking the old one and replace it with the new one?

class BroadcastDetailViewController: UIViewController {

    var player = AVPlayer()
    var playerItem: AVPlayerItem!

    var broadcast:Broadcasts?

    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!

    @IBAction func playBroadcastButton(_ sender: Any) {
        player.play()
        setupAVAudioSession()
    }

    private func setupAVAudioSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try AVAudioSession.sharedInstance().setActive(true)
            debugPrint("AVAudioSession is Active and Category Playback is set")
            UIApplication.shared.beginReceivingRemoteControlEvents()
            setupCommandCenter()
        } catch {
            debugPrint("Error: \(error)")
        }
    }

    private func setupCommandCenter() {

        // Meta
        var nowPlayingInfo = [String : Any]()

        nowPlayingInfo[MPMediaItemPropertyTitle] = broadcast?.title ?? "Radio Bass"
        nowPlayingInfo[MPMediaItemPropertyArtist] = "Radio Bass"
        nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = "Radio Bass."
        nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds
        nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds
        nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate

        MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo

        let commandCenter = MPRemoteCommandCenter.shared()
        commandCenter.playCommand.isEnabled = true
        commandCenter.pauseCommand.isEnabled = true
        commandCenter.playCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
            self?.player.play()
            return .success
        }
        commandCenter.pauseCommand.addTarget { [weak self] (event) -> MPRemoteCommandHandlerStatus in
            self?.player.pause()
            return .success
        }

        // Scrubber
        commandCenter.changePlaybackPositionCommand.addTarget { event in
            let seconds = (event as? MPChangePlaybackPositionCommandEvent)?.positionTime ?? 0
            let time = CMTime(seconds: seconds, preferredTimescale: 1)
            self.player.seek(to: time)
            return .success
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let urlAudioString = broadcast?.audio

        playerItem = AVPlayerItem(url: URL(string: urlAudioString!)!)
        player = AVPlayer(playerItem: playerItem)

        title = broadcast?.title

        let urlImageString = broadcast?.image
        let urlImage = URL(string: urlImageString!)

        titleLabel.text = broadcast?.title
        imageView.load(url: urlImage!)
    }
}

Body:
Release/free and stop AVPlayer and AVPlayerItem before going back to your table view controller

avPlayer.pause()
avPlayer.cancelPendingPrerolls() // stops network requests
avPlayer.replaceCurrentItem(with: nil)


问:
cant connect to mysql database from spring project
I´m having a weird issue with MySQL. When i run my Spring project it throws the exception:

```<code>java.sql.SQLException: Access denied for user 'root     '@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
</code>```

I can connect to MySQL using the command line mysql -u root -p whithout issues

Here´s my application.properties file:

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = admin

spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

spring.thymeleaf.cache = true
</code>```

Here´s the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ernesto</groupId>
    <artifactId>SpringLogInApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringLogInApp</name>
    <description>Login App With Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

I´ve tried reinstalling MySQL several times. The project is built with maven. The same happens if i switch user and password in application.properties. The schema "test" is already created. I´ve tried everything i found here at SO with no luck. Need some help.

Thanks in advance

答:
Have you tried deleting whitespace behind root in your application.properties?

It tries to connect for user 'root     ' which doesn't exist.

Body:
I´m having a weird issue with MySQL. When i run my Spring project it throws the exception:

java.sql.SQLException: Access denied for user 'root     '@'localhost' (using password: YES)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197) ~[mysql-connector-java-8.0.20.jar:8.0.20]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-3.4.5.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:176) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

I can connect to MySQL using the command line mysql -u root -p whithout issues

Here´s my application.properties file:

spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = admin

spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update

spring.thymeleaf.cache = true

Here´s the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.ernesto</groupId>
    <artifactId>SpringLogInApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringLogInApp</name>
    <description>Login App With Spring Boot</description>

    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

I´ve tried reinstalling MySQL several times. The project is built with maven. The same happens if i switch user and password in application.properties. The schema "test" is already created. I´ve tried everything i found here at SO with no luck. Need some help.

Thanks in advance


问:
Getting invalid attributes error when playing sound with MediaPlayer
suddenly my app doesnt play a sound when I call mediaPlayer.start().

I get following error in log:

```<code>2020-05-29 20:43:57.165 4719-1953/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags:  } when converting to stream
</code>```

I am doing this one when the app starts:

```<code>mMediaPlayer = MediaPlayer.create(context, R.raw.restaurant_order_received)
</code>```

Thanks for help

答:
I had no attributes configures...

so just do this:

```<code>mMediaPlayer = MediaPlayer()
mMediaPlayer.setAudioAttributes(AudioAttributes.Builder()
    .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
    .setUsage(AudioAttributes.USAGE_ALARM)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build())
mMediaPlayer.setDataSource(context, Uri.parse("android.resource://com.mypackage.name/raw/restaurant_order_received"))
mMediaPlayer.isLooping = true
mMediaPlayer.prepare()
</code>```

Body:
suddenly my app doesnt play a sound when I call mediaPlayer.start().

I get following error in log:

2020-05-29 20:43:57.165 4719-1953/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags:  } when converting to stream

I am doing this one when the app starts:

mMediaPlayer = MediaPlayer.create(context, R.raw.restaurant_order_received)

Thanks for help

Body:
I had no attributes configures...

so just do this:

mMediaPlayer = MediaPlayer()
mMediaPlayer.setAudioAttributes(AudioAttributes.Builder()
    .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
    .setLegacyStreamType(AudioManager.STREAM_MUSIC)
    .setUsage(AudioAttributes.USAGE_ALARM)
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build())
mMediaPlayer.setDataSource(context, Uri.parse("android.resource://com.mypackage.name/raw/restaurant_order_received"))
mMediaPlayer.isLooping = true
mMediaPlayer.prepare()


问:
Is there any way to change color after every 7 days after specific date?
I want to change color of div after every 7 days. I have tried changing it using if statements but I want more specific way of doing it (automatically after 7 days add color).

This is what I tried:

```<code>     <div class="hello">
    checking

</div>
<script>
    var currentDate = new Date().getDate()
        console.log(currentDate)
        var hello = document.querySelector(".hello")
        function getMondays() {
            var d = new Date(),
                month = d.getMonth(),
                mondays = [];
            d.setDate(1);
            // Get the first Monday in the month
            while (d.getDay() !== 1) {
                d.setDate(d.getDate() + 1);
            }

            // Get all the other Mondays in the month
            while (d.getMonth() === month) {
              console.log(new Date(d.getTime()))
                mondays.push(new Date(d.getTime()));
                d.setDate(d.getDate() + 7);
            }
            console.log(mondays)

            if(mondays.length === 4 ){
                hello.setAttribute("alt","")
                hello.removeAttribute("src")
                console.log("in 4")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate <= 31  ){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
            if(mondays.length === 5 ){
              console.log("in 5")
              if(currentDate > 0 && currentDate < mondays[0].getDate()){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[0].getDate() && currentDate < mondays[1].getDate()  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[1].getDate() && currentDate < mondays[2].getDate()  ){
                  hello.style.backgroundColor = "purple"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[2].getDate() && currentDate < mondays[3].getDate()  ){
                  hello.style.backgroundColor = "blue"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[3].getDate() && currentDate < mondays[4].getDate()   ){
                  hello.style.backgroundColor = "orange"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
              if(currentDate >= mondays[4].getDate() && currentDate <= 31  ){
                  hello.style.backgroundColor = "green"
                  hello.style.width = "50px"
                  hello.style.height = "28px"
              }
            }
        }
        getMondays()
   </script>
</code>```

in this code I am taking Mondays of the current month and adding color one by one. And I want to add 4 colors.

The issue is when we have 5 weeks: then it will not loop accordingly.

答:
You can use timer for this.
Your html:

```<code><div class="block"></div>
</code>```

Your css:

```<code>.block {
  width: 100px;
  height: 100px;
  background-color: green;
}
</code>```

And the most important. Your javascript:

```<code>const block = document.querySelector(".block");
const dayInMs = 24 * 60 * 60 * 1000;
const delay = dayInMs * 7;
const colorSet = ["blue", "green", "red"];
let colorIndex = 0;

setTimeout(changeColor, delay);

function changeColor() {
  if (colorIndex === colorSet.length) {
    colorIndex = 0;
  }
  block.style["background-color"] = colorSet[colorIndex];
  colorIndex++;
  setTimeout(changeColor, delay);
}
</code>```

Steps:
1.Get access to your DOM-element
2.Define a quantity of milliseconds in a days, since setTimeout works with milliseconds.
3.Define some color set in array or set, or another composite data-structure
4.Call a recursive timer, that every delay time will call changeColor function.

P.S. You can try setInterval, but recursive setTimeout is more reliable.

Here is codepen (you can change delay for another value, not to wait for 7 days :D):
https://codepen.io/evgeny-zubkov/pen/qBOeOxe?editors=1111

Body:
I want to change color of div after every 7 days. I have tried changing it using if statements but I want more specific way of doing it (automatically after 7 days add color).

This is what I tried:

    checking

in this code I am taking Mondays of the current month and adding color one by one. And I want to add 4 colors.

The issue is when we have 5 weeks: then it will not loop accordingly.

Body:
You can use timer for this.
Your html:

<div class="block"></div>

Your css:

.block {
  width: 100px;
  height: 100px;
  background-color: green;
}

And the most important. Your javascript:

const block = document.querySelector(".block");
const dayInMs = 24 * 60 * 60 * 1000;
const delay = dayInMs * 7;
const colorSet = ["blue", "green", "red"];
let colorIndex = 0;

setTimeout(changeColor, delay);

function changeColor() {
  if (colorIndex === colorSet.length) {
    colorIndex = 0;
  }
  block.style["background-color"] = colorSet[colorIndex];
  colorIndex++;
  setTimeout(changeColor, delay);
}

Steps:
1.Get access to your DOM-element
2.Define a quantity of milliseconds in a days, since setTimeout works with milliseconds.
3.Define some color set in array or set, or another composite data-structure
4.Call a recursive timer, that every delay time will call changeColor function.

P.S. You can try setInterval, but recursive setTimeout is more reliable.

Here is codepen (you can change delay for another value, not to wait for 7 days :D):
https://codepen.io/evgeny-zubkov/pen/qBOeOxe?editors=1111


问:
When I try to run this code it's gives me no output
I built it when I click to run it's showing no errors no warnings nothing

```<code>#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}
</code>```

I tried to run it from pass key point and it works but when I continue it's given me nothing

答:
The Code is working perfectly fine.
Check your results here.

As rng70 said, recheck your input values. Also, if you're adding spaces between your string input, it won't work because whitespace acts as a delimiter for scanf() by default.

Sorry to bother!

To be precise, characters after spaces are not considered as input for strings, if that's what your error is.

To solve that problem, you can use scanf("%[^\n]", name);

Check md5's post on this for assistance. Thanks.

Body:
I built it when I click to run it's showing no errors no warnings nothing

#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char name[20], address[30];
    char c;
    printf("put your pass key: ");
    c = getchar();

    printf("Enter your name: ");
    scanf("%s",name);

    printf("Enter your address: ");
    scanf("%s",address);

    printf("--------------------------\n");
    printf("Entered Name: %s\n",name);
    printf("Entered Address: %s\n",address);

    printf("Your pass key: ");
    putchar(c);
}

I tried to run it from pass key point and it works but when I continue it's given me nothing


问:
MapBox in Android : Unable to request location permissions in a fragment using requestLocationPermissions method
For my coding school project I am using mapbox map in a fragment. I manage to add map to a fragment with finding my (the user) location. However, it finds my location only when I go manually to my phone settings and allow the location permissions for the app. I was following mapbox tutorials and documentation, however it seems most of it is being written for MapBox map to be used in the activity. In the mapbox tutorials I see that the following is being used:

```<code>private void enableLocation() {
    if (PermissionsManager.areLocationPermissionsGranted(getContext())) {
        initializeLocationEngine();
        initializeLocationLayer();
    } else {
        permissionsManager = new PermissionsManager(this); // THIS, HOWEVER WORKS IN THE FRAGMENT
       permissionsManager.requestLocationPermissions(this); //HERE IS MY PROBLEM
    }
}
</code>```

The code that I have shown above in my app I use in fragments onCreateView, and since the parameter for the requestLocationPermissions method is the activity, I am unable to make that method run. I tried different options to refer to mainActivity that the fragment is associated to, however with no success. Therefore, my question is - is there some simple quick go around this problem where I can pass somehow activity in this method?

答:
You should be able to do requestPermissions(permissionsList, REQUEST_CODE); to request permission from within the fragment.
 There is no need to pass the mainActivity context.

How do you enable your location? I generally like to do it this way:

```<code>@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {

    mapboxMap.setStyle(new Style.Builder()
            .fromUri("mapbox://styles/mapbox/navigation-guidance-night-v4")
            .withSource(new GeoJsonSource(ISOCHRONE_RESPONSE_GEOJSON_SOURCE_ID)), style -> {

        mapboxMap.getUiSettings().setCompassMargins(0, 180, 20, 0);
        // Map is set up and the style has loaded. Now you can add
        // data or make other map adjustments
        MainActivity.this.mapboxMap = mapboxMap;

        trafficPlugin = new TrafficPlugin(mapView, mapboxMap, Objects.requireNonNull(
                mapboxMap.getStyle()));
        this.trafficPlugin.setVisibility(false);

        this.style = style;

        // Create an empty GeoJSON source using the empty feature collection
        setUpSource();

        mapboxMap.addOnMapClickListener(MainActivity.this);
        mapboxMap.addOnMapLongClickListener(MainActivity.this);

        initEmptyLayer(Objects.requireNonNull(mapboxMap.getStyle()));
        setUpImage(Objects.requireNonNull(mapboxMap.getStyle()));

        enableLocationComponent(style);
    });
}
</code>```

Then on my enableLocationCompnent function:

```<code>@SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(Style style) {
    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {

        LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(this)
                .layerAbove("empty-layer")
                .build();

        LocationComponentActivationOptions locationComponentActivationOptions = LocationComponentActivationOptions
                .builder(this, style)
                .locationComponentOptions(locationComponentOptions)
                .build();

        locationComponent = mapboxMap.getLocationComponent();
        // Activate with options
        locationComponent.activateLocationComponent(locationComponentActivationOptions);

        // Enable to make component visible
        locationComponent.setLocationComponentEnabled(true);

        // Set the component's camera mode
        locationComponent.setCameraMode(CameraMode.TRACKING);
        locationComponent.setRenderMode(RenderMode.COMPASS);
        initLocationEngine();

    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}
</code>```

Hope that helps!

Body:
For my coding school project I am using mapbox map in a fragment. I manage to add map to a fragment with finding my (the user) location. However, it finds my location only when I go manually to my phone settings and allow the location permissions for the app. I was following mapbox tutorials and documentation, however it seems most of it is being written for MapBox map to be used in the activity. In the mapbox tutorials I see that the following is being used:

private void enableLocation() {
    if (PermissionsManager.areLocationPermissionsGranted(getContext())) {
        initializeLocationEngine();
        initializeLocationLayer();
    } else {
        permissionsManager = new PermissionsManager(this); // THIS, HOWEVER WORKS IN THE FRAGMENT
       permissionsManager.requestLocationPermissions(this); //HERE IS MY PROBLEM
    }
}

The code that I have shown above in my app I use in fragments onCreateView, and since the parameter for the requestLocationPermissions method is the activity, I am unable to make that method run. I tried different options to refer to mainActivity that the fragment is associated to, however with no success. Therefore, my question is - is there some simple quick go around this problem where I can pass somehow activity in this method?

Body:
You should be able to do requestPermissions(permissionsList, REQUEST_CODE); to request permission from within the fragment.
 There is no need to pass the mainActivity context.

How do you enable your location? I generally like to do it this way:

@Override
public void onMapReady(@NonNull MapboxMap mapboxMap) {

    mapboxMap.setStyle(new Style.Builder()
            .fromUri("mapbox://styles/mapbox/navigation-guidance-night-v4")
            .withSource(new GeoJsonSource(ISOCHRONE_RESPONSE_GEOJSON_SOURCE_ID)), style -> {

        mapboxMap.getUiSettings().setCompassMargins(0, 180, 20, 0);
        // Map is set up and the style has loaded. Now you can add
        // data or make other map adjustments
        MainActivity.this.mapboxMap = mapboxMap;

        trafficPlugin = new TrafficPlugin(mapView, mapboxMap, Objects.requireNonNull(
                mapboxMap.getStyle()));
        this.trafficPlugin.setVisibility(false);

        this.style = style;

        // Create an empty GeoJSON source using the empty feature collection
        setUpSource();

        mapboxMap.addOnMapClickListener(MainActivity.this);
        mapboxMap.addOnMapLongClickListener(MainActivity.this);

        initEmptyLayer(Objects.requireNonNull(mapboxMap.getStyle()));
        setUpImage(Objects.requireNonNull(mapboxMap.getStyle()));

        enableLocationComponent(style);
    });
}

Then on my enableLocationCompnent function:

@SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(Style style) {
    // Check if permissions are enabled and if not request
    if (PermissionsManager.areLocationPermissionsGranted(this)) {

        LocationComponentOptions locationComponentOptions = LocationComponentOptions.builder(this)
                .layerAbove("empty-layer")
                .build();

        LocationComponentActivationOptions locationComponentActivationOptions = LocationComponentActivationOptions
                .builder(this, style)
                .locationComponentOptions(locationComponentOptions)
                .build();

        locationComponent = mapboxMap.getLocationComponent();
        // Activate with options
        locationComponent.activateLocationComponent(locationComponentActivationOptions);

        // Enable to make component visible
        locationComponent.setLocationComponentEnabled(true);

        // Set the component's camera mode
        locationComponent.setCameraMode(CameraMode.TRACKING);
        locationComponent.setRenderMode(RenderMode.COMPASS);
        initLocationEngine();

    } else {
        permissionsManager = new PermissionsManager(this);
        permissionsManager.requestLocationPermissions(this);
    }
}

Hope that helps!


问:
Google reCAPTCHA ERROR for site owner: Invalid site key
I cant get reCAPTCHA v3 working on my website. I have put the right code in from the Google reCAPTCHA v3 website but it shows "ERROR for site owner: Invalid site key" in the bottom right.

I'm only 7 and if I have missed something, please take it easy

```<code> <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recaptcha test</title>
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script>
      function onSubmit(token) {
          document.getElementById("demo-form").submit();
      }
    </script>
    <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>

<body>
<button class="g-recaptcha"
        data-sitekey="reCAPTCHA_site_key"
        data-callback='onSubmit'
        data-action='submit'>Submit</button>
<script>
    function onClick(e) {
        e.preventDefault();
        grecaptcha.ready(function() {
            grecaptcha.execute('reCAPTCHA_site_key', {action: 'submit'}).then(function(token) {
                // Add your logic to submit to your backend server here.
            });
        });
    }
</script>

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

Then, I tried reCAPTCHA v2 Checkbox, same things happened. Although, "ERROR for site owner: Invalid site key" was now in the top left:

```<code>    <!DOCTYPE html>?
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Recaptcha test</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>

    <script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
            async defer>
    </script>

<body>
<form action="?" method="POST">
    <div class="g-recaptcha" data-sitekey="your_site_key"></div>
    <br/>
    <input type="submit" value="Submit">
</form>
<script type="text/javascript">
    var onloadCallback = function() {
        alert("grecaptcha is ready!");
    };
</script>

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

答:
I have tried your code of reCAPTCHA v3 which you have mentioned.

reCAPTCHA_site_key is at three places please check if you have replaced it with correct site key under heading: "COPY SITE KEY".

Reason that it's showing "ERROR for site owner: Invalid site key" is you might be trying file system to access the key. It doesn't work on file systems ie, this will not work: file:///E:/Personal%20Data/stackoverflow/recapcha.html

Host your site on local server like IIS/Node etc, and add the same domain in domain configurations of recaptcha.

for example if your website is: https://www.testingrecapcha.com/ then add testingrecapcha.com in domains of rechapcha configurations. (to reach admin console of recapcha, use this: https://www.google.com/recaptcha/admin and select your relevant site and click on settings icon).

Body:
I cant get reCAPTCHA v3 working on my website. I have put the right code in from the Google reCAPTCHA v3 website but it shows "ERROR for site owner: Invalid site key" in the bottom right.

I'm only 7 and if I have missed something, please take it easy

 <!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Recaptcha test</title>

<button class="g-recaptcha"
        data-sitekey="reCAPTCHA_site_key"
        data-callback='onSubmit'
        data-action='submit'>Submit</button>

Then, I tried reCAPTCHA v2 Checkbox, same things happened. Although, "ERROR for site owner: Invalid site key" was now in the top left:

    <!DOCTYPE html>?

    <meta charset="UTF-8">
    <title>Recaptcha test</title>

<form action="?" method="POST">

    <input type="submit" value="Submit">
</form>


问:
Is it possible to read php code from other sites?
Just a curious question. I was wondering is it possible to read a sites php/server side codes? Is there any software/method that can be used to do so? Sometimes for educational purposes, i really want to see how people form the backend infrastructure of their sites. </p>

答:
If the other site does make their code downloadable you can:

```<code>include_once 'http://www.theirsite.com/run_dangerous_code.php
</code>```

But like every one else said, it is highly unlikely that this will happen.

ContentLicense: CC BY-SA 3.0

Body:
If the other site does make their code downloadable you can:

include_once 'http://www.theirsite.com/run_dangerous_code.php

But like every one else said, it is highly unlikely that this will happen.


问:
Patching away function call before importing?
If I'm importing from a module and want to prevent a function call from being ran in it, how can achieve that? For example...

sandbox.py

```<code>def foo():
    print("doing something I don't want to happen during testing like making a connection")
    ....

x = foo()

def get_num():
    return 1
</code>```

test_sandbox.py

```<code>from sandbox import get_num

def get_num():
    assert get_num() == 1
</code>```

I don't really care about foo or x, just want a way to make it so foo is not called when test_sandbox.py makes the import up top. In this current state, I will end up running foo.

How do I mock or patch to prevent foo from running during the import?

答:
You can do this using monkeypatch however, you need to know what foo is calling in order to patch it before importing. Taking your example we can illustrate how this would work.

```<code>import io
import sys

def test_get_num(monkeypatch):
    stdout = io.StringIO()

    with monkeypatch.context() as mc:
        mc.setattr(sys, 'stdout', stdout)
        from sandbox import get_num

        assert stdout.getvalue() == "doing something I don't want to happen during testing like making a connection\n"
        assert get_num() == 1
</code>```

And then when we run it:

```<code>$ -> pytest -s test_sandbox.py
========================= test session starts =========================================
collected 1 item

test_sandbox.py .
</code>```

Notice how even running pytest with -s to allow print statements to be shown in the console don't appear. You can do the same with foo in your real world example. If it is creating some database connection, then monkeypatch the connection to do nothing and then import after that. Hope that helps.

Body:
If I'm importing from a module and want to prevent a function call from being ran in it, how can achieve that? For example...

sandbox.py

def foo():
    print("doing something I don't want to happen during testing like making a connection")
    ....

x = foo()

def get_num():
    return 1

test_sandbox.py

from sandbox import get_num

def get_num():
    assert get_num() == 1

I don't really care about foo or x, just want a way to make it so foo is not called when test_sandbox.py makes the import up top. In this current state, I will end up running foo.

How do I mock or patch to prevent foo from running during the import?

Body:
You can do this using monkeypatch however, you need to know what foo is calling in order to patch it before importing. Taking your example we can illustrate how this would work.

import io
import sys

def test_get_num(monkeypatch):
    stdout = io.StringIO()

    with monkeypatch.context() as mc:
        mc.setattr(sys, 'stdout', stdout)
        from sandbox import get_num

        assert stdout.getvalue() == "doing something I don't want to happen during testing like making a connection\n"
        assert get_num() == 1

And then when we run it:

$ -> pytest -s test_sandbox.py
========================= test session starts =========================================
collected 1 item

test_sandbox.py .

Notice how even running pytest with -s to allow print statements to be shown in the console don't appear. You can do the same with foo in your real world example. If it is creating some database connection, then monkeypatch the connection to do nothing and then import after that. Hope that helps.


答:
I would rewrite the first function as the following:

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True if lst[:-1][i] +1 ==lst[1:][i] else False  for i,x in enumerate(lst[:-1])  ]

print(consecutive(lst))
[True, True, True, False]
</code>```

This shows that the first three elements are consecutive.

If you just want the consecutive pairs as set to True use the following code:

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for i,x in enumerate(lst[:-1]) if lst[:-1][i] +1 ==lst[1:][i]   ]

print(consecutive(lst))
[True, True, True]
</code>```

Title: python 3.6 bug or i am nuts

Body:
I would rewrite the first function as the following:

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True if lst[:-1][i] +1 ==lst[1:][i] else False  for i,x in enumerate(lst[:-1])  ]

print(consecutive(lst))
[True, True, True, False]

This shows that the first three elements are consecutive.

If you just want the consecutive pairs as set to True use the following code:

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for i,x in enumerate(lst[:-1]) if lst[:-1][i] +1 ==lst[1:][i]   ]

print(consecutive(lst))
[True, True, True]


问:
What are the most common Java Script functions used in Selenium WebDriver?
I am familiar with javascriptExecutor function which is used in Selenium WebDriver, such as how to click on an element, scroll down, and navigate the page. I would like to know if there are other functionalities of JS to implement in Selenium?</p>

答:
You can also get element text

```<code> private String jsGetElementText(String cssSelector) {
            JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
            return (String) javascriptExecutor.executeScript(String.format(
                    "var element = document.querySelector(\"%s\");\n" +
                            "if(element != null){\n" +
                            "    return element.innerHTML;\n" +
                            "}else{\n" +
                            "    return \"\";\n" +
                            "}", cssSelector));
        }
</code>```

Drag and Drop file

```<code>    public void dropFile(File filePath, WebElement target, int offsetX, int offsetY) {
        if (!filePath.exists())
            throw new WebDriverException("File not found: " + filePath.toString());

        JavascriptExecutor jse = (JavascriptExecutor) driver;

        String JS_DROP_FILE =
                "var target = arguments[0]," +
                        "    offsetX = arguments[1]," +
                        "    offsetY = arguments[2]," +
                        "    document = target.ownerDocument || document," +
                        "    window = document.defaultView || window;" +
                        "" +
                        "var input = document.createElement('INPUT');" +
                        "input.type = 'file';" +
                        "input.style.display = 'none';" +
                        "input.onchange = function () {" +
                        "  var rect = target.getBoundingClientRect()," +
                        "      x = rect.left + (offsetX || (rect.width >> 1))," +
                        "      y = rect.top + (offsetY || (rect.height >> 1))," +
                        "      dataTransfer = { files: this.files };" +
                        "" +
                        "  ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
                        "    var evt = document.createEvent('MouseEvent');" +
                        "    evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
                        "    evt.dataTransfer = dataTransfer;" +
                        "    target.dispatchEvent(evt);" +
                        "  });" +
                        "" +
                        "  setTimeout(function () { document.body.removeChild(input); }, 25);" +
                        "};" +
                        "document.body.appendChild(input);" +
                        "return input;";

        WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
        input.sendKeys(filePath.getAbsoluteFile().toString());
        waitFor(ExpectedConditions.stalenessOf(input));
    }
</code>```

change opacity for field

```<code>    public void changeOpacityForUploadField() {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.querySelector(\"input[id*='upload']\").style.opacity='1'");
    }
</code>```

Stop page loading

```<code>public void stopPageLoading() {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("return window.stop");
    }
</code>```

open browser extension

```<code>public void openBrowserExtension(){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.postMessage('clicked_browser_action', '*')");
}
</code>```

wait for page load

```<code>public void waitForPageLoad(){
        JavascriptExecutor js = (JavascriptExecutor) driver;
        waitForCondition().until(d->js.executeScript("return document.readyState").equals("complete"));
    }
</code>```

Body:
You can also get element text

 private String jsGetElementText(String cssSelector) {
            JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
            return (String) javascriptExecutor.executeScript(String.format(
                    "var element = document.querySelector(\"%s\");\n" +
                            "if(element != null){\n" +
                            "    return element.innerHTML;\n" +
                            "}else{\n" +
                            "    return \"\";\n" +
                            "}", cssSelector));
        }

Drag and Drop file

    public void dropFile(File filePath, WebElement target, int offsetX, int offsetY) {
        if (!filePath.exists())
            throw new WebDriverException("File not found: " + filePath.toString());

        JavascriptExecutor jse = (JavascriptExecutor) driver;

        String JS_DROP_FILE =
                "var target = arguments[0]," +
                        "    offsetX = arguments[1]," +
                        "    offsetY = arguments[2]," +
                        "    document = target.ownerDocument || document," +
                        "    window = document.defaultView || window;" +
                        "" +
                        "var input = document.createElement('INPUT');" +
                        "input.type = 'file';" +
                        "input.style.display = 'none';" +
                        "input.onchange = function () {" +
                        "  var rect = target.getBoundingClientRect()," +
                        "      x = rect.left + (offsetX || (rect.width >> 1))," +
                        "      y = rect.top + (offsetY || (rect.height >> 1))," +
                        "      dataTransfer = { files: this.files };" +
                        "" +
                        "  ['dragenter', 'dragover', 'drop'].forEach(function (name) {" +
                        "    var evt = document.createEvent('MouseEvent');" +
                        "    evt.initMouseEvent(name, !0, !0, window, 0, 0, 0, x, y, !1, !1, !1, !1, 0, null);" +
                        "    evt.dataTransfer = dataTransfer;" +
                        "    target.dispatchEvent(evt);" +
                        "  });" +
                        "" +
                        "  setTimeout(function () { document.body.removeChild(input); }, 25);" +
                        "};" +
                        "document.body.appendChild(input);" +
                        "return input;";

        WebElement input = (WebElement) jse.executeScript(JS_DROP_FILE, target, offsetX, offsetY);
        input.sendKeys(filePath.getAbsoluteFile().toString());
        waitFor(ExpectedConditions.stalenessOf(input));
    }

change opacity for field

    public void changeOpacityForUploadField() {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.querySelector(\"input[id*='upload']\").style.opacity='1'");
    }

Stop page loading

public void stopPageLoading() {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("return window.stop");
    }

open browser extension

public void openBrowserExtension(){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.postMessage('clicked_browser_action', '*')");
}

wait for page load

public void waitForPageLoad(){
        JavascriptExecutor js = (JavascriptExecutor) driver;
        waitForCondition().until(d->js.executeScript("return document.readyState").equals("complete"));
    }


问:
Access Contents of  with Javascript
```<code><noscript><div id="example">I want to get this innerHTML</div></noscript>

<script type="text/javascript"> alert($('example').innerHTML);</script>
</code>```

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

答:
Testing with Firefox 3.0.7, Safari 3.2.2, and MSIE 7.0.5730.13 (all on WinXP SP3) it appears that everything within the  tags is completely omitted from the DOM tree.

It may be possible to access the  element itself, however, and then use DOM methods to change its child elements.

OwnerDisplayName: macinjosh

ContentLicense: CC BY-SA 2.5

Title: Access Contents of <noscript> with Javascript

Body:
I want to get this innerHTML

This javascript snippet just returns an empty string. Is there a way of getting the contents of a noscript node?

p.s. I'm using prototype on this particular project.

Body:
Testing with Firefox 3.0.7, Safari 3.2.2, and MSIE 7.0.5730.13 (all on WinXP SP3) it appears that everything within the <noscript> tags is completely omitted from the DOM tree.

It may be possible to access the <noscript> element itself, however, and then use DOM methods to change its child elements.

OwnerDisplayName: Alnitak

LastEditorDisplayName: Alnitak


答:
You could calculate the current week number and use it for setting the color.

const containerEl = document.getElementById('container');
const containerEl2 = document.getElementById('container2');
const containerEl3 = document.getElementById('container3');
const containerEl4 = document.getElementById('container4');
const weekClassPrefix = "week-"

// source https://www.w3resource.com/javascript-exercises/javascript-date-exercise-24.php
let isoWeekNumber = function(dt) {
  let tdt = new Date(dt.valueOf());
  let dayn = (dt.getDay() + 6) % 7;
  tdt.setDate(tdt.getDate() - dayn + 3);
  let firstThursday = tdt.valueOf();
  tdt.setMonth(0, 1);
  if (tdt.getDay() !== 4) {
    tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
  }
  return 1 + Math.ceil((firstThursday - tdt) / (60 * 60 * 24 * 7 * 1000));
}

let setBackgroundColor = function(date, element) {
  let weekNo = isoWeekNumber(date);
  // NOTE: I use % 4 to ensure it's between 0 and 3. If you want more variance colors,
  // just set the number to the number of colors and add the classes to the css.
  // I recommend to put all styles in there as long as there is no real need to do it via js.
  element.classList.add(weekClassPrefix + (weekNo % 4));

  // For debugging only.
  element.innerHTML = date.toLocaleDateString("en-GB", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

let setCurrentBackgroundColor = function() {
  setBackgroundColor(new Date(), containerEl);
}

setCurrentBackgroundColor();
setBackgroundColor(new Date("2020-05-31"), containerEl2);
setBackgroundColor(new Date("2020-06-01"), containerEl3);
setBackgroundColor(new Date("2020-06-08"), containerEl4);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container, #container2, #container3, #container4 {
  width: auto;
  height: 28px;
  padding: 10px;
  color: white;
}

.week-0 {
  background-color: orange;
}

.week-1 {
  background-color: green;
}

.week-2 {
  background-color: purple;
}

.week-3 {
  background-color: blue;
}</code>```

```

Title: Is there any way to change color after every 7 days after specific date?

Body:
You could calculate the current week number and use it for setting the color.

const containerEl = document.getElementById('container');
const containerEl2 = document.getElementById('container2');
const containerEl3 = document.getElementById('container3');
const containerEl4 = document.getElementById('container4');
const weekClassPrefix = "week-"

// source https://www.w3resource.com/javascript-exercises/javascript-date-exercise-24.php
let isoWeekNumber = function(dt) {
  let tdt = new Date(dt.valueOf());
  let dayn = (dt.getDay() + 6) % 7;
  tdt.setDate(tdt.getDate() - dayn + 3);
  let firstThursday = tdt.valueOf();
  tdt.setMonth(0, 1);
  if (tdt.getDay() !== 4) {
    tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
  }
  return 1 + Math.ceil((firstThursday - tdt) / (60 * 60 * 24 * 7 * 1000));
}

let setBackgroundColor = function(date, element) {
  let weekNo = isoWeekNumber(date);
  // NOTE: I use % 4 to ensure it's between 0 and 3. If you want more variance colors,
  // just set the number to the number of colors and add the classes to the css.
  // I recommend to put all styles in there as long as there is no real need to do it via js.
  element.classList.add(weekClassPrefix + (weekNo % 4));

  // For debugging only.
  element.innerHTML = date.toLocaleDateString("en-GB", { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
}

let setCurrentBackgroundColor = function() {
  setBackgroundColor(new Date(), containerEl);
}

setCurrentBackgroundColor();
setBackgroundColor(new Date("2020-05-31"), containerEl2);
setBackgroundColor(new Date("2020-06-01"), containerEl3);
setBackgroundColor(new Date("2020-06-08"), containerEl4);

#container, #container2, #container3, #container4 {
  width: auto;
  height: 28px;
  padding: 10px;
  color: white;
}

.week-0 {
  background-color: orange;
}

.week-1 {
  background-color: green;
}

.week-2 {
  background-color: purple;
}

.week-3 {
  background-color: blue;
}

<div id="container">
</div>

<div id="container2">
</div>

<div id="container3">
</div>

<div id="container4">
</div>


问:
How to find two same items in a python list
So I want to be able to check if a list in a python program contains a particular value written twice.

```<code>list_one = [a, b, c, d, e, f, g]
</code>```

Here I want to check if two different items have the same value, for instance a == d

答:
This will check a list for duplicate values and produce a new list containing any values that were duplicated in the first list:</p>

```<code>items = ['a', 'b', 'c', 'b', 'd', 'e', 'f', 'g', 'a', 'c']
items.sort()
dups = [
    item1
    for item1, item2 in zip(items[:-1], items[1:])
    if item1 == item2
]
</code>```

Body:
So I want to be able to check if a list in a python program contains a particular value written twice.

list_one = [a, b, c, d, e, f, g]

Here I want to check if two different items have the same value, for instance a == d

Body:
This will check a list for duplicate values and produce a new list containing any values that were duplicated in the first list:

items = ['a', 'b', 'c', 'b', 'd', 'e', 'f', 'g', 'a', 'c']
items.sort()
dups = [
    item1
    for item1, item2 in zip(items[:-1], items[1:])
    if item1 == item2
]


问:
ASP.NET MVC3: Debug and Release app settings not working
My debug and release web.config app settings are not being read correctly.

Web.config:

```<code><appSettings>
 <add key="webpages:Version" value="1.0.0.0"/>
 <add key="ClientValidationEnabled" value="true"/>
 <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</code>```

Web.Debug.config

```<code><appSettings>
    <add key="ErrorEmailAddress" value="developerEmail@email.com" />
    <add key="TestModeEmailAddress" value="developerEmail@email.com" />
</appSettings>
</code>```

Web.Release.config

```<code><appSettings>
    <add key="ErrorEmailAddress" value="prodErrorEmail@email.com" />
</appSettings>
</code>```

However, calling:

```<code>WebConfigurationManager.AppSettings["ErrorEmailAddress"]
</code>```

is returning null (when debugging).

I have tried adding xdt:Transform="Insert" e.g.

```<code><add key="ErrorEmailAddress" value="prodErroEmail@email.com" xdt:Transform="Insert" />
</code>```

Any ideas?

答:
I've never had it working with not having the key in the default web.config.

This works for me:

Web.config

```<code><add key="Environment" value="Localhost" />
</code>```

Web.Debug.config

```<code><add key="Environment" value="Development" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</code>```

Web.Release.config

```<code><add key="Environment" value="Production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>
</code>```

Body:
My debug and release web.config app settings are not being read correctly.

Web.config:

<appSettings>
 <add key="webpages:Version" value="1.0.0.0"/>
 <add key="ClientValidationEnabled" value="true"/>
 <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

Web.Debug.config

<appSettings>
    <add key="ErrorEmailAddress" value="developerEmail@email.com" />
    <add key="TestModeEmailAddress" value="developerEmail@email.com" />
</appSettings>

Web.Release.config

<appSettings>
    <add key="ErrorEmailAddress" value="prodErrorEmail@email.com" />
</appSettings>

However, calling:

WebConfigurationManager.AppSettings["ErrorEmailAddress"]

is returning null (when debugging).

I have tried adding xdt:Transform="Insert" e.g.

<add key="ErrorEmailAddress" value="prodErroEmail@email.com" xdt:Transform="Insert" />

Any ideas?

Body:
I've never had it working with not having the key in the default web.config.

This works for me:

Web.config

<add key="Environment" value="Localhost" />

Web.Debug.config

<add key="Environment" value="Development" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>

Web.Release.config

<add key="Environment" value="Production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/>


问:
Concurrent modification should not be logged as ERROR?
We have an application running on a Wildfly 17. I have a scenario, which occurs occasionally, in which two background threads are accessing the same entity:

Thread A deletes the entity (for good reason)

Thread B is working on slightly older data and attempts to update the entity

When thread B is the later of the two, it fails due to the concurrent modification. This works correctly. It is retried automatically and finds that nothing needs to be done anymore (because the entity has been deleted). That is the intended behavior, when these two threads collide. All is fine!

However I find that this is logged as ERROR by CMTTxInterceptor:

```<code>2020-03-31 16:51:35,463 +0200 ERROR: as.ejb3.invocation - WFLYEJB0034: EJB Invocation failed on component ... for method ... throws ...:
  javax.ejb.EJBTransactionRolledbackException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:203) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:364) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:144) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
...
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_171]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)
Caused by: javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.wrapStaleStateException(AbstractEntityManagerImpl.java:1729) [hibernate-entitymanager.jar:5.0.12.Final]
... at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:185) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    ... 262 more
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3261) [hibernate-core.jar:5.0.12.Final]
...
</code>```

It seems to me, that this log is incorrect, mostly because this is not an ERROR. Concurrent modification is something normal, that is to be expected - and that our application logic handles. This log will distract my colleagues at the hotline.

Do you agree that the logging is incorrect, or am I missing something?

I think I will disable logging for "as.ejb3.invocation".

答:
In your case this exception was thrown because Hibernate detected that the entity previously fetched from database was changed (deleted) during the current transaction. So, there is nothing to update.

In this specific case I think you can ignore or swallow the exception. In other cases, it may be good to know about this exception, so I recommend swallow the exception but don’t disable as a whole on log level.

Body:
We have an application running on a Wildfly 17. I have a scenario, which occurs occasionally, in which two background threads are accessing the same entity:

Thread A deletes the entity (for good reason)

Thread B is working on slightly older data and attempts to update the entity

When thread B is the later of the two, it fails due to the concurrent modification. This works correctly. It is retried automatically and finds that nothing needs to be done anymore (because the entity has been deleted). That is the intended behavior, when these two threads collide. All is fine!

However I find that this is logged as ERROR by CMTTxInterceptor:

2020-03-31 16:51:35,463 +0200 ERROR: as.ejb3.invocation - WFLYEJB0034: EJB Invocation failed on component ... for method ... throws ...:
  javax.ejb.EJBTransactionRolledbackException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:203) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:364) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:144) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:422)
...
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [rt.jar:1.8.0_171]
    at org.apache.activemq.artemis.utils.ActiveMQThreadFactory$1.run(ActiveMQThreadFactory.java:118)
Caused by: javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.wrapStaleStateException(AbstractEntityManagerImpl.java:1729) [hibernate-entitymanager.jar:5.0.12.Final]
... at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:185) [wildfly-ejb3-17.0.1.Final.jar:17.0.1.Final]
    ... 262 more
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46) [hibernate-core.jar:5.0.12.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3261) [hibernate-core.jar:5.0.12.Final]
...

It seems to me, that this log is incorrect, mostly because this is not an ERROR. Concurrent modification is something normal, that is to be expected - and that our application logic handles. This log will distract my colleagues at the hotline.

Do you agree that the logging is incorrect, or am I missing something?

I think I will disable logging for "as.ejb3.invocation".


问:
getting rxjs value in sync, is this an anti pattern?
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

```<code>    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }
</code>```

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

```<code>{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

</code>```

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean

答:
after evaluating all I believe this is the best solution which is to use:

Angular async pipe

onPush to reduce multiple calls from template to method (important)

changeDetection mark for check when needed

cleaner if statement

Solution:

```<code>

<template>:
<td mat-cell *matCellDef="let element">
    {{getAssetNameAsync$(element) | async}}
</td>

<component>:
@Component({
    selector: 'app-scene-block-location',
    templateUrl: './block-location.component.html',
    styleUrls: ['./block-location.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

...

constructor(priate cd: ChangeDetectorRef) {}

someUpdateHappeningAtStore() {
    this.cd.markForCheck();
}

getAssetNameAsync$(i_page: IPager): Observable<string> {
     return (i_page.Player[0].$.src)
         ?
         this.storeSelector.getScene(i_page.Player[0].$.src)
         .map(x => x.Player.$.label)
         :
  this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
      .map(x => x.resource_name)
      .take(1);
}

</code>```

Body:
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean

Body:
after evaluating all I believe this is the best solution which is to use:

Angular async pipe

onPush to reduce multiple calls from template to method (important)

changeDetection mark for check when needed

cleaner if statement

Solution:

<template>:
<td mat-cell *matCellDef="let element">
    {{getAssetNameAsync$(element) | async}}
</td>

<component>:
@Component({
    selector: 'app-scene-block-location',
    templateUrl: './block-location.component.html',
    styleUrls: ['./block-location.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})

...

constructor(priate cd: ChangeDetectorRef) {}

someUpdateHappeningAtStore() {
    this.cd.markForCheck();
}

getAssetNameAsync$(i_page: IPager): Observable<string> {
     return (i_page.Player[0].$.src)
         ?
         this.storeSelector.getScene(i_page.Player[0].$.src)
         .map(x => x.Player.$.label)
         :
  this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
      .map(x => x.resource_name)
      .take(1);
}


问:
How can I define a 5x3 array of strings in python?
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

```<code>Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7
</code>```

I am coming from C/C++ and in this programming language it would look like this:

```<code>matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";
</code>```

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

答:
If you have the three lists defined as

```<code>firstnames = ["a", "b", "c", "d"]
lastnames = ["w", "x", "y", "z"]
grades = [1, 2, 3, 4]
</code>```

Then you could zip the lists, and use list comprehension as

```<code>merged = [[e1, e2, e3] for (e1, e2, e3) in zip(firstnames, lastnames, grades)]
</code>```

Body:
How can I define a 5x3 array of strings in python?

I want to save the following data in an array of strings:

Name    Surname Grade
Steve   Black   10
Jane    Red     10
Peter   Green   0
Kelly   Pink    7

I am coming from C/C++ and in this programming language it would look like this:

matrix[5][3];

matrix[0][0] = "Name";
matrix[0][1] = "Surname";
matrix[0][2] = "Grade";

matrix[1][0] = "Steve";
matrix[1][1] = "Black";
matrix[1][2] = "10";

...
...
...

matrix[4][0] = "Kelly";
matrix[4][1] = "Pink";
matrix[4][2] = "7";

Is there a way in python to create such table?

In case you know what kind of data type that is in python and how it work, please let me know.

Body:
If you have the three lists defined as

firstnames = ["a", "b", "c", "d"]
lastnames = ["w", "x", "y", "z"]
grades = [1, 2, 3, 4]

Then you could zip the lists, and use list comprehension as

merged = [[e1, e2, e3] for (e1, e2, e3) in zip(firstnames, lastnames, grades)]


问:
How to create a custom shaped CardView android

Hello, I'm semi new to android development and I want to create 2 card views that are custom shapes (as seen above) I was wondering if this is possible and how I would go about doing it. Thanks

答: I ended up using vectors made in Illustrator and importing them into Android Studio as PNGs. Then I set the PNGs as the background of LinearLayouts.</p>


问:
overriding the binary predicate when doing a lexicographical compare in ruby
If I have two arrays, a1 and a2 in ruby, to do a lexicographical comparison I do a1 <=> a2.

Is there a way to override how ruby compares each element?

What I'd like to do is something like

```<code>a1.collect(&:name) <=> a2.collect(&:name)
</code>```

without the collect because that's creating two new arrays (e.g. if we're sorting an array of arrays, a ton of time would be spent in the allocator).

I could write my own lexicographical compare function, but that seems very anti-ruby and I'm not sure if it would be faster because the the amount of time spent in ruby space (vs C space).

edit: another example would be for doing a case insensitive lexicographical compare of two arrays of strings.

答:
It's dangerous to change how arrays are compared, so you should create a subclass of Array. Suppose your a1 and a2 belong to A, which is a subclass of Array. Then, redefine <=> as follows:

```<code>class A; def <=> other; collect(&:name) <=> other.collect(&:name) end end
</code>```

Body:
If I have two arrays, a1 and a2 in ruby, to do a lexicographical comparison I do a1 <=> a2.

Is there a way to override how ruby compares each element?

What I'd like to do is something like

a1.collect(&:name) <=> a2.collect(&:name)

without the collect because that's creating two new arrays (e.g. if we're sorting an array of arrays, a ton of time would be spent in the allocator).

I could write my own lexicographical compare function, but that seems very anti-ruby and I'm not sure if it would be faster because the the amount of time spent in ruby space (vs C space).

edit: another example would be for doing a case insensitive lexicographical compare of two arrays of strings.

Body:
It's dangerous to change how arrays are compared, so you should create a subclass of Array. Suppose your a1 and a2 belong to A, which is a subclass of Array. Then, redefine <=> as follows:

class A; def <=> other; collect(&:name) <=> other.collect(&:name) end end


问:
Discrepency in Number of writes in Firebase console and Google cloud console Quota pages
Last couple of weeks, I have been Observing difference between number of writes in Firebase console Firestore Usage tab and Google cloud console Quota page.

Before that, The count fairly used to sync.

Number of writes in Firebase Firestore console usage tab:   9.2K

Number of writes in Google Cloud Console page, Quotas Page: 19307

Which is approximately double the number of writes in Firebase Firestore Usage Tab. Are there any Internal writes happening which google doesn't report?

Firebase Console Firestore Usage Tab Page

Google cloud Console Quotas page

I have attached the screenshots for the same.

Can anyone clear My Query. Is this a valid Scenario?
Note: I Don't have any other project linked to the platform.

答:
From your first screenshot you can see at the top left written on the graph “Does not include Imports/exports and may not match billing and quota usage”. Moreover, Google public documentation states that the Firebase console includes a usage dashboard that shows Cloud Firestore reads, writes, deletes and other metrics over time.

As a result of how the dashboard computes usage, the numbers reported can differ from billing reports. The billing reports are the final usage numbers.

The usage dashboard does not include reads and writes from managed import and export operations.


问:
'mergeDelayError' does not exist in RxJS 5
I came across this method in RxJS 4 and it seems quite helpful, however I can't seem to find it anywhere in RxJS 5.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/errors.md

Does anyone know if anything in RxJS 5 does similar behavior?

答:
You can add a polyfill for it like that.

function mergeDelayError(...sources: Array<Observable<any>>) {
    const final = new Subject();
    const catching = sources.map(obs => obs.pipe(
        catchError(e => {
            if (!final.hasError) {
                final.error(e);
            }
            return EMPTY;
        }),
    ));

    return concat(merge(...catching), final);
}

const o1$ = interval(150).pipe(take(5));
const o2$ = throwError(new Error('woops1'));
const o3$ = throwError(new Error('woops2'));

mergeDelayError(o1$, o2$, o3$).subscribe(
    x => console.log('next:', x),
    e => console.log('error:', e),
    () => console.log('completed'),
);
```

<p>output is</p>

```[Log] next: – 0
[Log] next: – 1
[Log] next: – 2
[Log] next: – 3
[Log] next: – 4
[Log] error: – Error: woops1
```

Body:
You can add a polyfill for it like that.

function mergeDelayError(...sources: Array<Observable<any>>) {
    const final = new Subject();
    const catching = sources.map(obs => obs.pipe(
        catchError(e => {
            if (!final.hasError) {
                final.error(e);
            }
            return EMPTY;
        }),
    ));

    return concat(merge(...catching), final);
}

const o1$ = interval(150).pipe(take(5));
const o2$ = throwError(new Error('woops1'));
const o3$ = throwError(new Error('woops2'));

mergeDelayError(o1$, o2$, o3$).subscribe(
    x => console.log('next:', x),
    e => console.log('error:', e),
    () => console.log('completed'),
);

output is

[Log] next: – 0
[Log] next: – 1
[Log] next: – 2
[Log] next: – 3
[Log] next: – 4
[Log] error: – Error: woops1