问:
Apache Hadoop accelerator -ignite environment variable setup
I am using apache ignite hadoop accelerator for apache hadoop.
When I use this configuration in ~/.bashrc file ignite.sh works fine but hadoop does not work and shows error.

Error: Could not find or load main class org.apache.hadoop.util.VersionInfo

```<code>export HADOOP_PREFIX=/app/hadoop
export HADOOP_HOME=$HADOOP_PREFIX
export HADOOP_COMMON_HOME=$HADOOP_HOME/share/hadoop/common
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=/app/hadoop/share/hadoop/mapreduce
export HADOOP_YARN_HOME=$HADOOP_PREFIX
export PATH=$PATH:$HADOOP_PREFIX/sbin:$HADOOP_PREFIX/bin

export IGNITE_HOME=/app/ignite2/apache-ignite-hadoop-1.9.0-bin
</code>```

I tried to change settings.

```<code>export HADOOP_PREFIX=/app/hadoop
export HADOOP_HOME=$HADOOP_PREFIX
export HADOOP_COMMON_HOME=$HADOOP_PREFIX
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=$HADOOP_PREFIX
export HADOOP_YARN_HOME=$HADOOP_PREFIX
export PATH=$PATH:$HADOOP_PREFIX/sbin:$HADOOP_PREFIX/bin
</code>```

Then hadoop works fine but ignite shows error

```<code>Ignite node stopped OK [uptime=00:00:02:626]
java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataOutputStream
</code>```

I also tried to make soft links but did not work. Tell me if I am missing something.

答:
Normally (for standard distributions such as Apache, Hortonworks, Cloudera) Ignite guesses all the Hadoop library locations based only on HADOOP_HOME environment variable value, thus, typically there is no need to specify the HADOOP_COMMON_HOME, HADOOP_HDFS_HOME, HADOOP_MAPRED_HOME explicitly. However, if you're using some specific Hadoop ditribution layout , you can specify these 3 variables, in which case they and only they will be used to locate the Hadoop libraries. If your Hadoop distribution requires values of these variables, that contradict to those required for Ignite, you will probably have to use different environments for Hadoop and for Ignite node processes.

Ignite will use the following libraries relative to the 3 above values:

```<code>${HADOOP_COMMON_HOME}/lib/*
${HADOOP_COMMON_HOME}/hadoop-common-*
${HADOOP_COMMON_HOME}/hadoop-auth-*

${HADOOP_HDFS_HOME}/lib/*
${HADOOP_HDFS_HOME}/hadoop-hdfs-*

${HADOOP_MAPRED_HOME}/lib/*
${HADOOP_MAPRED_HOME}/hadoop-mapreduce-client-common*
${HADOOP_MAPRED_HOME}/hadoop-mapreduce-client-core*

+ ${HADOOP_USER_LIBS}, if defined.
</code>```

Body:
I am using apache ignite hadoop accelerator for apache hadoop.
When I use this configuration in ~/.bashrc file ignite.sh works fine but hadoop does not work and shows error.

Error: Could not find or load main class org.apache.hadoop.util.VersionInfo

export HADOOP_PREFIX=/app/hadoop
export HADOOP_HOME=$HADOOP_PREFIX
export HADOOP_COMMON_HOME=$HADOOP_HOME/share/hadoop/common
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=/app/hadoop/share/hadoop/mapreduce
export HADOOP_YARN_HOME=$HADOOP_PREFIX
export PATH=$PATH:$HADOOP_PREFIX/sbin:$HADOOP_PREFIX/bin

export IGNITE_HOME=/app/ignite2/apache-ignite-hadoop-1.9.0-bin

I tried to change settings.

export HADOOP_PREFIX=/app/hadoop
export HADOOP_HOME=$HADOOP_PREFIX
export HADOOP_COMMON_HOME=$HADOOP_PREFIX
export HADOOP_CONF_DIR=$HADOOP_PREFIX/etc/hadoop
export HADOOP_HDFS_HOME=$HADOOP_PREFIX
export HADOOP_MAPRED_HOME=$HADOOP_PREFIX
export HADOOP_YARN_HOME=$HADOOP_PREFIX
export PATH=$PATH:$HADOOP_PREFIX/sbin:$HADOOP_PREFIX/bin

Then hadoop works fine but ignite shows error

Ignite node stopped OK [uptime=00:00:02:626]
java.lang.NoClassDefFoundError: org/apache/hadoop/fs/FSDataOutputStream

I also tried to make soft links but did not work. Tell me if I am missing something.

Body:
Normally (for standard distributions such as Apache, Hortonworks, Cloudera) Ignite guesses all the Hadoop library locations based only on HADOOP_HOME environment variable value, thus, typically there is no need to specify the HADOOP_COMMON_HOME, HADOOP_HDFS_HOME, HADOOP_MAPRED_HOME explicitly. However, if you're using some specific Hadoop ditribution layout , you can specify these 3 variables, in which case they and only they will be used to locate the Hadoop libraries. If your Hadoop distribution requires values of these variables, that contradict to those required for Ignite, you will probably have to use different environments for Hadoop and for Ignite node processes.

Ignite will use the following libraries relative to the 3 above values:

