问:
AJAX Update Query every 5 seconds to output album art for Icecast Server
Some background:

I have Icecast 2.4.3 running on a Windows computer. I have made a "Now Playing" xsl file that resides in the "web" directory of Icecast. An example of a currently playing song that would be in the file would be somethings like this:

```<code>getMusic({
    "/stream":{
        "server_name":"Radio",
        "title":"Jack Johnson - Crying Shame"}
    });
</code>```

From my webpage, I have a timeout function that will automatically change the artist and song title to a  with an id of "track-title2". This script looks something like this:

```<code><script>
function updateTitle() {
    $.ajax({
        type: 'GET',
        url: 'https://radio.domain.com/np.xsl',
        jsonpCallback: 'getMusic',
        dataType: 'jsonp'
    }).then(function (data) {
        var $track = $('#track-title').text(data['/stream'].title);
    }).fail(function (e) {
        console.log(e);
    }).always(function () {
        setTimeout(updateTitle, 5000);
    });
}
$(updateTitle);
</script>
</code>```

ALL THAT WORKS...

Now, I want to step up my webpage by adding album art by accessing a LAST.FM API. This function is in another separate PHP file called "loadme.php".

The Problem:

I cannot seem to figure out how to parse my AJAX GET request that (in this example) outputs to the screen Jack Johnson - Crying Shame. I need to grab all characters up to the "-" and similarly, take everything after the "-" and put this into two PHP variable, i.e. $artist and $title (respectively).

Since the artists and titles could change as well, I want this call to be similar to the script above.

The PHP call in my index.php:

```<code><?php
echo '<img id="albumart" style="text-align:center;" src="';
echo LastFMArtwork::getArtwork('Jack Johnson', 'Crying Shame', true, "small");
echo '">';
?>
</code>```

I have obviously hard coded the title to make sure that the API is correct... it is and the album art does show on my webpage.

Please help:
Develop a JSON AJAX script that updates every 5 seconds that calls the PHP function "LastFMArtwork::getArtwork" but can parse out the artist and title into two PHP variables. Any help and/or guidance is greatly appreciated.

Thanks.

答:
So, with a little (okay a bunch of) guidance from Brad, I was able to use a hybrid of SSE (Server Sent Events) and AJAX.

My index.php page:

<!DOCTYPE html>

  <link rel="icon" href="favicon.ico" type="image/x-icon">
  <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
     <meta name="apple-mobile-web-app-capable" content="yes">
  <link rel="apple-touch-icon" href="apple-touch-icon.png" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="description" content="Person's personal and professional radio station. ***Contains explicit content***">
  <meta name="keywords" content="icecast,radio,internet radio,station,mediamonkey">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3">
  <meta property="og:url" content="https://radio.domain.com" />
  <meta property="og:image" content="https://radio.domain.com/ogimage.png" />
  <meta property="og:site_name" content="Radio" />
  <meta property="og:description" content="Person's personal internet radio station" />
  <title id="track-title"></title>

Live Radio

        <audio id="radio" controls src="https://radio.domain.com/stream" type="audio/mp3"></audio>

```
</div>
</div>
</p>

<p><strong>My SSE page that is called from AJAX (getalbum.php):</strong></p>

```<?php
require_once("lastfm.php");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$exe = curl_init();
curl_setopt($exe, CURLOPT_URL, "https://radio.domain.com/np.xsl");
curl_setopt($exe, CURLOPT_HEADER, 0);
curl_setopt($exe, CURLOPT_RETURNTRANSFER, 1);
$raw = curl_exec($exe);
curl_close($exe);
$json = $raw;
//The next 7 lines gets rids of all the "extra stuff" from the np.xsl file
$json = str_replace("\n","",$json);
$json = str_replace("\t","",$json);
$json = str_replace("\"","",$json);
$json = str_replace("({","",$json);
$json = str_replace("\n\t","",$json);
$json = str_replace("parseMusic/stream:{title:","",$json);
$json = str_replace(" - MediaMonkey}});","",$json);
//Find the dash and minus one is the artist!
$artist = substr($json, 0, strpos($json, "-") - 1);
//Find the dash and add 2 and that is the title!
$title = substr($json, strpos($json, "-") + 2, strlen($json));
echo '
'.$artist.' - '.$title.'

';
echo '
';
flush();
```

Sceenshot from my live website:
screenshot1

Body:
Some background:

I have Icecast 2.4.3 running on a Windows computer. I have made a "Now Playing" xsl file that resides in the "web" directory of Icecast. An example of a currently playing song that would be in the file would be somethings like this:

getMusic({
    "/stream":{
        "server_name":"Radio",
        "title":"Jack Johnson - Crying Shame"}
    });

From my webpage, I have a timeout function that will automatically change the artist and song title to a  with an id of "track-title2". This script looks something like this:

ALL THAT WORKS...

Now, I want to step up my webpage by adding album art by accessing a LAST.FM API. This function is in another separate PHP file called "loadme.php".

The Problem:

I cannot seem to figure out how to parse my AJAX GET request that (in this example) outputs to the screen Jack Johnson - Crying Shame. I need to grab all characters up to the "-" and similarly, take everything after the "-" and put this into two PHP variable, i.e. $artist and $title (respectively).

Since the artists and titles could change as well, I want this call to be similar to the script above.

The PHP call in my index.php:

<?php
echo '';
?>

I have obviously hard coded the title to make sure that the API is correct... it is and the album art does show on my webpage.

Please help:
Develop a JSON AJAX script that updates every 5 seconds that calls the PHP function "LastFMArtwork::getArtwork" but can parse out the artist and title into two PHP variables. Any help and/or guidance is greatly appreciated.

Thanks.

Body:
So, with a little (okay a bunch of) guidance from Brad, I was able to use a hybrid of SSE (Server Sent Events) and AJAX.

My index.php page:

<!DOCTYPE html>
<html xml:lang="en" lang="en" dir="ltr" prefix="og: http://ogp.me/ns#">
 <head>
  <link rel="icon" href="favicon.ico" type="image/x-icon">
  <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
     <meta name="apple-mobile-web-app-capable" content="yes">
  <link rel="apple-touch-icon" href="apple-touch-icon.png" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="description" content="Person's personal and professional radio station. ***Contains explicit content***">
  <meta name="keywords" content="icecast,radio,internet radio,station,mediamonkey">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=3">
  <meta property="og:url" content="https://radio.domain.com" />
  <meta property="og:image" content="https://radio.domain.com/ogimage.png" />
  <meta property="og:site_name" content="Radio" />
  <meta property="og:description" content="Person's personal internet radio station" />
  <title id="track-title"></title>
  <style>
   html{width:100%;}
   body{background-color:#bfbfbf; text-align:center; font-family:Helvetica;}
   #wrapper{position:absolute; width:300px; height:450px; max-width:550px; max-height:700px; left:50%; transform:translate(-50%,0); -ms-transform:translate(-50%,0); -webkit-transform:translate(-50%,0); margin-right:-50%; text-align:center; box-shadow:1px 1px 20px 5px #4d4d4d;}
                        #albumart{position:relative; text-align:center; box-shadow:1px 1px 20px 5px #4d4d4d;}
   #radio{position: relative;}
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script>
function updateTitle() {
 $.ajax({
  type: 'GET',
  url: 'https://radio.domain.com/np.xsl',
  jsonpCallback: 'parseMusic',
  dataType: 'jsonp'
 }).then(function (data) {
  var $track = $('#track-title').text(data['/stream'].title);
  var text = $track.text();
  $track.text(text.replace(" - MediaMonkey",""));
 }).fail(function (e) {
  console.log(e);
 }).always(function () {
  setTimeout(updateTitle, 12500);
 });
}
$(updateTitle);
function sendRequest(){
    $.ajax({
     type: 'GET',
        url: 'https://radio.domain.com/getalbum.php',
        success: function(data){
                document.getElementById("art").innerHTML = data;
  console.log(data);
                setTimeout(function(){
                    sendRequest();
                }, 10000);
        }});
};
$(sendRequest);
</script>
</head>
<body>
        <div id="wrapper">
        <h2>Live Radio</h2>
        <span id="art"></span>
        <audio id="radio" controls src="https://radio.domain.com/stream" type="audio/mp3"></audio>
        </div>
</body>
</html>

My SSE page that is called from AJAX (getalbum.php):

<?php
require_once("lastfm.php");
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$exe = curl_init();
curl_setopt($exe, CURLOPT_URL, "https://radio.domain.com/np.xsl");
curl_setopt($exe, CURLOPT_HEADER, 0);
curl_setopt($exe, CURLOPT_RETURNTRANSFER, 1);
$raw = curl_exec($exe);
curl_close($exe);
$json = $raw;
//The next 7 lines gets rids of all the "extra stuff" from the np.xsl file
$json = str_replace("\n","",$json);
$json = str_replace("\t","",$json);
$json = str_replace("\"","",$json);
$json = str_replace("({","",$json);
$json = str_replace("\n\t","",$json);
$json = str_replace("parseMusic/stream:{title:","",$json);
$json = str_replace(" - MediaMonkey}});","",$json);
//Find the dash and minus one is the artist!
$artist = substr($json, 0, strpos($json, "-") - 1);
//Find the dash and add 2 and that is the title!
$title = substr($json, strpos($json, "-") + 2, strlen($json));
echo '<h4>'.$artist.' - '.$title.'</br></br>';
echo '<img id="albumart" title="'.$title.'" style="text-align:center;" width="280" height="280" src="';
echo LastFMArtwork::getArtwork("$artist", "$title", true, "extralarge");
echo '"></br>';
flush();

Sceenshot from my live website:
screenshot1


来源: stackexchange

问:
Understand recursion of w3.includeHTML JavaScript function
The below JavaScript function includes HTML from a file within an HTML tag with class "w3-include-html."

Can someone explain why w3.includeHTML(cb), so the function itself, is called again in the middle of the function? Doesn't that generate an infinite loop? Any help much appreciated.

```<code>w3.includeHTML = function(cb) {
  var z, i, elmnt, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          elmnt.innerHTML = this.responseText;
          elmnt.removeAttribute("w3-include-html");
          w3.includeHTML(cb);
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }
  if (cb) cb();
};
</code>```

答:
Can someone explain why w3.includeHTML(cb), so the function itself, is called again in the middle of the function?

In cause the file you included tries to include something else.

Doesn't that generate an infinite loop?

No, because the previous line removed the attribute from the element that has done the include.

ContentLicense: CC BY-SA 3.0

Body:
The below JavaScript function includes HTML from a file within an HTML tag with class "w3-include-html."

Can someone explain why w3.includeHTML(cb), so the function itself, is called again in the middle of the function? Doesn't that generate an infinite loop? Any help much appreciated.

w3.includeHTML = function(cb) {
  var z, i, elmnt, file, xhttp;
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          elmnt.innerHTML = this.responseText;
          elmnt.removeAttribute("w3-include-html");
          w3.includeHTML(cb);
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      return;
    }
  }
  if (cb) cb();
};


问:
Tomcat8 ClassNotFoundException BasicDataSourceFactory
Okay so I have been trying to get this to work for too long now. I really need some input for my case. I have read a lot of different questions about this and tried multiple solutions but nothing seems to be working for me.

I am trying to set up a database pooling on my environment on AWS. The environment config is:
64bit Amazon Linux 2017.03 v2.6.1 running Tomcat 8 Java 8.

The problem I am running in to is I get this exception:

```<code>javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory]
</code>```

My set up is like this:

First context.xml file that I have put inside the .war under WEB-INF/conf/context.xml, is this the correct location first of all?

```<code><Context>
<Resource name="jdbc/TestDB"
          auth="Container"
          type="javax.sql.DataSource"
          maxTotal="20"
          maxIdle="10"
          maxWaitMillis="10000"
          username="username"
          password="password"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://database-url.example"/>
