问:
Properly Shutting Down ActiveMQ and Spring DefaultMessageListenerContainer
Our system will not shutdown when a "Stop" command is issued from the Tomcat Manager.  I have determined that it is related to ActiveMQ/Spring.  I have even figured out how to get it to shutdown, however my solution is a hack (at least I hope this isn't the "correct" way to do it).  I would like to know the proper way to shutdown ActiveMQ so that I can remove my hack.

I inherited this component and I have no information about why certain architectural decisions were made, after a lot of digging I think I understand his thoughts, but I could be missing something.  In other words, the real problem could be in the way that we are trying to use ActiveMQ/Spring.

We run in ServletContainer (Tomcat 6/7) and use ActiveMQ 5.9.1 and Spring 3.0.0  Multiple instances of our application can run in a "group", with each instance running on it's own server.  ActiveMQ is used to facilitate communication between the multiple instances.  Each instance has it's own embedded broker and it's own set of queues.  Every queue on every instance has exactly 1 org.springframework.jms.listener.DefaultMessageListenerContainer listening to it, so 5 queues = 5 DefaultMessageListenerContainers for example.

Our system shut down properly until we fixed a bug by adding queuePrefetch="0" to the ConnectionFactory.  At first I assumed that this change was incorrect in some way, but now that I understand the situation, I am confident that we should not be using the prefetch functionality.

I have created a test application to replicate the issue.  Note that the information below makes no mention of message producers.  That is because I can replicate the issue without ever sending/processing a single message.  Simply creating the Broker, ConnectionFactory, Queues and Listeners during boot, is enough to keep the system from stopping properly.

Here is my sample configuration from my Spring XML.  I will be happy to provide my entire project if someone wants it:

```<code><amq:broker persistent="false" id="mybroker">
 <amq:transportConnectors>
  <amq:transportConnector uri="tcp://0.0.0.0:61616"/>
 </amq:transportConnectors>
</amq:broker>

<amq:connectionFactory id="ConnectionFactory" brokerURL="vm://localhost?broker.persistent=false" >
 <amq:prefetchPolicy>
  <amq:prefetchPolicy queuePrefetch="0"/>
 </amq:prefetchPolicy>
</amq:connectionFactory>

<amq:queue id="lookup.mdb.queue.cat" physicalName="DogQueue"/>
<amq:queue id="lookup.mdb.queue.dog" physicalName="CatQueue"/>
<amq:queue id="lookup.mdb.queue.fish" physicalName="FishQueue"/>

<bean id="messageListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer" abstract="true">
 <property name="connectionFactory" ref="ConnectionFactory"/>
</bean>

<bean parent="messageListener" id="cat">
 <property name="destination" ref="lookup.mdb.queue.dog"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>

<bean parent="messageListener" id="dog">
 <property name="destination" ref="lookup.mdb.queue.cat"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>

<bean parent="messageListener" id="fish">
 <property name="destination" ref="lookup.mdb.queue.fish"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>
</code>```

My hack involves using a ServletContextListener to manually stop the objects.   The hacky part is that I have to create additional threads to stop the DefaultMessageListenerContainers.  Perhaps I'm stopping the objects in the wrong order, but I've tried everything that I can imagine.  If I attempt to stop the objects in the main thread, then they hang indefinitely.

Thank you in advance!

UPDATE
I have tried the following based on boday's recommendation but it didn't work.  I have also tried to specify the amq:transportConnector uri as tcp://0.0.0.0:61616?transport.daemon=true

```<code>  <amq:broker persistent="false" id="mybroker" brokerName="localhost">
   <amq:transportConnectors>
    <amq:transportConnector uri="tcp://0.0.0.0:61616?daemon=true"/>
   </amq:transportConnectors>
  </amq:broker>

  <amq:connectionFactory id="connectionFactory" brokerURL="vm://localhost" >
   <amq:prefetchPolicy>
    <amq:prefetchPolicy queuePrefetch="0"/>
   </amq:prefetchPolicy>
  </amq:connectionFactory>
</code>```

At one point I tried to add similar properties to the brokerUrl parameter in the amq:connectionFactory element and the shutdown worked properly, however after further testing I learned that the properties were resulting in an exception to be thrown from VMTransportFactory.  This resulted in improper initialization and the basic message functionality didn't work.

答:
In case anyone else is wondering, as far as I can see it's not possible to have a daemon ListenerContainer using ActiveMQ.

When the ActiveMQConnection is started, it creates a ThreadPoolExecutor with non-daemon thread. This is seemingly to avoid issues when failing over the connection from one broker to another.

https://issues.apache.org/jira/browse/AMQ-796

```<code>executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, "ActiveMQ Connection Executor: " + transport);
        //Don't make these daemon threads - see https://issues.apache.org/jira/browse/AMQ-796
        //thread.setDaemon(true);
        return thread;
    }
});
</code>```

Body:
Our system will not shutdown when a "Stop" command is issued from the Tomcat Manager.  I have determined that it is related to ActiveMQ/Spring.  I have even figured out how to get it to shutdown, however my solution is a hack (at least I hope this isn't the "correct" way to do it).  I would like to know the proper way to shutdown ActiveMQ so that I can remove my hack.

I inherited this component and I have no information about why certain architectural decisions were made, after a lot of digging I think I understand his thoughts, but I could be missing something.  In other words, the real problem could be in the way that we are trying to use ActiveMQ/Spring.

We run in ServletContainer (Tomcat 6/7) and use ActiveMQ 5.9.1 and Spring 3.0.0  Multiple instances of our application can run in a "group", with each instance running on it's own server.  ActiveMQ is used to facilitate communication between the multiple instances.  Each instance has it's own embedded broker and it's own set of queues.  Every queue on every instance has exactly 1 org.springframework.jms.listener.DefaultMessageListenerContainer listening to it, so 5 queues = 5 DefaultMessageListenerContainers for example.

Our system shut down properly until we fixed a bug by adding queuePrefetch="0" to the ConnectionFactory.  At first I assumed that this change was incorrect in some way, but now that I understand the situation, I am confident that we should not be using the prefetch functionality.

I have created a test application to replicate the issue.  Note that the information below makes no mention of message producers.  That is because I can replicate the issue without ever sending/processing a single message.  Simply creating the Broker, ConnectionFactory, Queues and Listeners during boot, is enough to keep the system from stopping properly.

Here is my sample configuration from my Spring XML.  I will be happy to provide my entire project if someone wants it:

<amq:broker persistent="false" id="mybroker">
 <amq:transportConnectors>
  <amq:transportConnector uri="tcp://0.0.0.0:61616"/>
 </amq:transportConnectors>
</amq:broker>

<amq:connectionFactory id="ConnectionFactory" brokerURL="vm://localhost?broker.persistent=false" >
 <amq:prefetchPolicy>
  <amq:prefetchPolicy queuePrefetch="0"/>
 </amq:prefetchPolicy>
</amq:connectionFactory>

<amq:queue id="lookup.mdb.queue.cat" physicalName="DogQueue"/>
<amq:queue id="lookup.mdb.queue.dog" physicalName="CatQueue"/>
<amq:queue id="lookup.mdb.queue.fish" physicalName="FishQueue"/>

<bean id="messageListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer" abstract="true">
 <property name="connectionFactory" ref="ConnectionFactory"/>
</bean>

<bean parent="messageListener" id="cat">
 <property name="destination" ref="lookup.mdb.queue.dog"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>

<bean parent="messageListener" id="dog">
 <property name="destination" ref="lookup.mdb.queue.cat"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>

<bean parent="messageListener" id="fish">
 <property name="destination" ref="lookup.mdb.queue.fish"/>
 <property name="messageListener">
  <bean class="com.acteksoft.common.remote.jms.WorkerMessageListener"/>
 </property>
 <property name="concurrentConsumers" value="200"/>
 <property name="maxConcurrentConsumers" value="200"/>
</bean>

My hack involves using a ServletContextListener to manually stop the objects.   The hacky part is that I have to create additional threads to stop the DefaultMessageListenerContainers.  Perhaps I'm stopping the objects in the wrong order, but I've tried everything that I can imagine.  If I attempt to stop the objects in the main thread, then they hang indefinitely.

Thank you in advance!

UPDATE
I have tried the following based on boday's recommendation but it didn't work.  I have also tried to specify the amq:transportConnector uri as tcp://0.0.0.0:61616?transport.daemon=true

  <amq:broker persistent="false" id="mybroker" brokerName="localhost">
   <amq:transportConnectors>
    <amq:transportConnector uri="tcp://0.0.0.0:61616?daemon=true"/>
   </amq:transportConnectors>
  </amq:broker>

  <amq:connectionFactory id="connectionFactory" brokerURL="vm://localhost" >
   <amq:prefetchPolicy>
    <amq:prefetchPolicy queuePrefetch="0"/>
   </amq:prefetchPolicy>
  </amq:connectionFactory>

At one point I tried to add similar properties to the brokerUrl parameter in the amq:connectionFactory element and the shutdown worked properly, however after further testing I learned that the properties were resulting in an exception to be thrown from VMTransportFactory.  This resulted in improper initialization and the basic message functionality didn't work.

Body:
In case anyone else is wondering, as far as I can see it's not possible to have a daemon ListenerContainer using ActiveMQ.

When the ActiveMQConnection is started, it creates a ThreadPoolExecutor with non-daemon thread. This is seemingly to avoid issues when failing over the connection from one broker to another.

https://issues.apache.org/jira/browse/AMQ-796

executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, "ActiveMQ Connection Executor: " + transport);
        //Don't make these daemon threads - see https://issues.apache.org/jira/browse/AMQ-796
        //thread.setDaemon(true);
        return thread;
    }
});


来源: stackexchange

问:
Complicated join in ActiveRecord
I'm having an issue with a tricky ActiveRecord query.

I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

```<code>class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false
</code>```

I'm trying to write a query that says, given a user_id, get all tasks where there is no Response from that User linked to it.

So if User 1 is querying, and he only has a Response to task 1, he should see all tasks except task 1.

答:
One possible solution is to use a subquery to select all Task records that the User has Response to and they will be excluded from the main query. This will give you all Task records that the User (params[:user_id]) doesn't have Response to</p>