${HADOOP_COMMON_HOME}/lib/*
${HADOOP_COMMON_HOME}/hadoop-common-*
${HADOOP_COMMON_HOME}/hadoop-auth-*

${HADOOP_HDFS_HOME}/lib/*
${HADOOP_HDFS_HOME}/hadoop-hdfs-*

${HADOOP_MAPRED_HOME}/lib/*
${HADOOP_MAPRED_HOME}/hadoop-mapreduce-client-common*
${HADOOP_MAPRED_HOME}/hadoop-mapreduce-client-core*

+ ${HADOOP_USER_LIBS}, if defined.


来源: stackexchange

问:
All nodejs functions asyncronously running?
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

```<code>> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>
</code>```

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?

答:
Based on your question, the function you are using is not an async function and doesn't model async operations. It blocks until a result is returned.

Don't be confused by the results returned by your cli; it's normal to have that at times. Async operations however are used to abstract long running operations in node such as database requests, file i/o requests, online info requests etc that returns info at a later time.

A more appropriate approach is to use a function with callbacks,  use the es7 async and await or use event emitters. Those are the only ways to handle async operations in node.

You might want to read beginning node js

ContentLicense: CC BY-SA 3.0

Body:
I was trying to learn about async/promises/callbacks/js modules/etc... However, when I was trying to run a simple module which only required a file, and ran a function that only returned the parameter back, node was not outputting the result correctly. By this I mean that it would only sometimes return the value, and sometimes not.

I am pretty new so I could be wrong, but from what I understand this is async in node(?). But while researching I was only finding functions which do things like load, wait, timeout, etc. in lists for things that use async. But it seems that everything I run in node, no matter how simple runs with async and will not consistently output values? Here is an example of what I ran and recieved in the node console:

> function test(input){
... return input;
... }
> test('a')

> test('a')
'a'
>
> test(5)

> test(5)
5
>

Like I said, I was working on learning about a few things, but it started by looking into modules, so I was also wondering what a common 'pattern'(?) for handling this is, when exporting modules. Thanks.

Edit:

I'm not sure if I made it very clear, but for the most part I was really just wondering why a function as simple as this wouldn't be working, when the only functions I have seen people talk about async with are functions that are obviously waiting, in a sense. Not simple functions like this. I havent tried putting a callback with this yet, but I assume that works. I just didn't think you needed them for functions as simple as this?


问:
Get access to USB device on Linux (libusb-1.0)?
I am writing a small program to communicate with a specific USB HID product (identified by vendor and product IDs), using libusb-1.0 on Linux.  Right now, I have to run the program as root because "libusb requires write access to USB device nodes".  Is there a way to change the permissions on the device I need so that I don't need to run my program as root?</p>

答:
On modern Linux systems, udevd (man 7 udev) creates the device nodes for USB devices when they're plugged in.  Add a udev rule that matches your device (eg. you could match by USB Vendor and Product IDs), and sets the OWNER / GROUP / MODE of the device node.

The best approach is probably to create a new group for users who should be able to access the device, then set that as the group owner in the udev rule.  You may also need to use MODE to ensure that it has group read/write permissions.  Eg. your rule will probably look something like:

```<code>SUBSYSTEMS=="usb", ATTRS{idVendor}=="ffee", ATTRS{idProduct}=="5a5a", MODE="0660", GROUP="foobar"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On modern Linux systems, udevd (man 7 udev) creates the device nodes for USB devices when they're plugged in.  Add a udev rule that matches your device (eg. you could match by USB Vendor and Product IDs), and sets the OWNER / GROUP / MODE of the device node.

The best approach is probably to create a new group for users who should be able to access the device, then set that as the group owner in the udev rule.  You may also need to use MODE to ensure that it has group read/write permissions.  Eg. your rule will probably look something like:

SUBSYSTEMS=="usb", ATTRS{idVendor}=="ffee", ATTRS{idProduct}=="5a5a", MODE="0660", GROUP="foobar"


问:
Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
I am trying to deploy my website on windows server 2003.
Am i missing something or what is wrong from the following error message, how can I correct it? Thank

I am having the error message:

A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A connection
  was successfully established with the server, but then an error
  occurred during the login process. (provider: Shared Memory Provider,
  error: 0 - No process is on the other end of the pipe.)

Source Error:

An unhandled exception was generated during the execution of the
  current web request. Information regarding the origin and location of
  the exception can be identified using the exception stack trace below.

Stack Trace:

[SqlException (0x80131904): A connection was successfully established
  with the server, but then an error occurred during the login process.
  (provider: Shared Memory Provider, error: 0 - No process is on the
  other end of the pipe.)]

  System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection
  owningObject) +1019

  System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection
  owningConnection) +108

  System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection
  outerConnection, DbConnectionFactory connectionFactory) +126

  System.Data.SqlClient.SqlConnection.Open() +125

  NHibernate.Connection.DriverConnectionProvider.GetConnection() +104

  NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare()
  +15    NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect
  dialect, IConnectionHelper connectionHelper) +89

  NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory
  sessionFactory) +80

  NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping
  mapping, Settings settings, EventListeners listeners) +599

  NHibernate.Cfg.Configuration.BuildSessionFactory() +104

  MyProject.API.Data.SessionManager..cctor() in
  C:\Dev\Code\API\Data\SessionManager.cs:27

答:
This is old but I had the problem in the connect dialog that it was still defaulting to a database I had removed. And by running those commands the default database in the prompt wasn't changing.
I read somewhere I can't find now, that if you open the "Connect to Server" dialog and then select "Options" and select "Connection Properties" tab by typing the default database (no by selecting from the drop down) the database will then stay on that new value entered. This sounds like a flaw to me but in case someone was wondering about that, that should fix the issue, at least on SQL Server 2012

ContentLicense: CC BY-SA 4.0


问:
How to logout from twitter using Fabric Sdk for android
I used

```<code>Twitter.getSessionManager().clearActiveSession();
</code>```

This does not work,next time when i logIn using twitter, it opens the dialog with browser,takes previous login and just asks "Allow app to fetch your data?", but doesn't ask for username and password.Any help will be appreciated.

答:
You can now use:</p>

```<code>Digits.logout();
</code>```

Body:
I used

Twitter.getSessionManager().clearActiveSession();

This does not work,next time when i logIn using twitter, it opens the dialog with browser,takes previous login and just asks "Allow app to fetch your data?", but doesn't ask for username and password.Any help will be appreciated.

Body:
You can now use:

Digits.logout();


问:
how to randomize this set of questions?
I am making a multiple choice quiz game but I need this table's 20 question to be randomized everytime I pressed play again a new question should pop up. what code should I use

```<code>     public class TriviaQuizHelper extends SQLiteOpenHelper {

    Context context;
    private static final String DATABASE_NAME = "DATABASEQUIZ";
    private static final int DATABASE_VERSION = 17;
    private static final String TABLE_NAME = "TRIVIAQUIZ";
    private static final String UID = "_UID";
    private static final String QUESTION = "QUESTION";
    private static final String OPTA = "OPTA";
    private static final String OPTB = "OPTB";
    private static final String OPTC = "OPTC";
    private static final String OPTD = "OPTD";
    private static final String ANSWER = "ANSWER";
    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public TriviaQuizHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);

    }

    public void allQuestion() {
        TriviaQuestion q1 = new TriviaQuestion("Galileo was an Italian astronomer who developed?", "Telescope", "Airoplane", "Electricity", "Train", "Telescope");
        this.insert(q1);
        TriviaQuestion q2 = new TriviaQuestion("Who is the father of Geometry ?", "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid");
        this.insert(q2);
        TriviaQuestion q3 = new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel");
        this.insert(q3);
        TriviaQuestion q4 = new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova");
        this.insert(q4);
        TriviaQuestion q5 = new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh");
        this.insert(q5);
        TriviaQuestion q6 = new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi");
        this.insert(q6);
        TriviaQuestion q7 = new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician");
        this.insert(q7);
        TriviaQuestion q8 = new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music");
        this.insert(q8);
        TriviaQuestion q9 = new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen");
        this.insert(q9);
        TriviaQuestion q10 = new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke");
        this.insert(q10);
        TriviaQuestion q11 = new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa");
        this.insert(q11);
        TriviaQuestion q12 = new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein");
        this.insert(q12);
       TriviaQuestion q13 = new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump");
        this.insert(q13);
        TriviaQuestion q14 = new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates");
        this.insert(q14);
        TriviaQuestion q15 = new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs");
        this.insert(q15);
        TriviaQuestion q16 = new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page");
        this.insert(q16);
        TriviaQuestion q17 = new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar");
        this.insert(q17);
        TriviaQuestion q18 = new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi");
        this.insert(q18);
        TriviaQuestion q19 = new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo");
        this.insert(q19);
        TriviaQuestion q20 = new TriviaQuestion("the Founder of the most famous gaming platform steam is ?", "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell");
        this.insert(q20);
    }
    public void insert(TriviaQuestion triviaQuestion) {
        ContentValues contentvalues = new ContentValues();
       /* contentvalues.put(UID,triviaQuestion.getId());*/
        contentvalues.put(QUESTION, triviaQuestion.getQuestion());
        contentvalues.put(OPTA, triviaQuestion.getOpta());
        contentvalues.put(OPTB, triviaQuestion.getOptb());
        contentvalues.put(OPTC, triviaQuestion.getOptc());
        contentvalues.put(OPTD, triviaQuestion.getOptd());
        contentvalues.put(ANSWER, triviaQuestion.getAnswer());
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(TABLE_NAME, null, contentvalues);
    }
    public List<TriviaQuestion> getAllQuestion() {
        List<TriviaQuestion> que = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        String coloumns[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
        Cursor cursor = db.query(TABLE_NAME, coloumns, null, null, null, null, null);
        while (cursor.moveToNext()) {
            TriviaQuestion triviaQuestion = new TriviaQuestion();
            triviaQuestion.setId(cursor.getInt(0));
            triviaQuestion.setQuestion(cursor.getString(1));
            triviaQuestion.setOpta(cursor.getString(2));
            triviaQuestion.setOptb(cursor.getString(3));
            triviaQuestion.setOptc(cursor.getString(4));
            triviaQuestion.setOptd(cursor.getString(5));
            triviaQuestion.setAnswer(cursor.getString(6));
            que.add(triviaQuestion);
        }
        return que;
    }
}
</code>```

this is my other activity in order for the above code to function

```<code>public class TriviaQuestion extends Activity {
    private int id;
    private String question;
    private String opta;
    private String optb;
    private String optc;
    private String optd;
    private String answer;

    public TriviaQuestion(String q, String oa, String ob, String oc, String od, String ans) {

        question = q;
        opta = oa;
        optb = ob;
        optc = oc;
        optd = od;
        answer = ans;
    }

    public TriviaQuestion() {
        id = 0;
        question = "";
        opta = "";
        optb = "";
        optc = "";
        optd = "";
        answer = "";
    }

   /* public int getId() {
        return id;
    }*/

    public String getQuestion() {
        return question;
    }

    public String getOpta() {
        return opta;
    }

    public String getOptb() {
        return optb;
    }

    public String getOptc() {
        return optc;
    }

    public String getOptd() {
        return optd;
    }

    public String getAnswer() {
        return answer;
    }

    public void setId(int i) {
        id = i;
    }

    public void setQuestion(String q1) {
        question = q1;
    }

    public void setOpta(String o1) {
        opta = o1;
    }

    public void setOptb(String o2) {
        optb = o2;
    }

    public void setOptc(String o3) {
        optc = o3;
    }

    public void setOptd(String o4) {
        optd = o4;
    }

    public void setAnswer(String ans) {
        answer = ans;
    }

}
</code>```

答:
This can be done by simply shuffling the TiviaQuestion ArrayList.

Here is an example using String instead of TriviaQuestion

```<code>List<String> questions = new ArrayList<>();
questions.add("This is a question!");
questions.add("This is another question!");
questions.add("This is a third question!");

Collections.shuffle(questions);

