问:
Assertion Error when trying to integrate Redis into Node.js (TypeScript)
someone who's somewhat new to Redis and is somewhat novice at Node here.

I've been trying to integrate the node-redis module with a Typescript Node project I've been working on, which I've been testing with mocha and chai.

I'm trying to write basic Getter/Setter Functions I can integrate with the rest of my project (I'm using Redis to track the state of a Facebook Messenger Bot).

Any time I try to write a new Key-Value pair to the DB with my setKeyValue function, the transaction goes through (as verified through the redis-cli client), but the values returned for both setKeyValue and getValueFromKey don't correspond to what they should if the DB transaction was successful.

The code implementation I've written is below (in my redis_interaction.ts file):

import * as redis from 'redis';
var client = redis.createClient("6379", "127.0.0.1");

enum RedisResponse {
  OK,
  Fail
}

    // 'Setter' Function for Key Value Pairs within Redis Database
export function setKeyValue(key : string, value : string): RedisResponse {
  client.set(key, value, function(err, reply) {
    if(!err) {
      return RedisResponse.OK;
    }
  });
  return RedisResponse.Fail;
}

// 'Getter' Function for Key Value Pairs within Redis Database
export function getValueFromKey(key : string) : [string, RedisResponse] {
  client.get(key, function(err, reply) {
    if(!err) {
      return[reply, RedisResponse.OK];
    }
  });
  return["", RedisResponse.Fail];
}

// 'Delete' Function for Removing Keys from within Redis Database
export function deleteKeyFromRedis(key : string) : RedisResponse {
  client.del(key, function(err, reply) {
    if(!err) {
      if(reply) {
        return RedisResponse.OK;
      }
    }
  });
  return RedisResponse.Fail;
}
```

<p>I test this code with the following <code>mocha</code> tests:</p>

<pre class="lang-js prettyprint-override"><code>import {expect, assert} from 'chai';
import 'mocha';
import * as RedisInteraction from '../redis_interaction';
import {RedisResponse} from '../redis_types';

describe("Redis IO Works as expected", function() {
  describe("Can GET/SET", function() {
    it('Should be able to SET {Key, Value} Pair', function() {
      var result = RedisInteraction.setKeyValue("key","value");
      expect(result).to.equal(RedisResponse.OK);
    });

    it('Should be able to GET Value from Key', function() {
      const response = RedisInteraction.getValueFromKey("key");
      expect(response).to.equal("value");
    });
  });
  describe("Can DEL", function() {
    before(function() {
      RedisInteraction.setKeyValue("key_to_delete","value");
    });
    it("Should be able to DEL Key from Redis DB", function() {
      expect(RedisInteraction.deleteKeyFromRedis("key_to_delete"))
      .to.equal(RedisResponse.OK);
    });
  });
});
</code>```

However, when I actually run npm test, I receive the following errors:

```<code>> mocha lib/test/

  Redis IO Works as expected
    Can GET/SET
      1) Should be able to SET {Key, Value} Pair
      2) Should be able to GET Value from Key
    Can DEL
      3) Should be able to DEL Key from Redis DB

  0 passing (13ms)
  3 failing

  1) Redis IO Works as expected Can GET/SET Should be able to SET {Key, Value} Pair:

      AssertionError: expected 1 to equal 0
      + expected - actual

      -1
      +0

      at Context.<anonymous> (lib/test/redis_test.js:11:38)

  2) Redis IO Works as expected Can GET/SET Should be able to GET Value from Key:
     AssertionError: expected [ '', 1 ] to equal 'value'
      at Context.<anonymous> (lib/test/redis_test.js:15:40)

  3) Redis IO Works as expected Can DEL Should be able to DEL Key from Redis DB:

      AssertionError: expected 1 to equal 0
      + expected - actual

      -1
      +0

      at Context.<anonymous> (lib/test/redis_test.js:24:21)
</code>```

Am I doing something wrong regarding callbacks? For the life of me, I don't understand why the callbacks I've written aren't working correctly.

Many thanks, apologies for potential verbosity.

答:
Your issue is how you are currently handling the asynchronous nature of the calls to redis.  Looking at this function...

```<code>export function setKeyValue(key : string, value : string): RedisResponse {

  client.set(key, value, function(err, reply) {
    if(!err) {
      // Not a return from setKeyValue function
      return RedisResponse.OK;
    }
  });

  // Return value from setKeyValue
  return RedisResponse.Fail;
}
</code>```

You call the client set function, and provide a callback.  Execution will continue immediately, and reach the return RedisResponse.Fail statement.  The first return statement is actually a return from inside the callback - it is discarded as it is not used anywhere.

To write your setKeyValue function to accommodate this asynchronicity, it needs to have a callback argument:

```<code>export function setKeyValue(key : string, value : string, callback: (err: Error, response: RedisResponse) => void): void {

  client.set(key, value, function(err, reply) {
    // Now we know whether we succeeded

    // If there is an error, invoke the callback with the error
    // and a fail response
    if(err) {
      return callback(err, RedisResponse.Fail);
    }

    // Otherwise invoke it with a null error and an OK response
    callback(null, RedisResponse.OK);
  });
}
</code>```

When you are testing the function you need to wait for the async call to redis to finish, and then make your assertion - you can do this by providing a callback in the test:

```<code>it('Should be able to SET {Key, Value} Pair', function() {
  RedisInteraction.setKeyValue("key", "value", (err, redisResponse) => {
    expect(redisResponse).to.equal(RedisResponse.OK);
  });
});
</code>```

Just as an alternative to using this callback style of coding, it is often nicer to use a Promise-based implementation.  node-redis doesn't provide this for you, but it is relatively simple to implement.  I have removed the RedisResponse enum because it really isn't necessary - the resolution/rejection of the promise tells you whether the call succeeded or not. (This is also true for the above implementation)  The above function would become:

```<code>export function setKeyValue(key : string, value : string): Promise<null> {
  return new Promise((resolve, reject) => {
    client.set(key, value, function(err, reply) {
      if(err) {
        // If there's an error reject the promise providing the error
        return reject(err);
      }
      // Otherwise resolve it
      resolve();
  });
}
</code>```

You can then test it with:

```<code>it('Should be able to SET {Key, Value} Pair', function() {
  RedisInteraction.setKeyValue("key", "value")
  .then(() => {
     // Your test has passed, no need to do anything
  })
  .catch((error) => {
    // Your test failed, do something to let mocha know
    expect(true).to.equal(false);
  });
});
</code>```

Having shown you this, it is worth pointing out that the functions you have shown in your question don't appear to add any functionality over the node-redis functions, except for adding the (unnecessary) RedisResponse enum.  Essentially what you are testing is that node-redis works as it should, and that is the job of the authors of the library, not yours!

Body:
someone who's somewhat new to Redis and is somewhat novice at Node here.

I've been trying to integrate the node-redis module with a Typescript Node project I've been working on, which I've been testing with mocha and chai.

I'm trying to write basic Getter/Setter Functions I can integrate with the rest of my project (I'm using Redis to track the state of a Facebook Messenger Bot).

Any time I try to write a new Key-Value pair to the DB with my setKeyValue function, the transaction goes through (as verified through the redis-cli client), but the values returned for both setKeyValue and getValueFromKey don't correspond to what they should if the DB transaction was successful.

The code implementation I've written is below (in my redis_interaction.ts file):

import * as redis from 'redis';
var client = redis.createClient("6379", "127.0.0.1");

enum RedisResponse {
  OK,
  Fail
}

    // 'Setter' Function for Key Value Pairs within Redis Database
export function setKeyValue(key : string, value : string): RedisResponse {
  client.set(key, value, function(err, reply) {
    if(!err) {
      return RedisResponse.OK;
    }
  });
  return RedisResponse.Fail;
}

// 'Getter' Function for Key Value Pairs within Redis Database
export function getValueFromKey(key : string) : [string, RedisResponse] {
  client.get(key, function(err, reply) {
    if(!err) {
      return[reply, RedisResponse.OK];
    }
  });
  return["", RedisResponse.Fail];
}

// 'Delete' Function for Removing Keys from within Redis Database
export function deleteKeyFromRedis(key : string) : RedisResponse {
  client.del(key, function(err, reply) {
    if(!err) {
      if(reply) {
        return RedisResponse.OK;
      }
    }
  });
  return RedisResponse.Fail;
}

I test this code with the following mocha tests:

import {expect, assert} from 'chai';
import 'mocha';
import * as RedisInteraction from '../redis_interaction';
import {RedisResponse} from '../redis_types';

describe("Redis IO Works as expected", function() {
  describe("Can GET/SET", function() {
    it('Should be able to SET {Key, Value} Pair', function() {
      var result = RedisInteraction.setKeyValue("key","value");
      expect(result).to.equal(RedisResponse.OK);
    });

    it('Should be able to GET Value from Key', function() {
      const response = RedisInteraction.getValueFromKey("key");
      expect(response).to.equal("value");
    });
  });
  describe("Can DEL", function() {
    before(function() {
      RedisInteraction.setKeyValue("key_to_delete","value");
    });
    it("Should be able to DEL Key from Redis DB", function() {
      expect(RedisInteraction.deleteKeyFromRedis("key_to_delete"))
      .to.equal(RedisResponse.OK);
    });
  });
});

However, when I actually run npm test, I receive the following errors:

> mocha lib/test/

  Redis IO Works as expected
    Can GET/SET
      1) Should be able to SET {Key, Value} Pair
      2) Should be able to GET Value from Key
    Can DEL
      3) Should be able to DEL Key from Redis DB

  0 passing (13ms)
  3 failing

  1) Redis IO Works as expected Can GET/SET Should be able to SET {Key, Value} Pair:

      AssertionError: expected 1 to equal 0
      + expected - actual

      -1
      +0

      at Context.<anonymous> (lib/test/redis_test.js:11:38)

  2) Redis IO Works as expected Can GET/SET Should be able to GET Value from Key:
     AssertionError: expected [ '', 1 ] to equal 'value'
      at Context.<anonymous> (lib/test/redis_test.js:15:40)

  3) Redis IO Works as expected Can DEL Should be able to DEL Key from Redis DB:

      AssertionError: expected 1 to equal 0
      + expected - actual

      -1
      +0

      at Context.<anonymous> (lib/test/redis_test.js:24:21)

Am I doing something wrong regarding callbacks? For the life of me, I don't understand why the callbacks I've written aren't working correctly.

Many thanks, apologies for potential verbosity.

Body:
Your issue is how you are currently handling the asynchronous nature of the calls to redis.  Looking at this function...