</Context>
</code>```

Here I have tried to both supply the factory parameter with different values such as

```<code>    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
</code>```

I have also tried adding both the org.apache.tomcat.dbcp library, also in my .war under WEB-INF/lib/

The I have the web.xml in my .war under WEB-INF/web.xml

```<code><web-app>
. . .
  <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/TestDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>
</code>```

Then in my code I am doing this

```<code>public class Database {

private static DataSource dataSource;

static {
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        dataSource = (DataSource) envCtx.lookup("jdbc/TestDB");
    } catch(NamingException e) {
        e.printStackTrace();
    }
}

public static Connection getPoolConnection() {
    try {
        return dataSource.getConnection();
    } catch(SQLException e) {
        e.printStackTrace();
    }

    return null;
}
}
</code>```

The problem probably boils down to the library not existing on the correct place, I have read about that you need to add it to CATALINA_HOME/lib, is this not the same location as I have added the library? How can I otherwise add libraries to this folder on my AWS environment?

Is there any other changes I need to make or add another library?

What I notice is that even though I add libraries in my .war WEB-INF/lib folder and add the factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" or to somethling like factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" it is still not working. And even though I set the factory as DataSourceFactory I still get the same exception that the BasicDataSourceFactory can't be found.

I think I need some clear explanation on which files or libraries goes EXACTLY in which folder.

答:
Okay so I think I have figured out a way to solve it. I don't know if this is the best way though, but it seems to be working pretty good for me.

What I did was to skip all about the xml files and did everything in java instead.

I removed the stuff in context.xml and web.xml regarding the resource.

Then I changed my Database class like this, using some default settings I found and some that I modified for my case:

```<code>public class Database {

private static DataSource dataSource;

static {
    // Getting environment variables I have set in server
    String dbName = System.getProperty("DB_NAME");
    String userName = System.getProperty("DB_USERNAME");
    String password = System.getProperty("DB_PASSWORD");
    String hostname = System.getProperty("DB_HOSTNAME");
    String port = "3306"; //System.getProperty("RDS_PORT");

    PoolProperties p = new PoolProperties();
    p.setUrl("jdbc:mysql://" + hostname + ":" + port + "/" + dbName);
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername(userName);
    p.setPassword(password);
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(20);
    p.setInitialSize(5);
    p.setMaxWait(15000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMaxIdle(10);
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" +
            "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    dataSource = new DataSource();
    dataSource.setPoolProperties(p);
}

public static Connection getPoolConnection() {
    try {
        return dataSource.getConnection();
    } catch(SQLException e) {
        e.printStackTrace();
    }

    return null;
}
}
</code>```

To read more about this solution, I found my answer over here https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html under the section Code Example Plain Ol' Java

Body:
Okay so I have been trying to get this to work for too long now. I really need some input for my case. I have read a lot of different questions about this and tried multiple solutions but nothing seems to be working for me.

I am trying to set up a database pooling on my environment on AWS. The environment config is:
64bit Amazon Linux 2017.03 v2.6.1 running Tomcat 8 Java 8.

The problem I am running in to is I get this exception:

javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory]

My set up is like this:

First context.xml file that I have put inside the .war under WEB-INF/conf/context.xml, is this the correct location first of all?

<Context>
<Resource name="jdbc/TestDB"
          auth="Container"
          type="javax.sql.DataSource"
          maxTotal="20"
          maxIdle="10"
          maxWaitMillis="10000"
          username="username"
          password="password"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://database-url.example"/>
</Context>

Here I have tried to both supply the factory parameter with different values such as

    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

I have also tried adding both the org.apache.tomcat.dbcp library, also in my .war under WEB-INF/lib/

The I have the web.xml in my .war under WEB-INF/web.xml

<web-app>
. . .
  <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/TestDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
</web-app>

Then in my code I am doing this

public class Database {

private static DataSource dataSource;

static {
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        dataSource = (DataSource) envCtx.lookup("jdbc/TestDB");
    } catch(NamingException e) {
        e.printStackTrace();
    }
}

public static Connection getPoolConnection() {
    try {
        return dataSource.getConnection();
    } catch(SQLException e) {
        e.printStackTrace();
    }

    return null;
}
}

The problem probably boils down to the library not existing on the correct place, I have read about that you need to add it to CATALINA_HOME/lib, is this not the same location as I have added the library? How can I otherwise add libraries to this folder on my AWS environment?

Is there any other changes I need to make or add another library?

What I notice is that even though I add libraries in my .war WEB-INF/lib folder and add the factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" or to somethling like factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory" it is still not working. And even though I set the factory as DataSourceFactory I still get the same exception that the BasicDataSourceFactory can't be found.

I think I need some clear explanation on which files or libraries goes EXACTLY in which folder.

Body:
Okay so I think I have figured out a way to solve it. I don't know if this is the best way though, but it seems to be working pretty good for me.

What I did was to skip all about the xml files and did everything in java instead.

I removed the stuff in context.xml and web.xml regarding the resource.

Then I changed my Database class like this, using some default settings I found and some that I modified for my case:

public class Database {

private static DataSource dataSource;

static {
    // Getting environment variables I have set in server
    String dbName = System.getProperty("DB_NAME");
    String userName = System.getProperty("DB_USERNAME");
    String password = System.getProperty("DB_PASSWORD");
    String hostname = System.getProperty("DB_HOSTNAME");
    String port = "3306"; //System.getProperty("RDS_PORT");

    PoolProperties p = new PoolProperties();
    p.setUrl("jdbc:mysql://" + hostname + ":" + port + "/" + dbName);
    p.setDriverClassName("com.mysql.jdbc.Driver");
    p.setUsername(userName);
    p.setPassword(password);
    p.setJmxEnabled(true);
    p.setTestWhileIdle(false);
    p.setTestOnBorrow(true);
    p.setValidationQuery("SELECT 1");
    p.setTestOnReturn(false);
    p.setValidationInterval(30000);
    p.setTimeBetweenEvictionRunsMillis(30000);
    p.setMaxActive(20);
    p.setInitialSize(5);
    p.setMaxWait(15000);
    p.setRemoveAbandonedTimeout(60);
    p.setMinEvictableIdleTimeMillis(30000);
    p.setMaxIdle(10);
    p.setLogAbandoned(true);
    p.setRemoveAbandoned(true);
    p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;" +
            "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
    dataSource = new DataSource();
    dataSource.setPoolProperties(p);
}

public static Connection getPoolConnection() {
    try {
        return dataSource.getConnection();
    } catch(SQLException e) {
        e.printStackTrace();
    }

    return null;
}
}

To read more about this solution, I found my answer over here https://tomcat.apache.org/tomcat-8.0-doc/jdbc-pool.html under the section Code Example Plain Ol' Java


问:
PHP Fatal error: Uncaught exception 'Symfony\Component\Yaml\Exception\ParseException'
I have this bug when I use symfony 2.8, bug in config.yml maybe , help me please for resolve this problem and thanks advanced

FileLoaderLoadException in FileLoader.php line 133:
  The file "/var/www/html/authenti/app/config/config.yml" does not contain valid YAML in /var/www/html/authenti/app/config/config.yml (which is being imported from "/var/www/html/authenti/app/config/config_dev.yml").

code config.yml:

```<code>imports:
        - { resource: parameters.yml }
        - { resource: security.yml }
        - { resource: services.yml }

    # Put parameters here that don't need to change on each machine where the app is deployed
    # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
    parameters:
        locale: en

    framework:
        #esi: ~
        #translator: { fallbacks: ['%locale%'] }
        secret: '%secret%'
        router:
            resource: '%kernel.root_dir%/config/routing.yml'
            strict_requirements: ~
        form: ~
        csrf_protection: ~
        validation: { enable_annotations: true }
        #serializer: { enable_annotations: true }
        templating:
            engines: ['twig']
        default_locale: '%locale%'
        trusted_hosts: ~
        trusted_proxies: ~
        session:
            # handler_id set to null will use default session handler from php.ini
            handler_id: ~
        fragments: ~
        http_method_override: true

    # Twig Configuration
    twig:
        debug: '%kernel.debug%'
        strict_variables: '%kernel.debug%'

    # Doctrine Configuration
    doctrine:
        dbal:
            driver: pdo_mysql
            host: '%database_host%'
            port: '%database_port%'
            dbname: '%database_name%'
            user: '%database_user%'
            password: '%database_password%'
            charset: UTF8
            # if using pdo_sqlite as your database driver:
            #   1. add the path in parameters.yml
            #     e.g. database_path: '%kernel.root_dir%/data/data.db3'
            #   2. Uncomment database_path in parameters.yml.dist
            #   3. Uncomment next line:
            #path: '%database_path%'

        orm:
            auto_generate_proxy_classes: '%kernel.debug%'
            naming_strategy: doctrine.orm.naming_strategy.underscore
            auto_mapping: true

    # Swiftmailer Configuration
    swiftmailer:
        transport: '%mailer_transport%'
        host: '%mailer_host%'
        username: '%mailer_user%'
        password: '%mailer_password%'
        spool: { type: memory }

    imports:
        // ...
        - { resource: security.yml }
    // ...
    framework:
        // ...
        csrf_protection: ~
        form: ~
        session:
            handler_id: ~
        // ...
    fos_user:
        db_driver: orm
        firewall_name: main
        user_class: AppBundle\Entity\User
    lexik_jwt_authentication:
        private_key_path: %jwt_private_key_path%
        public_key_path:  %jwt_public_key_path%
        pass_phrase:      %jwt_key_pass_phrase%
        token_ttl:        %jwt_token_ttl%
    // ...
    dunglas_api:
        title:       "%api_name%"
        description: "%api_description%"
        enable_fos_user: true
    nelmio_cors:
        defaults:
            allow_origin:   ["%cors_allow_origin%"]
            allow_methods:  ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
            allow_headers:  ["content-type", "authorization"]
            expose_headers: ["link"]
            max_age:       3600
        paths:
            '^/': ~
</code>```

routing.yml:

```<code>app:
    resource: '@AppBundle/Controller/'
    type: annotation

api:
    resource: "."
    type:     "api"
    prefix: "/api"

api_login_check:
    path: "/login_check"
</code>```

parameters.yml.dist:

```<code># This file is a "template" of what your parameters.yml file should look like
    # Set parameters here that may be different on each deployment target of the app, e.g. development, staging, production.
    # https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
    parameters:
        database_host: 127.0.0.1
        database_port: ~
        database_name: symfony
        database_user: root
        database_password: ~
        # You should uncomment this if you want to use pdo_sqlite
        #database_path: "%kernel.root_dir%/data.db3"

        mailer_transport: smtp
        mailer_host: 127.0.0.1
        mailer_user: ~
        mailer_password: ~

        jwt_private_key_path: %kernel.root_dir%/var/jwt/private.pem
        jwt_public_key_path:  %kernel.root_dir%/var/jwt/public.pem
        jwt_key_pass_phrase : 'test'
        jwt_token_ttl:        86400

        cors_allow_origin: http://localhost:9000

        api_name:          Your API name
        api_description:   The full description of your API

        # A secret key that's used to generate certain security-related tokens
        secret: ThisTokenIsNotSoSecretChangeIt
</code>```

答:
try to indent well, I seen this for example to fix:

```<code>imports:
        - { resource: parameters.yml }
        - { resource: security.yml }
        - { resource: services.yml }
</code>```

Corrected:

```<code>imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }
</code>```

Body:
I have this bug when I use symfony 2.8, bug in config.yml maybe , help me please for resolve this problem and thanks advanced

FileLoaderLoadException in FileLoader.php line 133:
  The file "/var/www/html/authenti/app/config/config.yml" does not contain valid YAML in /var/www/html/authenti/app/config/config.yml (which is being imported from "/var/www/html/authenti/app/config/config_dev.yml").

code config.yml:

imports:
        - { resource: parameters.yml }
        - { resource: security.yml }
        - { resource: services.yml }

    # Put parameters here that don't need to change on each machine where the app is deployed
    # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
    parameters:
        locale: en

    framework:
        #esi: ~
        #translator: { fallbacks: ['%locale%'] }
        secret: '%secret%'
        router:
            resource: '%kernel.root_dir%/config/routing.yml'
            strict_requirements: ~
        form: ~
        csrf_protection: ~
        validation: { enable_annotations: true }
        #serializer: { enable_annotations: true }
        templating:
            engines: ['twig']
        default_locale: '%locale%'
        trusted_hosts: ~
        trusted_proxies: ~
        session:
            # handler_id set to null will use default session handler from php.ini
            handler_id: ~
        fragments: ~
        http_method_override: true

    # Twig Configuration
    twig:
        debug: '%kernel.debug%'
        strict_variables: '%kernel.debug%'

    # Doctrine Configuration
    doctrine:
        dbal:
            driver: pdo_mysql
            host: '%database_host%'
            port: '%database_port%'
            dbname: '%database_name%'
            user: '%database_user%'
            password: '%database_password%'
            charset: UTF8
            # if using pdo_sqlite as your database driver:
            #   1. add the path in parameters.yml
            #     e.g. database_path: '%kernel.root_dir%/data/data.db3'
            #   2. Uncomment database_path in parameters.yml.dist
            #   3. Uncomment next line:
            #path: '%database_path%'

        orm:
            auto_generate_proxy_classes: '%kernel.debug%'
            naming_strategy: doctrine.orm.naming_strategy.underscore
            auto_mapping: true

    # Swiftmailer Configuration
    swiftmailer:
        transport: '%mailer_transport%'
        host: '%mailer_host%'
        username: '%mailer_user%'
        password: '%mailer_password%'
        spool: { type: memory }

    imports:
        // ...
        - { resource: security.yml }
    // ...
    framework:
        // ...
        csrf_protection: ~
        form: ~
        session:
            handler_id: ~
        // ...
    fos_user:
        db_driver: orm
        firewall_name: main
        user_class: AppBundle\Entity\User
    lexik_jwt_authentication:
        private_key_path: %jwt_private_key_path%
        public_key_path:  %jwt_public_key_path%
        pass_phrase:      %jwt_key_pass_phrase%
        token_ttl:        %jwt_token_ttl%
    // ...
    dunglas_api:
        title:       "%api_name%"
        description: "%api_description%"
        enable_fos_user: true
    nelmio_cors:
        defaults:
            allow_origin:   ["%cors_allow_origin%"]
            allow_methods:  ["POST", "PUT", "GET", "DELETE", "OPTIONS"]
            allow_headers:  ["content-type", "authorization"]
            expose_headers: ["link"]
            max_age:       3600
        paths:
            '^/': ~

routing.yml:

app:
    resource: '@AppBundle/Controller/'
    type: annotation

api:
    resource: "."
    type:     "api"
    prefix: "/api"

api_login_check:
    path: "/login_check"

parameters.yml.dist:

# This file is a "template" of what your parameters.yml file should look like
    # Set parameters here that may be different on each deployment target of the app, e.g. development, staging, production.
    # https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
    parameters:
        database_host: 127.0.0.1
        database_port: ~
        database_name: symfony
        database_user: root
        database_password: ~
        # You should uncomment this if you want to use pdo_sqlite
        #database_path: "%kernel.root_dir%/data.db3"

        mailer_transport: smtp
        mailer_host: 127.0.0.1
        mailer_user: ~
        mailer_password: ~

        jwt_private_key_path: %kernel.root_dir%/var/jwt/private.pem
        jwt_public_key_path:  %kernel.root_dir%/var/jwt/public.pem
        jwt_key_pass_phrase : 'test'
        jwt_token_ttl:        86400

        cors_allow_origin: http://localhost:9000

        api_name:          Your API name
        api_description:   The full description of your API

        # A secret key that's used to generate certain security-related tokens
        secret: ThisTokenIsNotSoSecretChangeIt

Body:
try to indent well, I seen this for example to fix:

imports:
        - { resource: parameters.yml }
        - { resource: security.yml }
        - { resource: services.yml }

Corrected:

imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }


问:
Basic Vpython code error - "TypeError: bad operand type for unary -: 'tuple'"
First off my apologies if this is a noob issue but I am completely new to coding.

I am following a guide on building a harmonic oscilation simulator in Vpython but every time I try to run the program I get this error.

File "C:/Users/Nathan/Desktop/vspring", line 14
     F_spring=-k*(block.pos -L)
  TypeError: bad operand type for unary -: 'tuple'

Can someone please look at the code and tell me where I have gone wrong. I have literally followed the guide to the letter as I am just copying line by line what it tells me to put. But it has no trouble shooting. It just states "Your program is now ready to run"

```<code>from visual import *
from visual.graph import *