System.out.println(questions);
</code>```

Output

```<code>[This is another question!, This is a question!, This is a third question!]
</code>```

Title: how to randomize this set of questions?

Body:
I am making a multiple choice quiz game but I need this table's 20 question to be randomized everytime I pressed play again a new question should pop up. what code should I use

     public class TriviaQuizHelper extends SQLiteOpenHelper {

    Context context;
    private static final String DATABASE_NAME = "DATABASEQUIZ";
    private static final int DATABASE_VERSION = 17;
    private static final String TABLE_NAME = "TRIVIAQUIZ";
    private static final String UID = "_UID";
    private static final String QUESTION = "QUESTION";
    private static final String OPTA = "OPTA";
    private static final String OPTB = "OPTB";
    private static final String OPTC = "OPTC";
    private static final String OPTD = "OPTD";
    private static final String ANSWER = "ANSWER";
    private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " ( " + UID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + QUESTION + " VARCHAR(255), " + OPTA + " VARCHAR(255), " + OPTB + " VARCHAR(255), " + OPTC + " VARCHAR(255), " + OPTD + " VARCHAR(255), " + ANSWER + " VARCHAR(255));";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public TriviaQuizHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(DROP_TABLE);
        onCreate(sqLiteDatabase);

    }

    public void allQuestion() {
        TriviaQuestion q1 = new TriviaQuestion("Galileo was an Italian astronomer who developed?", "Telescope", "Airoplane", "Electricity", "Train", "Telescope");
        this.insert(q1);
        TriviaQuestion q2 = new TriviaQuestion("Who is the father of Geometry ?", "Aristotle", "Euclid", "Pythagoras", "Kepler", "Euclid");
        this.insert(q2);
        TriviaQuestion q3 = new TriviaQuestion("Who was known as Iron man of India ?", "Govind Ballabh Pant", "Jawaharlal Nehru", "Subhash Chandra Bose", "Sardar Vallabhbhai Patel", "Sardar Vallabhbhai Patel");
        this.insert(q3);
        TriviaQuestion q4 = new TriviaQuestion("The first woman in space was ?", "Valentina Tereshkova", "Sally Ride", "Naidia Comenci", "Tamara Press", "Valentina Tereshkova");
        this.insert(q4);
        TriviaQuestion q5 = new TriviaQuestion("Who is the Flying Sikh of India ?", "Mohinder Singh", "Joginder Singh", "Ajit Pal Singh", "Milkha singh", "Milkha singh");
        this.insert(q5);
        TriviaQuestion q6 = new TriviaQuestion("The Indian to beat the computers in mathematical wizardry is", "Ramanujam", "Rina Panigrahi", "Raja Ramanna", "Shakunthala Devi", "Shakunthala Devi");
        this.insert(q6);
        TriviaQuestion q7 = new TriviaQuestion("Who is Larry Pressler ?", "Politician", "Painter", "Actor", "Tennis player", "Politician");
        this.insert(q7);
        TriviaQuestion q8 = new TriviaQuestion("Michael Jackson is a distinguished person in the field of ?", "Pop Music", "Jounalism", "Sports", "Acting", "Pop Music");
        this.insert(q8);
        TriviaQuestion q9 = new TriviaQuestion("The first Indian to swim across English channel was ?", "V. Merchant", "P. K. Banerji", "Mihir Sen", "Arati Saha", "Mihir Sen");
        this.insert(q9);
        TriviaQuestion q10 = new TriviaQuestion("Who was the first Indian to make a movie?", "Dhundiraj Govind Phalke", " Asha Bhonsle", " Ardeshir Irani", "V. Shantaram", "Dhundiraj Govind Phalke");
        this.insert(q10);
        TriviaQuestion q11 = new TriviaQuestion("Who is known as the ' Saint of the gutters ?", "B.R.Ambedkar", "Mother Teresa", "Mahatma Gandhi", "Baba Amte", "Mother Teresa");
        this.insert(q11);
        TriviaQuestion q12 = new TriviaQuestion("Who invented the famous formula E=mc^2", "Albert Einstein", "Galilio", "Sarvesh", "Bill Gates", "Albert Einstein");
        this.insert(q12);
       TriviaQuestion q13 = new TriviaQuestion("Who is elected as president of us 2016", "Donald Trump", "Hilary Clinton", "Jhon pol", "Barack Obama", "Donald Trump");
        this.insert(q13);
        TriviaQuestion q14 = new TriviaQuestion("Who was the founder of company Microsoft", "Bill Gates", "Bill Clinton", "Jhon rio", "Steve jobs", "Bill Gates");
        this.insert(q14);
        TriviaQuestion q15 = new TriviaQuestion("Who was the founder of company Apple ?", "Steve Jobs", "Steve Washinton", "Bill Gates", "Jobs Wills", "Steve Jobs");
        this.insert(q15);
        TriviaQuestion q16 = new TriviaQuestion("Who was the founder of company Google ?", "Steve Jobs", "Bill Gates", "Larry Page", "Sundar Pichai", "Larry Page");
        this.insert(q16);
        TriviaQuestion q17 = new TriviaQuestion("Who is know as god of cricket ?", "Sachin Tendulkar", "Kapil Dev", "Virat Koli", "Dhoni", "Sachin Tendulkar");
        this.insert(q17);
        TriviaQuestion q18 = new TriviaQuestion("who has won ballon d'or of 2015 ?", "Lionel Messi", "Cristiano Ronaldo", "Neymar", "Kaka", "Lionel Messi");
        this.insert(q18);
        TriviaQuestion q19 = new TriviaQuestion("who has won ballon d'or of 2014 ?", "Neymar", "Lionel Messi", "Cristiano Ronaldo", "Kaka", "Cristiano Ronaldo");
        this.insert(q19);
        TriviaQuestion q20 = new TriviaQuestion("the Founder of the most famous gaming platform steam is ?", "Bill Cliton", "Bill Williams", "Gabe Newell", "Bill Gates", "Gabe Newell");
        this.insert(q20);
    }
    public void insert(TriviaQuestion triviaQuestion) {
        ContentValues contentvalues = new ContentValues();
       /* contentvalues.put(UID,triviaQuestion.getId());*/
        contentvalues.put(QUESTION, triviaQuestion.getQuestion());
        contentvalues.put(OPTA, triviaQuestion.getOpta());
        contentvalues.put(OPTB, triviaQuestion.getOptb());
        contentvalues.put(OPTC, triviaQuestion.getOptc());
        contentvalues.put(OPTD, triviaQuestion.getOptd());
        contentvalues.put(ANSWER, triviaQuestion.getAnswer());
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(TABLE_NAME, null, contentvalues);
    }
    public List<TriviaQuestion> getAllQuestion() {
        List<TriviaQuestion> que = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        String coloumns[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
        Cursor cursor = db.query(TABLE_NAME, coloumns, null, null, null, null, null);
        while (cursor.moveToNext()) {
            TriviaQuestion triviaQuestion = new TriviaQuestion();
            triviaQuestion.setId(cursor.getInt(0));
            triviaQuestion.setQuestion(cursor.getString(1));
            triviaQuestion.setOpta(cursor.getString(2));
            triviaQuestion.setOptb(cursor.getString(3));
            triviaQuestion.setOptc(cursor.getString(4));
            triviaQuestion.setOptd(cursor.getString(5));
            triviaQuestion.setAnswer(cursor.getString(6));
            que.add(triviaQuestion);
        }
        return que;
    }
}

this is my other activity in order for the above code to function

public class TriviaQuestion extends Activity {
    private int id;
    private String question;
    private String opta;
    private String optb;
    private String optc;
    private String optd;
    private String answer;

    public TriviaQuestion(String q, String oa, String ob, String oc, String od, String ans) {

        question = q;
        opta = oa;
        optb = ob;
        optc = oc;
        optd = od;
        answer = ans;
    }

    public TriviaQuestion() {
        id = 0;
        question = "";
        opta = "";
        optb = "";
        optc = "";
        optd = "";
        answer = "";
    }

   /* public int getId() {
        return id;
    }*/

    public String getQuestion() {
        return question;
    }

    public String getOpta() {
        return opta;
    }

    public String getOptb() {
        return optb;
    }

    public String getOptc() {
        return optc;
    }

    public String getOptd() {
        return optd;
    }

    public String getAnswer() {
        return answer;
    }

    public void setId(int i) {
        id = i;
    }

    public void setQuestion(String q1) {
        question = q1;
    }

    public void setOpta(String o1) {
        opta = o1;
    }

    public void setOptb(String o2) {
        optb = o2;
    }

    public void setOptc(String o3) {
        optc = o3;
    }

    public void setOptd(String o4) {
        optd = o4;
    }

    public void setAnswer(String ans) {
        answer = ans;
    }

}

Body:
This can be done by simply shuffling the TiviaQuestion ArrayList.

Here is an example using String instead of TriviaQuestion

List<String> questions = new ArrayList<>();
questions.add("This is a question!");
questions.add("This is another question!");
questions.add("This is a third question!");

Collections.shuffle(questions);

System.out.println(questions);

Output

[This is another question!, This is a question!, This is a third question!]


问:
Linux wait queue - Combination of exclusive and non-exclusive
Today in class we studied wait queues in Linux and something interesting came up when talking about exclusive/non-exclusive waits.

A question was asked:
What happens if a wait-queue has some processes waiting in the exclusive state and others in the non-exclusive state.

The lecturer replied that the wake_up() will traverse the queue, waking up all non-exclusive processes, until it encounters an exclusive one, and then it will just wake that last process up and stop.

For example:
Let N, E, represent a non-exclusive and exclusive process in the wait queue, respectively:

```<code>N - N - N - E - N - E - N - N
</code>```

The lecturer claimed that the first 4 waits will be woken up (N-N-N-E) and the kernel will stop traversing after the first E.

This sounded weird, since E is exclusive, meaning it doesn't want to be woken up with anyone else, and in this case it is woken up with others.

Googling the question yielded the following:

When a wait queue is “woken up” all tasks on the wait queue are
  enabled for the scheduler. If a task is added to a wait queue using an
  exclusive function then the wake up call will only wake up one
  exclusive task leaving the others still waiting. If a mixture of
  exclusive tasks and non exclusive tasks are added to the queue then
  the wake up function will wake up any non exclusive tasks until it
  wakes up the exclusive task. The wakeup order is normally the reverse
  of the order in which tasks are added to the queue.
  https://blackfin.uclinux.org/doku.php?id=linux-kernel:wait_queues

Which one is correct? Is the real answer something entirely different?

NOTE: In class we are talking about Linux2.4.18-14, i386 (please comment if additional info is needed on the system)

答:
```<code>N - N - N - E - N - E - N - N
</code>```

The first thing to note is that entries that are WQ_FLAG_EXCLUSIVE are added to the end of the queue instead of at the beginning. So, the cited example never occurs; wait queues are always sorted: all Ns, then all Es.

since E is exclusive, meaning it doesn't want to be woken up with anyone else, and in this case it is woken up with others

The second thing to note is that exclusive waiters don't want to be woken up with other exclusive waiters. Presumptively, non-exclusive waiters are performing entirely non-overlapping jobs, while exclusive waiters are doing related jobs--perhaps they all require the same shared resource, so waking them all would cause a "thundering herd" as they all try for the same lock.

Thus, what you found via Google is correct. Most of what you were told is also correct, namely that Linux stops after waking the first exclusive waiter it finds. The suggestion that the wait queue is unsorted by exclusivity was not correct, however.

Body:
Today in class we studied wait queues in Linux and something interesting came up when talking about exclusive/non-exclusive waits.

A question was asked:
What happens if a wait-queue has some processes waiting in the exclusive state and others in the non-exclusive state.

The lecturer replied that the wake_up() will traverse the queue, waking up all non-exclusive processes, until it encounters an exclusive one, and then it will just wake that last process up and stop.

For example:
Let N, E, represent a non-exclusive and exclusive process in the wait queue, respectively:

N - N - N - E - N - E - N - N

The lecturer claimed that the first 4 waits will be woken up (N-N-N-E) and the kernel will stop traversing after the first E.

This sounded weird, since E is exclusive, meaning it doesn't want to be woken up with anyone else, and in this case it is woken up with others.

Googling the question yielded the following:

When a wait queue is “woken up” all tasks on the wait queue are
  enabled for the scheduler. If a task is added to a wait queue using an
  exclusive function then the wake up call will only wake up one
  exclusive task leaving the others still waiting. If a mixture of
  exclusive tasks and non exclusive tasks are added to the queue then
  the wake up function will wake up any non exclusive tasks until it
  wakes up the exclusive task. The wakeup order is normally the reverse
  of the order in which tasks are added to the queue.
  https://blackfin.uclinux.org/doku.php?id=linux-kernel:wait_queues

Which one is correct? Is the real answer something entirely different?

NOTE: In class we are talking about Linux2.4.18-14, i386 (please comment if additional info is needed on the system)

Body:
N - N - N - E - N - E - N - N

The first thing to note is that entries that are WQ_FLAG_EXCLUSIVE are added to the end of the queue instead of at the beginning. So, the cited example never occurs; wait queues are always sorted: all Ns, then all Es.

since E is exclusive, meaning it doesn't want to be woken up with anyone else, and in this case it is woken up with others

The second thing to note is that exclusive waiters don't want to be woken up with other exclusive waiters. Presumptively, non-exclusive waiters are performing entirely non-overlapping jobs, while exclusive waiters are doing related jobs--perhaps they all require the same shared resource, so waking them all would cause a "thundering herd" as they all try for the same lock.

Thus, what you found via Google is correct. Most of what you were told is also correct, namely that Linux stops after waking the first exclusive waiter it finds. The suggestion that the wait queue is unsorted by exclusivity was not correct, however.


问:
Web Scraping with Python (city) as parameter
```<code>def findWeather(city):
  import urllib

  connection = urllib.urlopen("http://www.canoe.ca/Weather/World.html")
  rate = connection.read()
  connection.close()
  currentLoc = rate.find(city)
  curr = rate.find("currentDegree")
  temploc = rate.find("</span>", curr)
  tempstart = rate.rfind(">", 0, temploc)
  print "current temp:", rate[tempstart+1:temploc]