export function setKeyValue(key : string, value : string): RedisResponse {

  client.set(key, value, function(err, reply) {
    if(!err) {
      // Not a return from setKeyValue function
      return RedisResponse.OK;
    }
  });

  // Return value from setKeyValue
  return RedisResponse.Fail;
}

You call the client set function, and provide a callback.  Execution will continue immediately, and reach the return RedisResponse.Fail statement.  The first return statement is actually a return from inside the callback - it is discarded as it is not used anywhere.

To write your setKeyValue function to accommodate this asynchronicity, it needs to have a callback argument:

export function setKeyValue(key : string, value : string, callback: (err: Error, response: RedisResponse) => void): void {

  client.set(key, value, function(err, reply) {
    // Now we know whether we succeeded

    // If there is an error, invoke the callback with the error
    // and a fail response
    if(err) {
      return callback(err, RedisResponse.Fail);
    }

    // Otherwise invoke it with a null error and an OK response
    callback(null, RedisResponse.OK);
  });
}

When you are testing the function you need to wait for the async call to redis to finish, and then make your assertion - you can do this by providing a callback in the test:

it('Should be able to SET {Key, Value} Pair', function() {
  RedisInteraction.setKeyValue("key", "value", (err, redisResponse) => {
    expect(redisResponse).to.equal(RedisResponse.OK);
  });
});

Just as an alternative to using this callback style of coding, it is often nicer to use a Promise-based implementation.  node-redis doesn't provide this for you, but it is relatively simple to implement.  I have removed the RedisResponse enum because it really isn't necessary - the resolution/rejection of the promise tells you whether the call succeeded or not. (This is also true for the above implementation)  The above function would become:

export function setKeyValue(key : string, value : string): Promise<null> {
  return new Promise((resolve, reject) => {
    client.set(key, value, function(err, reply) {
      if(err) {
        // If there's an error reject the promise providing the error
        return reject(err);
      }
      // Otherwise resolve it
      resolve();
  });
}

You can then test it with:

it('Should be able to SET {Key, Value} Pair', function() {
  RedisInteraction.setKeyValue("key", "value")
  .then(() => {
     // Your test has passed, no need to do anything
  })
  .catch((error) => {
    // Your test failed, do something to let mocha know
    expect(true).to.equal(false);
  });
});

Having shown you this, it is worth pointing out that the functions you have shown in your question don't appear to add any functionality over the node-redis functions, except for adding the (unnecessary) RedisResponse enum.  Essentially what you are testing is that node-redis works as it should, and that is the job of the authors of the library, not yours!


来源: stackexchange

问:
Persistence of Value After Message Cycle
In the message life cycle there are flow vars, scoped to a flow or sub-flow, and session vars, that are scoped to the transaction but end with the message cycle. I need to keep a value across messages. What is the correct way to save a value across messages?</p>

答:
What you can do is to implement objectstore

https://docs.mulesoft.com/mule-user-guide/v/3.8/mule-object-stores

ContentLicense: CC BY-SA 3.0


问:
PouchDB in an Electron app gives error "dbFactory is not a function"

levelup.js?006c:115Uncaught TypeError: dbFactory is not a function

This is my question.
I use it in chrome, but it's ok.
When I use it in electron (Vue2.0), the same, but give me this tip.
Who can help me?

答:
Try to use init PouchDB as</p>

```<code>const PouchDB = require('electron').remote.require('pouchdb');
</code>```

Body:
Try to use init PouchDB as

const PouchDB = require('electron').remote.require('pouchdb');


问:
Is there a way to get Atom to autocomplete 'html' tags when building React Apps?
I'm just starting to learn React and am enjoying using it. However, it is very frustrating to me that Atom doesn't autocomplete html tags in .js files. Is there a way to fix this?

答: Yes, install this plugin on your atom https://orktes.github.io/atom-react/#automatic-closing-tag</p>


问:
how to initialize server context using gsoap to enable simple authentication (server only authentication)
I have server.pem and a server.jks for a back-end which is my client (soapui). I initialize ssl server context in order to enable simple authentication for my web service as follow:

```<code>int ssl_connection_flag = SOAP_SSL_DEFAULT; // Simple authentication

int soap_result = soap_ssl_server_context(soap_object,
                                                ssl_connection_flag,//SOAP_SSL_NO_AUTHENTICATION,//m_ssl_connection_flag,
                                                m_key_file.c_str(),//Settings::instance()->get_cert_mngr_tls_certificate_path().c_str(),//"D:\\ICA\\Release\\currentStore\\TLSCertificate.pem",//m_ssl_private_key_file_path.c_str(),/* keyfile: required when server must authenticate to clients (see SSL docs on how to obtain this file) */
                                                l_recover.c_str(),//"changeit",//PWDHelper::instance()->retrieve_pwd("k-tls-key").c_str(),//"changeit",//"12345678",//"server_key_password",/* password to read the key file (not used with GNUTLS) */
                                                m_ca_certs_file.c_str(),//Settings::instance()->get_cert_mngr_ca_path().c_str(),//"D:\\ICA\\Release\\currentStore\\CA.pem",//"D:\\CertificatBrahim\\CAs.pem",//m_ssl_ca_file_path.c_str(), /* optional cacert file to store trusted certificates */
                                                NULL, /* optional capath to directory with trusted certificates */
                                                NULL,/* DH file name or DH key len bits (minimum is 512, e.g. "512") to generate DH param, if NULL use RSA */
                                                NULL,
                                                NULL);
</code>```

The trouble is, when I look for in wireshark after sending my request from SoapUI to a remote PC where is located my server. The decoding looks like there is a mutual authentication going on.

But when I change

SOAP_SSL_DEFAULT

with

SOAP_SSL_NO_AUTHENTICATION

, and sent the same request, in wireshark it looks like there is a simple (only server authentication) going on.

But that confuses me, because if I follow gSoap documentation, the TLS/SSL option SOAP_SSL_NO_AUTHENTICATION, disable both client and server authentication.

Then my question is what am I doing wrong?

thanks in advance for your responses.

Best regards.

答: The SOAP_SSL_NO_AUTHENTICATION flag on the server side does not prevent the client from requesting the server to authenticate. This flag disables the requirement for a peer to authenticate to the requesting side. In your case the client is the requesting side and the flag is set at the server side.

Body:
I have server.pem and a server.jks for a back-end which is my client (soapui). I initialize ssl server context in order to enable simple authentication for my web service as follow:

int ssl_connection_flag = SOAP_SSL_DEFAULT; // Simple authentication

int soap_result = soap_ssl_server_context(soap_object,
                                                ssl_connection_flag,//SOAP_SSL_NO_AUTHENTICATION,//m_ssl_connection_flag,
                                                m_key_file.c_str(),//Settings::instance()->get_cert_mngr_tls_certificate_path().c_str(),//"D:\\ICA\\Release\\currentStore\\TLSCertificate.pem",//m_ssl_private_key_file_path.c_str(),/* keyfile: required when server must authenticate to clients (see SSL docs on how to obtain this file) */
                                                l_recover.c_str(),//"changeit",//PWDHelper::instance()->retrieve_pwd("k-tls-key").c_str(),//"changeit",//"12345678",//"server_key_password",/* password to read the key file (not used with GNUTLS) */
                                                m_ca_certs_file.c_str(),//Settings::instance()->get_cert_mngr_ca_path().c_str(),//"D:\\ICA\\Release\\currentStore\\CA.pem",//"D:\\CertificatBrahim\\CAs.pem",//m_ssl_ca_file_path.c_str(), /* optional cacert file to store trusted certificates */
                                                NULL, /* optional capath to directory with trusted certificates */
                                                NULL,/* DH file name or DH key len bits (minimum is 512, e.g. "512") to generate DH param, if NULL use RSA */
                                                NULL,
                                                NULL);

The trouble is, when I look for in wireshark after sending my request from SoapUI to a remote PC where is located my server. The decoding looks like there is a mutual authentication going on.

But when I change

SOAP_SSL_DEFAULT

with

SOAP_SSL_NO_AUTHENTICATION

, and sent the same request, in wireshark it looks like there is a simple (only server authentication) going on.

But that confuses me, because if I follow gSoap documentation, the TLS/SSL option SOAP_SSL_NO_AUTHENTICATION, disable both client and server authentication.

Then my question is what am I doing wrong?

thanks in advance for your responses.

Best regards.


问:
No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]
I am trying to use spring-data-solr in order to access to my Solr instance through my Spring boot application. I have the following bean class:

```<code>@SolrDocument(solrCoreName = "associations")
public class Association implements PlusimpleEntityI {
    @Id
    @Indexed
    private String id;
    @Indexed
    private String name;
    @Indexed
    private Point location;
    @Indexed
    private String description;
    @Indexed
    private Set<String> tags;
    @Indexed
    private Set<String> topics;
    @Indexed
    private Set<String> professionals;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Point getLocation() {
        return location;
    }

    public void setLocation(Point location) {
        this.location = location;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<String> getTags() {
        return tags;
    }

    public void setTags(Set<String> tags) {
        this.tags = tags;
    }

    public Set<String> getTopics() {
        return topics;
    }

    public void setTopics(Set<String> topics) {
        this.topics = topics;
    }

    public Set<String> getProfessionals() {
        return professionals;
    }

    public void setProfessionals(Set<String> professionals) {
        this.professionals = professionals;
    }
}
</code>```

I have implemented the following repository in order to access to the related information:

```<code>public interface AssociationsRepository extends SolrCrudRepository<Association, String> {
}
</code>```

I have created a configuration class which looks like the following one:

```<code>@Configuration
@EnableSolrRepositories(basePackages = {"com.package.repositories"}, multicoreSupport = true)
public class SolrRepositoryConfig {
    @Value("${solr.url}")
    private String solrHost;

    @Bean
    public SolrConverter solrConverter() {
        MappingSolrConverter solrConverter = new MappingSolrConverter(new SimpleSolrMappingContext());
        solrConverter.setCustomConversions(new CustomConversions(null));
        return solrConverter;
    }

    @Bean
    public SolrClientFactory solrClientFactory () throws Exception {
        return new MulticoreSolrClientFactory(solrClient());
    }

    @Bean
    public SolrClient solrClient() throws Exception {
        return new HttpSolrClient.Builder(solrHost).build();
    }

    @Bean
    public SolrOperations associationsTemplate() throws Exception {
        SolrTemplate solrTemplate = new SolrTemplate(solrClient());
        solrTemplate.setSolrConverter(solrConverter());
        return solrTemplate;
    }

}
</code>```

Unfortunately, when I try to read an association from my Solr instance I got the following error:

```<code>org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]
</code>```

I don't understand why it is not able to find a converter if I have explicitly defined it in the solrTemplate() method.

This is my POM definition:

```<code>    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-solr</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>
</code>```

Thank you for your help.

EDIT:
I've also tried with different BUILD-RELEASEs but they are highly unstable and I've found a lot of errors using them.

答:
Alessandro, as you can see directly in the GeoConverters class on GitHub, the implemented converters are only for:

```<code>org.springframework.data.geo.Point
</code>```

and not for:

```<code>org.springframework.data.solr.core.geo.Point
</code>```

Simply use this class and you don't even need a custom converter for this. Spring Data for Solr will perform the conversion for you.
I'm using a slightly patched version of the 3.0.0 M4, but I'm pretty sure this solution should apply seamlessly also to your case.

Body:
I am trying to use spring-data-solr in order to access to my Solr instance through my Spring boot application. I have the following bean class:

@SolrDocument(solrCoreName = "associations")
public class Association implements PlusimpleEntityI {
    @Id
    @Indexed
    private String id;
    @Indexed
    private String name;
    @Indexed
    private Point location;
    @Indexed
    private String description;
    @Indexed
    private Set<String> tags;
    @Indexed
    private Set<String> topics;
    @Indexed
    private Set<String> professionals;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Point getLocation() {
        return location;
    }

    public void setLocation(Point location) {
        this.location = location;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Set<String> getTags() {
        return tags;
    }

    public void setTags(Set<String> tags) {
        this.tags = tags;
    }

    public Set<String> getTopics() {
        return topics;
    }

    public void setTopics(Set<String> topics) {
        this.topics = topics;
    }

    public Set<String> getProfessionals() {
        return professionals;
    }

    public void setProfessionals(Set<String> professionals) {
        this.professionals = professionals;
    }
}

I have implemented the following repository in order to access to the related information:

public interface AssociationsRepository extends SolrCrudRepository<Association, String> {
}

I have created a configuration class which looks like the following one:

@Configuration
@EnableSolrRepositories(basePackages = {"com.package.repositories"}, multicoreSupport = true)
public class SolrRepositoryConfig {
    @Value("${solr.url}")
    private String solrHost;

    @Bean
    public SolrConverter solrConverter() {
        MappingSolrConverter solrConverter = new MappingSolrConverter(new SimpleSolrMappingContext());
        solrConverter.setCustomConversions(new CustomConversions(null));
        return solrConverter;
    }

    @Bean
    public SolrClientFactory solrClientFactory () throws Exception {
        return new MulticoreSolrClientFactory(solrClient());
    }

    @Bean
    public SolrClient solrClient() throws Exception {
        return new HttpSolrClient.Builder(solrHost).build();
    }

    @Bean
    public SolrOperations associationsTemplate() throws Exception {
        SolrTemplate solrTemplate = new SolrTemplate(solrClient());
        solrTemplate.setSolrConverter(solrConverter());
        return solrTemplate;
    }

}

Unfortunately, when I try to read an association from my Solr instance I got the following error:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]

I don't understand why it is not able to find a converter if I have explicitly defined it in the solrTemplate() method.

This is my POM definition:

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-solr</artifactId>
        <version>2.1.4.RELEASE</version>
    </dependency>

Thank you for your help.

EDIT:
I've also tried with different BUILD-RELEASEs but they are highly unstable and I've found a lot of errors using them.

Body:
Alessandro, as you can see directly in the GeoConverters class on GitHub, the implemented converters are only for:

org.springframework.data.geo.Point

and not for:

org.springframework.data.solr.core.geo.Point

Simply use this class and you don't even need a custom converter for this. Spring Data for Solr will perform the conversion for you.
I'm using a slightly patched version of the 3.0.0 M4, but I'm pretty sure this solution should apply seamlessly also to your case.


问:
call Live wallpaper within application
I am trying to implement following thing in android 2.x.

In my application i want to allow the user to create the custom live wallpaper kind of thing where
user chooses few images and then those image will rotate in a typical fashion and after that user will be able to set it all the view as a live wallpaper within the application only.

i have successfully implemented the selection of images and its rotation now i don't know how to set live wallpaper within the application. i have tried implementing  Live Wallpaper chooser but it is used to access already installed live wallpaper. but what about the dynamically created live wallpaper?

Even i tried to call it using following line of code

```<code>intent.setClassName("com.android.wallpaper.livepicker", "com.android.wallpaper.livepicker.LiveWallpaperPreview");
</code>```

But it is giving me an error

```<code>java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.android.wallpaper.livepicker/.LiveWallpaperPreview } from ProcessRecord{43f94a38 29784:com.vb.ui/10038} (pid=29784, uid=10038) requires null
</code>```

There might be few ways but m not sure about it

is it possible to install live wallpaper apk programmatically  so that once the live wallpaper is created it is being installed by the application ?

if live wallpapers are stored in some place then we can store user created live wallpaper at that place so when live wallpaper chooser is being selected we can see the live wallpaper in the list

答:
Maybe you should open this custom picking activity from within the standard "Settings" button a user sees when choosing your live wallpaper.

User goes into standard live wallpaper chooser, sees a list of installed LWPs, picks yours.

User sees your default implementation, chooses "Settings" button.

You show a list of settings, one of which is a PreferenceScreen named "Pick Images."

Assign an onClickListener to that preference item which launches your custom image picking activity.

ContentLicense: CC BY-SA 2.5

Title: call Live wallpaper within application

Body:
I am trying to implement following thing in android 2.x.

In my application i want to allow the user to create the custom live wallpaper kind of thing where
user chooses few images and then those image will rotate in a typical fashion and after that user will be able to set it all the view as a live wallpaper within the application only.

i have successfully implemented the selection of images and its rotation now i don't know how to set live wallpaper within the application. i have tried implementing  Live Wallpaper chooser but it is used to access already installed live wallpaper. but what about the dynamically created live wallpaper?

Even i tried to call it using following line of code

intent.setClassName("com.android.wallpaper.livepicker", "com.android.wallpaper.livepicker.LiveWallpaperPreview");

But it is giving me an error

java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.android.wallpaper.livepicker/.LiveWallpaperPreview } from ProcessRecord{43f94a38 29784:com.vb.ui/10038} (pid=29784, uid=10038) requires null