L=vector(1,0,0)
s=vector(1.,0,0)
block=sphere(radius=0.25, color=color.cyan, pos=L+s)
spring=cylinder(pos=(0,0,0), axis=L+s, radius=.1)
scene.autoscale=0
posgraph=gcurve(color=color.green)

k=100,; g=9.8; mu_s=.5; mu_k=.5; m=1.; dt=.0001; d=0.; t=0.
F_mu_s=mu_s*m*g
F_spring=-k*(block.pos-L)
almost_zero_p=mag(F_spring)*dt
block.p=vector(0,0,0)

while not(mag(block.p)<almost_zero_p and F_mu_s>=mag(F_spring)):
    if not(mag(block.p)<almost_zero_p):
        F_mu_k=m*g*mu_k*norm(block.p)
    else:
        F_ms_k=vector(0,0,0)

    F_spring=-k*(block.pos-L)
    Fnet=F_spring+F_mu_k
    block.p=block.p+Fnet*dt
    block.pos=block.pos+block.p/m*dt
    spring.axis=block.pos-spring.pos

    d=d+mag(block.p/m)*dt
    posgraph.plot(pos=(t,block.pos.x-L.x))
    t=t+dt

print "Total distance traveled is", d
</code>```

答:
When you do at line 12 :

```<code>k=100,
</code>```

You actually create a tuple (100,).

If you wanted to create a float, do :

```<code>k=100.
</code>```

Indeed when you were trying to do -k, the unary operator - doesn't work because of k type (tuple). I think this is just a syntax mistake.

Body:
First off my apologies if this is a noob issue but I am completely new to coding.

I am following a guide on building a harmonic oscilation simulator in Vpython but every time I try to run the program I get this error.

File "C:/Users/Nathan/Desktop/vspring", line 14
     F_spring=-k*(block.pos -L)
  TypeError: bad operand type for unary -: 'tuple'

Can someone please look at the code and tell me where I have gone wrong. I have literally followed the guide to the letter as I am just copying line by line what it tells me to put. But it has no trouble shooting. It just states "Your program is now ready to run"

from visual import *
from visual.graph import *

L=vector(1,0,0)
s=vector(1.,0,0)
block=sphere(radius=0.25, color=color.cyan, pos=L+s)
spring=cylinder(pos=(0,0,0), axis=L+s, radius=.1)
scene.autoscale=0
posgraph=gcurve(color=color.green)

k=100,; g=9.8; mu_s=.5; mu_k=.5; m=1.; dt=.0001; d=0.; t=0.
F_mu_s=mu_s*m*g
F_spring=-k*(block.pos-L)
almost_zero_p=mag(F_spring)*dt
block.p=vector(0,0,0)

while not(mag(block.p)<almost_zero_p and F_mu_s>=mag(F_spring)):
    if not(mag(block.p)<almost_zero_p):
        F_mu_k=m*g*mu_k*norm(block.p)
    else:
        F_ms_k=vector(0,0,0)

    F_spring=-k*(block.pos-L)
    Fnet=F_spring+F_mu_k
    block.p=block.p+Fnet*dt
    block.pos=block.pos+block.p/m*dt
    spring.axis=block.pos-spring.pos

    d=d+mag(block.p/m)*dt
    posgraph.plot(pos=(t,block.pos.x-L.x))
    t=t+dt

print "Total distance traveled is", d

Body:
When you do at line 12 :

k=100,

You actually create a tuple (100,).

If you wanted to create a float, do :

k=100.

Indeed when you were trying to do -k, the unary operator - doesn't work because of k type (tuple). I think this is just a syntax mistake.


Title: How to convert values of a matrix into percentage without changing the format in R

Body:
I have a matrix which is res

 > res
                     [,1]         [,2]       [,3]       [,4]       [,5]
        [1,]  0.025431667  0.024636307 0.02812685 0.02733088 0.02807624
        [2,] -0.005383589  0.000000000 0.02807624 0.02258878 0.02322090
        [3,] -0.002674251 -0.002674251 0.05502400 0.00000000 0.01385476
        [4,]  0.055024000  0.061028259 0.05932779 0.05956794 0.05839394
        [5,]  0.059327790  0.059567938 0.05839394 0.06048811 0.05944368

I want to have the results as percentage and keep the data structure unchanged.

When I try something like percent(res) from scales I get a vector instead of a matrix

> percent(res)
 [1] "2.54%"  "-0.54%" "-0.27%" "5.50%"  "5.93%"  "2.46%"  "0.00%"  "-0.27%"
 [9] "6.10%"  "5.96%"  "2.81%"  "2.81%"  "5.50%"  "5.93%"  "5.84%"  "2.73%"
[17] "2.26%"  "0.00%"  "5.96%"  "6.05%"  "2.81%"  "2.32%"  "1.39%"  "5.84%"
[25] "5.94%"

Any suggestions?

Body:
And also:

require(scales)
mat <- matrix(rexp(200, rate=.1), ncol=5, nrow=5)
> mat
           [,1]     [,2]      [,3]       [,4]      [,5]
[1,]  0.8633327  0.59608  4.255264  4.9075876 14.690223
[2,] 13.3531120 33.97510  9.292887  9.2030803  8.963202
[3,] 10.9540116 13.00999  3.345536 12.0012241 16.985236
[4,]  8.7139062 40.25450 22.578629  0.7283414  1.389453
[5,] 15.0364007 11.74895  8.764188 13.8024305  9.303271
> res <- apply(mat, 2, function(x) percent(x/100))
> res
     [,1]    [,2]    [,3]    [,4]    [,5]
[1,] "0.9%"  "0.6%"  "4.3%"  "4.9%"  "14.7%"
[2,] "13.4%" "34.0%" "9.3%"  "9.2%"  "9.0%"
[3,] "11.0%" "13.0%" "3.3%"  "12.0%" "17.0%"
[4,] "8.7%"  "40.3%" "22.6%" "0.7%"  "1.4%"
[5,] "15.0%" "11.7%" "8.8%"  "13.8%" "9.3%"
> res <- apply(mat, 2, function(x) percent(x)) #or without '/100' if you want 9% instead of 0.9%


问:
Difference between DispatchQueue.main.async and Dispatch.main.asyncAfter(.now(),{})
Is there a difference between DispatchQueue.main.async and Dispatch.main.asyncAfter(.now(),{})

My question is specifically about asyncAfter with .now() as the delay time.

The second question is if both methods allow the current UI thread to end before executing the closure in the next runloop?

I find that displaying an alert using UIAlertController in the closure of the former causes some erratic behavior. And with the latter, together with a delay of about 0.3 seconds, it works well.

答: There is no difference if you chooses to use asyncAfter with .now. Here is the proof. Both function should start executing immediately after getting called


问:
3d array access in numpy
I have NxMx3 numpy array and want to get access to subarrays of size 3. For example I want instead of

```<code>arr = [[[...]]]
for i in range(N):
    for j in range(M):
        b = do_something(arr[i][j])