</code>```

The link is provided above. The issue I have is everytime I run the program and use, say "Brussels" in Belgium, as the parameter, i.e findWeather("Brussels"), it will always print 24c as the temperature whereas (as I am writing this) it should be 19c. This is the case for many other cities provided by the site. Help on this code would be appreciated.

Thanks!

答:
This one should work:   </p>

```<code>import requests
from bs4 import BeautifulSoup
url = 'http://www.canoe.ca/Weather/World.html'
response = requests.get(url)
# Get the text of the contents
html_content = response.text
# Convert the html content into a beautiful soup object
soup = BeautifulSoup(html_content, 'lxml')
cities = soup.find_all("span", class_="titleText")

cels = soup.find_all("span", class_="currentDegree")

for x,y in zip(cities,cels):
    print (x.text,y.text)
</code>```

Body:
def findWeather(city):
  import urllib

  connection = urllib.urlopen("http://www.canoe.ca/Weather/World.html")
  rate = connection.read()
  connection.close()
  currentLoc = rate.find(city)
  curr = rate.find("currentDegree")
  temploc = rate.find("", curr)
  tempstart = rate.rfind(">", 0, temploc)
  print "current temp:", rate[tempstart+1:temploc]

The link is provided above. The issue I have is everytime I run the program and use, say "Brussels" in Belgium, as the parameter, i.e findWeather("Brussels"), it will always print 24c as the temperature whereas (as I am writing this) it should be 19c. This is the case for many other cities provided by the site. Help on this code would be appreciated.

Thanks!

Body:
This one should work:

import requests
from bs4 import BeautifulSoup
url = 'http://www.canoe.ca/Weather/World.html'
response = requests.get(url)
# Get the text of the contents
html_content = response.text
# Convert the html content into a beautiful soup object
soup = BeautifulSoup(html_content, 'lxml')
cities = soup.find_all("span", class_="titleText")

cels = soup.find_all("span", class_="currentDegree")

for x,y in zip(cities,cels):
    print (x.text,y.text)


问:
Error: array_flip() expects parameter 1 to be array, string given
I am new to Laravel, getting the following error,

array_flip() expects parameter 1 to be array, string given

```<code>in GuardsAttributes.php line 188
at HandleExceptions->handleError(2, 'array_flip() expects parameter 1 to be array, string given', '/Users/aaronmk2/Desktop/CodingDojo/php/onetoone/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php', 188, array('attributes' => array('name' => '2250 nw 59st Seattle, WA 98107')))
at array_flip('name') in GuardsAttributes.php line 188
at Model->fillableFromArray(array('name' => '2250 nw 59st Seattle, WA 98107')) in Model.php line 216
at Model->fill(array('name' => '2250 nw 59st Seattle, WA 98107')) in Model.php line 145
at Model->__construct(array('name' => '2250 nw 59st Seattle, WA 98107')) in web.php line 24
</code>```

Here is the code that is creating the problem

```<code>Route::get('/insert', function(){
    $user = User::findOrFail(1);

    $address = new Address(['name' => '2250 nw 59st Seattle, WA 98107']);

    $user->address()->save( $address);
});
</code>```

What is the issue and how can I fix it.

答:
If you'll look into 5.4 source code, you'll see that this error occurs because you have defined $fillable property as a string, like:

```<code>protected $fillable = 'name';
</code>```

But it should be an array:

```<code>protected $fillable = ['name'];
</code>```

Body:
I am new to Laravel, getting the following error,

array_flip() expects parameter 1 to be array, string given

in GuardsAttributes.php line 188
at HandleExceptions->handleError(2, 'array_flip() expects parameter 1 to be array, string given', '/Users/aaronmk2/Desktop/CodingDojo/php/onetoone/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/GuardsAttributes.php', 188, array('attributes' => array('name' => '2250 nw 59st Seattle, WA 98107')))
at array_flip('name') in GuardsAttributes.php line 188
at Model->fillableFromArray(array('name' => '2250 nw 59st Seattle, WA 98107')) in Model.php line 216
at Model->fill(array('name' => '2250 nw 59st Seattle, WA 98107')) in Model.php line 145
at Model->__construct(array('name' => '2250 nw 59st Seattle, WA 98107')) in web.php line 24

Here is the code that is creating the problem

Route::get('/insert', function(){
    $user = User::findOrFail(1);

    $address = new Address(['name' => '2250 nw 59st Seattle, WA 98107']);

    $user->address()->save( $address);
});

What is the issue and how can I fix it.

Body:
If you'll look into 5.4 source code, you'll see that this error occurs because you have defined $fillable property as a string, like:

protected $fillable = 'name';

But it should be an array:

protected $fillable = ['name'];


问:
suffix or operands invalid for `move' with gcc
So after trying to compile a C program with gcc on Mac I was met with an unexpected error.

The original program was reduced to a simple test printf statement.

```<code>#include <stdio.h>
int main(void){
printf("test");
return 0;
}
</code>```

error:

```<code>/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:36:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:44:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:52:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:57:suffix or operands invalid for `movq'
</code>```

What causes this issue and how do i resolve it?

答:
So it seems to be a conflict between brew and Macports. I dont know specifically what caused the conflict.

But Uninstalling Macports allowed me to successfully compile without the issue:

```<code>sudo port -fp uninstall installed
</code>```

Hope this helps anyone else experiencing the same issue.

Body:
So after trying to compile a C program with gcc on Mac I was met with an unexpected error.

The original program was reduced to a simple test printf statement.

#include <stdio.h>
int main(void){
printf("test");
return 0;
}

error:

/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:36:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:44:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:52:suffix or operands invalid for `movq'
/var/folders/bh/npq9sw994k3bzrxgwyc9kv2h0000gn/T//cceggs5M.s:57:suffix or operands invalid for `movq'

What causes this issue and how do i resolve it?

Body:
So it seems to be a conflict between brew and Macports. I dont know specifically what caused the conflict.

But Uninstalling Macports allowed me to successfully compile without the issue:

sudo port -fp uninstall installed

Hope this helps anyone else experiencing the same issue.


问:
WSO2 Identity Server - Sending Multiple Attributes in the Request to a Custom Policy Info Point (PIP) in WSO2IS
I'm using WSO2IS 5.3.0 and I have followed the instructions on this web site: https://docs.wso2.com/display/IS530/Writing+a+Custom+Policy+Info+Point

I've successfully implemented the custom PIP attribute finder (KMarketJDBCAttributeFinder), so far so good. The problem I'm having is that I want to send more than one attribute, but the AttributeFinder only picks one. Next, my policy and request:

XACML Policy:

<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
        xmlns:xacml="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
        PolicyId="My-Custom-Policy"
        RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
        Version="1.0">
<Target>
  <AnyOf>
    <AllOf>
      <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">subj-id</AttributeValue>
        <AttributeDesignator
                MustBePresent="false"
                Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id"
                DataType="http://www.w3.org/2001/XMLSchema#string"/>
      </Match>
    </AllOf>
  </AnyOf>
</Target>
<Rule RuleId="rule1" Effect="Permit">
  <Target>
    <AnyOf>
      <AllOf>
        <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
          <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">action-value</AttributeValue>
          <AttributeDesignator
                  MustBePresent="false"
                  Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
                  AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
                  DataType="http://www.w3.org/2001/XMLSchema#string"/>
        </Match>
      </AllOf>
    </AnyOf>
  </Target>
  <Condition>
    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
      <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/>
      <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">some-value-returned-by-custom-pip-finder-jar</AttributeValue>
      <AttributeDesignator
              Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
              AttributeId="urn:my:custom:id:data-one"
              DataType="http://www.w3.org/2001/XMLSchema#string"
              MustBePresent="false"/>
    </Apply>
  </Condition>