There might be few ways but m not sure about it

is it possible to install live wallpaper apk programmatically  so that once the live wallpaper is created it is being installed by the application ?

if live wallpapers are stored in some place then we can store user created live wallpaper at that place so when live wallpaper chooser is being selected we can see the live wallpaper in the list


问:
Xamarin on Visual Studio deploy Android App without debugging
i have a Forms Project.
My Android subproject suddenly successfully deploy on reald Android device but debug doesn't start (app starts without debugging attached to visual studio).
Last Visual Studio 2015 console message says:

Deploy successfully on Motorola Nexus 6

Anybody can help me please?
Maybe i lost/changed something in Android Project properties?

Thanks,
Lewix

答:
this happened to me too; maybe you forgot to set a launcher activity
 [Activity(Label = "yourAppName", MainLauncher = true, Icon = "@drawable/icon")]</p>


问:
Multiple lined UIAlertController message
Is there a way to format the message (not the title) string of a UIAlertController to show multiple lines? I've tried the "/n" character and that doesn't work. I also can't use NSString and formatting it.

Thanks!

Edit: d'oh it should have been \n not /n. Here's the correct code

```<code>let alertController = UIAlertController(title: "blah", message: "1. blah \n2. blah \n3. blah", preferredStyle: .actionSheet)
</code>```

答:
It will work with \n as edited.

```<code>let alert = UIAlertController(title: "Title",
                              message: "message: \n message",
                              preferredStyle: UIAlertControllerStyle.alert)

let cancelAction = UIAlertAction(title: "OK",
                                 style: .cancel, handler: nil)

alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
</code>```

Body:
Is there a way to format the message (not the title) string of a UIAlertController to show multiple lines? I've tried the "/n" character and that doesn't work. I also can't use NSString and formatting it.

Thanks!

Edit: d'oh it should have been \n not /n. Here's the correct code

let alertController = UIAlertController(title: "blah", message: "1. blah \n2. blah \n3. blah", preferredStyle: .actionSheet)

Body:
It will work with \n as edited.

let alert = UIAlertController(title: "Title",
                              message: "message: \n message",
                              preferredStyle: UIAlertControllerStyle.alert)

let cancelAction = UIAlertAction(title: "OK",
                                 style: .cancel, handler: nil)

alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)


问:
How to save changes to my orginal image in vb.net?
I'm using this code to save image

```<code> PictureBox1.Image.Save(filePath)
</code>```

after that I crop image and I want to save it again by replacing the old one with the new cropped one

any help please

regards,,,

答:
This's the answer

Dim bmp1 As New Bitmap(PictureBox1.Image)
        If System.IO.File.Exists(filePath) Then
            System.IO.File.Delete(filePath)
        End If

        bmp1.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg)
        ' Dispose of the image files.
        bmp1.Dispose()```

Body:
I'm using this code to save image

 PictureBox1.Image.Save(filePath)

after that I crop image and I want to save it again by replacing the old one with the new cropped one

any help please

regards,,,


问:
PHP: How to set timezone for an offset DateTime
I'm trying to create a DateTime object offset from the present with a specific timezone. It works for 'today', or an absolute value like '2017-07-16 00:00:00', but if I try an offset, like '+1 sundays' it always has a timezone of "S".

```<code>$dtz = date_default_timezone_get();//"America/Vancouver"
$now = new \DateTime('today', new \DateTimeZone($dtz));
$sunday = new \DateTime('+1 sundays', new \DateTimeZone($dtz));
$later = new \DateTime('2357-04-13', new \DateTimeZone($dtz));
$tz1 = $now->getTimezone()->getName();//"America/Vancouver"
$tz2 = $sunday->getTimezone()->getName();//"S"
$tz3 = $later->getTimezone()->getName();//"America/Vancouver"
</code>```

How should I do this?

答:
The first parameter to DateTime should be a valid date/time string. It even takes null when using timezone as second parameter.

'+1 sundays' is not under the category of valid date/time string. Check the complete list here

Below should work -

```<code>$sunday = $now->modify('+1 sundays');
echo $sunday->getTimezone()->getName();//"America/Vancouver"
</code>```

Body:
I'm trying to create a DateTime object offset from the present with a specific timezone. It works for 'today', or an absolute value like '2017-07-16 00:00:00', but if I try an offset, like '+1 sundays' it always has a timezone of "S".

$dtz = date_default_timezone_get();//"America/Vancouver"
$now = new \DateTime('today', new \DateTimeZone($dtz));
$sunday = new \DateTime('+1 sundays', new \DateTimeZone($dtz));
$later = new \DateTime('2357-04-13', new \DateTimeZone($dtz));
$tz1 = $now->getTimezone()->getName();//"America/Vancouver"
$tz2 = $sunday->getTimezone()->getName();//"S"
$tz3 = $later->getTimezone()->getName();//"America/Vancouver"

How should I do this?

Body:
The first parameter to DateTime should be a valid date/time string. It even takes null when using timezone as second parameter.

'+1 sundays' is not under the category of valid date/time string. Check the complete list here

Below should work -

$sunday = $now->modify('+1 sundays');
echo $sunday->getTimezone()->getName();//"America/Vancouver"


问:
Ruby—how to loop through indefinite user input
So I have a little ruby program I run on the console.

Sometimes I want to type input in (as much as I want, until I ctrl+c outta there), sometimes I want to put a file as input (e.g. ruby robot_simulator.rb < test_data.txt)

Currently I have this code:

```<code>while(true)
  input = gets.chomp