```<code>Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Complicated join in ActiveRecord

Body:
I'm having an issue with a tricky ActiveRecord query.

I have three models, User, Task, and Response. A user submits responses to tasks. I'm using the has_many, through: pattern in ActiveRecord.

class Task < ApplicationRecord
  has_many :users, through: :responses
  has_many :responses

class User < ApplicationRecord
  has_many :responses
  has_many :tasks, through: :responses

class Response < ApplicationRecord
  belongs_to :task, optional: false
  belongs_to :user, optional: false

I'm trying to write a query that says, given a user_id, get all tasks where there is no Response from that User linked to it.

So if User 1 is querying, and he only has a Response to task 1, he should see all tasks except task 1.

Body:
One possible solution is to use a subquery to select all Task records that the User has Response to and they will be excluded from the main query. This will give you all Task records that the User (params[:user_id]) doesn't have Response to

Task.where.not(id: Response.select(:task_id).where(user_id: params[:user_id]))


问:
Async function inside a class
I get this error when I try to run an async function described in a class

masterClass.js

```<code>class MasterClass{

  async function updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}
</code>```

test.js

```<code>const MasterClass =  require('./MasterClass.js')
let m = new MasterClass()
m.updateData(a, b)
</code>```

Error

```<code>async function updateData(a, b){
                 ^^^^^^^^^^
SyntaxError: Unexpected identifier
</code>```

答:
You dont need function as pointed out by @dfsq in the comments

Then you have to use module.exports or export to exposed  your class as a module.

masterclass.js

```<code>module.exports = class MasterClass{

  async updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}
</code>```

Title: Async function inside a class

Body:
I get this error when I try to run an async function described in a class

masterClass.js

class MasterClass{

  async function updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}

test.js

const MasterClass =  require('./MasterClass.js')
let m = new MasterClass()
m.updateData(a, b)

Error

async function updateData(a, b){
                 ^^^^^^^^^^
SyntaxError: Unexpected identifier

Body:
You dont need function as pointed out by @dfsq in the comments

Then you have to use module.exports or export to exposed  your class as a module.

masterclass.js

module.exports = class MasterClass{

  async updateData(a, b){
    let [ res1, res2 ] = await Promise.all(call1, call2);
    return  [ res1, res2 ]
  }

}


问:
How can mongodb handle ObjectId timestamp beyond Tue, 19 Jan 2038?
As per MongoDB official docs, it states that:

ObjectId values consists of 12-bytes, where the first four bytes are a
  timestamp that reflect the ObjectId’s creation, specifically:

a 4-byte value representing the seconds since the Unix epoch,

a 3-byte machine identifier,

a 2-byte process id, and

a 3-byte counter, starting with a random value.

I'm just wondering what's gonna happen on Tue, 19 Jan 2038 03:14:08 GMT when the unix time will be equal to 2147483648 which doesn't fit the 4-byte timestamp in ObjectId *philosoraptor meme*

答:
Unsigned 2,147,483,648 perfectly fits into 4 bytes. 4 bytes is enough to hold values up to 4,294,967,295, which is a unix epoch for Sunday, 7 February 2106 06:28:16 GMT.

If ObjectID's survive without changes till then, the timestamp part will start from 0, if you care:

```<code>> new Date();
ISODate("2106-02-08T12:41:20.450Z")

> db.t.insert({welcome:"from the future"});
WriteResult({ "nInserted" : 1 })

> db.t.find().pretty();
{
    "_id" : ObjectId("0001a7b306c389186a3a9323"),
    "welcome" : "from the future"
}

> db.t.find()[0]._id.getTimestamp();
ISODate("1970-01-02T06:07:47Z")
</code>```

Body:
Unsigned 2,147,483,648 perfectly fits into 4 bytes. 4 bytes is enough to hold values up to 4,294,967,295, which is a unix epoch for Sunday, 7 February 2106 06:28:16 GMT.

If ObjectID's survive without changes till then, the timestamp part will start from 0, if you care:

> new Date();
ISODate("2106-02-08T12:41:20.450Z")

> db.t.insert({welcome:"from the future"});
WriteResult({ "nInserted" : 1 })

> db.t.find().pretty();
{
    "_id" : ObjectId("0001a7b306c389186a3a9323"),
    "welcome" : "from the future"
}

> db.t.find()[0]._id.getTimestamp();
ISODate("1970-01-02T06:07:47Z")


问:
How can I multiply a with either b or c after I solved my initial out of bounds exception
I am new to Java programming and I want to make a program of calculating the speed of a car in relation of the gear and the RPM.

I searched different sites or topics, but couldn't find something. Maybe the answer was there, but I haven't seen it :D.

A little but not complete program for example:

```<code>import java.util.Scanner;

public class Speed {
    public static void main(String[] args) {

        double Gear, MPH, RPM
        double TireDia = 78;
        double Pi = 3.1415;
        double RatioGearOne = 3.4;
        double RatioGearTwo = 2.5;
        double RatioGearThree = 1.6;

        Scanner input = new
        Scanner (System.in);

        System.out.println("What gear is it in?");
        Gear = input.nextDouble();

        System.out.println("How many RPM are shown?");
        RPM = input.nextDouble();

        MPH = Gear * RPM * Pi * TireDia * 60 / 1000000;
        System.out.println("The car is going: " + MPH + " MPH");
    }
}
</code>```

Like I asked, I want that you can enter Gear 1 or Gear 2 or Gear 3 multiplied by PRM, Pi, etc to display me the MPH.
I read that you can do this with an array too, but i want it line that for now, cause I understand it a bit more at the time.

I hope you can help me.

UPDATE:

I got it working as I want it for now and cleaned it a bit with your suggestions. Now I need to figure out how I get around the out of bounds error, but havent figured it out how, (searching for hours by now) and get the speed in a whole number.
Thanks for help so far.

This is my current Program:

```<code>import java.util.Scanner;

public class geschwindigkeitAuto {
public static void main(String[] args) {

    double gang, kmh, upm;

    Scanner input = new Scanner (System.in);

    double[] übersetzungen = {3.7, 1.95, 1.3, 1.03, 0.84, 0.68};

    System.out.println("Welcher Gang ist Eingelegt? (wähle 1 bis 6): ");
    gang = input.nextInt();

    System.out.println("Wieviele Umdrehungen werden angezeigt? (wähle 0-6500): ");
    upm = input.nextInt();

    kmh = upm / übersetzungen[(int)gang -1] / 3.62 * 68 * 3.141 * 60 / 100000;
    System.out.print("Die Geschwindigkeit des Autos beträgt: " + kmh + " kmh");
}
}
</code>```

UPDATE 2

I have searched more and watched some videos for the OutOfBoundExcenption to avoid and I have found a solution so that I cannot input less than 1 or more than 6 to my program without failing.
The only thing is now, how to tell the user to input a different number after he made a wrong choise instead of fist going through the whoule sequenz.

```<code>import java.util.Scanner;

public class geschwindigkeitAuto {
public static void main(String[] args) {
    double gang, kmh = 0, upm;

    Scanner input = new Scanner (System.in);

    double[] übersetzungen = {3.7, 1.95, 1.3, 1.03, 0.84, 0.68};

    System.out.println("Welcher Gang ist Eingelegt? (wähle Gang 1 bis 6): ");
    gang = input.nextInt();

    System.out.println("Wieviele Umdrehungen werden angezeigt? (wähle 0-6500): ");
    upm = input.nextInt();

    try {
        kmh = upm / übersetzungen[(int)gang -1] / 3.62 * 68 * 3.141 * 60 / 100000; }
    catch(ArrayIndexOutOfBoundsException ex) {
        System.out.println("Du hast einen nicht vorhandenen Gang gewählt! "
        + "Es gibt nur 6 Gänge zur Auswahl" + "\n"); }

    System.out.println("Die Geschwindigkeit des Autos beträgt: " + kmh + " kmh" + "\n");

    System.out.print("Noch eine Berechnung? (J/N) : ");
    System.out.printf("\n");
    String var= input.next();
        if(var.equalsIgnoreCase("J")) {
        main(null);
    }
}
}
</code>```

答:
If you’re adamant that you don’t want to use an array then you can use a switch statement:

```<code>switch(gear) {
     case 1: ratioGearOne * ...
     case 2: ratioGearTwo * ...
     ...
}
</code>```

etc etc. You’ll also need a default: that’s run whenever the input doesn’t conform to one of the cases (e.g. print an error).

If you were to use an array you could do it like this:

```<code>double[] ratios = { 3.4, 2.5, 1.6 }
</code>```

Then you could calculate the MPH like so:

```<code>MPH = ratios[gear - 1] * ...
</code>```

Note you need to subtract one from the gear since array indexes start from 0. I believe you’d also need to change your gear variable to an int (use nextInt()) since you can’t have half an index.

As other commenters have said I’d strongly recommend reading up on Java conventions (particularly variable naming) before getting into any bad habits.

Body:
I am new to Java programming and I want to make a program of calculating the speed of a car in relation of the gear and the RPM.

I searched different sites or topics, but couldn't find something. Maybe the answer was there, but I haven't seen it :D.

A little but not complete program for example:

import java.util.Scanner;

public class Speed {
    public static void main(String[] args) {

        double Gear, MPH, RPM
        double TireDia = 78;
        double Pi = 3.1415;
        double RatioGearOne = 3.4;
        double RatioGearTwo = 2.5;
        double RatioGearThree = 1.6;

        Scanner input = new
        Scanner (System.in);

        System.out.println("What gear is it in?");
        Gear = input.nextDouble();

        System.out.println("How many RPM are shown?");
        RPM = input.nextDouble();

        MPH = Gear * RPM * Pi * TireDia * 60 / 1000000;
        System.out.println("The car is going: " + MPH + " MPH");
    }
}

Like I asked, I want that you can enter Gear 1 or Gear 2 or Gear 3 multiplied by PRM, Pi, etc to display me the MPH.
I read that you can do this with an array too, but i want it line that for now, cause I understand it a bit more at the time.

I hope you can help me.

UPDATE:

I got it working as I want it for now and cleaned it a bit with your suggestions. Now I need to figure out how I get around the out of bounds error, but havent figured it out how, (searching for hours by now) and get the speed in a whole number.
Thanks for help so far.

This is my current Program:

import java.util.Scanner;

public class geschwindigkeitAuto {
public static void main(String[] args) {

    double gang, kmh, upm;

    Scanner input = new Scanner (System.in);

    double[] übersetzungen = {3.7, 1.95, 1.3, 1.03, 0.84, 0.68};

    System.out.println("Welcher Gang ist Eingelegt? (wähle 1 bis 6): ");
    gang = input.nextInt();

    System.out.println("Wieviele Umdrehungen werden angezeigt? (wähle 0-6500): ");
    upm = input.nextInt();

    kmh = upm / übersetzungen[(int)gang -1] / 3.62 * 68 * 3.141 * 60 / 100000;
    System.out.print("Die Geschwindigkeit des Autos beträgt: " + kmh + " kmh");
}
}

UPDATE 2

I have searched more and watched some videos for the OutOfBoundExcenption to avoid and I have found a solution so that I cannot input less than 1 or more than 6 to my program without failing.
The only thing is now, how to tell the user to input a different number after he made a wrong choise instead of fist going through the whoule sequenz.

import java.util.Scanner;

public class geschwindigkeitAuto {
public static void main(String[] args) {
    double gang, kmh = 0, upm;

    Scanner input = new Scanner (System.in);

    double[] übersetzungen = {3.7, 1.95, 1.3, 1.03, 0.84, 0.68};

    System.out.println("Welcher Gang ist Eingelegt? (wähle Gang 1 bis 6): ");
    gang = input.nextInt();

    System.out.println("Wieviele Umdrehungen werden angezeigt? (wähle 0-6500): ");
    upm = input.nextInt();

    try {
        kmh = upm / übersetzungen[(int)gang -1] / 3.62 * 68 * 3.141 * 60 / 100000; }
    catch(ArrayIndexOutOfBoundsException ex) {
        System.out.println("Du hast einen nicht vorhandenen Gang gewählt! "
        + "Es gibt nur 6 Gänge zur Auswahl" + "\n"); }

    System.out.println("Die Geschwindigkeit des Autos beträgt: " + kmh + " kmh" + "\n");

    System.out.print("Noch eine Berechnung? (J/N) : ");
    System.out.printf("\n");
    String var= input.next();
        if(var.equalsIgnoreCase("J")) {
        main(null);
    }
}
}

Body:
If you’re adamant that you don’t want to use an array then you can use a switch statement:

switch(gear) {
     case 1: ratioGearOne * ...
     case 2: ratioGearTwo * ...
     ...
}

etc etc. You’ll also need a default: that’s run whenever the input doesn’t conform to one of the cases (e.g. print an error).

If you were to use an array you could do it like this:

double[] ratios = { 3.4, 2.5, 1.6 }

Then you could calculate the MPH like so:

MPH = ratios[gear - 1] * ...

Note you need to subtract one from the gear since array indexes start from 0. I believe you’d also need to change your gear variable to an int (use nextInt()) since you can’t have half an index.

As other commenters have said I’d strongly recommend reading up on Java conventions (particularly variable naming) before getting into any bad habits.


问:
Nodejs: Wait for a promise to get resolved
In this code, variables adminName and adminPassword should get values before the execution of if statements. But if statements are executing before the then handler function. thats why the validation not working.

```<code>function validateAdminLogin()
{

var adminName="";
var adminPassword="";

var isValid=true;

var UserDAO = require('./js/DAO/UserDAO');
var wait=require('wait.for-es6');
var admin=document.getElementById("adminform").elements.namedItem("username").value;
var adminPwd=document.getElementById("adminform").elements.namedItem("pwd").value;

    UserDAO.getAdminCredentials().then(function(rows){

    adminName= rows.username;
    adminPassword=rows.password;

    alert(admin+"----"+adminName);

    },function(error){
    alert(error);
    console.log(error);
    });

    //alert(admin+"-------"+adminName);

if(admin!==adminName)
{
alert("Invalid username");
isValid=false;
}

if(adminPwd!==adminPassword)
{
alert("Invalid password");
isValid=false;
}

return isValid;
}
</code>```

I'm also including the code in which I've written the promise.

```<code>getAdminCredentials: function()
{
    var deferred = q.defer();

    $query =  "SELECT * FROM `user` where type='administrator' ";

    connection.connect(function(err) {

        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }

     // console.log("Successfully connected.");
    });

    connection.query($query, function(err, rows, fields) {
        if(err){
            console.log("An error ocurred performing the query.");
            console.log(err);
            deferred.reject(err);
            return;
        }
        else
            {
             console.log("Query succesfully executed");
            userDTO.setUserId(rows[0].user_id);
           userDTO.setUsername(rows[0].username);
           userDTO.setPassword(rows[0].password);

           deferred.resolve(userDTO);

            }

    });

    return deferred.promise;

    connection.end();
}
</code>```

How do I deal with this asynchronous nature of nodejs? Please help.

答:
You simply have to put your if statement inside the then() statement.

Everything that needs the credentials should be put in the then or in other following then().
For example, you might return your promise:

```<code>return UserDAO.getAdminCredentials().then(function(rows){ ...
</code>```

and when calling your function add a then() to it:

```<code>validateAdminLogin().then( ... )
</code>```

Body:
In this code, variables adminName and adminPassword should get values before the execution of if statements. But if statements are executing before the then handler function. thats why the validation not working.

function validateAdminLogin()
{

var adminName="";
var adminPassword="";

var isValid=true;

var UserDAO = require('./js/DAO/UserDAO');
var wait=require('wait.for-es6');
var admin=document.getElementById("adminform").elements.namedItem("username").value;
var adminPwd=document.getElementById("adminform").elements.namedItem("pwd").value;

    UserDAO.getAdminCredentials().then(function(rows){

    adminName= rows.username;
    adminPassword=rows.password;

    alert(admin+"----"+adminName);

    },function(error){
    alert(error);
    console.log(error);
    });

    //alert(admin+"-------"+adminName);

if(admin!==adminName)
{
alert("Invalid username");
isValid=false;
}

if(adminPwd!==adminPassword)
{
alert("Invalid password");
isValid=false;
}

return isValid;
}

I'm also including the code in which I've written the promise.

getAdminCredentials: function()
{
    var deferred = q.defer();

    $query =  "SELECT * FROM `user` where type='administrator' ";

    connection.connect(function(err) {

        if(err){
            console.log(err.code);
            console.log(err.fatal);
        }

     // console.log("Successfully connected.");
    });

    connection.query($query, function(err, rows, fields) {
        if(err){
            console.log("An error ocurred performing the query.");
            console.log(err);
            deferred.reject(err);
            return;
        }
        else
            {
             console.log("Query succesfully executed");
            userDTO.setUserId(rows[0].user_id);
           userDTO.setUsername(rows[0].username);
           userDTO.setPassword(rows[0].password);

           deferred.resolve(userDTO);

            }

    });

    return deferred.promise;

    connection.end();
}

How do I deal with this asynchronous nature of nodejs? Please help.

Body:
You simply have to put your if statement inside the then() statement.

Everything that needs the credentials should be put in the then or in other following then().
For example, you might return your promise:

return UserDAO.getAdminCredentials().then(function(rows){ ...

and when calling your function add a then() to it:

validateAdminLogin().then( ... )


问:
What would be a use case for Thread.Sleep(Timeout.Infinite)?
I happened to lay my eyes on an intellisense tool tip regarding the parameter passed to System.Threading.Thread.Sleep(int millisecondsTimeout), saying something like "(…) Specify System.Threading.Timeout.Infinite to block the thread indefinitely". And I am intrigued.

I can understand why one might include short inactive delays within a possibly endless loop, thus yielding processing power to other executing threads when no immediate action in the sleeping thread is required, although I typically prefer implementing such delays with EventWaitHandlers so that I can avoid waiting a full sleeping delay if I signal the thread to gracefully end its execution from a different thread.

But I cannot see when I might need to suspend a thread indefinitely, and in a way that, as far as I can tell, can only be interrupted through a rather ungraceful Thread.Abort()/ThreadAbortException pair.

So what would be a working scenario where I might want to suspend a thread indefinitely?

答: You can use .Interrupt() to wake a sleeping thread (causing ThreadInterruptedException in the code that was calling .Sleep(), which can be caught and handled), so this provides a mechanism to say "sleep until someone prods you". I'm not saying it is necessarily the best mechanism for this, but: it may have uses for you.


问:
Appending a XML fragment in Another xml in Python
Need to read a CSV file and using the details in it need to create an XML snippet, That needs to be placed in another snippet of XML in a particular area(Inside a node).
The first portion is completed. Need to do the second portion. need some help in this area. Also the result needs to write in the new XML file.

import csv
import lxml.etree as ET
import xml.etree.cElementTree as ETT
from lxml import etree, html

csvFile = open('parameters.csv')
readCsv = csv.reader(csvFile)
data = []

for row in readCsv:
    data.append(row)
csvFile.close()

def convert_row(row):
    return """<hashTree><TransactionController guiclass="TransactionControllerGui" testclass="TransactionController" testname="%s" enabled="true">
          <boolProp name="TransactionController.includeTimers">false</boolProp>
          <boolProp name="TransactionController.parent">false</boolProp>
        </TransactionController>
        <hashTree>
          <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true">
            <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
              <collectionProp name="Arguments.arguments" />
            </elementProp>
            <stringProp name="HTTPSampler.domain">"%s"
            </stringProp>
            <stringProp name="HTTPSampler.port">
            </stringProp>
            <stringProp name="HTTPSampler.protocol">
            </stringProp>
            <stringProp name="HTTPSampler.contentEncoding">
            </stringProp>
            <stringProp name="HTTPSampler.path">"%s"
            </stringProp>
            <stringProp name="HTTPSampler.method">"%s"</stringProp>
            <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
            <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
            <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
            <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
            <stringProp name="HTTPSampler.embedded_url_re">
            </stringProp>
            <stringProp name="HTTPSampler.connect_timeout">
            </stringProp>
            <stringProp name="HTTPSampler.response_timeout">
            </stringProp>
          </HTTPSamplerProxy>
        </hashTree>
        </hashTree>"""%(row[0],row[1],row[2],row[3])

fragment = '\n'.join([convert_row(row) for row in data[1:]])

TF = ET.parse('testXml.xml')
content = TF.findall("//jmeterTestPlan/hashTree/hashTree/hashTree/")
content.append(fragment)

print(content)```

答:
You need to convert string to XML before appending.</p>

```<code>fragment = '\n'.join([convert_row(row) for row in data[1:]])
aet=ET.fromstring(fragment)
TF = ET.ElementTree(file='testXml.xml')
for child in TF.xpath('//jmeterTestPlan/hashTree/hashTree[1]'):
child.append(aet)
TF.write('out.jmx')
</code>```

Body:
You need to convert string to XML before appending.

fragment = '\n'.join([convert_row(row) for row in data[1:]])
aet=ET.fromstring(fragment)
TF = ET.ElementTree(file='testXml.xml')
for child in TF.xpath('//jmeterTestPlan/hashTree/hashTree[1]'):
child.append(aet)
TF.write('out.jmx')


问:
JavaFX - How to focus keyboard input within one Pane contained in a Hbox with other panes
The situation is described in the following picture :
enter image description here

It's a simple game where I need to use "←" or "→" on the keyboard to move the player's brick,however when I do so the application's focus simply moved to the levelPane or the infoPane, is there any way to explicitly allow only the gamePane to receive keyboard input and the level pane will only be focused if I use my mouse and clicked on it?

Javafx code below:

```<code>public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Game.fxml"));
    Parent page = loader.load();
    Scene scene = new Scene(page);

    Pane levelPane = (Pane)loader.getNamespace().get("levelPane");
    Pane gamePane = (Pane)loader.getNamespace().get("gamePane");
    Pane infoPane = (Pane)loader.getNamespace().get("infoPane");

    Button lv1 = (Button)loader.getNamespace().get("level1");
    Button lv2 = (Button)loader.getNamespace().get("level2");
    Button lv3 = (Button)loader.getNamespace().get("level3");
    Button lv4 = (Button)loader.getNamespace().get("level4");
    Button lv5 = (Button)loader.getNamespace().get("level5");

    Label info = (Label)loader.getNamespace().get("info");

    levelPane.setFocusTraversable(false);
    infoPane.setFocusTraversable(false);
    //gamePane.setFocusTraversable(true);

    gamePane.requestFocus();

    Circle ball = new Circle(10, Color.CADETBLUE);
    ball.relocate(5, 5);

    Rectangle playerBrick = new Rectangle(Data.PLAYER_BRICK_LENGTH,Data.PLAYER_BRICK_WEIGTH,Color.BLACK);
    playerBrick.setArcWidth(20);
    playerBrick.setArcHeight(20);
    playerBrick.setX(150);
    playerBrick.setY(350);

    ArryList<Rectangle> breakableBricks = new ArryList<Rectangle>();

    for (int i = 0; i < Data.BRICK_COUNT ; i++){
        breakableBricks.add(new Rectangle(Data.B_B_LENGTH,Data.B_B_WEIGTH,Color.RED));
        breakableBricks[i].setArcWidth(20);
        breakableBricks[i].setArcHeight(20);
        if(i%5 == 0){
            pixelCountY += Data.B_B_WEIGTH + 10;
        }
        playerBrick.setX(pixelCountX);
        playerBrick.setY(pixelCountY);
        pixelCountX += Data.B_B_LENGTH + 10;
    }

    gamePane.getChildren().add(ball);
    gamePane.getChildren().add(playerBrick);
    gamePane.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));

    gamePane.setOnKeyPressed(new EventHandler<KeyEvent>(){
        @Override
        public void handle(KeyEvent event){
            switch (event.getCode()){
                case LEFT: goLeft = true;break;
                case RIGHT: goRight = true;break;
            }
        }
    });

    gamePane.setOnKeyReleased(new EventHandler<KeyEvent>(){
        @Override
        public void handle(KeyEvent event){
            switch (event.getCode()){
                case LEFT: goLeft = false;break;
                case RIGHT: goRight = false;break;
            }
        }
    });

    primaryStage.setScene(scene);
    primaryStage.show();

    Timeline timeline = new Timeline(new KeyFrame(Duration.millis(20),new EventHandler<ActionEvent>() {

        double dx = Data.HORIZONTAL_VELOCITY; //Step on x or velocity
        double dy = Data.VERTICAL_VELOCITY; //Step on y
        double playerBrickSpeed = Data.PLAYER_BRICK_S;//Player Brick moving speed

        @Override
        public void handle(ActionEvent t) {
            //move the ball
            ball.setLayoutX(ball.getLayoutX() + dx);
            ball.setLayoutY(ball.getLayoutY() + dy);

            Bounds bounds = gamePane.getBoundsInLocal();
            Bounds brickB = playerBrick.getLayoutBounds();

            //If the ball reaches the left or right border make the step negative
            if(ball.getLayoutX() <= (bounds.getMinX() + ball.getRadius()) ||
                    ball.getLayoutX() >= (bounds.getMaxX() - ball.getRadius()) ){

                dx = -dx;

            }

            //If the ball reeaches the brick's wall makes the ball bounce
            if(ball.getLayoutY() < brickB.getMaxY() & ball.getLayoutY() > brickB.getMinY()){
                if(ball.getLayoutX() > brickB.getMinX() - Data.HORIZONTAL_VELOCITY & ball.getLayoutX() < brickB.getMinX() + Data.HORIZONTAL_VELOCITY  || ball.getLayoutX() > brickB.getMaxX() - Data.HORIZONTAL_VELOCITY & ball.getLayoutX() < brickB.getMaxX() + Data.HORIZONTAL_VELOCITY ){
                    dx = -dx;
                }
            }

            if(ball.getLayoutX() > brickB.getMinX() & ball.getLayoutX() < brickB.getMaxX()){
                if(ball.getLayoutY() < brickB.getMaxY() + Data.VERTICAL_VELOCITY & ball.getLayoutY() > brickB.getMaxY() - Data.VERTICAL_VELOCITY || ball.getLayoutY() > brickB.getMinY() - Data.VERTICAL_VELOCITY & ball.getLayoutY() < brickB.getMinY() + Data.VERTICAL_VELOCITY){
                    dy = -dy;
                }
            }

            //If the ball reaches the bottom or top border make the step negative
            if((ball.getLayoutY() >= (bounds.getMaxY() - ball.getRadius())) ||
                    (ball.getLayoutY() <= (bounds.getMinY() + ball.getRadius()))){

                dy = -dy;

            }
            //Moving the player's brick
            if(goRight & brickB.getMaxX() < bounds.getMaxX() + Data.PLAYER_BRICK_S & goRight & brickB.getMaxX() < bounds.getMaxX() - Data.PLAYER_BRICK_S){
                playerBrick.setX(playerBrick.getX() + Data.PLAYER_BRICK_S);
            }

            if(goLeft & brickB.getMinX() > bounds.getMinX() + Data.PLAYER_BRICK_S & goLeft & brickB.getMinX() > bounds.getMinX() - Data.PLAYER_BRICK_S){
                playerBrick.setX(playerBrick.getX() - Data.PLAYER_BRICK_S);
            }

        }
    }));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();
}
</code>```

答:
Can't help much unless you show your code but I think you should use GamePane.requestFocus() or brick.requestFocus() to make the GamePane/brick listen to your keyboard inputs.

According to the Javadoc for Node, the node.requestFocus() method

Requests that this Node get the input focus, and that this Node's
  top-level ancestor become the focused window.

Body:
The situation is described in the following picture :
enter image description here

It's a simple game where I need to use "←" or "→" on the keyboard to move the player's brick,however when I do so the application's focus simply moved to the levelPane or the infoPane, is there any way to explicitly allow only the gamePane to receive keyboard input and the level pane will only be focused if I use my mouse and clicked on it?

Javafx code below:

public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Game.fxml"));
    Parent page = loader.load();
    Scene scene = new Scene(page);

    Pane levelPane = (Pane)loader.getNamespace().get("levelPane");
    Pane gamePane = (Pane)loader.getNamespace().get("gamePane");
    Pane infoPane = (Pane)loader.getNamespace().get("infoPane");

    Button lv1 = (Button)loader.getNamespace().get("level1");
    Button lv2 = (Button)loader.getNamespace().get("level2");
    Button lv3 = (Button)loader.getNamespace().get("level3");
    Button lv4 = (Button)loader.getNamespace().get("level4");
    Button lv5 = (Button)loader.getNamespace().get("level5");

    Label info = (Label)loader.getNamespace().get("info");

    levelPane.setFocusTraversable(false);
    infoPane.setFocusTraversable(false);
    //gamePane.setFocusTraversable(true);

    gamePane.requestFocus();

    Circle ball = new Circle(10, Color.CADETBLUE);
    ball.relocate(5, 5);

    Rectangle playerBrick = new Rectangle(Data.PLAYER_BRICK_LENGTH,Data.PLAYER_BRICK_WEIGTH,Color.BLACK);
    playerBrick.setArcWidth(20);
    playerBrick.setArcHeight(20);
    playerBrick.setX(150);
    playerBrick.setY(350);

    ArryList<Rectangle> breakableBricks = new ArryList<Rectangle>();

    for (int i = 0; i < Data.BRICK_COUNT ; i++){
        breakableBricks.add(new Rectangle(Data.B_B_LENGTH,Data.B_B_WEIGTH,Color.RED));
        breakableBricks[i].setArcWidth(20);
        breakableBricks[i].setArcHeight(20);
        if(i%5 == 0){
            pixelCountY += Data.B_B_WEIGTH + 10;
        }
        playerBrick.setX(pixelCountX);
        playerBrick.setY(pixelCountY);
        pixelCountX += Data.B_B_LENGTH + 10;
    }

    gamePane.getChildren().add(ball);
    gamePane.getChildren().add(playerBrick);
    gamePane.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.SOLID, CornerRadii.EMPTY, BorderWidths.DEFAULT)));

    gamePane.setOnKeyPressed(new EventHandler<KeyEvent>(){
        @Override
        public void handle(KeyEvent event){
            switch (event.getCode()){
                case LEFT: goLeft = true;break;
                case RIGHT: goRight = true;break;
            }
        }
    });

    gamePane.setOnKeyReleased(new EventHandler<KeyEvent>(){
        @Override
        public void handle(KeyEvent event){
            switch (event.getCode()){
                case LEFT: goLeft = false;break;
                case RIGHT: goRight = false;break;
            }
        }
    });

    primaryStage.setScene(scene);
    primaryStage.show();

    Timeline timeline = new Timeline(new KeyFrame(Duration.millis(20),new EventHandler<ActionEvent>() {

        double dx = Data.HORIZONTAL_VELOCITY; //Step on x or velocity
        double dy = Data.VERTICAL_VELOCITY; //Step on y
        double playerBrickSpeed = Data.PLAYER_BRICK_S;//Player Brick moving speed

        @Override
        public void handle(ActionEvent t) {
            //move the ball
            ball.setLayoutX(ball.getLayoutX() + dx);
            ball.setLayoutY(ball.getLayoutY() + dy);

            Bounds bounds = gamePane.getBoundsInLocal();
            Bounds brickB = playerBrick.getLayoutBounds();

            //If the ball reaches the left or right border make the step negative
            if(ball.getLayoutX() <= (bounds.getMinX() + ball.getRadius()) ||
                    ball.getLayoutX() >= (bounds.getMaxX() - ball.getRadius()) ){

                dx = -dx;

            }

            //If the ball reeaches the brick's wall makes the ball bounce
            if(ball.getLayoutY() < brickB.getMaxY() & ball.getLayoutY() > brickB.getMinY()){
                if(ball.getLayoutX() > brickB.getMinX() - Data.HORIZONTAL_VELOCITY & ball.getLayoutX() < brickB.getMinX() + Data.HORIZONTAL_VELOCITY  || ball.getLayoutX() > brickB.getMaxX() - Data.HORIZONTAL_VELOCITY & ball.getLayoutX() < brickB.getMaxX() + Data.HORIZONTAL_VELOCITY ){
                    dx = -dx;
                }
            }

            if(ball.getLayoutX() > brickB.getMinX() & ball.getLayoutX() < brickB.getMaxX()){
                if(ball.getLayoutY() < brickB.getMaxY() + Data.VERTICAL_VELOCITY & ball.getLayoutY() > brickB.getMaxY() - Data.VERTICAL_VELOCITY || ball.getLayoutY() > brickB.getMinY() - Data.VERTICAL_VELOCITY & ball.getLayoutY() < brickB.getMinY() + Data.VERTICAL_VELOCITY){
                    dy = -dy;
                }
            }

            //If the ball reaches the bottom or top border make the step negative
            if((ball.getLayoutY() >= (bounds.getMaxY() - ball.getRadius())) ||
                    (ball.getLayoutY() <= (bounds.getMinY() + ball.getRadius()))){

                dy = -dy;

            }
            //Moving the player's brick
            if(goRight & brickB.getMaxX() < bounds.getMaxX() + Data.PLAYER_BRICK_S & goRight & brickB.getMaxX() < bounds.getMaxX() - Data.PLAYER_BRICK_S){
                playerBrick.setX(playerBrick.getX() + Data.PLAYER_BRICK_S);
            }

            if(goLeft & brickB.getMinX() > bounds.getMinX() + Data.PLAYER_BRICK_S & goLeft & brickB.getMinX() > bounds.getMinX() - Data.PLAYER_BRICK_S){
                playerBrick.setX(playerBrick.getX() - Data.PLAYER_BRICK_S);
            }

        }
    }));
    timeline.setCycleCount(Timeline.INDEFINITE);
    timeline.play();
}