</Rule>
<Rule RuleId="rule2" Effect="Deny"/>
</Policy>
```

<hr>

<p><strong>XACML Request:</strong></p>

<pre class="lang-xml prettyprint-override"><code><Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">
    <Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">subj-id</AttributeValue>
        </Attribute>
    </Attributes>

    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">action-value</AttributeValue>
        </Attribute>
    </Attributes>

    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">re-src-id</AttributeValue>
        </Attribute>
        <Attribute AttributeId="urn:my:custom:id:data-one" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">data-one</AttributeValue>
        </Attribute>
        <Attribute AttributeId="urn:my:custom:id:data-two" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">data-two</AttributeValue>
        </Attribute>
    </Attributes>
</Request>
</code>```

As you can see, I'm sending three attributes as part of the resource category; but when I debug the code, I only see that one of those attributes is picked up (the others are ignored)

Also, from the request and policy I have used customs AttributeId: urn:my:custom:id:data-one and urn:my:custom:id:data-two

¿How can I send multiple attributes (without using the option "Multiple Requests", I just one to send one single request) and confirm that all attributes are properly obtained by my custom attributeFinder PIP extension?

答:
Analyzing the code of the Abstract class in charge of picking up the attributes from the request, the method that creates the bag of attributes only picks one; and that's way my test is not working.

The solution I found was to create my own abstract class that implements the class PIPAttributeFinder and pick up all attributes from the request:

... (other code)

    List<String> resourceList = new ArrayList<String>();

    EvaluationResult resource = evaluationCtx.getAttribute(new URI("http://www.w3.org/2001/XMLSchema#string"), new URI("urn:oasis:names:tc:xacml:1.0:resource:resource-id"), issuer, new URI("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"));
    if (resource != null && resource.getAttributeValue() != null && resource.getAttributeValue().isBag()) {
        key = (BagAttribute) resource.getAttributeValue();
        if (key.size() > 0) {
            Iterator iterator = key.iterator();
            String encodeAttribute = "";
            while(iterator.hasNext()) {
                AttributeValue attributeValue = (AttributeValue)iterator.next();
                encodeAttribute = attributeValue.encode();
                resourceList.add(encodeAttribute);
            }
            if (log.isDebugEnabled()) {
                log.debug(String.format("Finding attributes for the resource %1$s", new Object[]{encodeAttribute}));
            }
            resourceId = "empty-value";
        }
    }

... (other code)

    attributeValues = this.getAttributeValues(subjectId, resourceId, resourceList, actionId, environmentId, attributeId.toString(), issuer);

... (other code)
```

Keep in mind that you need to modify the signature of the method getAttributeValues

Body:
I'm using WSO2IS 5.3.0 and I have followed the instructions on this web site: https://docs.wso2.com/display/IS530/Writing+a+Custom+Policy+Info+Point

I've successfully implemented the custom PIP attribute finder (KMarketJDBCAttributeFinder), so far so good. The problem I'm having is that I want to send more than one attribute, but the AttributeFinder only picks one. Next, my policy and request:

XACML Policy:

<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
        xmlns:xacml="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17"
        PolicyId="My-Custom-Policy"
        RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:first-applicable"
        Version="1.0">
<Target>
  <AnyOf>
    <AllOf>
      <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-regexp-match">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">subj-id</AttributeValue>
        <AttributeDesignator
                MustBePresent="false"
                Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"
                AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id"
                DataType="http://www.w3.org/2001/XMLSchema#string"/>
      </Match>
    </AllOf>
  </AnyOf>
</Target>
<Rule RuleId="rule1" Effect="Permit">
  <Target>
    <AnyOf>
      <AllOf>
        <Match MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
          <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">action-value</AttributeValue>
          <AttributeDesignator
                  MustBePresent="false"
                  Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action"
                  AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id"
                  DataType="http://www.w3.org/2001/XMLSchema#string"/>
        </Match>
      </AllOf>
    </AnyOf>
  </Target>
  <Condition>
    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
      <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/>
      <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">some-value-returned-by-custom-pip-finder-jar</AttributeValue>
      <AttributeDesignator
              Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource"
              AttributeId="urn:my:custom:id:data-one"
              DataType="http://www.w3.org/2001/XMLSchema#string"
              MustBePresent="false"/>
    </Apply>
  </Condition>
</Rule>
<Rule RuleId="rule2" Effect="Deny"/>
</Policy>

XACML Request:

<Request xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" CombinedDecision="false" ReturnPolicyIdList="false">
    <Attributes Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">subj-id</AttributeValue>
        </Attribute>
    </Attributes>

    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">action-value</AttributeValue>
        </Attribute>
    </Attributes>

    <Attributes Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource">
        <Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">re-src-id</AttributeValue>
        </Attribute>
        <Attribute AttributeId="urn:my:custom:id:data-one" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">data-one</AttributeValue>
        </Attribute>
        <Attribute AttributeId="urn:my:custom:id:data-two" IncludeInResult="false">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">data-two</AttributeValue>
        </Attribute>
    </Attributes>
</Request>

As you can see, I'm sending three attributes as part of the resource category; but when I debug the code, I only see that one of those attributes is picked up (the others are ignored)

Also, from the request and policy I have used customs AttributeId: urn:my:custom:id:data-one and urn:my:custom:id:data-two

¿How can I send multiple attributes (without using the option "Multiple Requests", I just one to send one single request) and confirm that all attributes are properly obtained by my custom attributeFinder PIP extension?

Body:
Analyzing the code of the Abstract class in charge of picking up the attributes from the request, the method that creates the bag of attributes only picks one; and that's way my test is not working.

The solution I found was to create my own abstract class that implements the class PIPAttributeFinder and pick up all attributes from the request:

... (other code)

    List<String> resourceList = new ArrayList<String>();

    EvaluationResult resource = evaluationCtx.getAttribute(new URI("http://www.w3.org/2001/XMLSchema#string"), new URI("urn:oasis:names:tc:xacml:1.0:resource:resource-id"), issuer, new URI("urn:oasis:names:tc:xacml:3.0:attribute-category:resource"));
    if (resource != null && resource.getAttributeValue() != null && resource.getAttributeValue().isBag()) {
        key = (BagAttribute) resource.getAttributeValue();
        if (key.size() > 0) {
            Iterator iterator = key.iterator();
            String encodeAttribute = "";
            while(iterator.hasNext()) {
                AttributeValue attributeValue = (AttributeValue)iterator.next();
                encodeAttribute = attributeValue.encode();
                resourceList.add(encodeAttribute);
            }
            if (log.isDebugEnabled()) {
                log.debug(String.format("Finding attributes for the resource %1$s", new Object[]{encodeAttribute}));
            }
            resourceId = "empty-value";
        }
    }

... (other code)

    attributeValues = this.getAttributeValues(subjectId, resourceId, resourceList, actionId, environmentId, attributeId.toString(), issuer);

... (other code)

Keep in mind that you need to modify the signature of the method getAttributeValues


问:
Why do I need to keep hbase/lib folder in hdfs?
I have a main cluster which has some data in Hbase, and I want to replicate it. I've already created a backup cluster and created snapshot of the table I want to replicate. I am trying to export the snapshot from source cluster to destination, but I am getting some errors.
I am executing

```<code>./hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot mySnap -copy-to hdfs://198.58.88.11:9000/hbase
</code>```

and as a result of execution I got

```<code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/vagrant/hbase/lib/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/vagrant/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
2015-03-05 10:58:43,155 INFO  [main] snapshot.ExportSnapshot: Copy Snapshot Manifest
2015-03-05 10:58:43,596 INFO  [main] Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
2015-03-05 10:58:43,597 INFO  [main] jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
2015-03-05 10:58:43,890 INFO  [main] mapreduce.JobSubmitter: Cleaning up the staging area file:/home/vagrant/hadoop/hadoop-datastore/mapred/staging/vagrant1489762780/.staging/job_local1489762780_0001
2015-03-05 10:58:43,892 ERROR [main] snapshot.ExportSnapshot: Snapshot export failed
java.io.FileNotFoundException: File does not exist: hdfs://namenode:9000/home/vagrant/hbase/lib/hbase-client-1.0.0.jar
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1072)
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1064)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1064)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:288)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:224)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:93)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(ClientDistributedCacheManager.java:57)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:265)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:389)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1285)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1282)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1614)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1282)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1303)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.runCopyJob(ExportSnapshot.java:775)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.run(ExportSnapshot.java:934)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.innerMain(ExportSnapshot.java:1008)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.main(ExportSnapshot.java:1012)
</code>```

So, as I understood, it tries to find base-client-1.0.0.jar
But is looking in hdfs://namenode:9000/home/vagrant/hbase/lib/hbase-client-1.0.0.jar and not in local storage.
Any ideas why it is happening?

答:
I have stumbled upon this with HBase 1.0 and HDFS 2.6.0 from Cloudera 5.

The workaround that I used and which made it work is ..to actually copy those JARs into HDFS. I know that it's ugly, but it works so it's better that nothing.

Start with:

```<code>export CLUSTER_NAME=<your_hdfs_cluster_name>
</code>```

..and then create the necessary dirs with:

```<code>hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hbase/lib/
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/zookeeper
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hadoop-mapreduce
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hadoop
</code>```

...and copy all the JARs with:

```<code>hdfs dfs -cp file:///usr/lib/hbase/lib/*.jar hdfs://$CLUSTER_NAME/usr/lib/hbase/lib/
hdfs dfs -cp file:///usr/lib/zookeeper/*.jar hdfs://$CLUSTER_NAME/usr/lib/zookeeper
hdfs dfs -cp file:///usr/lib/hadoop-mapreduce/*.jar hdfs://$CLUSTER_NAME/usr/lib/hadoop-mapreduce
hdfs dfs -cp file:///usr/lib/hadoop/*.jar hdfs://$CLUSTER_NAME/usr/lib/hadoop
</code>```

Body:
I have a main cluster which has some data in Hbase, and I want to replicate it. I've already created a backup cluster and created snapshot of the table I want to replicate. I am trying to export the snapshot from source cluster to destination, but I am getting some errors.
I am executing

./hbase org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot mySnap -copy-to hdfs://198.58.88.11:9000/hbase

and as a result of execution I got

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/vagrant/hbase/lib/slf4j-log4j12-1.7.7.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/vagrant/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
2015-03-05 10:58:43,155 INFO  [main] snapshot.ExportSnapshot: Copy Snapshot Manifest
2015-03-05 10:58:43,596 INFO  [main] Configuration.deprecation: session.id is deprecated. Instead, use dfs.metrics.session-id
2015-03-05 10:58:43,597 INFO  [main] jvm.JvmMetrics: Initializing JVM Metrics with processName=JobTracker, sessionId=
2015-03-05 10:58:43,890 INFO  [main] mapreduce.JobSubmitter: Cleaning up the staging area file:/home/vagrant/hadoop/hadoop-datastore/mapred/staging/vagrant1489762780/.staging/job_local1489762780_0001
2015-03-05 10:58:43,892 ERROR [main] snapshot.ExportSnapshot: Snapshot export failed
java.io.FileNotFoundException: File does not exist: hdfs://namenode:9000/home/vagrant/hbase/lib/hbase-client-1.0.0.jar
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1072)
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1064)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1064)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:288)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:224)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:93)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(ClientDistributedCacheManager.java:57)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:265)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:301)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:389)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1285)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1282)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1614)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1282)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1303)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.runCopyJob(ExportSnapshot.java:775)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.run(ExportSnapshot.java:934)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.innerMain(ExportSnapshot.java:1008)
    at org.apache.hadoop.hbase.snapshot.ExportSnapshot.main(ExportSnapshot.java:1012)

So, as I understood, it tries to find base-client-1.0.0.jar
But is looking in hdfs://namenode:9000/home/vagrant/hbase/lib/hbase-client-1.0.0.jar and not in local storage.
Any ideas why it is happening?

Body:
I have stumbled upon this with HBase 1.0 and HDFS 2.6.0 from Cloudera 5.

The workaround that I used and which made it work is ..to actually copy those JARs into HDFS. I know that it's ugly, but it works so it's better that nothing.

Start with:

export CLUSTER_NAME=<your_hdfs_cluster_name>

..and then create the necessary dirs with:

hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hbase/lib/
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/zookeeper
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hadoop-mapreduce
hdfs dfs -mkdir -p hdfs://$CLUSTER_NAME/usr/lib/hadoop

...and copy all the JARs with:

hdfs dfs -cp file:///usr/lib/hbase/lib/*.jar hdfs://$CLUSTER_NAME/usr/lib/hbase/lib/
hdfs dfs -cp file:///usr/lib/zookeeper/*.jar hdfs://$CLUSTER_NAME/usr/lib/zookeeper
hdfs dfs -cp file:///usr/lib/hadoop-mapreduce/*.jar hdfs://$CLUSTER_NAME/usr/lib/hadoop-mapreduce
hdfs dfs -cp file:///usr/lib/hadoop/*.jar hdfs://$CLUSTER_NAME/usr/lib/hadoop


问:
Would tf.upgrade.py work to update tensorflow files 0.x to 1.0.1 or does it only upgrade to 1.0 version
https://www.tensorflow.org/install/migration

Please help! I need to migrate to the latest version

答: It's basically the same thing. Most of the code is compatible there are only a few categories of things that might causes issues. But yes, you can use it to migrate. Just make sure that you then continue to follow along with any release updates to keep your code up to date!


答:
In getAllQuestion() you can shuffle the que List before returning it to randomize them.</p>

```<code>Collections.shuffle(que);
</code>```

Title: how to randomize this set of questions?

Body:
In getAllQuestion() you can shuffle the que List before returning it to randomize them.

Collections.shuffle(que);


问:
Editing a Wizard multistep form after save - Wicked Gem / Rails
I've been going round in circles all day with this. I have a large multi-step form using the Wicked gem and Ruby on Rails. It works perfectly but I can't figure out how to to get back into the form to edit individual entries.

Iim trying to make the ability to go into the client show page, click an individual client and then from there go back into the quote to edit and update it. As the Wicked gem only seems to work with show and update actions, if I try to build a standard edit action Wicked expects to be on a step therefore doesn't work.
I read the I would have to factor the edit action into my show/update actions but I'm having difficulties. Any help would be great thanks!

Clients Controller:

```<code>class ClientsController < ApplicationController
before_action :authenticate_user!, only: [:index, :show, :edit]
before_action :set_client, only: [:edit, :show, :update]