</code>```

It kind of works, but when I run it with a file as input, it finishes by crashing with this error:

```<code>robot_simulator.rb:23:in `<main>': undefined method `chomp' for nil:NilClass (NoMethodError)
</code>```

Is there a nice way to continuously get input from console/files?

答:
The problem is while(true)

It should be something more like while(input = gets)

If the chomp is necessary, use the (ruby 2.3) & operator, so that it only runs if gets is not nil:

while(input = gets&.chomp)

Body:
So I have a little ruby program I run on the console.

Sometimes I want to type input in (as much as I want, until I ctrl+c outta there), sometimes I want to put a file as input (e.g. ruby robot_simulator.rb < test_data.txt)

Currently I have this code:

while(true)
  input = gets.chomp

It kind of works, but when I run it with a file as input, it finishes by crashing with this error:

robot_simulator.rb:23:in `<main>': undefined method `chomp' for nil:NilClass (NoMethodError)

Is there a nice way to continuously get input from console/files?


问:
How to avoid warning : Preparing debugger support of iPAD
I am using Xcode 9 beta and running on iPAD OS version 10.3.2. But while running Xcode is warning as in attached screenshot. It is loading and loading....

答: Same here.. Wait for 20 to 30 minutes and will work !!</p>


问:
Using `self` as a context in a `with` statement
I often see code that uses self to manage a context. For example

```<code>with self:
    self.x = 4
    self.y = 6
</code>```

What's going on here? What does using self as a context allow?

答:
What's going on here? What does using self as a context allow?

As long as the class has implemented the necessary "hooks" that a context manager should, Python allows it to be used like a normal context manager. Here is an excerpt from the docs which helps clear things up here:

Python’s with statement supports the concept of a runtime context defined by a context manager. This is implemented using a pair of methods that allow user-defined classes to define a runtime context that is entered before the statement body is executed and exited when the statement ends:

contextmanager.__enter__()
  Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager.
  [...]

contextmanager.__exit__(exc_type, exc_val, exc_tb)
  Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the with statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None.
  [...]

As stated above, when you implement the necessary __enter__ and __exit__ magic methods for your class, Python allows you to treat it as a context manager.

Body:
I often see code that uses self to manage a context. For example

with self:
    self.x = 4
    self.y = 6

What's going on here? What does using self as a context allow?


问:
mSSQL, SQL view, select, percentage query
So this is the requirement I need to meet:
Aggregated data of all the schools in the ESD, grouped by

SchoolDistrict.SchoolDistrictID

(get the same data as the school district scenario above, then add grouping by district, filtered to

EducationServiceDistrict. EducationServiceDistrictID

)
Also calculate percentage of pass, fail, and untested

How do I calculate the percentage pass, fail, and untested?
This is the query I have written so far.

```<code>CREATE VIEW district_map AS
 SELECT * and SchoolDistrictID,
        EducationServiceDistrict
   FROM SchoolDistrict_View
         and SchoolDistrict,
        EducationServiceDistrict
  GROUP BY EducationServiceDistrict.EducationServiceDistrictID
  ORDER BYLeadWaterTestLocation.PassFail
</code>```

答:
This is the general idea of how these problems are solved - if you understand this simplified version you will be able to solve your problem.</p>

```<code>    select d.districtName,
    s.studentCount,
    case when s.studentCount=0 then 0 else s.passed / s.studentCount * 100 end as PassedPct
    from district d
    join (select districtId,
          sum(studentCount) as studentCount,
          sum(passed) as passed
          from schools
          group by districtId) as s
    on d.districtId = s.districtId
    order by d.districtName
</code>```

Body:
So this is the requirement I need to meet:
Aggregated data of all the schools in the ESD, grouped by

SchoolDistrict.SchoolDistrictID

(get the same data as the school district scenario above, then add grouping by district, filtered to

EducationServiceDistrict. EducationServiceDistrictID

)
Also calculate percentage of pass, fail, and untested

How do I calculate the percentage pass, fail, and untested?
This is the query I have written so far.

CREATE VIEW district_map AS
 SELECT * and SchoolDistrictID,
        EducationServiceDistrict
   FROM SchoolDistrict_View
         and SchoolDistrict,
        EducationServiceDistrict
  GROUP BY EducationServiceDistrict.EducationServiceDistrictID
  ORDER BYLeadWaterTestLocation.PassFail

Body:
This is the general idea of how these problems are solved - if you understand this simplified version you will be able to solve your problem.

    select d.districtName,
    s.studentCount,
    case when s.studentCount=0 then 0 else s.passed / s.studentCount * 100 end as PassedPct
    from district d
    join (select districtId,
          sum(studentCount) as studentCount,
          sum(passed) as passed
          from schools
          group by districtId) as s
    on d.districtId = s.districtId
    order by d.districtName


问:
How to connect android emulator to the internet
How can I connect my Android emulator to the internet, e.g. to use the browser? I've found lots of advice on what do to when your connected through a proxy, but that's not the case here, my machine (Windows 7) is directly connected to the router.</p>

答: I have a windows 7 machine(64bit) and my emulator wasn't working.  After a lot of looking around, I ended up statical adding my router to the network DNS properties(192.168.1.1). And it started working.</p>


问:
Flask doesn't render src's within static HTML?
I have a very simple flask script below that is supposed to display a dashboard containing some figures that are independent HTML files.

```<code>from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/')
def home():

    return send_from_directory('.', 'dashboard.html')

if __name__ == '__main__':
    app.run(debug=True)
</code>```

The HTML file figure.html displays within the dashboard, but is MASSIVELY outdated.  I can open figure.html manually and see that the up-to-date pie chart is different than the one being displayed.

A sample of the HTML from dashboard.html that is supposed to display the figure in figure.html is below:

```<code>  <div class="col-sm-4">
    <div class="chart-wrapper">
      <div class="chart-stage">
        <iframe width="100%" height="480px" frameborder="0" scrolling="no" src="static/figure.html"></iframe>
      </div>
      <div class="chart-notes">
        Display Figure #1.
      </div>
    </div>
  </div>
</code>```

I suspect that this is caused by a caching issue.

Does anyone know how to make the correct figure.html file display?

答:
Try doing a page refresh which ignores cached content doing Ctrl+Shift+F5 if you're using a browser like Google Chrome.

If you never want the page to be cached or to futher control how caching works, you can view this answer here.

Body:
I have a very simple flask script below that is supposed to display a dashboard containing some figures that are independent HTML files.

from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route('/')
def home():

    return send_from_directory('.', 'dashboard.html')

if __name__ == '__main__':
    app.run(debug=True)

The HTML file figure.html displays within the dashboard, but is MASSIVELY outdated.  I can open figure.html manually and see that the up-to-date pie chart is different than the one being displayed.

A sample of the HTML from dashboard.html that is supposed to display the figure in figure.html is below:

        Display Figure #1.

I suspect that this is caused by a caching issue.

Does anyone know how to make the correct figure.html file display?


问:
how to prevent netcdf4 in python from loading entire variable when using datetime
I am looking to verify my understanding of how python objects behave in this example.

Say I have on a laptop with limited memory a very large netcdf4 dataset, for example a million points in the unlimited dimension which is "time" with units of seconds since 2015-11-12 16:0:8.000000 0:00. I want to access, as a datetime object, the very first and the very last time without loading all the values in memory.

Now I know I can get at the first and last dates as datetime objects with this code:

```<code>import netCDF4 as nc4
from netCDF4 import Dataset
cdf = Dataset(fname,mode="r",format='NETCDF4')
time_var = cdf.variables['time']
dtime = nc4.num2date(time_var[0:10],time_var.units)
print('data starts at %s' % dtime[0])
</code>```

The print statement gives me what I want:

"data starts at 2015-11-12 16:00:08"

Now did python load all the 'time' data into memory to do this?  Or, as I have come to understand using MATLAB, cdf is now a pointer to the 'time' variable in the open file.

Many thanks,
Marinna

答:
Yes, cdf is a pointer or view into the open file, not a copy into memory. This answer discusses this.
https://stackoverflow.com/a/4371049/1211981
As @bart mentioned you should just use:

```<code>dtime = nc4.num2date(time_var[0],time_var.units)
</code>```

and

```<code>dtime2 = nc4.num2date(time_var[-1],time_var.units)
</code>```

to get the times you want.  No big copy into memory.

Body:
I am looking to verify my understanding of how python objects behave in this example.

Say I have on a laptop with limited memory a very large netcdf4 dataset, for example a million points in the unlimited dimension which is "time" with units of seconds since 2015-11-12 16:0:8.000000 0:00. I want to access, as a datetime object, the very first and the very last time without loading all the values in memory.

Now I know I can get at the first and last dates as datetime objects with this code:

import netCDF4 as nc4
from netCDF4 import Dataset
cdf = Dataset(fname,mode="r",format='NETCDF4')
time_var = cdf.variables['time']
dtime = nc4.num2date(time_var[0:10],time_var.units)
print('data starts at %s' % dtime[0])

The print statement gives me what I want:

"data starts at 2015-11-12 16:00:08"

Now did python load all the 'time' data into memory to do this?  Or, as I have come to understand using MATLAB, cdf is now a pointer to the 'time' variable in the open file.

Many thanks,
Marinna