问:
Use a pipe which depends on a service in another service
In a service A, I need to use a pipe P. This pipe P needs a service B to work.  What I did so far in something like this:

My P pipe definition

```<code>export class PPipe implements PipeTransform {

  constructor(private aService: AService) {}

  transform(value:number) : string {
    return number.toString();
  }
}
</code>```

How I use it in my service B

```<code>@Injectable()
export class BService {

  pPipe = new PPipe();

  myFn() {
    const nbToStr = pPipe.transform(69);
  }
}
</code>```

But I get an error when building: Expected 1 arguments, but got 0..

Do I need to pass an instance of PPipe everytime I want to use it ? If so, how it is doable from a HTML template ?

Thanks for helping

答:
You need to inject the pipe.
If you create something with new yourself, Angulars DI has no way to interact.

```<code>export class BService {
  constructor(private pPipe:PPipe) {}
</code>```

This way Angular creates a PPipe instance and passes dependencies to its constructor.

Body:
In a service A, I need to use a pipe P. This pipe P needs a service B to work.  What I did so far in something like this:

My P pipe definition

export class PPipe implements PipeTransform {

  constructor(private aService: AService) {}

  transform(value:number) : string {
    return number.toString();
  }
}

How I use it in my service B

@Injectable()
export class BService {

  pPipe = new PPipe();