def index
    @clients = Client.order('created_at DESC').paginate(page: params[:page], per_page: 10)
end

def show; end

def new
    @client = Client.new
end

def edit; end

def update
    if @client.update_attributes(client_params)
        redirect_to client_quotes_path
        flash[:success] = 'Client successfully updated'
    else
        render 'edit'
    end
    render_wizard @client
end

# After client is completed:
def create
    @client = Client.new(client_params)
    if @client.valid?
        @client.save
        session[:current_user_id] = @client.id
        ClientMailer.new_client(@client).deliver
        redirect_to quotes_path
    else
        flash[:alert] = 'Sorry, there was a problem with your message. Please contact us directly at ...'
        render :new
    end
end

private

def set_client
    @client = Client.find(params[:id])
end

def client_params
    params.require(:client).permit(:first_name, :last_name, :title, :email, :email_confirmation,
                                   :phone, :time, :reminder, :ref_number, :day, :note, :logs_reminder)
end
end
</code>```

Quotes Controller:

```<code>class QuotesController < ApplicationController
include Wicked::Wizard
before_action :set_client, only: [:show, :update, :quote_success]
steps :profile, :employment, :general_questions, :indemnity_details, :declarations

def show
    @client.build_doctor unless @client.doctor.present?
    @client.build_dentist unless @client.dentist.present?
    @client.old_insurers.build
    @client.practice_addresses.build
    render_wizard
end

def update
    @client.update(client_params)
    render_wizard @client
end

def quote_success; end

private

def set_client
    current_user = Client.find_by_id(session[:current_user_id])
    @client = current_user
end

# After full quote form is completed:
def finish_wizard_path
    if @client.valid?
        ClientMailer.new_quote(@client).deliver
        ClientMailer.new_quote_user_message(@client).deliver
      end
        quote_success_path
    end
end