Body:
Yes, cdf is a pointer or view into the open file, not a copy into memory. This answer discusses this.
https://stackoverflow.com/a/4371049/1211981
As @bart mentioned you should just use:

dtime = nc4.num2date(time_var[0],time_var.units)

and

dtime2 = nc4.num2date(time_var[-1],time_var.units)

to get the times you want.  No big copy into memory.


问:
InvalidResourceType The resource type could not be found in the namespace Azure Python SDK Error
I'm hitting the following error when trying to run:

resource_client.resources.get( 'MyResourceGroup', 'Microsoft.Network', '/Resource/Group/Id', 'routeTables', 'Subnet-1-RouteTable', '2015-01-01' ):

For reference, here is the function documentation.

Error:

```<code>Message: The resource type could not be found in the namespace 'Microsoft.Network' for api version '2015-01-01'.
</code>```

I've tried modifying the following without success:

changing API version to 'v2015-01-01' (I can't find any examples of anyone calling this Azure Python SDK function to figure out what the format is supposed to be, any pointer to one would be greatly appreciated)

using 'Microsoft.Network/routeTables' instead of 'routeTables'

I can't find a list of API versions, but I have seen 2015-01-01 thrown around so I used that here, but if someone has a list of APIs or one that will work for this resource type that would be great.

答:
Is there a specific reason you don't want to use the "azure-mgmt-network" client directly?
https://learn.microsoft.com/en-us/python/api/azure.mgmt.network.v2017_03_01.operations.routetablesoperations?view=azure-python

This should simplify a lot your situation.

To answer to your specific problem, I think "routeTable" just does not exist in 2015-01-01 (as the message said). This is an old ApiVersion, and that's not even supported in official SDKs. You should try 2017-03-01.

And about the call itself example, this unittest might help you:
https://github.com/Azure/azure-sdk-for-python/blob/master/azure-mgmt/tests/test_mgmt_resource.py#L156-L164

But again, I strongly suggest you to just use the Network client and not generic Resource.

(I own the Python SDK at MS)

Body:
I'm hitting the following error when trying to run:

resource_client.resources.get( 'MyResourceGroup', 'Microsoft.Network', '/Resource/Group/Id', 'routeTables', 'Subnet-1-RouteTable', '2015-01-01' ):

For reference, here is the function documentation.

Error:

Message: The resource type could not be found in the namespace 'Microsoft.Network' for api version '2015-01-01'.

I've tried modifying the following without success:

changing API version to 'v2015-01-01' (I can't find any examples of anyone calling this Azure Python SDK function to figure out what the format is supposed to be, any pointer to one would be greatly appreciated)

using 'Microsoft.Network/routeTables' instead of 'routeTables'

I can't find a list of API versions, but I have seen 2015-01-01 thrown around so I used that here, but if someone has a list of APIs or one that will work for this resource type that would be great.


问:
Getting random number from 6502 assembler
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

```<code>. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK
</code>```

Now when I try to iterate say 10 times with the following code, it never returns.

```<code>. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK
</code>```

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.

答:
Thanks to Ross Ridge for suggesting that the called function was changing the value in the Y register. I knew it had to be something obvious!

By storing Y before the JSR, and restoring after, it now will iterate properly.  Here is the quick fix:

Edit:  Updated 7/10/17 - to show full code and incorporate JeremyP suggestion.  This is essentially a coin flip iterator (50000 repetitions) for purposes of experimenting with random

```<code>.C 033c  A9 00       LDA #$00
.C 033e  85 FB       STA $FB    ; set up register for counter
.C 0340  85 FC       STA $FC
.C 0342  A2 C8       LDX #$C8   ; outer loop= 200
.C 0344  86 FD       STX $FD
.C 0346  A0 FA       LDY #$FA   ; inner loop=250
.C 0348  84 FE       STY $FE
.C 034a  20 94 E0    JSR $E094  ; Get random# Vic20 Address (E09B for C64)
.C 034d  A5 63       LDA $64
.C 034f  C9 80       CMP #$80   ; >128 = HEADS
.C 0351  90 0D       BCC $0360  ; else continue loop
.C 0353  18          CLC        ; increment 2 byte number
.C 0354  A5 FB       LDA $FB
.C 0356  69 01       ADC #$01   ; LSB
.C 0358  85 FB       STA $FB
.C 035a  A5 FC       LDA $FC
.C 035c  69 00       ADC #$00   ; MSB
.C 035e  85 FC       STA $FC
.C 0360  C6 FE       DEC $FE
.C 0362  D0 E6       BNE $034A  ; end inner loop
.C 0364  C6 FD       DEC $FD
.C 0366  D0 DE       BNE $0346  ; end outer loop
.C 0368  60          RTS        ; return to basic
</code>```

I can get the random number by LDA $63 or LDA $64 inside the loop and use it for my purposes.

This turned out to be a lot slower than expected, taking only half the time it would've taken in BASIC.  The RND function takes a lot of cycles, however, I found this Compute! article which uses the SID chip as a random number generator.

```<code>LDA #$FF  ; maximum frequency value
STA $D40E ; voice 3 frequency low byte
STA $D40F ; voice 3 frequency high byte
LDA #$80  ; noise waveform, gate bit off
STA $D412 ; voice 3 control register
</code>```

Once turned on it generates numbers independently and doesn't have to be executed again.  A loop that repeatadly calls LDA $D41B will get you a new random number on each iteration.  In my test 50,000 iterations took 1.25 seconds and million took a little over 24 seconds.  Pretty impressive for a 1MHz computer!

ContentLicense: CC BY-SA 4.0

Body:
Trying to generate a series of random numbers on my Commodore 64 (C64) using JSR $E09A and retrieving the number from $63 and $64. (which according to all the documentation I've seen is the same routine when you use RND(0) from BASIC. But can't get it to iterate. The following will work and place a different number in $63 and $64 when executed by itself.

. C000  A5 00    LDA $00
. C002  20 9A E0 JSR $E09A
. C005  00       BRK

Now when I try to iterate say 10 times with the following code, it never returns.

. C000  A0 0A    LDY #$0A
. C002  A9 00    LDA #$00
. C004  20 9A E0 JSR $E09A
. C007  88       DEY
. C008  D0 F8    BNE $C002
. C00A  00       BRK

Am I missing something so obvious I can't see it. I'm not worried about how "random" it is. At this point I just want a series of random numbers.

Body:
Thanks to Ross Ridge for suggesting that the called function was changing the value in the Y register. I knew it had to be something obvious!

By storing Y before the JSR, and restoring after, it now will iterate properly.  Here is the quick fix:

Edit:  Updated 7/10/17 - to show full code and incorporate JeremyP suggestion.  This is essentially a coin flip iterator (50000 repetitions) for purposes of experimenting with random

.C 033c  A9 00       LDA #$00
.C 033e  85 FB       STA $FB    ; set up register for counter
.C 0340  85 FC       STA $FC
.C 0342  A2 C8       LDX #$C8   ; outer loop= 200
.C 0344  86 FD       STX $FD
.C 0346  A0 FA       LDY #$FA   ; inner loop=250
.C 0348  84 FE       STY $FE
.C 034a  20 94 E0    JSR $E094  ; Get random# Vic20 Address (E09B for C64)
.C 034d  A5 63       LDA $64
.C 034f  C9 80       CMP #$80   ; >128 = HEADS
.C 0351  90 0D       BCC $0360  ; else continue loop
.C 0353  18          CLC        ; increment 2 byte number
.C 0354  A5 FB       LDA $FB
.C 0356  69 01       ADC #$01   ; LSB
.C 0358  85 FB       STA $FB
.C 035a  A5 FC       LDA $FC
.C 035c  69 00       ADC #$00   ; MSB
.C 035e  85 FC       STA $FC
.C 0360  C6 FE       DEC $FE
.C 0362  D0 E6       BNE $034A  ; end inner loop
.C 0364  C6 FD       DEC $FD
.C 0366  D0 DE       BNE $0346  ; end outer loop
.C 0368  60          RTS        ; return to basic

I can get the random number by LDA $63 or LDA $64 inside the loop and use it for my purposes.

This turned out to be a lot slower than expected, taking only half the time it would've taken in BASIC.  The RND function takes a lot of cycles, however, I found this Compute! article which uses the SID chip as a random number generator.

LDA #$FF  ; maximum frequency value
STA $D40E ; voice 3 frequency low byte
STA $D40F ; voice 3 frequency high byte
LDA #$80  ; noise waveform, gate bit off
STA $D412 ; voice 3 control register

Once turned on it generates numbers independently and doesn't have to be executed again.  A loop that repeatadly calls LDA $D41B will get you a new random number on each iteration.  In my test 50,000 iterations took 1.25 seconds and million took a little over 24 seconds.  Pretty impressive for a 1MHz computer!


问:
Python] How to modify the value from the first 'read' txt to 'write' txt
read.txt got the numbers with comma like this.
1,1,1,1\n
2,2,2,2\n
3,3,3,3

and i wanna change the each value by the program and i wanna replace the new
value to write.txt

I did in many ways but I don't know how to find the comma.

```<code>infile = open("read.txt", "r")
outfile = open("write.txt", "w")

total1 =0
count1 =0

line = infile.readline()
while line !="":
    value = float(line)
    total1 = total1 + value
    count1 = count1 + 1
    line = infile.readline()

outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")

infile.close()
outfile.close()
</code>```

答:
First check out the python CSV module https://docs.python.org/3.6/library/csv.html

But for your original question, if you are reading in a csv file and want to get each "value" you want to split, with something like

```<code>f = open("someFile.csv")
for line in f:                             # Loop iterates through file by grabbing text seperated by \n
    listOfValuesInLine = line.split(",")   #Returns a list of strings that were sepearted by ","
    print(listOfValuesInLine)              #Prints something like ["value1","value2","value3"] etc
</code>```

Body:
read.txt got the numbers with comma like this.
1,1,1,1\n
2,2,2,2\n
3,3,3,3

and i wanna change the each value by the program and i wanna replace the new
value to write.txt

I did in many ways but I don't know how to find the comma.

infile = open("read.txt", "r")
outfile = open("write.txt", "w")

total1 =0
count1 =0

line = infile.readline()
while line !="":
    value = float(line)
    total1 = total1 + value
    count1 = count1 + 1
    line = infile.readline()

outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")

infile.close()
outfile.close()

Body:
First check out the python CSV module https://docs.python.org/3.6/library/csv.html

But for your original question, if you are reading in a csv file and want to get each "value" you want to split, with something like

f = open("someFile.csv")
for line in f:                             # Loop iterates through file by grabbing text seperated by \n
    listOfValuesInLine = line.split(",")   #Returns a list of strings that were sepearted by ","
    print(listOfValuesInLine)              #Prints something like ["value1","value2","value3"] etc


问:
Send e-mail without persist anything in database
In my rails app, I want that my client can send a few informations by e-mail directly from the page. So until now a created a controller, view and the specific route.

Every tutorial that I was able to find people put the action mailer on the create method or update. In this case I only put a few inputs on the page and submit button.
It's possible to do this?

Controller name: contato_controller

The view: contato/index.html.erb

I also set the configurations on the Production.rb basing on the another question I find:

```<code>  config.action_mailer.smtp_settings = {
     address: "smtp.gmail.com",
     port: 587,
     domain: 'localhost',
     user_name: 'username',
     password: 'password',
     authentication: 'plain',
     enable_starttls_auto: true
  }
</code>```

答:
ActionMailer does not require, nor does it use a database. It just needs a Notifier class to trigger emails. This is covered in the ActionMailer guide.

Remember that create and update methods in your controller are also not linked to any sort of database unless you're involving models in your code. It is only by convention that create actually creates database entries, it's not a hard requirement, nor is it done automatically for you.

These are just default endpoints created as part of the REST interface. create could send an email when you submit a form, or it could forward the call to some API. It's entirely up to you.

Body:
In my rails app, I want that my client can send a few informations by e-mail directly from the page. So until now a created a controller, view and the specific route.

Every tutorial that I was able to find people put the action mailer on the create method or update. In this case I only put a few inputs on the page and submit button.
It's possible to do this?

Controller name: contato_controller

The view: contato/index.html.erb

I also set the configurations on the Production.rb basing on the another question I find:

  config.action_mailer.smtp_settings = {
     address: "smtp.gmail.com",
     port: 587,
     domain: 'localhost',
     user_name: 'username',
     password: 'password',
     authentication: 'plain',
     enable_starttls_auto: true
  }


问:
Rails looping in Partial
Hi I am currently running a loop in a partial for my collections model like so:

product/show.html.erb

```<code><div class="card card-block">
   <%= render partial: 'products/collects', locals: {product: @product} %>
</div>
</code>```

Partial _collects.html.erb

```<code><% current_user.collections.each do |collection| %>
    <div class="row">
      <div class="col-lg-6 d-flex justify-content-start">
        <h4><%= collection.name %></h4>
      </div>
      <div id="collection_<%= collection.id %>_<%= product.id %>_collects">
        <% if collection.collects?(product) %>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>
                <i class="fa fa-times" data-toggle='tooltip' data-placement='top' title='Remove this Product'></i>
            <% end %>
        <%- else -%>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>
                <i class="fa fa-plus" data-toggle='tooltip' data-placement='top' title='Collect this Product'></i>
            <% end %>
        <% end %>
      </div>
    </div>
<% end %>
<br>
<div  class="row">
  <%= link_to 'Create new Collection', new_collection_path, class: 'btn btn-secondary btn-block' %>
</div>
</code>```

this works great, except when I want to target the div below with js:

```<code><div id="collection_<%= collection.id %>_<%= product.id %>_collects">
</code>```

Is there a way to run the loop and only have the following inside the partial

```<code><div id="collection_<%= collection.id %>_<%= product.id %>_collects">
        <% if collection.collects?(product) %>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>
                <i class="fa fa-times" data-toggle='tooltip' data-placement='top' title='Remove this Product'></i>
            <% end %>
        <%- else -%>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>
                <i class="fa fa-plus" data-toggle='tooltip' data-placement='top' title='Collect this Product'></i>
            <% end %>
        <% end %>
      </div>
</code>```

or is it better to update the below js and target the div, not the partial?

products/collects/create.js.erb

```<code>$('#collection_<%= @collection.id %>_<%= @product.id %>_collects').html("<%=j render partial: 'products/collects', locals: {product: @product} %>");
</code>```

UPDATE

I found a couple of other questions that lead me down the rabit hole of the partial and rendering loops. specifically this and the docs

by adding  a second local and an object for the collections like so

```<code><%= render partial: 'products/collects', locals: {product: @product, collection: collection}, object: collection %>
</code>```

I was able to show the page without a no method error, but it shows
like so

what have I done wrong?

答:
I found that by rendering the partial inside the collection loop like so

```<code> <% @collections.each do |collection| %>
          <%= collection.name %><
<%= render partial: 'products/collects', locals: {product: @product, collection: collection} %>
    <% end %>
</code>```

and setting up my partial like so:

```<code><div id="collection_<%= collection.id %>_<%= product.id %>_collects">
  <% if collection.collects?(product) %>
      <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>
          <i class="material-icons">subtract</i></i>
      <% end %>
  <%- else -%>
      <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>
          <i class="material-icons">add</i>
      <% end %>
  <% end %>
</div>
</code>```

I was able to run my loop and render the partial. In my initial locals call I had missed the collection: collection.  I recommend going down the rabbit hole of the partial and rendering loops, as mentioned in my update.

Title: Rails looping in Partial

Body:
Hi I am currently running a loop in a partial for my collections model like so:

product/show.html.erb

   <%= render partial: 'products/collects', locals: {product: @product} %>

Partial _collects.html.erb

<% current_user.collections.each do |collection| %>

<%= collection.name %>

      <div id="collection_<%= collection.id %>_<%= product.id %>_collects">
        <% if collection.collects?(product) %>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>

            <% end %>
        <%- else -%>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>

            <% end %>
        <% end %>

<% end %>

  <%= link_to 'Create new Collection', new_collection_path, class: 'btn btn-secondary btn-block' %>

this works great, except when I want to target the div below with js:

<div id="collection_<%= collection.id %>_<%= product.id %>_collects">

Is there a way to run the loop and only have the following inside the partial

<div id="collection_<%= collection.id %>_<%= product.id %>_collects">
        <% if collection.collects?(product) %>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>

            <% end %>
        <%- else -%>
            <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>

            <% end %>
        <% end %>

or is it better to update the below js and target the div, not the partial?

products/collects/create.js.erb

$('#collection_<%= @collection.id %>_<%= @product.id %>_collects').html("<%=j render partial: 'products/collects', locals: {product: @product} %>");

UPDATE

I found a couple of other questions that lead me down the rabit hole of the partial and rendering loops. specifically this and the docs

by adding  a second local and an object for the collections like so

<%= render partial: 'products/collects', locals: {product: @product, collection: collection}, object: collection %>

I was able to show the page without a no method error, but it shows
like so

what have I done wrong?

Body:
I found that by rendering the partial inside the collection loop like so

 <% @collections.each do |collection| %>
          <%= collection.name %><
<%= render partial: 'products/collects', locals: {product: @product, collection: collection} %>
    <% end %>

and setting up my partial like so:

<div id="collection_<%= collection.id %>_<%= product.id %>_collects">
  <% if collection.collects?(product) %>
      <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :delete, remote: true, id: 'remove-button' do %>
          <i class="material-icons">subtract</i></i>
      <% end %>
  <%- else -%>
      <%= link_to product_collect_path(product.id, collection_id: collection.id), method: :post, remote: true, id: 'collects-button' do %>
          <i class="material-icons">add</i>
      <% end %>
  <% end %>
</div>

I was able to run my loop and render the partial. In my initial locals call I had missed the collection: collection.  I recommend going down the rabbit hole of the partial and rendering loops, as mentioned in my update.


问:
AWS CloudFormation for Lambda and SNS Topic
I have a cloud formation script which I am using to create a Lambda and SNS Topic.

Here is the yml script for SNS Topic and Lambda creation,

```<code>SampleSNSTopic:
Type: AWS::SNS::Topic
Properties:
  DisplayName: sampleTopic
  TopicName: sampleTopic
SampleLambdaFunction:
Type: AWS::Lambda::Function
DependsOn: SampleSNSTopic
Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Role: !Ref SomeRole
  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: !Ref SampleSNSTopic
          };
          sns.publish(params, context.done);
      };
  Runtime: nodejs6.10
  Timeout: 300
  MemorySize: 512
</code>```

Question: Using a !Ref on topic ARN fails,

```<code>TopicArn: !Ref SampleSNSTopic
</code>```

Is this the right way to do it? Or is there some other way where I can use my SNS topic's ARN to create lambda in cloud formation?

答:
This is something like the answer to this question:

CloudFormation - Access Parameter from Lambda Code

Essentially you assign the Ref value to an Environment key/value:

```<code>Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Environment:
    Variables:
      SNS_TOPIC_ARN: !Ref SampleSNSTopic
</code>```

Then you can access that within the Lambda:

```<code>  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: process.env.SNS_TOPIC_ARN
          };
          sns.publish(params, context.done);
      };
</code>```

Body:
I have a cloud formation script which I am using to create a Lambda and SNS Topic.

Here is the yml script for SNS Topic and Lambda creation,

SampleSNSTopic:
Type: AWS::SNS::Topic
Properties:
  DisplayName: sampleTopic
  TopicName: sampleTopic
SampleLambdaFunction:
Type: AWS::Lambda::Function
DependsOn: SampleSNSTopic
Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Role: !Ref SomeRole
  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: !Ref SampleSNSTopic
          };
          sns.publish(params, context.done);
      };
  Runtime: nodejs6.10
  Timeout: 300
  MemorySize: 512