  myFn() {
    const nbToStr = pPipe.transform(69);
  }
}

But I get an error when building: Expected 1 arguments, but got 0..

Do I need to pass an instance of PPipe everytime I want to use it ? If so, how it is doable from a HTML template ?

Thanks for helping

Body:
You need to inject the pipe.
If you create something with new yourself, Angulars DI has no way to interact.

export class BService {
  constructor(private pPipe:PPipe) {}

This way Angular creates a PPipe instance and passes dependencies to its constructor.


问:
In Python, when to use a Dictionary, List or Set?
When should I use a dictionary, list or set?

Are there scenarios that are more suited for each data type?

答:
When use them, I make an exhaustive cheatsheet of their methods for your reference:</p>

```<code>class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}
</code>```

Body:
When use them, I make an exhaustive cheatsheet of their methods for your reference:

class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}


问:
Class 'Twilio\Rest\Client' not found in laravel 5.2 ,how to do call recording using Twilio of incoming and out going calls
This is My code

```<code> $client = new Twilio\Rest\Client($sid, $token);

 $call = $client->calls->create(
        "+9xxxxxxxxxx9",
        array("url" => "http://demo.twilio.com/docs/voice.xml", "record"
      => true)
    );
</code>```

how to do call recording using Twilio of incoming and out going calls?
Thanks in advance :)