</code>```

write

```<code>map(lambda x: do_something(x), ???) # x - is array of size 3
</code>```

How can I do this?

The function do_something takes arrays of size 3 and returns a scalar, and I want to get the array of the results by applying the function to each length-3 subarray of my input.

答:
If possible, you should manually vectorize your original function, because making use of vectorized arithmetic would be the most efficient solution.

If you don't want to or can't do that, you can use numpy.vectorize to use your function that works along a single dimension and generalize it to higher-dimensional arrays. it probably won't be faster than looping manually (vectorize is essentially a wrapper for a for loop), but at least it will give you a more straightforward interface to calling your function.

Example:

```<code>import numpy as np

def foo(x):
    ''''sum three numbers from input'''
    return x[0]+x[1]+x[2] # otherwise x.sum(), of course

foo_vector = np.vectorize(foo,signature='(n)->()')

# try with dummy input
arr = np.random.rand(2,4,3)
#print(foo(arr)) # leads to an error
print(foo_vector(arr).shape)
# (2, 4)
print(np.allclose(foo_vector(arr),arr.sum(axis=-1)))
# True
</code>```

As you can see from the above, vectorize handles additional leading dimensions of your array, and applies your function appropriately. Since you exactly want to apply your function along the last dimension, this should work like a charm, and applying foo_vector to an array of shape (M,N,3) should return an array of shape (M,N) with the result.

Title: 3d array access in numpy

Body:
I have NxMx3 numpy array and want to get access to subarrays of size 3. For example I want instead of

arr = [[[...]]]
for i in range(N):
    for j in range(M):
        b = do_something(arr[i][j])

write

map(lambda x: do_something(x), ???) # x - is array of size 3

How can I do this?

The function do_something takes arrays of size 3 and returns a scalar, and I want to get the array of the results by applying the function to each length-3 subarray of my input.

Body:
If possible, you should manually vectorize your original function, because making use of vectorized arithmetic would be the most efficient solution.

If you don't want to or can't do that, you can use numpy.vectorize to use your function that works along a single dimension and generalize it to higher-dimensional arrays. it probably won't be faster than looping manually (vectorize is essentially a wrapper for a for loop), but at least it will give you a more straightforward interface to calling your function.

Example:

import numpy as np

def foo(x):
    ''''sum three numbers from input'''
    return x[0]+x[1]+x[2] # otherwise x.sum(), of course

foo_vector = np.vectorize(foo,signature='(n)->()')

# try with dummy input
arr = np.random.rand(2,4,3)
#print(foo(arr)) # leads to an error
print(foo_vector(arr).shape)
# (2, 4)
print(np.allclose(foo_vector(arr),arr.sum(axis=-1)))
# True

As you can see from the above, vectorize handles additional leading dimensions of your array, and applies your function appropriately. Since you exactly want to apply your function along the last dimension, this should work like a charm, and applying foo_vector to an array of shape (M,N,3) should return an array of shape (M,N) with the result.


问:
Quickbooks QBXML - how to exclude fields
I want to get all inventory items from quickbooks with only full name and quantity on hand fields, in order to get a smaller xml. Do you know how to achieve this?

This is the xml query request:

```<code><?xml version="1.0" encoding="utf-8"?>
<?qbxml version="10.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <ItemInventoryQueryRq>
        </ItemInventoryQueryRq>
    </QBXMLMsgsRq>
</QBXML>
</code>```

答:
You can use this tag to pick specifically which fields you want to include:

<IncludeRetElement>

For example, this gets invoices, but only the TxnID, EditSequence, and RefNumber fields:

```<code><?xml version="1.0" encoding="utf-8"?>
<?qbxml version="8.0"?>
<QBXML>
  <QBXMLMsgsRq onError="stopOnError">
    <InvoiceQueryRq requestID="abcd1234">

      <TxnID>ABCD-1234</TxnID>

      <IncludeRetElement>TxnID</IncludeRetElement>
      <IncludeRetElement>EditSequence</IncludeRetElement>
      <IncludeRetElement>RefNumber</IncludeRetElement>

    </InvoiceQueryRq>
  </QBXMLMsgsRq>