Question: Using a !Ref on topic ARN fails,

TopicArn: !Ref SampleSNSTopic

Is this the right way to do it? Or is there some other way where I can use my SNS topic's ARN to create lambda in cloud formation?

Body:
This is something like the answer to this question:

CloudFormation - Access Parameter from Lambda Code

Essentially you assign the Ref value to an Environment key/value:

Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Environment:
    Variables:
      SNS_TOPIC_ARN: !Ref SampleSNSTopic

Then you can access that within the Lambda:

  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: process.env.SNS_TOPIC_ARN
          };
          sns.publish(params, context.done);
      };


问:
JNA - Reading multiple pressed keys
I'm using JNA to block keyboard while my program install other components. I would like to create an escape keys combination, like CTRL + SHIFT + KEY.

How can I check if those three keys are pressed? When I check info.vkCode for one single key, it works fine...

```<code>new Thread(new Runnable() {
    @Override
    public void run() {
        lib = User32.INSTANCE;
        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        keyboardHook = new LowLevelKeyboardProc() {
        @Override
        public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
            if (nCode >= 0) {
                //CTRL + SHIFT + F12, for example --- ERROR
                if (info.vkCode == 160 && info.vkCode == 162 && info.vkCode == 123) {
                    lib.UnhookWindowsHookEx(hhk);
                }
                else {
                    return new LRESULT(1);
                }
            }
                return lib.CallNextHookEx(hhk, nCode, wParam, null);
            }
        };
        hhk = lib.SetWindowsHookEx(13, keyboardHook, hMod, 0);

        int result;
        MSG msg = new MSG();
        while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
            if (result == -1) {
                break;
            }
            else {
                lib.TranslateMessage(msg);
                lib.DispatchMessage(msg);
            }
        }
        lib.UnhookWindowsHookEx(hhk);
    }
}).start();
</code>```