答:
Have you updated composer.json to include the Twilio library?

If not, run the following command line:

```<code>composer require twilio/sdk
</code>```

This should then update composer and download the SDK files. See if this fixes your issue.

Or follow the setup instructions here.

If you have already added twilio to the composer.json file, try running:

```<code>composer update --no-scripts
</code>```

And then

```<code>php artisan optimize
</code>```

Body:
This is My code

 $client = new Twilio\Rest\Client($sid, $token);

 $call = $client->calls->create(
        "+9xxxxxxxxxx9",
        array("url" => "http://demo.twilio.com/docs/voice.xml", "record"
      => true)
    );

how to do call recording using Twilio of incoming and out going calls?
Thanks in advance :)

Body:
Have you updated composer.json to include the Twilio library?

If not, run the following command line:

composer require twilio/sdk

This should then update composer and download the SDK files. See if this fixes your issue.

Or follow the setup instructions here.

If you have already added twilio to the composer.json file, try running:

composer update --no-scripts

And then

php artisan optimize


问:
Fill a drawed circle with the midpoint algorithm in c-> infinite-loop?

I am trying to draw a filled circle with the midpoint algorithm. I already managed to draw an unfilled circle with y0 = 320; x0 = 240; radius = 180 -with the following code (reference: https://en.wikipedia.org/wiki/Midpoint_circle_algorithm):

```<code>int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while (x >= y)
{
    putpixel(x0 + x, y0 + y);
    putpixel(x0 + y, y0 + x);
    putpixel(x0 - y, y0 + x);
    putpixel(x0 - x, y0 + y);
    putpixel(x0 - x, y0 - y);
    putpixel(x0 - y, y0 - x);
    putpixel(x0 + y, y0 - x);
    putpixel(x0 + x, y0 - y);

    if (err <= 0)
    {
        y++;
        err += dy;
        dy += 2;
    }
    if (err > 0)
    {
        x--;
        dx += 2;
        err += dx - (radius << 1);
    }
}
</code>```

This delivers the following output (saved in a bitmap):

Now I want, that this unfilled yellow circle will be filled, so it looks like this:

I thought I can accommplish this with setting the radius everytime to radius-- so it draws the same circle with a -1 radius - and that until radius=0. So basically it draws everytime a new circle filled up with the old circle until there is now circle to draw anymore (radius=0). My code for this is:

int x0, int y0, int radius;

```<code>x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while(radius!=0) {
    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);

        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += dx - (radius << 1);
        }
    }

    x0 = x0 - 1;     //getting the next circle until radius = 0
    y0 = y0 -1;
    radius = radius - 1;

    x = radius-1;
    y = 0;
    dx = 1;
    dy = 1;
    err = dx - (radius << 1);

}
</code>```

This should be the code to my idea how I could fill up, but all i get is an infinite-loop.. Has anyone an idea why? Or has anyone another way to fill up the circle using the midpoint algorithm?

Greetings

答: This question is a duplicate of fast algorithm for drawing filled circles?.</p>

Body:
I am trying to draw a filled circle with the midpoint algorithm. I already managed to draw an unfilled circle with y0 = 320; x0 = 240; radius = 180 -with the following code (reference: https://en.wikipedia.org/wiki/Midpoint_circle_algorithm):

int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while (x >= y)
{
    putpixel(x0 + x, y0 + y);
    putpixel(x0 + y, y0 + x);
    putpixel(x0 - y, y0 + x);
    putpixel(x0 - x, y0 + y);
    putpixel(x0 - x, y0 - y);
    putpixel(x0 - y, y0 - x);
    putpixel(x0 + y, y0 - x);
    putpixel(x0 + x, y0 - y);

    if (err <= 0)
    {
        y++;
        err += dy;
        dy += 2;
    }
    if (err > 0)
    {
        x--;
        dx += 2;
        err += dx - (radius << 1);
    }
}

This delivers the following output (saved in a bitmap):

Now I want, that this unfilled yellow circle will be filled, so it looks like this:

I thought I can accommplish this with setting the radius everytime to radius-- so it draws the same circle with a -1 radius - and that until radius=0. So basically it draws everytime a new circle filled up with the old circle until there is now circle to draw anymore (radius=0). My code for this is:

int x0, int y0, int radius;

x0 = 320;     //assign values
y0 = 240;
radius = 180;

int x = radius-1;
int y = 0;
int dx = 1;
int dy = 1;
int err = dx - (radius << 1);

while(radius!=0) {
    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);

        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += dx - (radius << 1);
        }
    }

    x0 = x0 - 1;     //getting the next circle until radius = 0
    y0 = y0 -1;
    radius = radius - 1;

    x = radius-1;
    y = 0;
    dx = 1;
    dy = 1;
    err = dx - (radius << 1);

}

This should be the code to my idea how I could fill up, but all i get is an infinite-loop.. Has anyone an idea why? Or has anyone another way to fill up the circle using the midpoint algorithm?

Greetings


问:
Only 2 clusters are plotted instead of 3 after Linear Discriminant Analysis
I cant put all my data into a graph. This is what I got

This is what I need to get

I'm using this code:

```<code>import pandas
import matplotlib.pyplot as plt

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import numpy as np

dataset = np.loadtxt("wine.data.csv", delimiter=",")
print(dataset)
X = dataset[:,1:14]
y = dataset[:,0]
target_names = ['class_0', 'class_1', 'class_2']

lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit(X,y).transform(X)
plt.figure()
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
    plt.scatter(X_lda[y == i, 0], X_lda[y == i, 1], c=c, label=target_name)

plt.show()
plt.plot([-6,2],[-6,4],"k-")
plt.plot([5,0],[-6,4],"k-")
plt.legend()
plt.title('LDA of WINE dataset')
plt.show()
</code>```

The dataset is downloaded from here WINE dataset. Also I am using Python 2.7. I am new to this and would appreciate any kind of help.
Thank you in advance!

答:
Remove the first plt.show()

```<code># plt.show() # remove this
plt.plot([-6,2],[-6,4],"k-")
plt.plot([5,0],[-6,4],"k-")
plt.legend()
plt.title('LDA of WINE dataset')
plt.show()
</code>```