def client_params
    params.require(:client).permit(:name, :email, :email_confirmation, :phone, :date_required,
                                   :title, :first_name, :last_name, :date_of_birth, :nationality, :reg_body, :reg_date, :reg_type, :reg_number,
                                   :qual_place, :qual_year, :post_grad, :membership ...
</code>```

Routes:

```<code>Rails.application.routes.draw do

devise_for :users

root 'clients#new'

get 'client', to: 'clients#new', as: 'client'
post 'client', to: 'clients#create'

get '/client_quotes', to: 'clients#index', as: 'client_quotes'
get '/client_quotes/:id', to: 'clients#show', as: 'client_quote'
get '/client_quotes/:id/edit', to: 'clients#edit', as: 'edit_client_quote'
patch '/client_quotes/:id', to: 'clients#update'
put '/client_quotes/:id', to: 'clients#update'

resources :quotes, only: [:index, :show, :update, :quote_success]

get 'quote-success' => 'quotes#quote_success'

devise_scope :user do
    get '/login' => 'devise/sessions#new'
end
end
</code>```

答: My solution to this in the end was rather than have the edit form as a multi step wizard, I've joined the form data together in a separate view page and got a traditional route to it as you mention. Not perfect but does the job!</p>

Body:
I've been going round in circles all day with this. I have a large multi-step form using the Wicked gem and Ruby on Rails. It works perfectly but I can't figure out how to to get back into the form to edit individual entries.

Iim trying to make the ability to go into the client show page, click an individual client and then from there go back into the quote to edit and update it. As the Wicked gem only seems to work with show and update actions, if I try to build a standard edit action Wicked expects to be on a step therefore doesn't work.
I read the I would have to factor the edit action into my show/update actions but I'm having difficulties. Any help would be great thanks!

Clients Controller:

class ClientsController < ApplicationController
before_action :authenticate_user!, only: [:index, :show, :edit]
before_action :set_client, only: [:edit, :show, :update]

def index
    @clients = Client.order('created_at DESC').paginate(page: params[:page], per_page: 10)
end

def show; end

def new
    @client = Client.new
end

def edit; end

def update
    if @client.update_attributes(client_params)
        redirect_to client_quotes_path
        flash[:success] = 'Client successfully updated'
    else
        render 'edit'
    end
    render_wizard @client
end

# After client is completed:
def create
    @client = Client.new(client_params)
    if @client.valid?
        @client.save
        session[:current_user_id] = @client.id
        ClientMailer.new_client(@client).deliver
        redirect_to quotes_path
    else
        flash[:alert] = 'Sorry, there was a problem with your message. Please contact us directly at ...'
        render :new
    end
end

private

def set_client
    @client = Client.find(params[:id])
end

def client_params
    params.require(:client).permit(:first_name, :last_name, :title, :email, :email_confirmation,
                                   :phone, :time, :reminder, :ref_number, :day, :note, :logs_reminder)
end
end

Quotes Controller:

class QuotesController < ApplicationController
include Wicked::Wizard
before_action :set_client, only: [:show, :update, :quote_success]
steps :profile, :employment, :general_questions, :indemnity_details, :declarations

def show
    @client.build_doctor unless @client.doctor.present?
    @client.build_dentist unless @client.dentist.present?
    @client.old_insurers.build
    @client.practice_addresses.build
    render_wizard
end

def update
    @client.update(client_params)
    render_wizard @client
end

def quote_success; end

private

def set_client
    current_user = Client.find_by_id(session[:current_user_id])
    @client = current_user
end

# After full quote form is completed:
def finish_wizard_path
    if @client.valid?
        ClientMailer.new_quote(@client).deliver
        ClientMailer.new_quote_user_message(@client).deliver
      end
        quote_success_path
    end
end

def client_params
    params.require(:client).permit(:name, :email, :email_confirmation, :phone, :date_required,
                                   :title, :first_name, :last_name, :date_of_birth, :nationality, :reg_body, :reg_date, :reg_type, :reg_number,
                                   :qual_place, :qual_year, :post_grad, :membership ...

Routes:

Rails.application.routes.draw do

devise_for :users

root 'clients#new'

get 'client', to: 'clients#new', as: 'client'
post 'client', to: 'clients#create'

get '/client_quotes', to: 'clients#index', as: 'client_quotes'
get '/client_quotes/:id', to: 'clients#show', as: 'client_quote'
get '/client_quotes/:id/edit', to: 'clients#edit', as: 'edit_client_quote'
patch '/client_quotes/:id', to: 'clients#update'
put '/client_quotes/:id', to: 'clients#update'

resources :quotes, only: [:index, :show, :update, :quote_success]

get 'quote-success' => 'quotes#quote_success'

devise_scope :user do
    get '/login' => 'devise/sessions#new'
end
end


问:
How can I adjust the .init event for TinyMCE in EpiServer 8.0?
We need to get to the .init event for TinyMCE in the CMS to be able to adjust some of the settings.  How can we do this?  Here is an example of something we'd like to be able to perform.

```<code>tinymce.init({
    some_property : 'do something'
});
</code>```

This is so we can adjust content filtering in TinyMCE.  My understanding is that this version of EpiServer uses TinyMCE 3.9.3. Thanks for your help.

答: There is a section about creating an implementation of IDynamicConfigurationOptions in the EPiServer documentation specific for TinyMCE. You have to create a class that implements IDynamicConfigurationOptions and in the GetConfigurationOptions() method you can return your data in the dictionary.</p>

Body:
We need to get to the .init event for TinyMCE in the CMS to be able to adjust some of the settings.  How can we do this?  Here is an example of something we'd like to be able to perform.

tinymce.init({
    some_property : 'do something'
});

This is so we can adjust content filtering in TinyMCE.  My understanding is that this version of EpiServer uses TinyMCE 3.9.3. Thanks for your help.


问:
What will happen when you put variable as counter in a for statement?
Can anyone tell the value of counter at each iteration?</p>

```<code>Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As Integer
        For x = 1 To 10 Step (x)
            x = x + 1
            MsgBox(x)
        Next
    End Sub

End Class
</code>```

答:
The iterations will be:

x=2

x=4

x=6

x=8

x=10

But how?

For the first time when you execute a loop the value will be x=1.

Later inside the loop the value of x becomes x=x+1 ie x=2.

Now this value is used as step so your code takes steps of size 2.

In VB once the size of a step is calculated it is not recalculated. For example here in the second iteration the value becomes x=4 that doesn't mean it will now take a step size 4. It will use previously calculated value ie 2.

Body:
Can anyone tell the value of counter at each iteration?

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim x As Integer
        For x = 1 To 10 Step (x)
            x = x + 1
            MsgBox(x)
        Next
    End Sub

End Class


问:
How to change the field delete instead of id in loopback?
I want to the delete a few rows in MySQL table using loopabck. But I don't want to use the id to delete the record. I'm trying it in Angular SDK. My code is:

```<code>ModelName.destroyById({ fieldName : myValue })
                          .$promise
                          .then(function() {

                          });
</code>```

I'd be very thankful for ideas.

答:
Seems like you need to use the destroyAll method, which does what you want, but you need to set up remoting for it first, since it's disabled by default:

```<code>  ModelName.remoteMethod('destroyAll', {
    isStatic: true,
    description: 'Delete all matching records',
    accessType: 'WRITE',
    accepts: {arg: 'where', type: 'object', description: 'filter.where object'},
    http: {verb: 'del', path: '/'}
  });
</code>```

Then after that you regenerate your Angular client and you can use it like this in the client side:

```<code>ModelName.destroyAll({ filter: { fieldName : myValue }}).$promise.then(...)
</code>```

Note that using destroyAll is risky as if you have any mistakes in your code you will end up losing data. Enabling it to client side might be security concern.

Another way to do this is to write your own remote method which uses destroyAll in turn with proper validation of the inputs.

Body:
I want to the delete a few rows in MySQL table using loopabck. But I don't want to use the id to delete the record. I'm trying it in Angular SDK. My code is:

ModelName.destroyById({ fieldName : myValue })
                          .$promise
                          .then(function() {

                          });

I'd be very thankful for ideas.

Body:
Seems like you need to use the destroyAll method, which does what you want, but you need to set up remoting for it first, since it's disabled by default:

  ModelName.remoteMethod('destroyAll', {
    isStatic: true,
    description: 'Delete all matching records',
    accessType: 'WRITE',
    accepts: {arg: 'where', type: 'object', description: 'filter.where object'},
    http: {verb: 'del', path: '/'}
  });

Then after that you regenerate your Angular client and you can use it like this in the client side:

ModelName.destroyAll({ filter: { fieldName : myValue }}).$promise.then(...)

Note that using destroyAll is risky as if you have any mistakes in your code you will end up losing data. Enabling it to client side might be security concern.

Another way to do this is to write your own remote method which uses destroyAll in turn with proper validation of the inputs.


问:
How to display the output of the following code using iterators?
This code is for creating adjacency list(i think) and i want to display the content in the vector

```<code>#include<iostream>
#include<vector>
int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector< int > graph[ N + 1 ];
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph[ u ].push_back( v );
    }
    /*vector<int>iterator::it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;*/
}
</code>```

I tried to display the output using the lines commented in the code but it gives me compile error saying:

```<code>struct std::iterator used without template parameters
</code>```

Your help will be appreciated....

答:
You can use index instead of iterators in C++ vectors.

```<code>for(int i=0;i<M;i++)
    cout<<graph[i]<<endl;
</code>```

In order to use iterator you have to correct your code such as following:

```<code>#include<iostream>
#include<vector>
#include <stdio.h>
using namespace std;

int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector<int> graph;
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph.push_back(u);
        graph.push_back(v);
    }
    vector<int>::iterator it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;
}
</code>```

you problem is creating array of vector in your instantiation.

Body:
This code is for creating adjacency list(i think) and i want to display the content in the vector

#include<iostream>
#include<vector>
int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector< int > graph[ N + 1 ];
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph[ u ].push_back( v );
    }
    /*vector<int>iterator::it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;*/
}

I tried to display the output using the lines commented in the code but it gives me compile error saying:

struct std::iterator used without template parameters

Your help will be appreciated....

Body:
You can use index instead of iterators in C++ vectors.

for(int i=0;i<M;i++)
    cout<<graph[i]<<endl;

In order to use iterator you have to correct your code such as following:

#include<iostream>
#include<vector>
#include <stdio.h>
using namespace std;

int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector<int> graph;
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph.push_back(u);
        graph.push_back(v);
    }
    vector<int>::iterator it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;
}

you problem is creating array of vector in your instantiation.


问:
check if any duplicate words exist in a string using regex
Using regex in javascript, how to check for the condition when duplicate words are present in a string?
The words could be located any where in the string:

Given: "but boys run fast boys are strong" or

"boys boys"

expected result: true, since there are 2 repeats of the word "boys"

答:
Taking into consideration that spaces are there after each word</p>

```<code>var string = "but boys run fast boys are strong";

var strArray= string.split(" ");

var unique = [];
 for(var i =0; i< strArray.length; i++)
 {
   eval(unique[strArray] = new Object());
 }