</QBXML>
</code>```

Example from this wiki:

http://www.consolibyte.com/docs/index.php/QbXML_for_Querying_for_Invoices,_and_limiting_returned_info

http://www.consolibyte.com/docs/index.php/Example_qbXML_Requests

You may also want to reference Intuit's documentation which shows this, the QuickBooks OSR:

https://developer-static.intuit.com/qbsdk-current/common/newosr/index.html

Body:
I want to get all inventory items from quickbooks with only full name and quantity on hand fields, in order to get a smaller xml. Do you know how to achieve this?

This is the xml query request:

<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="10.0"?>
<QBXML>
    <QBXMLMsgsRq onError="stopOnError">
        <ItemInventoryQueryRq>
        </ItemInventoryQueryRq>
    </QBXMLMsgsRq>
</QBXML>

Body:
You can use this tag to pick specifically which fields you want to include:

<IncludeRetElement>

For example, this gets invoices, but only the TxnID, EditSequence, and RefNumber fields:

<?xml version="1.0" encoding="utf-8"?>
<?qbxml version="8.0"?>
<QBXML>
  <QBXMLMsgsRq onError="stopOnError">
    <InvoiceQueryRq requestID="abcd1234">

      <TxnID>ABCD-1234</TxnID>

      <IncludeRetElement>TxnID</IncludeRetElement>
      <IncludeRetElement>EditSequence</IncludeRetElement>
      <IncludeRetElement>RefNumber</IncludeRetElement>

    </InvoiceQueryRq>
  </QBXMLMsgsRq>
</QBXML>

Example from this wiki:

http://www.consolibyte.com/docs/index.php/QbXML_for_Querying_for_Invoices,_and_limiting_returned_info

http://www.consolibyte.com/docs/index.php/Example_qbXML_Requests

You may also want to reference Intuit's documentation which shows this, the QuickBooks OSR:

https://developer-static.intuit.com/qbsdk-current/common/newosr/index.html


问:
How to search for an optimal solution that depends on a specific values in a matrix in C#
I need to extract the best path in terms of its length from a rectangular array like this array:

The pathfinding rules:

Start from the indexes provided in the method signature where the rowIndex and colIndex are the positions of the starting point.`

The ones must be able to connect with each other either horizontally, vertically, or diagonally.

The last point on the path is the cell with a value of one that has no path to any other surrounding cells with a value of one.

I tried the following recursion algorithm, but it does not work for me and generate wrong output i.e. not as expected!!.

Here are the results: Results

```<code>        using System;
        using System.IO;
        using System.Text;
        using System.Drawing;
        using System.Collections;
        using System.ComponentModel;
        using System.Windows.Forms;
        using System.Data;
        using System.Threading;
        using AUV_Topology;
        using System.Collections.Generic;
        using System.Media;
        using System.Linq;

        namespace AUVtopology
        {
            public partial class Form1 : Form
            {
              static int[,] array;
              static List<int[]> path;

// *******************************************************************************************************************************//
        //This method is used to make sure the coordinate array
        //is contained in the list. List.contains(new int[] {val1,val2}) was not enough.
        static Boolean containsArray(List<int[]> list, int[] array)
        {
            if (array == null || array.Length == 0)
            {
                return false;
            }
            foreach (var listArray in list)
            {
                if (listArray != null && listArray.Length == array.Length)
                {
                    for (int i = 0; i < listArray.Length; i++)
                    {
                        if (i != listArray.Length - 1)
                        {
                            if (array[i] != listArray[i] && array[i + 1] != listArray[i + 1])
                            {
                                continue;
                            }

                            return true;

                        }

                    }

                }
            }
            return false;
        }

// *******************************************************************************************************************************//

        //This is the recursive method of the algorithm. It finds the
        //maximum path of 1 cells in a matrix of 0/1 cells
        static List<int[]> getMaxPath(int[,] array, List<int[]> maxPath, int rowIndex, int colIndex)
        {

            //Add the current cell to the path.
            maxPath.Add(new int[] { rowIndex, colIndex });

            //Get the array limits.
            int rowLength = array.GetLength(0);
            int colLength = array.GetLength(1);

            //If the path contains all the cells in the matrix, stop
            if (maxPath.Count >= rowLength * colLength)
            {
                return maxPath;
            }

            //remove one from lengths to make it the maximum index
            colLength = colLength - 1;
            rowLength = rowLength - 1;

            //We'll use this variable to see which of the
            //potential 7 paths are the longest.
            List<int[]> futurePath;

            //Go over all 8 possible adjoining cells:
            //If we can go one down, one right, and it's a spot we
            //have not yet visited
            if (colIndex < colLength && rowIndex < rowLength &&
                array[rowIndex + 1, colIndex + 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex + 1, colIndex + 1 }))
            {

                //We use maxPath first, since this is the first
                //direction and by default is the longest
                maxPath = getMaxPath(array, maxPath, rowIndex + 1, colIndex + 1);
            }

            //If we can go one down, and it's a spot we have not
            //yet visited
            if (colIndex < colLength &&
              array[rowIndex, colIndex + 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex, colIndex + 1 }))
            {

                //We use futurePath now, since this is a second
                //direction and a potential contender
                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex + 1);

                //We only need the maximum path.
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one down and one left, and it's a spot
            //we have not yet visited
            if (rowIndex > 0 && colIndex < colLength &&
               array[rowIndex - 1, colIndex + 1] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex + 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex + 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one left, and it's a spot we have not
            //yet visited
            if (rowIndex > 0 &&
               array[rowIndex - 1, colIndex] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one left and one up, and it's a spot we
            //have not yet visited
            if (rowIndex > 0 && colIndex > 0 &&
              array[rowIndex - 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex - 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up, and it's a spot we have not yet
            //visited
            if (colIndex > 0 &&
                array[rowIndex, colIndex - 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up and one right, and it's a spot we
            //have not yet visited
            if (colIndex > 0 && rowIndex < rowLength &&
              array[rowIndex + 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one right, and it's a spot we have not
            //yet visited
            if (rowIndex < rowLength &&
              array[rowIndex + 1, colIndex] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //We return the max path. Note: If none of the directions around
            //us was applicable, we simply return the path we started
            //with our cell included.
            return maxPath;
        }
</code>```

Is prim algorithm the best choice ?