Title: JNA - Reading multiple pressed keys

Body:
I'm using JNA to block keyboard while my program install other components. I would like to create an escape keys combination, like CTRL + SHIFT + KEY.

How can I check if those three keys are pressed? When I check info.vkCode for one single key, it works fine...

new Thread(new Runnable() {
    @Override
    public void run() {
        lib = User32.INSTANCE;
        HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
        keyboardHook = new LowLevelKeyboardProc() {
        @Override
        public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
            if (nCode >= 0) {
                //CTRL + SHIFT + F12, for example --- ERROR
                if (info.vkCode == 160 && info.vkCode == 162 && info.vkCode == 123) {
                    lib.UnhookWindowsHookEx(hhk);
                }
                else {
                    return new LRESULT(1);
                }
            }
                return lib.CallNextHookEx(hhk, nCode, wParam, null);
            }
        };
        hhk = lib.SetWindowsHookEx(13, keyboardHook, hMod, 0);

        int result;
        MSG msg = new MSG();
        while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
            if (result == -1) {
                break;
            }
            else {
                lib.TranslateMessage(msg);
                lib.DispatchMessage(msg);
            }
        }
        lib.UnhookWindowsHookEx(hhk);
    }
}).start();


问:
Cannot compile Typescript Ubuntu
```<code>throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
      ^
TSError: ⨯ Unable to compile TypeScript
Cannot find type definition file for 'jasmine'. (2688)
Cannot find type definition file for 'node'. (2688)

api/public/reports/api-report.spec.ts (1,46): Cannot find module './api-report'. (2307)
...
20 lines of different modules not found
src/api/public/reports/api-report.spec.ts (134,17): Cannot find name 'expect'. (2304)
</code>```

^ Above errors when attempting to do "npm test" with test as "jasmine-ts /folder/*.spec.ts"

Ubuntu 16.04

I've looked extensively, reinstalled node, npm, nvm, jasmine. Looked at my code. No clue what it could be.

答:
Since it can't find the type definitions for node, I can only assume that you are working on a node app, and do not have the type definitions installed. You'll need to:

```<code>npm install @types/node --save-dev
</code>```

...and then reference this file with a triple slash directive.

See the documentation on type definitions and references. It sounds like you'll need to do this for jasmine as well.

It also sounds like you might not be importing other modules appropriately, but it would be impossible to tell without seeing the code.

Title: Cannot compile Typescript Ubuntu

Body:
throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
      ^
TSError: ⨯ Unable to compile TypeScript
Cannot find type definition file for 'jasmine'. (2688)
Cannot find type definition file for 'node'. (2688)

api/public/reports/api-report.spec.ts (1,46): Cannot find module './api-report'. (2307)
...
20 lines of different modules not found
src/api/public/reports/api-report.spec.ts (134,17): Cannot find name 'expect'. (2304)

^ Above errors when attempting to do "npm test" with test as "jasmine-ts /folder/*.spec.ts"

Ubuntu 16.04

I've looked extensively, reinstalled node, npm, nvm, jasmine. Looked at my code. No clue what it could be.

Body:
Since it can't find the type definitions for node, I can only assume that you are working on a node app, and do not have the type definitions installed. You'll need to:

npm install @types/node --save-dev

...and then reference this file with a triple slash directive.

See the documentation on type definitions and references. It sounds like you'll need to do this for jasmine as well.

It also sounds like you might not be importing other modules appropriately, but it would be impossible to tell without seeing the code.


问:
Perl: Verify the command line argument is an integer and not a file
I need to check if the (Perl) command line argument is only an integer and a file.

I can check is the right number of arguments are entered:

```<code>if (@ARGV != 2){
</code>```

And, I can check to make sure the order of arguments is correct:

```<code>    if ($ARGV[0] >= $ARGV[1])
</code>```

But, I don't know how to check if the argument is a file. I want to print and error message if it is a file.

Thanks

答:
You can do this manually with a few checks.

```<code>sub usage {
    return "$0 <integer> <filename>\n";
}

if( @ARGV != 2          ||    # right number of arguments
    $ARGV[0] !~ /^\d+$/ ||    # first one is an integer
    !-f $ARGV[1]        ||    # second is a readable file
    !-r $ARGV[1]
) {
    die usage();
}
</code>```

Note there's no need for an extra check that arguments are in the correct order.

Or you can do it with a module like Getopt::Args. This is the better solution as it's declarative, and removes a lot of redundancy and potential for mistakes.

```<code>#!/usr/bin/env perl

use strict;
use warnings;
use v5.10;
use Getopt::Args;

arg integer => (
    isa         => 'Int',
    required    => 1,
    comment     => 'an integer',
);
arg filename => (
    isa         => 'Str',
    required    => 1,
    comment     => 'a filename',
);

# Extra checks for a readable filename.
my $args = optargs();
if( !-r $args->{filename} ||
    !-f $args->{filename}
) {
    die usage();
}
</code>```

It will produce its own usage message.

```<code>$ perl ~/tmp/test.pl
usage: test.pl INTEGER FILENAME

  Arguments:
    INTEGER    an integer
    FILENAME   a filename
</code>```

For future programs it will handle --options and subcommands as well.

If you don't like this one, there are many Getopt modules to choose from.

Body:
I need to check if the (Perl) command line argument is only an integer and a file.

I can check is the right number of arguments are entered:

if (@ARGV != 2){

And, I can check to make sure the order of arguments is correct:

    if ($ARGV[0] >= $ARGV[1])

But, I don't know how to check if the argument is a file. I want to print and error message if it is a file.

Thanks

Body:
You can do this manually with a few checks.

sub usage {
    return "$0 <integer> <filename>\n";
}

if( @ARGV != 2          ||    # right number of arguments
    $ARGV[0] !~ /^\d+$/ ||    # first one is an integer
    !-f $ARGV[1]        ||    # second is a readable file
    !-r $ARGV[1]
) {
    die usage();
}

Note there's no need for an extra check that arguments are in the correct order.

Or you can do it with a module like Getopt::Args. This is the better solution as it's declarative, and removes a lot of redundancy and potential for mistakes.

#!/usr/bin/env perl

use strict;
use warnings;
use v5.10;
use Getopt::Args;

arg integer => (
    isa         => 'Int',
    required    => 1,
    comment     => 'an integer',
);
arg filename => (
    isa         => 'Str',
    required    => 1,
    comment     => 'a filename',
);

# Extra checks for a readable filename.
my $args = optargs();
if( !-r $args->{filename} ||
    !-f $args->{filename}
) {
    die usage();
}

It will produce its own usage message.

$ perl ~/tmp/test.pl
usage: test.pl INTEGER FILENAME

  Arguments:
    INTEGER    an integer
    FILENAME   a filename

For future programs it will handle --options and subcommands as well.

If you don't like this one, there are many Getopt modules to choose from.


问:
Accessing variables from other class - If-Statment does not work
I have two classes, both "scanning" a name and a password from the user. When I try to check if they are correct, my if-statement always returns "false".

```<code>public class User{
   Scanner scan = new S...
   String username, pw;

   public void regis(){
      username = scan.nextLine();
      pw = scan.nextLine();
   }
   public String getUsername(){
      return username;
   }
   //same for getPw()..
}

public class Check{
   Scanner scan2 = new ...;
   User usr = new User();

   public void check(){
      String name, pass;
      System.out.print("name?");
      name = scan.nextLine();
      System.out.print("password?");
      pass = scan.nextLine();

      if(name.equals(usr.getUsername()) && pass.equals(usr.getPw())){
         return true;
      }else{
         return false;
      }
   }
}
</code>```

I always get "false" as result. I tried to set username and pw from class User to static and it worked. Why is my solution not working?

Thanks in advance.

答:
You are not calling the method on User

```<code>User usr = new User();
</code>```

then you need to call to get the values to fill username and pw

```<code>usr.regis ();
</code>```

Body:
I have two classes, both "scanning" a name and a password from the user. When I try to check if they are correct, my if-statement always returns "false".

public class User{
   Scanner scan = new S...
   String username, pw;

   public void regis(){
      username = scan.nextLine();
      pw = scan.nextLine();
   }
   public String getUsername(){
      return username;
   }
   //same for getPw()..
}

public class Check{
   Scanner scan2 = new ...;
   User usr = new User();

   public void check(){
      String name, pass;
      System.out.print("name?");
      name = scan.nextLine();
      System.out.print("password?");
      pass = scan.nextLine();

      if(name.equals(usr.getUsername()) && pass.equals(usr.getPw())){
         return true;
      }else{
         return false;
      }
   }
}

I always get "false" as result. I tried to set username and pw from class User to static and it worked. Why is my solution not working?

Thanks in advance.

Body:
You are not calling the method on User

User usr = new User();

then you need to call to get the values to fill username and pw

usr.regis ();


问:
What is the best practice for responsive website widths?
I have recently started learning how to use CSS media queries to develop websites that are responsive / mobile friendly however, I am not familiar with the best practices associated with determining which width ranges to develop designs for.

For example, I normally use three sets of CSS rules. One for a small width (mobile) , one for a medium width (tablet or small laptop screen) and one for a large width (desktop).

This is what it looks like in code:

```<code>@media screen and (min-width: 1495px)  {
//CSS RULES HERE
}

@media screen and (max-width: 1494px) and (min-width: 1245px) {
//CSS RULES HERE
}

@media screen and (max-width: 1244px) and (min-width: 751px) {
//CSS RULES HERE
}
</code>```

My sizing conventions (min width & max width) are completely arbitrary and I determine whether it works from trial and error. Often This doesn't work very well and I can't get the design to look good on all difference screen resolutions.

First of all.... Is there a best practice for the most ideal width ranges to use?

Secondly, is there a framework or template that will make all of this easier?

(That is not Bootstrap).

FYI: I use Foundation 6 to as a grid system but I haven't really found information much on responsive sites in Foundation 6.

答:
I usually go for a single breakpoint at 768px.
With that I go for three queries (and they worked out pretty well so far) :

desktop (min-width is 768) [sheet #1]

mobile (max-width is 768) [sheet #2]

portrait (according to orientation) [sheet #2]

I don't think there's really a strict and fixed set of breakpoints that everyone should be using, I feel like it's more depending on what you need for your website.

Although, if you still wanna have a look at a set of breakpoints, I have bookmarked this a long time ago : ResponsiveDesign.is - breakpoints

Body:
I have recently started learning how to use CSS media queries to develop websites that are responsive / mobile friendly however, I am not familiar with the best practices associated with determining which width ranges to develop designs for.

For example, I normally use three sets of CSS rules. One for a small width (mobile) , one for a medium width (tablet or small laptop screen) and one for a large width (desktop).

This is what it looks like in code:

@media screen and (min-width: 1495px)  {
//CSS RULES HERE
}

@media screen and (max-width: 1494px) and (min-width: 1245px) {
//CSS RULES HERE
}

@media screen and (max-width: 1244px) and (min-width: 751px) {
//CSS RULES HERE
}

My sizing conventions (min width & max width) are completely arbitrary and I determine whether it works from trial and error. Often This doesn't work very well and I can't get the design to look good on all difference screen resolutions.

First of all.... Is there a best practice for the most ideal width ranges to use?

Secondly, is there a framework or template that will make all of this easier?

(That is not Bootstrap).

FYI: I use Foundation 6 to as a grid system but I haven't really found information much on responsive sites in Foundation 6.


问:
Inserting and deleting into a linked list error
Writing the LinkedList class manually. Been trying to figure this out for a couple days. I need to be able to insert and delete Nodes from the list. Insertion and deletion seem to work fine until there are four or more Nodes in the list. After there are a few Nodes linked, values start to be inserted at the end of the list then mess up all insertions from there. For deletions, delete will sometimes 'delete' the first Node, making the second Node the new head. I can't see where the mistake is. I have main that implements the insert/delete methods. Below the code is sample output, but here is the code I have:

```<code>class SortedLinkedList {
private int size;
private Node head;

public SortedLinkedList() {
    size = 0;
    head = null;
} //constructor

public Node appropriatePosition(int k) {
    Node curr = head;

    if(head == null)
        return head;
    else if(curr.data >= k)
        return null;
    else if(curr.next == null)
        return curr;
    else if(curr.next.data > k)
        return curr;
    while(curr.next != null) { //null? write new if
        curr = curr.next;
        }
    return curr;
}

public void insert(int k) {
    Node appPos = appropriatePosition(k);
    Node insNode = new Node(k);

    if(appPos == null && head != null) {
        insNode.next = head;
        head = insNode;
    }
    else if(appPos == null && head == null)
        head = insNode;
    else {
        insNode.next = appPos.next;
        appPos.next = insNode;
    }
    size++;
}

public Node find(int p) {
    if(head == null)
        return null;
    if(head.data == p)
        return head;

    Node curr = head;
    Node prev = null;
    while(curr.data != p) {
        prev = curr;
        curr = curr.next;
        if(curr == null)
            return null;
        else if(curr.data > p) {
            System.out.println("Value not found");
            return curr;
        }
        else if(curr == null)
            return null;
    }
    return prev;
}

public void delete(int q) {
    Node findVal = find(q);
    if(head == null)
        System.out.println("Cannot delete: SortedLinkedList is empty");
    else if(findVal.data == head.data)
        head = head.next;
    else if(head.next == null)
        System.out.println("Cannot find value");
    else if(findVal == null)
            System.out.println("Cannot delete: SortedLinkedList is empty");
    else if(findVal.data > q)
        System.out.println("Value not found");
    else  {
        findVal.next = findVal.next.next;
        size--;
    }
}

class Node {
public Node next = null;
public int data;

public Node(int k){
    data = k;
}
public Node(Node s) {
    data = s.data;
    next = s;
}
}
</code>```

Sample output for insert:

Insert
Enter value: 2 Print:
2
Insert
Enter value: 5 Print:
2 5
Insert
Enter value: 5 Print:
2 5 5
Insert
Enter value: 7 Print:
2 5 5 7
Insert
Enter value: -9 Print:
-9 2 5 5 7
Insert
Enter value: -3 Print:
-9 -3 2 5 5 7
Insert
Enter value: 6 Print:
-9 -3 2 5 5 7 6
Insert
Enter value: 4 Print:
-9 -3 2 5 5 7 6 4
Insert
Enter value: 6
-9 -3 2 5 5 7 6 4 6

Sample output for delete:

Delete
Enter value: 7 Print:
-9 -3 2 5 5 6 4 6
Delete
Enter value: 2 Print:
-9 -3 5 5 6 4 6
Delete
Enter value: -3 Print:
-3 5 5 6 4 6
Delete
Enter value: -3 Print:
5 5 6 4 6

答:
Your delete was checking the wrong thing. This delete is simpler and does the trick

```<code>public void deleteNew(int p) {
        Node curr = head;
        Node prev = null;
        while (curr != null) {
            if (curr.data == p) {
                prev.next = curr.next;
                size--;
                break;
            }
            prev = curr;
            curr = curr.next;
        }
    }
</code>```

I will work on the insert next.

```<code>public void insertNew(int k){
    Node prev = null, curr = head;

    Node insert = null;
    if (head == null){
        head = new Node(k);
        size++;
    }
    else{
        while (curr != null) {
            if (curr.data > k) {
                insert = new Node(k);
                insert.next = curr;
                if (prev != null)
                    prev.next = insert;
                size++;
                if (insert.data < head.data)
                    head = insert;
                break;
            }
            prev = curr;
            curr = curr.next;
        }
    }
}
</code>```

Saving major omissions these should be simpler and doing what you need them to do. Tried with

```<code>SortedLinkedList l = new SortedLinkedList();
        l.insertNew(5);
        l.insertNew(4);
        l.insertNew(3);
        l.insertNew(2);
        l.insertNew(1);
        l.insertNew(0);
        l.deleteNew(5);
        l.deleteNew(1);
        l.insertNew(1);
</code>```

Body:
Writing the LinkedList class manually. Been trying to figure this out for a couple days. I need to be able to insert and delete Nodes from the list. Insertion and deletion seem to work fine until there are four or more Nodes in the list. After there are a few Nodes linked, values start to be inserted at the end of the list then mess up all insertions from there. For deletions, delete will sometimes 'delete' the first Node, making the second Node the new head. I can't see where the mistake is. I have main that implements the insert/delete methods. Below the code is sample output, but here is the code I have:

class SortedLinkedList {
private int size;
private Node head;

public SortedLinkedList() {
    size = 0;
    head = null;
} //constructor

public Node appropriatePosition(int k) {
    Node curr = head;

    if(head == null)
        return head;
    else if(curr.data >= k)
        return null;
    else if(curr.next == null)
        return curr;
    else if(curr.next.data > k)
        return curr;
    while(curr.next != null) { //null? write new if
        curr = curr.next;
        }
    return curr;
}

public void insert(int k) {
    Node appPos = appropriatePosition(k);
    Node insNode = new Node(k);

    if(appPos == null && head != null) {
        insNode.next = head;
        head = insNode;
    }
    else if(appPos == null && head == null)
        head = insNode;
    else {
        insNode.next = appPos.next;
        appPos.next = insNode;
    }
    size++;
}

public Node find(int p) {
    if(head == null)
        return null;
    if(head.data == p)
        return head;

    Node curr = head;
    Node prev = null;
    while(curr.data != p) {
        prev = curr;
        curr = curr.next;
        if(curr == null)
            return null;
        else if(curr.data > p) {
            System.out.println("Value not found");
            return curr;
        }
        else if(curr == null)
            return null;
    }
    return prev;
}

public void delete(int q) {
    Node findVal = find(q);
    if(head == null)
        System.out.println("Cannot delete: SortedLinkedList is empty");
    else if(findVal.data == head.data)
        head = head.next;
    else if(head.next == null)
        System.out.println("Cannot find value");
    else if(findVal == null)
            System.out.println("Cannot delete: SortedLinkedList is empty");
    else if(findVal.data > q)
        System.out.println("Value not found");
    else  {
        findVal.next = findVal.next.next;
        size--;
    }
}

class Node {
public Node next = null;
public int data;

public Node(int k){
    data = k;
}
public Node(Node s) {
    data = s.data;
    next = s;
}
}

Sample output for insert:

Insert
Enter value: 2 Print:
2
Insert
Enter value: 5 Print:
2 5
Insert
Enter value: 5 Print:
2 5 5
Insert
Enter value: 7 Print:
2 5 5 7
Insert
Enter value: -9 Print:
-9 2 5 5 7
Insert
Enter value: -3 Print:
-9 -3 2 5 5 7
Insert
Enter value: 6 Print:
-9 -3 2 5 5 7 6
Insert
Enter value: 4 Print:
-9 -3 2 5 5 7 6 4
Insert
Enter value: 6
-9 -3 2 5 5 7 6 4 6

Sample output for delete:

Delete
Enter value: 7 Print:
-9 -3 2 5 5 6 4 6
Delete
Enter value: 2 Print:
-9 -3 5 5 6 4 6
Delete
Enter value: -3 Print:
-3 5 5 6 4 6
Delete
Enter value: -3 Print:
5 5 6 4 6

Body:
Your delete was checking the wrong thing. This delete is simpler and does the trick

public void deleteNew(int p) {
        Node curr = head;
        Node prev = null;
        while (curr != null) {
            if (curr.data == p) {
                prev.next = curr.next;
                size--;
                break;
            }
            prev = curr;
            curr = curr.next;
        }
    }

I will work on the insert next.

public void insertNew(int k){
    Node prev = null, curr = head;

    Node insert = null;
    if (head == null){
        head = new Node(k);
        size++;
    }
    else{
        while (curr != null) {
            if (curr.data > k) {
                insert = new Node(k);
                insert.next = curr;
                if (prev != null)
                    prev.next = insert;
                size++;
                if (insert.data < head.data)
                    head = insert;
                break;
            }
            prev = curr;
            curr = curr.next;
        }
    }
}

Saving major omissions these should be simpler and doing what you need them to do. Tried with

SortedLinkedList l = new SortedLinkedList();
        l.insertNew(5);
        l.insertNew(4);
        l.insertNew(3);
        l.insertNew(2);
        l.insertNew(1);
        l.insertNew(0);
        l.deleteNew(5);
        l.deleteNew(1);
        l.insertNew(1);