</code>```

Body:
Taking into consideration that spaces are there after each word

var string = "but boys run fast boys are strong";

var strArray= string.split(" ");

var unique = [];
 for(var i =0; i< strArray.length; i++)
 {
   eval(unique[strArray] = new Object());
 }


问:
For alphanumeric tags separated by commas?
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma and nothing else, no spaces. (e.g. "Cars,Vehicle,Tiger Cactus, Bed")

An example of what I mean is this, these would be valid tags:

```<code>boy,man,girl,woman,tyrannosaurus rex,lion
</code>```

And these would be invalid tags:

```<code>hat, cat, rat, c3po, @gmail
</code>```

Because there are spaces between the tags and invalid characters.

Also, how would I count the tags for imposing a limit?

Edited for clarification!

答:
(?:([\w\s]+)(?:,\s*))* would get any number of tags separated by commas.

(?:([\w\s]+)(?:,\s*)){n} would match n tags where n is an integer.

(?:([\w\s]+)(?:,\s*)){0,n} would match 0 to n tags where n is an integer.

In order to count the tags, you'll need to check the number of captured groups.

Body:
I'm new to RegEx and JavaScript and I was wondering if anyone knew what the RegEx would be for detecting whether or not an input field contained the following type of format:

At least one alphanumeric tag which can contain spaces (e.g. "Test Tag" but not "Test@Tag")

Each tag separated by a single comma and nothing else, no spaces. (e.g. "Cars,Vehicle,Tiger Cactus, Bed")

An example of what I mean is this, these would be valid tags:

boy,man,girl,woman,tyrannosaurus rex,lion

And these would be invalid tags:

hat, cat, rat, c3po, @gmail

Because there are spaces between the tags and invalid characters.

Also, how would I count the tags for imposing a limit?

Edited for clarification!


问:
ArrayOutofBounds and NumberFormat Exception
I am getting those two exceptions when using token split method and parse int.
ArrayOutofBounds when I have the printline statement in the code, and the other one when I comment out the printline statement

```<code>public class MyArtistNodes {

public ArrayList<ArtistNode> myArtistNodes = null;

public MyArtistNodes(String filename) {
       Scanner input;

       try {
           input = new Scanner(new File(filename));
           myArtistNodes = new ArrayList<ArtistNode>();
           while(input != null && input.hasNext()) {

               String line = input.nextLine();
               String[] tokens = line.trim().split("@");
               tokens = line.split(" ");
              // System.out.println(tokens.length+" "+tokens[1]+" -- "+Integer.parseInt(tokens[0].trim()));
               ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
               myArtistNodes.add(newA);
           }
           input.close();

       } catch (NumberFormatException | FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }
</code>```

Error:

```<code>     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

     at MyArtistNodes.<init>(MyArtistNodes.java:27)

     at Exam3Step3A.<init>(Exam3Step3A.java:6)

     at Exam3.main(Exam3.java:6)
</code>```

答:
Your inputs are in the form of (String, int), ..., but you parse them in the form of ('int', 'String'), ..., basically this line:

```<code>ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
</code>```

should look like this:

```<code>ArtistNode newA = new ArtistNode(tokens[0],Integer.parseInt(tokens[1].trim()));
</code>```

Body:
I am getting those two exceptions when using token split method and parse int.
ArrayOutofBounds when I have the printline statement in the code, and the other one when I comment out the printline statement

public class MyArtistNodes {

public ArrayList<ArtistNode> myArtistNodes = null;

public MyArtistNodes(String filename) {
       Scanner input;

       try {
           input = new Scanner(new File(filename));
           myArtistNodes = new ArrayList<ArtistNode>();
           while(input != null && input.hasNext()) {

               String line = input.nextLine();
               String[] tokens = line.trim().split("@");
               tokens = line.split(" ");
              // System.out.println(tokens.length+" "+tokens[1]+" -- "+Integer.parseInt(tokens[0].trim()));
               ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));
               myArtistNodes.add(newA);
           }
           input.close();

       } catch (NumberFormatException | FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

Error:

     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

     at MyArtistNodes.<init>(MyArtistNodes.java:27)

     at Exam3Step3A.<init>(Exam3Step3A.java:6)

     at Exam3.main(Exam3.java:6)

Body:
Your inputs are in the form of (String, int), ..., but you parse them in the form of ('int', 'String'), ..., basically this line:

ArtistNode newA = new ArtistNode(tokens[1],Integer.parseInt(tokens[0].trim()));

should look like this:

ArtistNode newA = new ArtistNode(tokens[0],Integer.parseInt(tokens[1].trim()));


问:
java: maximum execution time within for-loop
I've got the folowing code:

```<code>    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }
</code>```

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

答:
You can get the System time before you start the loop and compare it after each iteration to check if the time is over the specified time, like this:

On for loop starting:

```<code>long start = System.currentTimeMillis();
</code>```

in each iteration:

```<code>if(start + 10_800_000 >= System.currentTimeMillis()){
    start = System.currentTimeMillis();
    i++;
}
</code>```

and you have to remove the i++ in the for loop

```<code>for (int i = 0; i<7;) {
</code>```

Body:
I've got the folowing code:

    List<String> instances2 = Arrays.asList("instances/umps20.txt","instances/umps22.txt","instances/umps24.txt","instances/umps26.txt","instances/umps28.txt","instances/umps30.txt","instances/umps32.txt");
    List<Integer> qq1 = Arrays.asList(9,10,11,12,13,14,14);
    List<Integer> qq2 = Arrays.asList(4,4,5,5,5,5,6);

    for (int i = 0; i<7; i++) {
        Tournament t = p.process(instances2.get(i));
        int nTeams = t.getNTeams();
        int q1 = qq1.get(i);
        int q2 = qq2.get(i);
        UndirectedGraph graph = g.create(t, q1, q2);
        new Choco(graph, nTeams);
        }
    }

Now i want to put a limit on each iteration. So after let's say 3h = 10 800 000ms, i would like for everything in the for-loop to stop and start the next iteration over the loop. Any ideas?

Thanks in advance!

Nicholas

Body:
You can get the System time before you start the loop and compare it after each iteration to check if the time is over the specified time, like this:

On for loop starting:

long start = System.currentTimeMillis();

in each iteration:

if(start + 10_800_000 >= System.currentTimeMillis()){
    start = System.currentTimeMillis();
    i++;
}

and you have to remove the i++ in the for loop

for (int i = 0; i<7;) {


问:
Implement clipboard operations via menu
I'm developing my first commercial Firemonkey application (also my first commercial application in any language). I have used native FMX controls and also one control from TMSSoftware (TTMSFMXGrid). The keyboard clipboard operations -- Ctrl+X, Ctrl+C, Ctrl+V -- work "out of the box". But I would like my application to provide menu items with the same functionality as the keyboard shortcuts.

I have set my program up so that there is a TMenuBar visible when compiling for Windows. When compiling for OS X, the TMenuBar is invisible but a TMainMenu comes up instead. For simplicity, we could just discuss the scenario of compiling for Windows when the TMenuBar is visible.

It's easy to program the TMenuItems of TMenuBar to perform the cut, copy and paste operations. That is not the issue. I have been unable to figure out how to disable the cut and copy menu items when nothing (or nothing relevant) is selected and how to disable the paste when there is nothing (or nothing relevant) on the clipboard.

How can I do that?

(I am using Berlin 10.1 Update 2.)

答:
You can read about Copy/Cut/Paste with FMX from Embarcadero here:

Multi-Device Apps and Clipboard Support

And because your question is about Windows now you should understand internals of Windows Clipboard. Good start is article from Zarko Gajic:

Basic Clipboard Operations (Cut/Copy/Paste)

And also about listening Clipboard to reseive notifications about clipboard content changing:

Listening to the Clipboard: Clipboard Delphi Spy with Custom Clipboard Formats

Another good article about clipboard in OS X and Windows with FMX:

Copying and pasting the contents of a FireMonkey TBitmap

Title: Implement clipboard operations via menu


问:
.net core Input tag helper does not appear to be rendering correctly
I have an issue where a .net core input tag helper does not appear to be rendering correctly.

```<code><input id="FullName" type="text" class="standard-textbox" asp-for="Contact.FullName" data-validation-required="@Html.Raw(Contact.FullNameValidationErrorMessage.Trim())" placeholder="@Contact.FullNameLabel.Trim()" required />
</code>```

This is being rendered as:

```<code><input id="FullName" type="text" class="standard-textbox" asp-for="Contact.FullName" data-validation-required="Please enter your name so we know who we're talking to." placeholder="Your full name" required="" aria-required="true" aria-describedby="FullName-error">
</code>```

You will note the asp-for helper is not being re-rendered as a "name" attribute.

On another site, which uses essentially the same form, the input field is rendered correctly with asp-for being changed to name.

答:
Figured it out!

The Views/_ViewImports.cshtml file was missing the following line:

```<code>@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
</code>```

Adding this line to the file fixed this issue.

Body:
I have an issue where a .net core input tag helper does not appear to be rendering correctly.

<input id="FullName" type="text" class="standard-textbox" asp-for="Contact.FullName" data-validation-required="@Html.Raw(Contact.FullNameValidationErrorMessage.Trim())" placeholder="@Contact.FullNameLabel.Trim()" required />

This is being rendered as:

<input id="FullName" type="text" class="standard-textbox" asp-for="Contact.FullName" data-validation-required="Please enter your name so we know who we're talking to." placeholder="Your full name" required="" aria-required="true" aria-describedby="FullName-error">

You will note the asp-for helper is not being re-rendered as a "name" attribute.

On another site, which uses essentially the same form, the input field is rendered correctly with asp-for being changed to name.

Body:
Figured it out!

The Views/_ViewImports.cshtml file was missing the following line:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Adding this line to the file fixed this issue.


问:
what will happen if two threads are joined in Java?
Say i have two threads t1 and t2, as per Oracle docs, t1.join means the current thread will wait for t1 to finish.My question is, what if the threads have already finished ? eg:

```<code>Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();
while (true)
{
    try {
    t1.join();
    t2.join();
    break;
    }
}
</code>```

What if t2 is already finished ?

答:
From the documentation of join():

An invocation of this method behaves in exactly the same way as the invocation

```<code>join(0)
</code>```

And the documentation of join(long millis) says:

This implementation uses a loop of this.wait calls conditioned on this.isAlive.

So if isAlive returns false (i.e. the thread finished), the wait is never called and join just returns immediately.

Body:
Say i have two threads t1 and t2, as per Oracle docs, t1.join means the current thread will wait for t1 to finish.My question is, what if the threads have already finished ? eg:

Thread t1 = new Thread(new EventThread("e1"));
t1.start();
Thread e2 = new Thread(new EventThread("e2"));
t2.start();
while (true)
{
    try {
    t1.join();
    t2.join();
    break;
    }
}

What if t2 is already finished ?

Body:
From the documentation of join():

An invocation of this method behaves in exactly the same way as the invocation

join(0)

And the documentation of join(long millis) says:

This implementation uses a loop of this.wait calls conditioned on this.isAlive.

So if isAlive returns false (i.e. the thread finished), the wait is never called and join just returns immediately.