As soon as you call plt.show(), the plot is generated and all your code below this line will be ignored.

Furthermore, change [0, 1, 2] to [1, 2, 3]:

```<code>for c, i, target_name in zip("rgb", [1, 2, 3], target_names):
    plt.scatter(X_lda[y == i, 0], X_lda[y == i, 1], c=c, label=target_name)
</code>```

Now you get your desired output.

Body:
I cant put all my data into a graph. This is what I got

This is what I need to get

I'm using this code:

import pandas
import matplotlib.pyplot as plt

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import numpy as np

dataset = np.loadtxt("wine.data.csv", delimiter=",")
print(dataset)
X = dataset[:,1:14]
y = dataset[:,0]
target_names = ['class_0', 'class_1', 'class_2']

lda = LinearDiscriminantAnalysis(n_components=2)
X_lda = lda.fit(X,y).transform(X)
plt.figure()
for c, i, target_name in zip("rgb", [0, 1, 2], target_names):
    plt.scatter(X_lda[y == i, 0], X_lda[y == i, 1], c=c, label=target_name)

plt.show()
plt.plot([-6,2],[-6,4],"k-")
plt.plot([5,0],[-6,4],"k-")
plt.legend()
plt.title('LDA of WINE dataset')
plt.show()

The dataset is downloaded from here WINE dataset. Also I am using Python 2.7. I am new to this and would appreciate any kind of help.
Thank you in advance!

Body:
Remove the first plt.show()

# plt.show() # remove this
plt.plot([-6,2],[-6,4],"k-")
plt.plot([5,0],[-6,4],"k-")
plt.legend()
plt.title('LDA of WINE dataset')
plt.show()

As soon as you call plt.show(), the plot is generated and all your code below this line will be ignored.

Furthermore, change [0, 1, 2] to [1, 2, 3]:

for c, i, target_name in zip("rgb", [1, 2, 3], target_names):
    plt.scatter(X_lda[y == i, 0], X_lda[y == i, 1], c=c, label=target_name)

Now you get your desired output.


问:
Configuration for application in docker container on cluster
How can I deploy an application in a docker container on a cluster of machines and configure that application with settings like database username and password and other application specific settings. without putting the settings in the container as config file and without placing the settings on de machine, because the machine is recyclable. Also Environment variables are no options because these are visible in logs and not really suited for passwords and private keys imo.

The application is a Node.js application when developing I run it with a JSON config file. The production environment will exists of multiple machines in a AWS ECS environment. The machines all run docker in a cluster and the application it self is a docker image, and multiple instances of the application will run with an load balancer dividing the load between the instances.

答:
What you are looking for is Docker swarm which is responsible for running and mannaging containers running on a cluster of machines. Docker swarm has a very nice feature for securing configuration such as passwords ... called Docker secrets.

You can create docker secrets for usernames and passwords, and those secrets will be shared among the containers in the cluster in an encrypted and secure way.


问:
TypeError: must be str, not datetime.timedelta
here is my code it works fine for the first print and the give me this error
TypeError: must be str, not datetime.timedelta

```<code>import datetime
hour = datetime.datetime.now().hour
tomorrow = datetime.datetime.now()
for i in range(50):
    hour += 1
    print(hour)
    if hour >= 23:
        tomorrow = tomorrow + datetime.timedelta(days=1)
        tomorrow = tomorrow.strftime('%d/%m/%Y')
        hour = 9
        print (tomorrow)
</code>```

here is the output :

```<code>13
14
15
16
17
18
19
20
21
22
23
07/12/2017
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Traceback (most recent call last):
  File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in <module>
    tomorrow = tomorrow + datetime.timedelta(days=1)
TypeError: must be str, not datetime.timedelta
</code>```

please can someone tell me why it works fine at first then i get that error

答:
It works the first time because tomorrow is a datetime.datetime instance then:

```<code>tomorrow = datetime.datetime.now()
</code>```

However, after that first time, you replace tomorrow with a string:

```<code>tomorrow = tomorrow.strftime('%d/%m/%Y')
</code>```

You can't add a timedelta() object to a string. Don't rebind tomorrow. Either assign the string to a different name, or only format the object for printing (and not assign it to a name at all):

```<code>if hour >= 23:
    tomorrow = tomorrow + datetime.timedelta(days=1)
    tomorrow_formatted = tomorrow.strftime('%d/%m/%Y')
    hour = 9
    print(tomorrow_formatted)  # different name
    print(tomorrow.strftime('%d/%m/%Y'))  # print the `strftime()` result
</code>```

Body:
here is my code it works fine for the first print and the give me this error
TypeError: must be str, not datetime.timedelta

import datetime
hour = datetime.datetime.now().hour
tomorrow = datetime.datetime.now()
for i in range(50):
    hour += 1
    print(hour)
    if hour >= 23:
        tomorrow = tomorrow + datetime.timedelta(days=1)
        tomorrow = tomorrow.strftime('%d/%m/%Y')
        hour = 9
        print (tomorrow)

here is the output :

13
14
15
16
17
18
19
20
21
22
23
07/12/2017
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Traceback (most recent call last):
  File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in <module>
    tomorrow = tomorrow + datetime.timedelta(days=1)
TypeError: must be str, not datetime.timedelta

please can someone tell me why it works fine at first then i get that error

Body:
It works the first time because tomorrow is a datetime.datetime instance then:

tomorrow = datetime.datetime.now()

However, after that first time, you replace tomorrow with a string:

tomorrow = tomorrow.strftime('%d/%m/%Y')

You can't add a timedelta() object to a string. Don't rebind tomorrow. Either assign the string to a different name, or only format the object for printing (and not assign it to a name at all):

if hour >= 23:
    tomorrow = tomorrow + datetime.timedelta(days=1)
    tomorrow_formatted = tomorrow.strftime('%d/%m/%Y')
    hour = 9
    print(tomorrow_formatted)  # different name
    print(tomorrow.strftime('%d/%m/%Y'))  # print the `strftime()` result