答:
Here is code using a Class Project that works without compiler errors</p>

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Auv_Topology
{
    public class Cell
    {

        public int row { get; set; }
        public int col { get; set; }
        public int value { get; set; }
        public Boolean visited { get; set; }

    }

    public class EnumCell : IEnumerator<Cell>
    {
        public EnumCell() { }

        public EnumCell(int startRow, int startCol, List<List<Cell>> graph)
        {
            this.row = startRow;
            this.col = startCol;
            this.numberOfRows = graph.Count;
            this.numberOfCols = graph[0].Count;
            this.graph = graph;
        }
        public enum XY
        {
            Y = 0,  //row
            X = 1   //col
        }

        public enum LOCATIONS : byte
        {
            TOP_LEFT = 0,
            TOP_MIDDLE,
            TOP_RIGHT,
            LEFT,
            RIGHT,
            BOTTOM_LEFT,
            BOTTOM_MIDDLE,
            BOTTOM_RIGHT,
            END,
            INVALID
        }

        public List<List<Cell>> graph { get; set; }
        public int row { get; set; }
        public int col { get; set; }
        public int numberOfRows { get; set; }
        public int numberOfCols { get; set; }

        //offsets are in same order as enum location as y-offset(row), x-offset (col)
        private List<List<int>> offsets = new List<List<int>>() {
        new List<int>() { -1, -1 },
        new List<int>() { -1, 0 },
        new List<int>() { -1, +1 },
        new List<int>() { 0, -1 },
        new List<int>() { 0, +1 },
        new List<int>() { +1, -1 },
        new List<int>() { +1, 0 },
        new List<int>() { +1, +1 }
    };
        public LOCATIONS position { get; set; }

        public EnumCell GetEnumerator()
        {
            return new EnumCell(row, col, graph);
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        public Cell Current
        {
            get
            {
                try
                {
                    // move to first valie postion
                    for (LOCATIONS location = position; location < LOCATIONS.END; location++)
                    {
                        if ((row + offsets[(byte)location][(int)XY.Y] >= 0) && (row + offsets[(byte)location][(int)XY.Y] < numberOfRows) &&
                            (col + offsets[(byte)location][(int)XY.X] > 0) && (col + offsets[(byte)location][(int)XY.X] < numberOfCols))
                        {
                            position = (LOCATIONS)location;
                            int newRow = row + offsets[(byte)location][(int)XY.Y];
                            int newCol = col + offsets[(byte)location][(int)XY.X];
                            return graph[newRow][newCol];
                        }
                    }
                    throw new InvalidOperationException();
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public Boolean MoveNext()
        {
            Boolean results = false;
            for (LOCATIONS location = ++position; location < LOCATIONS.END; location++)
            {
                int y = offsets[(byte)location][(int)XY.Y];
                int x = offsets[(byte)location][(int)XY.X];
                if ((row + y >= 0) && (row + y < numberOfRows) &&
                    (col + x > 0) && (col + x < numberOfCols))
                {
                    if (graph[row + y][col + x].value == 1)
                    {
                        position = (LOCATIONS)location;
                        return true;
                    }
                }
            }

            return results;
        }

        public void Reset()
        {
            position = LOCATIONS.TOP_LEFT;
        }
        public void Dispose()
        {
        }
    }
}
</code>```

Body:
I need to extract the best path in terms of its length from a rectangular array like this array:

The pathfinding rules:

Start from the indexes provided in the method signature where the rowIndex and colIndex are the positions of the starting point.`

The ones must be able to connect with each other either horizontally, vertically, or diagonally.

The last point on the path is the cell with a value of one that has no path to any other surrounding cells with a value of one.

I tried the following recursion algorithm, but it does not work for me and generate wrong output i.e. not as expected!!.

Here are the results: Results

        using System;
        using System.IO;
        using System.Text;
        using System.Drawing;
        using System.Collections;
        using System.ComponentModel;
        using System.Windows.Forms;
        using System.Data;
        using System.Threading;
        using AUV_Topology;
        using System.Collections.Generic;
        using System.Media;
        using System.Linq;

        namespace AUVtopology
        {
            public partial class Form1 : Form
            {
              static int[,] array;
              static List<int[]> path;

// *******************************************************************************************************************************//
        //This method is used to make sure the coordinate array
        //is contained in the list. List.contains(new int[] {val1,val2}) was not enough.
        static Boolean containsArray(List<int[]> list, int[] array)
        {
            if (array == null || array.Length == 0)
            {
                return false;
            }
            foreach (var listArray in list)
            {
                if (listArray != null && listArray.Length == array.Length)
                {
                    for (int i = 0; i < listArray.Length; i++)
                    {
                        if (i != listArray.Length - 1)
                        {
                            if (array[i] != listArray[i] && array[i + 1] != listArray[i + 1])
                            {
                                continue;
                            }

                            return true;

                        }

                    }

                }
            }
            return false;
        }

// *******************************************************************************************************************************//

        //This is the recursive method of the algorithm. It finds the
        //maximum path of 1 cells in a matrix of 0/1 cells
        static List<int[]> getMaxPath(int[,] array, List<int[]> maxPath, int rowIndex, int colIndex)
        {

            //Add the current cell to the path.
            maxPath.Add(new int[] { rowIndex, colIndex });

            //Get the array limits.
            int rowLength = array.GetLength(0);
            int colLength = array.GetLength(1);

            //If the path contains all the cells in the matrix, stop
            if (maxPath.Count >= rowLength * colLength)
            {
                return maxPath;
            }

            //remove one from lengths to make it the maximum index
            colLength = colLength - 1;
            rowLength = rowLength - 1;

            //We'll use this variable to see which of the
            //potential 7 paths are the longest.
            List<int[]> futurePath;

            //Go over all 8 possible adjoining cells:
            //If we can go one down, one right, and it's a spot we
            //have not yet visited
            if (colIndex < colLength && rowIndex < rowLength &&
                array[rowIndex + 1, colIndex + 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex + 1, colIndex + 1 }))
            {

                //We use maxPath first, since this is the first
                //direction and by default is the longest
                maxPath = getMaxPath(array, maxPath, rowIndex + 1, colIndex + 1);
            }

            //If we can go one down, and it's a spot we have not
            //yet visited
            if (colIndex < colLength &&
              array[rowIndex, colIndex + 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex, colIndex + 1 }))
            {

                //We use futurePath now, since this is a second
                //direction and a potential contender
                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex + 1);

                //We only need the maximum path.
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one down and one left, and it's a spot
            //we have not yet visited
            if (rowIndex > 0 && colIndex < colLength &&
               array[rowIndex - 1, colIndex + 1] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex + 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex + 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //If we can go one left, and it's a spot we have not
            //yet visited
            if (rowIndex > 0 &&
               array[rowIndex - 1, colIndex] == 1 &&
               !containsArray(maxPath, new int[] { rowIndex - 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one left and one up, and it's a spot we
            //have not yet visited
            if (rowIndex > 0 && colIndex > 0 &&
              array[rowIndex - 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex - 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex - 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up, and it's a spot we have not yet
            //visited
            if (colIndex > 0 &&
                array[rowIndex, colIndex - 1] == 1 &&
                !containsArray(maxPath, new int[] { rowIndex, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one up and one right, and it's a spot we
            //have not yet visited
            if (colIndex > 0 && rowIndex < rowLength &&
              array[rowIndex + 1, colIndex - 1] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex - 1 }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex - 1);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }
            //If we can go one right, and it's a spot we have not
            //yet visited
            if (rowIndex < rowLength &&
              array[rowIndex + 1, colIndex] == 1 &&
              !containsArray(maxPath, new int[] { rowIndex + 1, colIndex }))
            {

                futurePath = getMaxPath(array, maxPath, rowIndex + 1, colIndex);
                if (futurePath.Count > maxPath.Count)
                {
                    maxPath = futurePath;
                }
            }

            //We return the max path. Note: If none of the directions around
            //us was applicable, we simply return the path we started
            //with our cell included.
            return maxPath;
        }

Is prim algorithm the best choice ?

Body:
Here is code using a Class Project that works without compiler errors

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Auv_Topology
{
    public class Cell
    {

        public int row { get; set; }
        public int col { get; set; }
        public int value { get; set; }
        public Boolean visited { get; set; }

    }

    public class EnumCell : IEnumerator<Cell>
    {
        public EnumCell() { }

        public EnumCell(int startRow, int startCol, List<List<Cell>> graph)
        {
            this.row = startRow;
            this.col = startCol;
            this.numberOfRows = graph.Count;
            this.numberOfCols = graph[0].Count;
            this.graph = graph;
        }
        public enum XY
        {
            Y = 0,  //row
            X = 1   //col
        }

        public enum LOCATIONS : byte
        {
            TOP_LEFT = 0,
            TOP_MIDDLE,
            TOP_RIGHT,
            LEFT,
            RIGHT,
            BOTTOM_LEFT,
            BOTTOM_MIDDLE,
            BOTTOM_RIGHT,
            END,
            INVALID
        }

        public List<List<Cell>> graph { get; set; }
        public int row { get; set; }
        public int col { get; set; }
        public int numberOfRows { get; set; }
        public int numberOfCols { get; set; }

        //offsets are in same order as enum location as y-offset(row), x-offset (col)
        private List<List<int>> offsets = new List<List<int>>() {
        new List<int>() { -1, -1 },
        new List<int>() { -1, 0 },
        new List<int>() { -1, +1 },
        new List<int>() { 0, -1 },
        new List<int>() { 0, +1 },
        new List<int>() { +1, -1 },
        new List<int>() { +1, 0 },
        new List<int>() { +1, +1 }
    };
        public LOCATIONS position { get; set; }

        public EnumCell GetEnumerator()
        {
            return new EnumCell(row, col, graph);
        }

        object IEnumerator.Current
        {
            get
            {
                return Current;
            }
        }

        public Cell Current
        {
            get
            {
                try
                {
                    // move to first valie postion
                    for (LOCATIONS location = position; location < LOCATIONS.END; location++)
                    {
                        if ((row + offsets[(byte)location][(int)XY.Y] >= 0) && (row + offsets[(byte)location][(int)XY.Y] < numberOfRows) &&
                            (col + offsets[(byte)location][(int)XY.X] > 0) && (col + offsets[(byte)location][(int)XY.X] < numberOfCols))
                        {
                            position = (LOCATIONS)location;
                            int newRow = row + offsets[(byte)location][(int)XY.Y];
                            int newCol = col + offsets[(byte)location][(int)XY.X];
                            return graph[newRow][newCol];
                        }
                    }
                    throw new InvalidOperationException();
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public Boolean MoveNext()
        {
            Boolean results = false;
            for (LOCATIONS location = ++position; location < LOCATIONS.END; location++)
            {
                int y = offsets[(byte)location][(int)XY.Y];
                int x = offsets[(byte)location][(int)XY.X];
                if ((row + y >= 0) && (row + y < numberOfRows) &&
                    (col + x > 0) && (col + x < numberOfCols))
                {
                    if (graph[row + y][col + x].value == 1)
                    {
                        position = (LOCATIONS)location;
                        return true;
                    }
                }
            }

            return results;
        }

        public void Reset()
        {
            position = LOCATIONS.TOP_LEFT;
        }
        public void Dispose()
        {
        }
    }
}


答:
You can write a simple UDF and get the date from adding week in it.

Here is the simple example

```<code>import spark.implicits._
val data = spark.sparkContext.parallelize(Seq(
  (29,"City 2", 72),
  (28,"City 3", 48),
  (28,"City 2", 19),
  (27,"City 2", 16),
  (28,"City 1", 84),
  (28,"City 4", 72),
  (29,"City 4", 39),
  (27,"City 3", 42),
  (26,"City 3", 68),
  (27,"City 1", 89),
  (27,"City 4", 104),
  (26,"City 2", 19),
  (29,"City 3", 27)
)).toDF("week", "city", "sale")

val getDateFromWeek = udf((week : Int) => {
  //create a default date for week 1
  val week1 = LocalDate.of(2016, 12, 30)
  val day = "Friday"
  //add week from the week column
  val result = week1.plusWeeks(week).format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))
  //return result as Friday (date)
  s"${day} (${result})"
})

//use the udf and create a new column named day
data.withColumn("day", getDateFromWeek($"week")).show
</code>```

can anyone convert this to Pyspark?

Title: Find date of each week in from week in Spark Dataframe

Body:
I want to add a column with date of each corresponding week in Dataframe (appending friday in each date)
My Dataframe looks like this

+----+------+---------+

|Week| City|sum(Sale)|
+----+------+---------+
| 29|City 2| 72|
| 28|City 3| 48|
| 28|City 2| 19|
| 27|City 2| 16|
| 28|City 1| 84|
| 28|City 4| 72|
| 29|City 4| 39|
| 27|City 3| 42|
| 26|City 3| 68|
| 27|City 1| 89|
| 27|City 4| 104|
| 26|City 2| 19|
| 29|City 3| 27|
+----+------+---------+

I need to convert it as below dataframe

----+------+---------+---------------  |
|Week| City|sum(Sale)|perticular day(dd/mm/yyyy)  |
+----+------+---------+---------------|
| 29|City 2| 72|Friday(07/21/2017)|
| 28|City 3| 48|Friday(07/14/2017)|
| 28|City 2| 19|Friday(07/14/2017)|
| 27|City 2| 16|Friday(07/07/2017)|
| 28|City 1| 84|Friday(07/14/2017)|
| 28|City 4| 72|Friday(07/14/2017)|
| 29|City 4| 39|Friday(07/21/2017)|
| 27|City 3| 42|Friday(07/07/2017)|
| 26|City 3| 68|Friday(06/30/2017)|
| 27|City 1| 89|Friday(07/07/2017)|
| 27|City 4| 104|Friday(07/07/2017)|
| 26|City 2| 19|Friday(06/30/2017)|
| 29|City 3| 27|Friday(07/21/2017)|
+----+------+---------+

please help me

Body:
You can write a simple UDF and get the date from adding week in it.

Here is the simple example

import spark.implicits._
val data = spark.sparkContext.parallelize(Seq(
  (29,"City 2", 72),
  (28,"City 3", 48),
  (28,"City 2", 19),
  (27,"City 2", 16),
  (28,"City 1", 84),
  (28,"City 4", 72),
  (29,"City 4", 39),
  (27,"City 3", 42),
  (26,"City 3", 68),
  (27,"City 1", 89),
  (27,"City 4", 104),
  (26,"City 2", 19),
  (29,"City 3", 27)
)).toDF("week", "city", "sale")

val getDateFromWeek = udf((week : Int) => {
  //create a default date for week 1
  val week1 = LocalDate.of(2016, 12, 30)
  val day = "Friday"
  //add week from the week column
  val result = week1.plusWeeks(week).format(DateTimeFormatter.ofPattern("MM/dd/yyyy"))
  //return result as Friday (date)
  s"${day} (${result})"
})

//use the udf and create a new column named day
data.withColumn("day", getDateFromWeek($"week")).show

can anyone convert this to Pyspark?

ContentLicense: CC BY-SA 4.0


问:
How can spring @Cacheable work in service level with a dao call
I have the following code:

```<code>@Service
public class MyServiceImpl implements MyService {
    @Autowired
    private MyDao myDao;

    @Cacheable("callDao")
    @Override
    public MyResultModel callDao(MyCondition condition) {
        System.out.println("call without cache");
        return myDao.call(condition);
    }

    @Cacheable("cacheTest")
    @Override
    public MyResultModel cacheTest(MyCondition condition) {
        System.out.println("call without cache");
        return new MyResultModel(someProperties);
    }
}
</code>```

However, the callDao cache does not work since the method still calls the DB all the time. On the other hand, cacheTest does work properly. What is wrong with my callDao method?

Here is my configuration:

```<code>@Bean
public CacheManager cacheManager(RedisCacheManagerConfiguration configuration,
        @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(configuration.getDefaultExpiration());
    cacheManager.setUsePrefix(configuration.isUsePrefix());
    cacheManager.setLoadRemoteCachesOnStartup(configuration.isLoadRemoteCachesOnStartup());
    return cacheManager;
}

@Bean
public RedisTemplate<String, String> stringRedisTemplate(
        @Qualifier("stringRedisSerializer") RedisSerializer<String> keySerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> valueSerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> hashKeySerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> hashValueSerializer,
        JedisConnectionFactory connectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setKeySerializer(keySerializer);
    template.setValueSerializer(valueSerializer);
    template.setHashKeySerializer(hashKeySerializer);
    template.setHashValueSerializer(hashValueSerializer);
    template.setConnectionFactory(connectionFactory);
    template.afterPropertiesSet();

    return template;
}

@Bean(name = "stringRedisSerializer")
public StringRedisSerializer stringRedisSerializer() {
    return new StringRedisSerializer();
}
</code>```

I only configured CacheManager and RedisTemplate. I also added the @EnableCaching annotation.

Hear is MyCondition:

```<code>public class MyCondition implements Serializable {

    /**
     * @since JDK 1.8
     */
    private static final long serialVersionUID = 6262123870251938833L;

    private String guid;
    private Boolean isDelete;

    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public Boolean getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Boolean isDelete) {
        this.isDelete = isDelete;
    }
}
</code>```

Hear is how i call these method

```<code>@EnableCaching
@EnableAutoConfiguration
@ComponentScan({ "com.mypackage" })
@SpringBootApplication
public class Application extends ContextIdApplicationContextInitializer {
    public static ConfigurableApplicationContext ctx;

    public static void main(String[] args) throws Exception {
        ctx = SpringApplication.run(Application.class, args);

        MyService myService = ctx.getBean(MyService.class);

        for (int i = 0; i < 10; i++) {
            MyCondition condition = new ConditionForRideCard();
            condition.setGuid("adsgsfdhgsfgfdghhsdfgfadf");
            myService.callDao(condition);
            System.out.println("-------------------------------------------------------");
            myService.cacheTest(condition);
            System.out.println("=======================================================");
            Thread.sleep(1000);
        }
    }
}
</code>```

AND i get result like this:

```<code>call without cache
-------------------------------------------------------
call without cache
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
</code>```

答:
As StuPointerException pointed out (in his deleted answer, requires 10000 reputation to see) and M. Deinum in the comments, you need to implement both equals() and hashCode() in your MyCondition class.

Spring's cache abstraction works by caching the result of the method call based on the arguments. In this case, you have only one argument (MyCondition). However, the generated key will use the hashCode() implementation of the parameters.

In your case, you didn't implement equals() nor hashCode(), so every time you create a new MyCondition object, it will have a different hashcode, and thus, Spring won't know that it has its result cached.

This doesn't explain why the cacheTest() method does work though. But I guess this is due to code we're not seeing right now (either you're using a different condition, or there's something else going on).

Body:
I have the following code:

@Service
public class MyServiceImpl implements MyService {
    @Autowired
    private MyDao myDao;

    @Cacheable("callDao")
    @Override
    public MyResultModel callDao(MyCondition condition) {
        System.out.println("call without cache");
        return myDao.call(condition);
    }

    @Cacheable("cacheTest")
    @Override
    public MyResultModel cacheTest(MyCondition condition) {
        System.out.println("call without cache");
        return new MyResultModel(someProperties);
    }
}

However, the callDao cache does not work since the method still calls the DB all the time. On the other hand, cacheTest does work properly. What is wrong with my callDao method?

Here is my configuration:

@Bean
public CacheManager cacheManager(RedisCacheManagerConfiguration configuration,
        @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    cacheManager.setDefaultExpiration(configuration.getDefaultExpiration());
    cacheManager.setUsePrefix(configuration.isUsePrefix());
    cacheManager.setLoadRemoteCachesOnStartup(configuration.isLoadRemoteCachesOnStartup());
    return cacheManager;
}

@Bean
public RedisTemplate<String, String> stringRedisTemplate(
        @Qualifier("stringRedisSerializer") RedisSerializer<String> keySerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> valueSerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> hashKeySerializer,
        @Qualifier("stringRedisSerializer") RedisSerializer<String> hashValueSerializer,
        JedisConnectionFactory connectionFactory) {
    StringRedisTemplate template = new StringRedisTemplate();
    template.setKeySerializer(keySerializer);
    template.setValueSerializer(valueSerializer);
    template.setHashKeySerializer(hashKeySerializer);
    template.setHashValueSerializer(hashValueSerializer);
    template.setConnectionFactory(connectionFactory);
    template.afterPropertiesSet();

    return template;
}

@Bean(name = "stringRedisSerializer")
public StringRedisSerializer stringRedisSerializer() {
    return new StringRedisSerializer();
}

I only configured CacheManager and RedisTemplate. I also added the @EnableCaching annotation.

Hear is MyCondition:

public class MyCondition implements Serializable {

    /**
     * @since JDK 1.8
     */
    private static final long serialVersionUID = 6262123870251938833L;

    private String guid;
    private Boolean isDelete;

    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    public Boolean getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Boolean isDelete) {
        this.isDelete = isDelete;
    }
}

Hear is how i call these method

@EnableCaching
@EnableAutoConfiguration
@ComponentScan({ "com.mypackage" })
@SpringBootApplication
public class Application extends ContextIdApplicationContextInitializer {
    public static ConfigurableApplicationContext ctx;

    public static void main(String[] args) throws Exception {
        ctx = SpringApplication.run(Application.class, args);

        MyService myService = ctx.getBean(MyService.class);

        for (int i = 0; i < 10; i++) {
            MyCondition condition = new ConditionForRideCard();
            condition.setGuid("adsgsfdhgsfgfdghhsdfgfadf");
            myService.callDao(condition);
            System.out.println("-------------------------------------------------------");
            myService.cacheTest(condition);
            System.out.println("=======================================================");
            Thread.sleep(1000);
        }
    }
}

AND i get result like this:

call without cache
-------------------------------------------------------
call without cache
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================
call without cache
-------------------------------------------------------
=======================================================


问:
UIButton animation view
I am new developer in iPhone.

I want to create uibutton.

When I click the button, then the button will be flash like as below.

How to create the flash, when I click my button?

答:
If you want to change the button image when you clicked on button now set different images for both default and highlighted stats. As:

```<code>[tempButton setImage:[UIImage imageNamed:@"NormalImage.png"]
            forState:UIControlStateNormal];
[tempButton setImage:[UIImage imageNamed:@"HighlightImage.png"]
            forState:UIControlStateHighlighted];
</code>```

If you want the flash effect for the same image, when button is clicked on,
In your XIB, Goto Inspector window > control > check the Highlighted property.
You can try this by code as:

```<code> [tempButton setShowsTouchWhenHighlighted:YES];

//or
tempButton.highlighted = YES;
</code>```

Title: UIButton animation view

Body:
If you want to change the button image when you clicked on button now set different images for both default and highlighted stats. As:

[tempButton setImage:[UIImage imageNamed:@"NormalImage.png"]
            forState:UIControlStateNormal];
[tempButton setImage:[UIImage imageNamed:@"HighlightImage.png"]
            forState:UIControlStateHighlighted];

If you want the flash effect for the same image, when button is clicked on,
In your XIB, Goto Inspector window > control > check the Highlighted property.
You can try this by code as:

 [tempButton setShowsTouchWhenHighlighted:YES];

//or
tempButton.highlighted = YES;

ContentLicense: CC BY-SA 2.5


问:
customizing the css for audio tag
i have this audio control and i am trying to change even the color of the player but i can't target it i found some posts talking about doing this using javascript is that the only way to write css for it.

```<code><audio controls class="radio-audio">
   <source src="" type="audio/mpeg"></audio>
</code>```

i tried to write some code like this found it somewhere on the internet but still i don't see any changes.

it is all hover and focus not doing much

```<code>.radio-audio:hover, .radio-audio:focus, .radio-audio:active {
    -webkit-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -moz-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    transform: scale(1.05);
}

.radio-audio {
    -webkit-transition: all 0.5s linear;
    -moz-transition: all 0.5s linear;
    -o-transition: all 0.5s linear;
    transition: all 0.5s linear;
    -moz-box-shadow: 2px 2px 4px 0px #006773;
    -webkit-box-shadow: 2px 2px 4px 0px #006773;
    box-shadow: 2px 2px 4px 0px #006773;
    -moz-border-radius: 7px 7px 7px 7px;
    -webkit-border-radius: 7px 7px 7px 7px;
    border-radius: 7px 7px 7px 7px;
}
</code>```

答:
I have prepared you on codepen.io a model with all the css tags to access the graphics properties of an audio object

link

Title: customizing the css for audio tag

Body:
i have this audio control and i am trying to change even the color of the player but i can't target it i found some posts talking about doing this using javascript is that the only way to write css for it.

<audio controls class="radio-audio">
   <source src="" type="audio/mpeg"></audio>

i tried to write some code like this found it somewhere on the internet but still i don't see any changes.

it is all hover and focus not doing much

.radio-audio:hover, .radio-audio:focus, .radio-audio:active {
    -webkit-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -moz-box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    box-shadow: 15px 15px 20px rgba(0, 0, 0, 0.4);
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    transform: scale(1.05);
}

.radio-audio {
    -webkit-transition: all 0.5s linear;
    -moz-transition: all 0.5s linear;
    -o-transition: all 0.5s linear;
    transition: all 0.5s linear;
    -moz-box-shadow: 2px 2px 4px 0px #006773;
    -webkit-box-shadow: 2px 2px 4px 0px #006773;
    box-shadow: 2px 2px 4px 0px #006773;
    -moz-border-radius: 7px 7px 7px 7px;
    -webkit-border-radius: 7px 7px 7px 7px;
    border-radius: 7px 7px 7px 7px;
}


问:
How do I get from google-services.json to GoogleServices-info.plist?
I am building for iOS in Unity using the Firebase Unity plugin and getting an error that says that there is no GoogleServices-info.plist found in my project and so it fails to build for iOS. According to the Firebase docs, you're supposed to download the plist file from the Dasboard but of course when you go there you find they only offer you a .json file download for iOS projects.

What am I missing? How do I get a .plist file? Is it supposed to generate?

答:
Follow below steps

```<code>▪   Go to dashboard select your app
▪    Go Settings > general > your apps
▪    Select iOS app
▪   Click on Download the latest config file
</code>```

You will get info.plist file

Body:
Follow below steps

▪   Go to dashboard select your app
▪    Go Settings > general > your apps
▪    Select iOS app
▪   Click on Download the latest config file

You will get info.plist file


问:
Get IP address using uWebSockets
Please, how can I get sender IP address using uWebSockets?

```<code>const wss = new uws.Server({
  server: server,
  perMessageDeflate: false
});

wss.on(`connection`, ws => {
  ws.remoteAddress = ws.upgradeReq.connection.remoteAddress;
  console.log(`user connected: `, ws.remoteAddress);
});
</code>```

user connected is undefined

答:
Please try this:

```<code>wss.on(`connection`, ws => {
ws.remoteAddress = ws._socket.remoteAddress;
   console.log(`user connected: `, ws.remoteAddress);
});
</code>```

You can also log ws._socket to know what it is.

Title: Get IP address using uWebSockets

Body:
Please, how can I get sender IP address using uWebSockets?

const wss = new uws.Server({
  server: server,
  perMessageDeflate: false
});

wss.on(`connection`, ws => {
  ws.remoteAddress = ws.upgradeReq.connection.remoteAddress;
  console.log(`user connected: `, ws.remoteAddress);
});

user connected is undefined

Body:
Please try this:

wss.on(`connection`, ws => {
ws.remoteAddress = ws._socket.remoteAddress;
   console.log(`user connected: `, ws.remoteAddress);
});

You can also log ws._socket to know what it is.


问:
libMobileGestalt MobileGestaltSupport.m:153 MobileGestalt.c:550 Xcode Console
I am getting Following messages on Xcode Console View

libMobileGestalt MobileGestaltSupport.m:153: pid 231 (myproject) does
not have sandbox access for frZQaeyWLUvLjeuEK43hmg and IS NOT
appropriately entitled

libMobileGestalt MobileGestalt.c:550: no access to InverseDeviceID
(see )

MacOs Sierra Version: 10.12.4
Xcode Version 8.3
Programming Language : Objective C

I get this message after application launch, Device is plugged with xcode while running the application. It seems like a rare issue. Anyone can help me to solve this?

答:
I am getting the same issue when trying to display the GoogleMap using GMSMapView. but it is just a warning (I still don't know how to get rid of it). What i wanted to say is the Google Map view display and functionality works fine with this warning too. (I checked in IOS 10.3)

check if you are trying to display the map in a subview there is a separate way to display (This is an easy guide i found - http://www.ryanwright.me/cookbook/ios/obj-c/maps/gmap/subview)

otherwise try

self.view = gmsMapView;


问:
How do I diagnose heap corruption errors on Windows?
I'm using Windows 8.1 64-bit with Visual Studio 2013 Ultimate. I am porting a program from Linux to Windows which uses C++, OpenGL and SDL. I have the appropriate libraries custom compiled through cmake on 64-bit on Windows. When I run the program from Visual Studio, the IDE says there's a head corruption. This is no surprise since I'm using pointers to instantiate objects, and I'm using raw pointers which I do plan to change to smart pointers for the sake of the argument. I'll be doing the boost magic later.

In the meantime, I used my Linux computer to diagnose any memory leaks through Valgrind and there was nothing serious reported from Valgrind. I then proceeded to use CppCheck but there was nothing serious on there either. Maybe I'm being too lenient here and Windows might actually be taking the less serious stuff more serious than Linux does, which is a surprise since MSVC tends to be more forgiving than GCC.

So, the program works on Linux and it doesn't on Windows. (Just great!) And Visual Studio isn't helping by throwing exceptions all over the place which makes me hate Windows even more. I started googling around for a solution and came across this thing called gflags or page helper, so I installed the debugging tools and tried to launch gflags but I have no idea how to use it! I then later found that you had to use some other tool called adp and then attach gflags to it, so when I launched adp it crashes. So now I have no idea what to do and am on the verge of aborting the port (which is funny since many people are complaining how hard it is to port programs from Windows to Linux while the opposite is true).

So, now I appeal to this community for help: how do I debug/diagnose heap corruption errors that occur on Windows but not on Linux? Am I really supposed to be using gflags or should I just use my guts on this?

答:
The @Carlos's solution is perfect for smaller problems. But for huge problems, the resulting slow down is sometimes something you cannot stomach.

In this case, one can place

```<code>ASSERT(_CrtCheckMemory());
</code>```

somewhere in the code, where one suspects the problem already to be present. This command checks the heap at (and only at) the spot it is inserted, and not after every new or delete call as in the case of _CRTDBG_CHECK_ALWAYS_DF. This keeps the execution time reasonable, compared to option _CRTDBG_CHECK_ALWAYS_DF.

One can find the problematic line of code pretty quickly by using a binary search kind of approach for placing the asserts.

However, sometimes _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF) and/or _CrtCheckMemory() aren't able to detect problems. Then using gflags is another possibility, which is able to show where the heap-corruption happens. In a nutshell:

enable page heap (usually you would need admin's priveleges), e.g.:
```<code>"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /enable <full_path_to_exe_to_debug.exe> /full
</code>```
there will be a report, that heap checks for exe_to_debug.exe were activated.

run program in debugger. Accesses out of bounds, which would corrupt the heap lead now to access violation and are easily seen in the the debugger.

disable page heap once debugging is done, e.g.:
```<code>"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /disable <full_path_to_exe_to_debug.exe>
</code>```

programs with activated heap check can be listed via
```<code>"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p
</code>```

Body:
The @Carlos's solution is perfect for smaller problems. But for huge problems, the resulting slow down is sometimes something you cannot stomach.

In this case, one can place

ASSERT(_CrtCheckMemory());

somewhere in the code, where one suspects the problem already to be present. This command checks the heap at (and only at) the spot it is inserted, and not after every new or delete call as in the case of _CRTDBG_CHECK_ALWAYS_DF. This keeps the execution time reasonable, compared to option _CRTDBG_CHECK_ALWAYS_DF.

One can find the problematic line of code pretty quickly by using a binary search kind of approach for placing the asserts.

However, sometimes _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF) and/or _CrtCheckMemory() aren't able to detect problems. Then using gflags is another possibility, which is able to show where the heap-corruption happens. In a nutshell:

enable page heap (usually you would need admin's priveleges), e.g.:

"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /enable <full_path_to_exe_to_debug.exe> /full

there will be a report, that heap checks for exe_to_debug.exe were activated.

run program in debugger. Accesses out of bounds, which would corrupt the heap lead now to access violation and are easily seen in the the debugger.

disable page heap once debugging is done, e.g.:

"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p /disable <full_path_to_exe_to_debug.exe>

programs with activated heap check can be listed via

"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\gflags.exe" /p