问:
WebDav library Sardine on Android with httpclientandroidlib
Referencing to this thread Using webdav on Android
It is possible to use the Sardine lib ( http://code.google.com/p/sardine/) in combination with the httpclientandroidlib ( http://code.google.com/p/httpclientandroidlib/).

But I keep getting a java.lang.VerifyError Exception.

I tried to reference the Sardine lib as a jar file and as Eclipse-project but its always the same.

If i read the Messages from dalvikVM, before the exeption is thrown, there are problems with javax.xml.bind.JAXBContext.newInstance(). But i cant add the JAXB library or source to to the project because I get several Dx Errors:

```<code>    [2011-10-28 16:48:40 - FireTablet] Dx 1 error; aborting
    [2011-10-28 16:48:40 - FireTablet] Conversion to Dalvik format failed with error 1
    [2011-10-28 16:49:00 - FireTablet] Dx
    trouble processing "javax/xml/bind/PrintConversionEvent.class":
</code>```

So this cant be the solution. Does anyone know how to run the sardine library on android?

I am very grateful for help!

Exceptions:

```<code>10-28 16:21:33.602: I/Process(22992): Sending signal. PID: 22992 SIG: 9
10-28 16:30:59.005: I/dalvikvm(23056): Could not find method javax.xml.bind.JAXBContext.newInstance, referenced from method com.googlecode.sardine.util.SardineUtil.<clinit>
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to resolve static method 20578: Ljavax/xml/bind/JAXBContext;.newInstance ([Ljava/lang/Class;)Ljavax/xml/bind/JAXBContext;
10-28 16:30:59.005: D/dalvikvm(23056): VFY: replacing opcode 0x71 at 0x000a
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to resolve exception class 2678 (Ljavax/xml/bind/JAXBException;)
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to find exception handler at addr 0x50
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejected Lcom/googlecode/sardine/util/SardineUtil;.<clinit> ()V
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejecting opcode 0x0d at 0x0050
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejected Lcom/googlecode/sardine/util/SardineUtil;.<clinit> ()V
10-28 16:30:59.005: W/dalvikvm(23056): Verifier rejected class Lcom/googlecode/sardine/util/SardineUtil;
10-28 16:30:59.005: D/AndroidRuntime(23056): Shutting down VM
10-28 16:30:59.005: W/dalvikvm(23056): threadid=1: thread exiting with uncaught exception (group=0x40015578)
10-28 16:30:59.009: E/AndroidRuntime(23056): FATAL EXCEPTION: main
10-28 16:30:59.009: E/AndroidRuntime(23056): java.lang.VerifyError: com.googlecode.sardine.util.SardineUtil
10-28 16:30:59.009: E/AndroidRuntime(23056):    at com.googlecode.sardine.impl.SardineImpl.list(SardineImpl.java:339)
10-28 16:30:59.009: E/AndroidRuntime(23056):    at hsr.ifs.firetablet.network.WebDavConnector.getFacilityNames(WebDavConnector.java:36)
</code>```

I use Android API-Level 10 & Java 1.6.

答: I also had the same issue and modified the Sardine project to use SimpleXml instead of JAXB. Here is my version of the library: https://github.com/thegrizzlylabs/sardine-android</p>

Body:
Referencing to this thread Using webdav on Android
It is possible to use the Sardine lib ( http://code.google.com/p/sardine/) in combination with the httpclientandroidlib ( http://code.google.com/p/httpclientandroidlib/).

But I keep getting a java.lang.VerifyError Exception.

I tried to reference the Sardine lib as a jar file and as Eclipse-project but its always the same.

If i read the Messages from dalvikVM, before the exeption is thrown, there are problems with javax.xml.bind.JAXBContext.newInstance(). But i cant add the JAXB library or source to to the project because I get several Dx Errors:

    [2011-10-28 16:48:40 - FireTablet] Dx 1 error; aborting
    [2011-10-28 16:48:40 - FireTablet] Conversion to Dalvik format failed with error 1
    [2011-10-28 16:49:00 - FireTablet] Dx
    trouble processing "javax/xml/bind/PrintConversionEvent.class":

So this cant be the solution. Does anyone know how to run the sardine library on android?

I am very grateful for help!

Exceptions:

10-28 16:21:33.602: I/Process(22992): Sending signal. PID: 22992 SIG: 9
10-28 16:30:59.005: I/dalvikvm(23056): Could not find method javax.xml.bind.JAXBContext.newInstance, referenced from method com.googlecode.sardine.util.SardineUtil.<clinit>
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to resolve static method 20578: Ljavax/xml/bind/JAXBContext;.newInstance ([Ljava/lang/Class;)Ljavax/xml/bind/JAXBContext;
10-28 16:30:59.005: D/dalvikvm(23056): VFY: replacing opcode 0x71 at 0x000a
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to resolve exception class 2678 (Ljavax/xml/bind/JAXBException;)
10-28 16:30:59.005: W/dalvikvm(23056): VFY: unable to find exception handler at addr 0x50
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejected Lcom/googlecode/sardine/util/SardineUtil;.<clinit> ()V
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejecting opcode 0x0d at 0x0050
10-28 16:30:59.005: W/dalvikvm(23056): VFY:  rejected Lcom/googlecode/sardine/util/SardineUtil;.<clinit> ()V
10-28 16:30:59.005: W/dalvikvm(23056): Verifier rejected class Lcom/googlecode/sardine/util/SardineUtil;
10-28 16:30:59.005: D/AndroidRuntime(23056): Shutting down VM
10-28 16:30:59.005: W/dalvikvm(23056): threadid=1: thread exiting with uncaught exception (group=0x40015578)
10-28 16:30:59.009: E/AndroidRuntime(23056): FATAL EXCEPTION: main
10-28 16:30:59.009: E/AndroidRuntime(23056): java.lang.VerifyError: com.googlecode.sardine.util.SardineUtil
10-28 16:30:59.009: E/AndroidRuntime(23056):    at com.googlecode.sardine.impl.SardineImpl.list(SardineImpl.java:339)
10-28 16:30:59.009: E/AndroidRuntime(23056):    at hsr.ifs.firetablet.network.WebDavConnector.getFacilityNames(WebDavConnector.java:36)

I use Android API-Level 10 & Java 1.6.


问:
Friendship association problem
I'm building a social network, and I'm stucked in the friendship relation. These are my data:

Table friendship:

```<code> create_table "friendships", :force => true do |t|
t.integer  "user_id"
t.integer  "friend_id"
t.boolean  "confirmed"
t.datetime "created_at"
t.datetime "updated_at"
</code>```

Association in friendship model:

```<code>   class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
</code>```

My mistaken Association in user model:

```<code>  has_many :friendships #table that contains the reference of friends
  has_many :friends, :through=>:friendships, :conditions => ['confirmed = false'] #my performed request to others friends
  has_many :inverse_friendship, :class_name=>"Friendship", :foreign_key=>"friend_id" #someone requested friendship to me
  has_many :inverse_friends, :through=>:inverse_friendship, :source=>:user
</code>```

The boolean confirmed in the table friendship, mean if the requests are accepted by both friends, it's false for default when a friend request is submitted.
What I want to obtain in the model User is:

has many :requests_sent # when the confirm in the Friendship model is set to false and I'm the source (user_id)

has many :request_recieved # when the confirm in the Friendship model is set to false and I'm the target (friend_id)

has many :friends #when the confirm in the Friendship model is set to true and I'm either the source (user_id) or the target (friend_id)

As you can notice from the code I posted I tried to put :condition=>'confirmed=false', but rails apply the condition to the user model, not to the Friendship model, so that's not the right way to achieve my 3 goals, with a free method in the model User ?
Tnx

P.S I don't want change my models, I just would like to have a solution for the existing ones

答:
An option would be to put the condition in the friendship model as a named_scope, then you should be able to do something like:

@user.friends.confirmed

ContentLicense: CC BY-SA 2.5

Title: Friendship association problem

Body:
I'm building a social network, and I'm stucked in the friendship relation. These are my data:

Table friendship:

 create_table "friendships", :force => true do |t|
t.integer  "user_id"
t.integer  "friend_id"
t.boolean  "confirmed"
t.datetime "created_at"
t.datetime "updated_at"

Association in friendship model:

   class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"

My mistaken Association in user model:

  has_many :friendships #table that contains the reference of friends
  has_many :friends, :through=>:friendships, :conditions => ['confirmed = false'] #my performed request to others friends
  has_many :inverse_friendship, :class_name=>"Friendship", :foreign_key=>"friend_id" #someone requested friendship to me
  has_many :inverse_friends, :through=>:inverse_friendship, :source=>:user

The boolean confirmed in the table friendship, mean if the requests are accepted by both friends, it's false for default when a friend request is submitted.
What I want to obtain in the model User is:

has many :requests_sent # when the confirm in the Friendship model is set to false and I'm the source (user_id)

has many :request_recieved # when the confirm in the Friendship model is set to false and I'm the target (friend_id)

has many :friends #when the confirm in the Friendship model is set to true and I'm either the source (user_id) or the target (friend_id)

As you can notice from the code I posted I tried to put :condition=>'confirmed=false', but rails apply the condition to the user model, not to the Friendship model, so that's not the right way to achieve my 3 goals, with a free method in the model User ?
Tnx

P.S I don't want change my models, I just would like to have a solution for the existing ones


问:
Converting a Location to LatLng
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:

```<code>LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());
</code>```

Then I recalled the addMarker method:

```<code> mMap.addMarker(new MarkerOptions()
    .title(getString(R.string.default_info_title))
    .position(mCurrentPlace)
    .snippet(getString(R.string.default_info_snippet)))
</code>```

But Launching the application by "Run", it arrested.

Where am I goning wrong?

Thanks.

答:
MAP Activity

```<code>public class MapsActivity2 extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {

private GoogleMap mMap;

LatLng loc;
Location location;
private double currentLatitude = 0;
private double currentLongitude = 0;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or atLnmove the camera. In this case,
 * we just add a marker near Sydney, Australia.
            * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
            */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker
in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLg(sydney));

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationButtonClickListener(MapsActivity2.this);

}

public double getLatitude(){
    if(location != null){
        currentLatitude = location.getLatitude();
    }
    // return latitude
    return currentLatitude;
}

public double getLongitude(){
    if(location != null){
        currentLongitude = location.getLongitude();
    }
    // return longitude
    return currentLongitude;
}

@Override
public boolean onMyLocationButtonClick() {
    location=mMap.getMyLocation();
    currentLatitude=getLatitude();
    currentLongitude=getLongitude();

    LatLng currentLocation = new LatLng(currentLatitude, currentLongitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));

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

Resource XML

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.atziant.parashar.gmapsapi.MapsActivity2" />
</code>```

Title: Converting a Location to LatLng

Body:
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:

LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());

Then I recalled the addMarker method:

 mMap.addMarker(new MarkerOptions()
    .title(getString(R.string.default_info_title))
    .position(mCurrentPlace)
    .snippet(getString(R.string.default_info_snippet)))

But Launching the application by "Run", it arrested.

Where am I goning wrong?

Thanks.

Body:
MAP Activity

public class MapsActivity2 extends FragmentActivity implements
OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {

private GoogleMap mMap;

LatLng loc;
Location location;
private double currentLatitude = 0;
private double currentLongitude = 0;
LocationManager locationManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or atLnmove the camera. In this case,
 * we just add a marker near Sydney, Australia.
            * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
            */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
//        LatLng sydney = new LatLng(-34, 151);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker
in Sydney"));
//        mMap.moveCamera(CameraUpdateFactory.newLg(sydney));

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationButtonClickListener(MapsActivity2.this);

}

public double getLatitude(){
    if(location != null){
        currentLatitude = location.getLatitude();
    }
    // return latitude
    return currentLatitude;
}

public double getLongitude(){
    if(location != null){
        currentLongitude = location.getLongitude();
    }
    // return longitude
    return currentLongitude;
}

@Override
public boolean onMyLocationButtonClick() {
    location=mMap.getMyLocation();
    currentLatitude=getLatitude();
    currentLongitude=getLongitude();

    LatLng currentLocation = new LatLng(currentLatitude, currentLongitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Marker in Current Location"));

    return false;
}
}

Resource XML

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.atziant.parashar.gmapsapi.MapsActivity2" />


问:
Google Drive App Folder backup data getting lost on app uninstall
I have implemented database backup and restore to Google Drive App folder using Google Drive Android API. I tested it and it was working fine, which means I could create my db file in the hidden app folder in Google Drive, and on uninstalling and reinstalling the app, I could use the restore functionality of my app to restore the database.

But recently, it has stopped working. Now, when I take back up and uninstall my app and try to restore it from Google Drive's app folder, it fails to find my backup file. Has Google or Android changed anything recently?

I have done all my testing on Android 6.0.1, Nexus 5. I know starting 6.0, Google has introduced Auto Backup. But does it also delete anything previously stored in App folder? It was working on 6.0.1 till 2-3 days back. The google-play-services version of my Nexus 5 is 10.2.98. Please help.

答:
For those who are still experiencing this problem and using the latest Drive API for Android, the solution marked above is deprecated. This worked for me after much, much searching:</p>

```<code>DriveClient driveClient = Drive.getDriveClient(MainActivity.this, googleSignInAccount);

driveClient.requestSync().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // Do stuff here
    }
});
</code>```

Body:
For those who are still experiencing this problem and using the latest Drive API for Android, the solution marked above is deprecated. This worked for me after much, much searching:

DriveClient driveClient = Drive.getDriveClient(MainActivity.this, googleSignInAccount);

driveClient.requestSync().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // Do stuff here
    }
});


问:
JPA / EclipseLink lazy collections not loading
I have a User entity with this mapping:

```<code>@OneToMany(mappedBy = "supervisor", fetch = LAZY, cascade = [CascadeType.REFRESH])
List<Group> supervisedGroups = new ArrayList<Group>()
</code>```

and a Group entity with this mapping:

```<code>@ManyToOne(fetch = LAZY, cascade = [CascadeType.REFRESH])
@JoinColumn(name = "supervisor")
User supervisor
</code>```

I fetch a user thanks to a repository

```<code>User user = userRepository.findById(id)
</code>```

The findById method is wrapped by a transaction (method is intercepted by a transaction manager advice), and the JPA unit of work lasts as long as the request last (session per view).

When I get the user, I do a

```<code>user.getSupervisedGroups()
</code>```

This returns me an empty list. The collection type is the Eclipselinks's IndirectList and even if i call the size() method it does nothing more.

But if I execute

```<code>entitymanager.refresh(user)
user.getSupervisedGroups()
</code>```

Then I have 2 items in my list... Why ? Does it means EclipseLink does not support at all LAZY fetching on collections ?

答:
The answer by James might be the origin of the problem. Another solution is to disable EclipseLinks L2 cache:

Persistence Unit property:

```<code><property name="eclipselink.cache.shared.default" value="false"/>
</code>```

Or JPA 2.0 persistence unit element:

```<code><shared-cache-mode>NONE</shared-cache-mode>
</code>```

Source: https://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F

Body:
I have a User entity with this mapping:

@OneToMany(mappedBy = "supervisor", fetch = LAZY, cascade = [CascadeType.REFRESH])
List<Group> supervisedGroups = new ArrayList<Group>()

and a Group entity with this mapping:

@ManyToOne(fetch = LAZY, cascade = [CascadeType.REFRESH])
@JoinColumn(name = "supervisor")
User supervisor

I fetch a user thanks to a repository

User user = userRepository.findById(id)

The findById method is wrapped by a transaction (method is intercepted by a transaction manager advice), and the JPA unit of work lasts as long as the request last (session per view).

When I get the user, I do a

user.getSupervisedGroups()

This returns me an empty list. The collection type is the Eclipselinks's IndirectList and even if i call the size() method it does nothing more.

But if I execute

entitymanager.refresh(user)
user.getSupervisedGroups()

Then I have 2 items in my list... Why ? Does it means EclipseLink does not support at all LAZY fetching on collections ?

Body:
The answer by James might be the origin of the problem. Another solution is to disable EclipseLinks L2 cache:

Persistence Unit property:

<property name="eclipselink.cache.shared.default" value="false"/>

Or JPA 2.0 persistence unit element:

<shared-cache-mode>NONE</shared-cache-mode>

Source: https://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F


问:
check previous and current element of array
Imagine: I have a an array: ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];

I consider which function should I use to:

find first NaN element in array (let say index = 2) and check if the next (index = 3) is also NaN and if yes (delete from array element with index = 2).

So the result of the transformed array should be: ["1", "2",".", "4", "3", "-", "12"];

I do not want your code, just suggestion/help how to start it.

Thank you for your responses and help.

答:
You can use Array#filter to find if current and next items are NaN.

const data = ["1", "2", "X", ".", "4", "3", "Z", "-", "12", "END"];

const result = data.filter((c, i, arr) => i + 1 === arr.length || !(isNaN(c) && isNaN(arr[i + 1])));

console.log(result);```


问:
Python, reading special word from file
So I have this list of word in a textfile, I did not produce the text file so I do not know the file encoding.

the list : http://s000.tinyupload.com/?file_id=31195244104486221180

Notepad++ tells me that it's ANSI.

When running this script (reader1.py) :

```<code>if __name__ == '__main__':
    words = open("test_list.txt").read().splitlines()
    for word in words:
        print word
        with open("test_list-rewrite.txt", "a") as myfile:
                myfile.write(word + '\n')
</code>```

the word piirilä is displayed as piirilõ in the console, however in the new file it's stored as piirilä

What I wonder is, if I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

word = word.decode('cp-1252') raise an exception

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

Edit

after some more fidling I found something weird, made this

```<code>#!/usr/bin/env python
# --*-- encoding: utf-8 --*--

import hashlib

word1 = 'piirilä'
word2 = 'piirilõ'
word3 = 'Whatitis'

print word1
print hashlib.sha256(word1).hexdigest()
print word2
print hashlib.sha256(word2).hexdigest()
print word3
print hashlib.sha256(word3).hexdigest()
</code>```

which outputs this :

```<code>piiril├ñ
278394edd22799ae29bc881dc66e45e45a9a18972c45a35208b6a3d71e209a10
piiril├Á
7e158cf465d3afadd865684f979f46a5282ef93127c150b55273801086fa3c09
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
</code>```

And I added hashlib.sha256(word).hexdigest() to reader1.py

which then outputs this :

```<code>billycorgan
d94a3821ad2b6d26aedf4db13b551d9e0eefeaf92d0615946cdc0215ec974692
brescos64
8840d0e40a83d711ce0b44ed66a5d1e4df06fbf6c5c168e98af4775c6e19f52b
matvois
ef5e930806489e8fcc8e0746ce5f8cb4c6715a56d2fd73d42b1c711b5e71474f
kbeans
c207d8366f3dbae64357088dee8eeeb35a047b2e021342c82aa0bd8c15753d74
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
cphu
1427ebcff066a5386d0649842fb60b014bebfc5a1589896a62488865e8f06c50
de'mystifierait
83665461f98de4c270e6a4d69a445ea2f9079693824c0544a9add4caee5c7dd2
wendelboe
1423bf5d682dafdc72937d92811b5ff9d856681e94204d565cb0f29b809f5e13
ketanshah
f9977718f33f9068f20c52321ef02be3611e7c7a0aebb59421e74f864c259f53
piirilõ
a238ede50bc349279c62399b275cfa3271f63bc5e7499cc40aaa4ff84198666d
gasoline
4325ed4bef2a2a10c97cbb8235f822602efc0f04a900f0eb537f8e9fee9728aa
BabyBlues
8168fce33124ecec74e647f119de5b3cda795dcc69c4237d8cf27b10aca07b94
</code>```

so I get 3 different hashes, which one is the one I want?

答:
had a look at your textfile.

The linux file command told me its charset is ISO-8859 text (, with CRLF line terminators). So may be thats why your

```<code>word = word.decode('cp-1252')
</code>```

raised an exception.

Have a look at Determine the encoding of text in Python which is about determining the encoding of a textfile in python.

Best,
me

Title: Python, reading special word from file

Body:
So I have this list of word in a textfile, I did not produce the text file so I do not know the file encoding.

the list : http://s000.tinyupload.com/?file_id=31195244104486221180

Notepad++ tells me that it's ANSI.

When running this script (reader1.py) :

if __name__ == '__main__':
    words = open("test_list.txt").read().splitlines()
    for word in words:
        print word
        with open("test_list-rewrite.txt", "a") as myfile:
                myfile.write(word + '\n')

the word piirilä is displayed as piirilõ in the console, however in the new file it's stored as piirilä

What I wonder is, if I compute the hash256 of the variable word, will it run it on piirilä or piirilõ?

word = word.decode('cp-1252') raise an exception

Thanks

PS : Windows 8.1 64 bits, python 2.7 64 bits

Edit

after some more fidling I found something weird, made this

#!/usr/bin/env python
# --*-- encoding: utf-8 --*--

import hashlib

word1 = 'piirilä'
word2 = 'piirilõ'
word3 = 'Whatitis'

print word1
print hashlib.sha256(word1).hexdigest()
print word2
print hashlib.sha256(word2).hexdigest()
print word3
print hashlib.sha256(word3).hexdigest()

which outputs this :

piiril├ñ
278394edd22799ae29bc881dc66e45e45a9a18972c45a35208b6a3d71e209a10
piiril├Á
7e158cf465d3afadd865684f979f46a5282ef93127c150b55273801086fa3c09
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f

And I added hashlib.sha256(word).hexdigest() to reader1.py

which then outputs this :

billycorgan
d94a3821ad2b6d26aedf4db13b551d9e0eefeaf92d0615946cdc0215ec974692
brescos64
8840d0e40a83d711ce0b44ed66a5d1e4df06fbf6c5c168e98af4775c6e19f52b
matvois
ef5e930806489e8fcc8e0746ce5f8cb4c6715a56d2fd73d42b1c711b5e71474f
kbeans
c207d8366f3dbae64357088dee8eeeb35a047b2e021342c82aa0bd8c15753d74
Whatitis
d338e8077b6c9d3d2f09e4e2d4a2a5f52152b72e9b6bb5c456a67f63d853e75f
cphu
1427ebcff066a5386d0649842fb60b014bebfc5a1589896a62488865e8f06c50
de'mystifierait
83665461f98de4c270e6a4d69a445ea2f9079693824c0544a9add4caee5c7dd2
wendelboe
1423bf5d682dafdc72937d92811b5ff9d856681e94204d565cb0f29b809f5e13
ketanshah
f9977718f33f9068f20c52321ef02be3611e7c7a0aebb59421e74f864c259f53
piirilõ
a238ede50bc349279c62399b275cfa3271f63bc5e7499cc40aaa4ff84198666d
gasoline
4325ed4bef2a2a10c97cbb8235f822602efc0f04a900f0eb537f8e9fee9728aa
BabyBlues
8168fce33124ecec74e647f119de5b3cda795dcc69c4237d8cf27b10aca07b94

so I get 3 different hashes, which one is the one I want?

Body:
had a look at your textfile.

The linux file command told me its charset is ISO-8859 text (, with CRLF line terminators). So may be thats why your

word = word.decode('cp-1252')

raised an exception.

Have a look at Determine the encoding of text in Python which is about determining the encoding of a textfile in python.

Best,
me


问:
Transaction certificate / TCerts in Hyperledger Fabric 1.0
How transaction certificate or TCert is being used in Hyperledger Fabric 1.0? Various documentation said that Tcert is used for each transaction and clients can request for TCert(s). However, I just can't find any more in-depth discussion on this topic in the official documentation. I can't find how it is used even examining the SDK documentation and some samples.

Is it still being used in 1.0+? If yes, where can I find information about how it can be used?

答:
No, TCerts are not supported in Fabric 1.0+

In the future you will be able to use Identity Mixer instead. Check https://jira.hyperledger.org/browse/FAB-2005 for additional info on this work.


问:
How to convert a list into a string in lisp
How do you convert a list into a string? I am trying to use parse-int to take a list of numbers and convert them to decimal, but i end up getting an error saying "The control-string must be a string, not (contents)".
I'm using format, but I'm not sure if I'm using it incorrectly.

Here's my code:

```<code>    (princ "Enter a or list of hexadecimal numbers: ")
    (setq numList (read-from-string (concatenate 'string "(" (read-line) ")")))
    (defun hextodec(nums)
            (setq  numString (format "%s" nums))
            (setq newNum (parse-integer numString :radix 16))
            (write nums)
            (princ " = ")
            (write newNum)
    ) ;This will format the number that the user enters
    (hextodec numList)
</code>```

答:
Format's first argument is the stream to print to.  You seem to intend to return the string instead of printing, so you should put nil there: (format nil "~s" nums)

The format control string "%s" does not contain any format directives.  The entire format form does not make much sense here, as you seem to intend to loop over the given nums instead.  You should employ some looping construct for that, e. g. loop, do, map, mapcar ….

Body:
How do you convert a list into a string? I am trying to use parse-int to take a list of numbers and convert them to decimal, but i end up getting an error saying "The control-string must be a string, not (contents)".
I'm using format, but I'm not sure if I'm using it incorrectly.

Here's my code:

    (princ "Enter a or list of hexadecimal numbers: ")
    (setq numList (read-from-string (concatenate 'string "(" (read-line) ")")))
    (defun hextodec(nums)
            (setq  numString (format "%s" nums))
            (setq newNum (parse-integer numString :radix 16))
            (write nums)
            (princ " = ")
            (write newNum)
    ) ;This will format the number that the user enters
    (hextodec numList)