问:
How can I retrieve mention entities from a Microsoft Teams message as well as LUIS intent entities?
I have a bot that I'm currently working on that takes advantage of the LuisRecognizer to match intents defined in my model. The initial message that kicks off the bot uses a mention to identify the target of the subsequent action.

The LUIS model correctly identifies the subject of the intent but their entity obviously only references the raw string value of the identified user. From the documentation, I am told that the original message should have an entities array of its own that includes the original mentions. I should be able to access this on session.message.entities from within my NodeJS bot implementation. However, session.message does not exist on ANY incoming message that was matched against a LUIS intent.

How can I retrieve the original message's entity list?

Here is how my bot is initialized:

```<code>const recognizer = new builder.LuisRecognizer(config.get('bot.model'))
const intents = new builder.IntentDialog({ recognizers: [recognizer] })

intents.matches('reward', '/reward')
bot.dialog('/', intents)

bot.dialog('/reward', [(session, context, next) => {
  // session.message does not exist here
}])
</code>```

答:
To address your question regarding the entity list, have you attempted using context.entities instead of session.message.entities? While session.message does have an 'entities' property, the session object itself doesn't receive data from the LUIS call unlike your context object.

The context (or args, or results) object you passed in as your second parameter in the waterfall step contains the intents and entities generated from LUIS.

I've created a bot that incorporates Cortana's prebuilt alarm app for its LUIS app. Below is the code for the 1st waterfall step of the dialog '/set_alarm'. It will console log the session.message and context object (called args here) from the LUIS call:

```<code>bot.dialog('/', intents);
intents.matches('builtin.intent.alarm.set_alarm', '/set_alarm');

bot.dialog('/set_alarm', [
    function (session, args, next) {
        if (session.message) {
            console.log('===\n1st waterfall step, session.message object found:');
            console.log(session.message);
        } else {
            console.log('session.message object not found.');
        }
        if (args) {
            console.log('===\nargs object found:');
            console.log(args);
        }
        ...
    },
    // additional waterfall steps
])
</code>```

Here is the output of the console output of the 1st waterfall step. This is a screencap of the chatbot interactions via the emulator.

If you're still having issues could you log your context object so we could see what it contains?
Regarding the lack of a session.message object, are you receiving any error messages? Your posted code doesn't look to have any problems.

You can find the repo for this chatbot on github here: https://github.com/stevengum97/SO_Q43146320

Body:
I have a bot that I'm currently working on that takes advantage of the LuisRecognizer to match intents defined in my model. The initial message that kicks off the bot uses a mention to identify the target of the subsequent action.

The LUIS model correctly identifies the subject of the intent but their entity obviously only references the raw string value of the identified user. From the documentation, I am told that the original message should have an entities array of its own that includes the original mentions. I should be able to access this on session.message.entities from within my NodeJS bot implementation. However, session.message does not exist on ANY incoming message that was matched against a LUIS intent.

How can I retrieve the original message's entity list?

Here is how my bot is initialized:

const recognizer = new builder.LuisRecognizer(config.get('bot.model'))
const intents = new builder.IntentDialog({ recognizers: [recognizer] })

intents.matches('reward', '/reward')
bot.dialog('/', intents)

bot.dialog('/reward', [(session, context, next) => {
  // session.message does not exist here
}])

Body:
To address your question regarding the entity list, have you attempted using context.entities instead of session.message.entities? While session.message does have an 'entities' property, the session object itself doesn't receive data from the LUIS call unlike your context object.

The context (or args, or results) object you passed in as your second parameter in the waterfall step contains the intents and entities generated from LUIS.

I've created a bot that incorporates Cortana's prebuilt alarm app for its LUIS app. Below is the code for the 1st waterfall step of the dialog '/set_alarm'. It will console log the session.message and context object (called args here) from the LUIS call:

bot.dialog('/', intents);
intents.matches('builtin.intent.alarm.set_alarm', '/set_alarm');

bot.dialog('/set_alarm', [
    function (session, args, next) {
        if (session.message) {
            console.log('===\n1st waterfall step, session.message object found:');
            console.log(session.message);
        } else {
            console.log('session.message object not found.');
        }
        if (args) {
            console.log('===\nargs object found:');
            console.log(args);
        }
        ...
    },
    // additional waterfall steps
])

Here is the output of the console output of the 1st waterfall step. This is a screencap of the chatbot interactions via the emulator.

If you're still having issues could you log your context object so we could see what it contains?
Regarding the lack of a session.message object, are you receiving any error messages? Your posted code doesn't look to have any problems.

You can find the repo for this chatbot on github here: https://github.com/stevengum97/SO_Q43146320


来源: stackexchange

问:
Detect shake gesture IOS Swift
I'm developing a app with a gesture system, basically if I turn the iPhone to left my app will do a function, if I turn the iPhone to Right, other function, with others gestures.

I don't have idea how to work with that, i'm trying search in google but not work, the result is only touch gesture and not motion gesture.

someone have a tutorial to help me?

答:
Swift3 ios10:</p>
```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.becomeFirstResponder() // To get shake gesture
}

// We are willing to become first responder to get shake motion
override var canBecomeFirstResponder: Bool {
    get {
        return true
    }
}

// Enable detection of shake motion
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        print("Why are you shaking me?")
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Detect shake gesture IOS Swift

Body:
Swift3 ios10:

override func viewDidLoad() {
    super.viewDidLoad()
    self.becomeFirstResponder() // To get shake gesture
}

// We are willing to become first responder to get shake motion
override var canBecomeFirstResponder: Bool {
    get {
        return true
    }
}

// Enable detection of shake motion
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
    if motion == .motionShake {
        print("Why are you shaking me?")
    }
}

ContentLicense: CC BY-SA 4.0


问:
Why is my nav bar not all the way at the top and 100% width?
I'm trying to create a nav bar at the top of my webpage: http://www.giltmantis.com and there's like 5px or so of white around it.  Why is it not the full width and all the way at the top?

here's the html:

```<code><html>
<head>
<link rel="stylesheet" href="http://www.giltmantis.com/style.css">
</head>
<body>
<div id="nav"><img src="giltmantis5.png"></div>
</body>
</html>
</code>```

and the css:

```<code>#nav { float: left; clear: both; width: 100%; margin: 0; padding: 0; background: #000; }
</code>```

答:
Your body tag has an 8px margin.

set body { margin: 0} in your css.

Body:
I'm trying to create a nav bar at the top of my webpage: http://www.giltmantis.com and there's like 5px or so of white around it.  Why is it not the full width and all the way at the top?

here's the html:

<link rel="stylesheet" href="http://www.giltmantis.com/style.css">

and the css:

#nav { float: left; clear: both; width: 100%; margin: 0; padding: 0; background: #000; }


答:
Your body has a margin of 8px, set it either to 0 or remove it from your body.

Webpage without margin:

Title: Why is my nav bar not all the way at the top and 100% width?


问:
Vuejs 2 - watch route when going from child to parent
I have the following route structure

```<code>/event/:id/schedule/:id
</code>```

What I want is that, when the user goes to a child component/route, some elements of the parent hide. When the user goes back to the parent, those elements should come back.

On the parent component, i've tried watching the $route object, but nothing is triggered. Attaching hooks at mounted/created methods of the parents component, won't work, because the user is still in those routes. I saw something about

```<code>watch(){
        $route: {
            console.log('route change');
        }
    }
</code>```

I also tried this:

```<code>route: {

        canReuse: false

    },
</code>```

It didn't work, and if it didn't, I wouldn't want to use it.

Any other ideas would be really helpful. thanks.

答:
just discovered some route hooks/navigation guards in the vue-router docs.Just used the following for to the parent component.

```<code>beforeRouteUpdate (to, from, next) {
        // called when the route that renders this component has changed,
        // but this component is reused in the new route.
        // For example, for a route with dynamic params /foo/:id, when we
        // navigate between /foo/1 and /foo/2, the same Foo component instance
        // will be reused, and this hook will be called when that happens.
        // has access to `this` component instance.
    },
</code>```

this worked perfectly

Body:
I have the following route structure

/event/:id/schedule/:id

What I want is that, when the user goes to a child component/route, some elements of the parent hide. When the user goes back to the parent, those elements should come back.

On the parent component, i've tried watching the $route object, but nothing is triggered. Attaching hooks at mounted/created methods of the parents component, won't work, because the user is still in those routes. I saw something about

watch(){
        $route: {
            console.log('route change');
        }
    }

I also tried this:

route: {

        canReuse: false

    },

It didn't work, and if it didn't, I wouldn't want to use it.

Any other ideas would be really helpful. thanks.

Body:
just discovered some route hooks/navigation guards in the vue-router docs.Just used the following for to the parent component.

beforeRouteUpdate (to, from, next) {
        // called when the route that renders this component has changed,
        // but this component is reused in the new route.
        // For example, for a route with dynamic params /foo/:id, when we
        // navigate between /foo/1 and /foo/2, the same Foo component instance
        // will be reused, and this hook will be called when that happens.
        // has access to `this` component instance.
    },

this worked perfectly


问:
Java eclipse tic tac toe game
How do I fix my tic tac toe game?
The code below is as far as I got. It runs but not properly.please help.I'm using eclipse neon</p>

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

public class TicTacToeGame  {

 // Declare variables

    public char[][] board; //the game board
    public boolean xTurn; //if true X's turn, if false O's turn
    public Scanner keyboard; //reads user input

    public TicTacToeGame()  {

    xTurn = true;
    keyboard = new Scanner(System.in);

        //create the board
        board = new char[3][3];

        //initialize the board
        for(int r = 0; r < 3; r++)  {

            for(int c = 0; c < 3; c++)
                board[r][c] = ' ';
        }
    }

        public void displayRow(int row)  {

            System.out.println(" " + board[row][0] + " | " + board[row][1] + " | " + board[row][2]);
        }

         //the rest of the game board

        public void displayBoard()  {

            displayRow(0);
            System.out.println("-----------");
            displayRow(1);
            System.out.println("-----------");
            displayRow(2);

            System.out.println("Which row, column would you like to move to? Enter two numbers between 0-2 separated by a space to indicate position.");
        }

        public boolean getMove()  {

            boolean invalid = true;
            int row = 0, column = 0;

            //user input
            while(invalid)  {

                row = keyboard.nextInt();
                column = keyboard.nextInt();

                //check for valid spot
                if(row >= 0 && row <= 2 && column >= 0 && column <= 2)  {

                    //check that the position is not taken
                    if(board[row][column] != ' ')
                        System.out.println("That position is already taken");
                    else
                        invalid = false;
                }
            }

            //fill in the game board with the player mark
            if(xTurn)
                board[row][column] = 'X';
            else
                board[row][column] = 'O';

            return winner(row,column);
        }

        //check for win

        public boolean winner(int lastR, int lastC)  {

            boolean winner = false; // no winner
            char symbol = board[lastR][lastC]; //last made mark

            //check left-right
            int numFound = 0;
            for(int c = 0; c < 3; c++)  {
                if(board[lastR][c] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            //check up-down
            numFound = 0;
            for(int r = 0; r < 3; r++)  {
                if(board[r][lastC] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            //check both diagonals
            numFound = 0;
            for(int i = 0; i < 3; i++)  {
                if(board[i][i] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            numFound = 0;
            for(int i = 0; i < 3; i++)  {
                if(board[i][2-i] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            return winner;
        }

        public boolean boardFull()  {

            //how many spots that are taken by each player
            int numSpotsFilled = 0;

            for(int r = 0; r < 3; r++)  {

                for(int c = 0; c < 3; c++)  {
                    if(board[r][c] == 'X' || board[r][c] == 'O')
                        numSpotsFilled++;
                }
            }

            return numSpotsFilled == 9;

        }

         //start  game.

        public void play()  {

            while(true)  {

                displayBoard();

                if(xTurn)
                    System.out.println("X's Turn!");
                else
                    System.out.println("O's Turn!");

                int choice = keyboard.nextInt();

                if(choice == 1)  {

                    if(getMove())  {
                        // winner!
                        displayBoard(); //display winner board

                        if(xTurn)
                            System.out.println("X Wins!");
                        else
                            System.out.println("O Wins!");

                        System.exit(0);
                    }
                    else if(boardFull())  {
                        //tie
                        displayBoard(); //display tie board

                        System.out.println("Tie!");

                        System.exit(0);
                    }
                    else  {
                        //no winner
                        xTurn = !xTurn;  //switch players
                    }
                }
            }
    }

    public static void main(String[] args){
                    TicTacToeGame game = new TicTacToeGame();

                    game.play();
                }

        }
</code>```

答:
In your play() method you're reading a variable called choice which is never used (but to start the game), if you remove these lines:

```<code>int choice = keyboard.nextInt(); //Remove this line

if (choice == 1) { //Remove this line
    //Keep the code here
} //Remove this line
</code>```

Your game will run properly.

Otherwise if you run with an input: 2 0 for example it will never work.

I also recommend you to always use the curly braces for your if-else / for / while / etc instructions.

Title: Java eclipse tic tac toe game

Body:
How do I fix my tic tac toe game?
The code below is as far as I got. It runs but not properly.please help.I'm using eclipse neon

import java.util.Scanner;

public class TicTacToeGame  {

 // Declare variables

    public char[][] board; //the game board
    public boolean xTurn; //if true X's turn, if false O's turn
    public Scanner keyboard; //reads user input

    public TicTacToeGame()  {

    xTurn = true;
    keyboard = new Scanner(System.in);

        //create the board
        board = new char[3][3];

        //initialize the board
        for(int r = 0; r < 3; r++)  {

            for(int c = 0; c < 3; c++)
                board[r][c] = ' ';
        }
    }

        public void displayRow(int row)  {

            System.out.println(" " + board[row][0] + " | " + board[row][1] + " | " + board[row][2]);
        }

         //the rest of the game board

        public void displayBoard()  {

            displayRow(0);
            System.out.println("-----------");
            displayRow(1);
            System.out.println("-----------");
            displayRow(2);

            System.out.println("Which row, column would you like to move to? Enter two numbers between 0-2 separated by a space to indicate position.");
        }

        public boolean getMove()  {

            boolean invalid = true;
            int row = 0, column = 0;

            //user input
            while(invalid)  {

                row = keyboard.nextInt();
                column = keyboard.nextInt();

                //check for valid spot
                if(row >= 0 && row <= 2 && column >= 0 && column <= 2)  {

                    //check that the position is not taken
                    if(board[row][column] != ' ')
                        System.out.println("That position is already taken");
                    else
                        invalid = false;
                }
            }

            //fill in the game board with the player mark
            if(xTurn)
                board[row][column] = 'X';
            else
                board[row][column] = 'O';

            return winner(row,column);
        }

        //check for win

        public boolean winner(int lastR, int lastC)  {

            boolean winner = false; // no winner
            char symbol = board[lastR][lastC]; //last made mark

            //check left-right
            int numFound = 0;
            for(int c = 0; c < 3; c++)  {
                if(board[lastR][c] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            //check up-down
            numFound = 0;
            for(int r = 0; r < 3; r++)  {
                if(board[r][lastC] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            //check both diagonals
            numFound = 0;
            for(int i = 0; i < 3; i++)  {
                if(board[i][i] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            numFound = 0;
            for(int i = 0; i < 3; i++)  {
                if(board[i][2-i] == symbol)
                    numFound++;
            }

            if(numFound == 3)
                winner = true;

            return winner;
        }

        public boolean boardFull()  {

            //how many spots that are taken by each player
            int numSpotsFilled = 0;

            for(int r = 0; r < 3; r++)  {

                for(int c = 0; c < 3; c++)  {
                    if(board[r][c] == 'X' || board[r][c] == 'O')
                        numSpotsFilled++;
                }
            }

            return numSpotsFilled == 9;

        }

         //start  game.

        public void play()  {

            while(true)  {

                displayBoard();

                if(xTurn)
                    System.out.println("X's Turn!");
                else
                    System.out.println("O's Turn!");

                int choice = keyboard.nextInt();

                if(choice == 1)  {

                    if(getMove())  {
                        // winner!
                        displayBoard(); //display winner board

                        if(xTurn)
                            System.out.println("X Wins!");
                        else
                            System.out.println("O Wins!");

                        System.exit(0);
                    }
                    else if(boardFull())  {
                        //tie
                        displayBoard(); //display tie board

                        System.out.println("Tie!");

                        System.exit(0);
                    }
                    else  {
                        //no winner
                        xTurn = !xTurn;  //switch players
                    }
                }
            }
    }

    public static void main(String[] args){
                    TicTacToeGame game = new TicTacToeGame();

                    game.play();
                }

        }

Body:
In your play() method you're reading a variable called choice which is never used (but to start the game), if you remove these lines:

int choice = keyboard.nextInt(); //Remove this line

if (choice == 1) { //Remove this line
    //Keep the code here
} //Remove this line

Your game will run properly.

Otherwise if you run with an input: 2 0 for example it will never work.

I also recommend you to always use the curly braces for your if-else / for / while / etc instructions.


问:
Is there any phone that doesn't have sms inbox content provider?
Is there any phone that doesn't have typical sms content provider ("content://sms/inbox")?

Or there is any phone that has different fields scheme?

答: Android is open-source, so, technically, a company doing a custom ROM could desactivate this kind of functionnality, but I think that if the phone is able to send/receive SMS, the content provider will still be there.</p>

ContentLicense: CC BY-SA 2.5


问:
Updating Ruby Hash Values with Array Values
I've created the following hash keys with values parsed from PDF into array:

```<code>columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
h = Hash[columns.map.with_index.to_h]
=> {"Sen"=>0, "P-Hire#"=>1, "Emp#"=>2, "DOH"=>3, "Last"=>4, "First"=>5}
</code>```

Now I want to update the value of each key with 6 equivalent values from another parsed data array:

```<code>rows = list.text.scan(/^.+/)
row = rows[0].tr(',', '')
@data = row.split
=> ["2", "6", "239", "05/05/67", "Harp", "Erin"]
</code>```

I can iterate over @data in the view and it will list each of the 6 values. When I try to do the same in the controller it sets the same value to each key:

```<code>data.each do |e|
  h.update(h){|key,v1| (e) }
end
=>
{"Sen"=>"Harper", "P-Hire#"=>"Harper", "Emp#"=>"Harper", "DOH"=>"Harper", "Last"=>"Harper", "First"=>"Harper"
</code>```

So it's setting the value of each key to the last value of the looped array...

答:
I would just do:

```<code>h.keys.zip(@data).to_h
</code>```

If the only purpose of h is as an interim step getting to the result, you can dispense with it and do:

```<code>columns.zip(@data).to_h
</code>```

Body:
I've created the following hash keys with values parsed from PDF into array:

columns = ["Sen", "P-Hire#", "Emp#", "DOH", "Last", "First"]
h = Hash[columns.map.with_index.to_h]
=> {"Sen"=>0, "P-Hire#"=>1, "Emp#"=>2, "DOH"=>3, "Last"=>4, "First"=>5}

Now I want to update the value of each key with 6 equivalent values from another parsed data array:

rows = list.text.scan(/^.+/)
row = rows[0].tr(',', '')
@data = row.split
=> ["2", "6", "239", "05/05/67", "Harp", "Erin"]

I can iterate over @data in the view and it will list each of the 6 values. When I try to do the same in the controller it sets the same value to each key:

data.each do |e|
  h.update(h){|key,v1| (e) }
end
=>
{"Sen"=>"Harper", "P-Hire#"=>"Harper", "Emp#"=>"Harper", "DOH"=>"Harper", "Last"=>"Harper", "First"=>"Harper"

So it's setting the value of each key to the last value of the looped array...

Body:
I would just do:

h.keys.zip(@data).to_h

If the only purpose of h is as an interim step getting to the result, you can dispense with it and do:

columns.zip(@data).to_h


问:
Internet Explorer 11 automation VBA Document Empty
I am just starting to learn Internet Explorer Automation using VBA and I am facing an issue.

The Document object is empty which prevents me from going further than just loading a page. I have been looking around the net for a solution to this and could not find anything working so here I am, asking for your help.

NB: My VBA level is intermediate

Windows 8.1 pro 64 bit

I wrote an example code

答:
I had a the same issue (nothing in the .document) , with Internet Explorer 11.

I had to add the site to the Compatibility View list (gear, compatibility view, add)

Hopefully this will help someone avoid the time I spent looking for a solution.


问:
How to distribute a 200MB database to a locally executed HTML5 web page
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

```<code>var data = {....};
</code>```

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.

Body:
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

var data = {....};

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.

Body:
I have an answer. Instead of dumping a single JSON object, I dumped an empty object and then filled in the fields. Sort of like this:

var all_files = {};
all_files[".489454.padl"] = [3601335];
all_files[".bash_history"] = [3601336];
all_files[".bash_profile"] = [3601337, 4243581];
all_files[".bash_profile-anaconda.bak"] = [3601338];
all_files[".bashrc"] = [3601339, 4243582];
all_files[".CFUserTextEncoding"] = [3601340, 3953453, 3953467, 3953492, 3953506, 3953520, 3953534, 3953655, 3953669, 3953683, 3954184, 3954198, 3954212, 3954226, 3954240, 3954254, 3954268, 3954282, 3954298, 3954741, 3954755, 3954771, 3954786, 3954817, 3954833, 3954847, 3954863, 3954884, 3954898, 3954912, 3954928, 3955916, 3955930, 3955944, 3955958, 3955983, 3955997, 3956011, 3956025, 3956039, 3956055, 3956069, 3956083, 3956097, 3956111, 3956125, 3956139, 3956153, 3956167, 3956181, 3956195, 3956209, 3956223, 3956237, 3956257, 3956273, 3956287, 3956301, 3956328, 3956347, 3956361, 3956375, 3956393, 3956407, 3956421, 3956441, 3956457, 3956494, 3956508, 3956522, 3956541, 3956557, 3956574, 3956588, 3956602, 3956618, 3956632, 3956649, 3956665, 3956765, 3956779, 3956793, 3956808, 3956824, 3956838, 3966259, 3966273, 3966288, 3966308, 3966326, 3966340, 3966354, 3966369, 3966384, 3966402, 3966416, 3966432, 3966453, 3966469, 3966483, 3966497, 3966542, 3966556, 3966570, 3966584, 3966598, 3966612, 3966636, 3966652, 3966666, 3966682, 3966697, 3966711, 3966729, 3966756, 3966770, 3966784, 3966798, 3966812, 3966826, 3966887, 3966901, 3966917, 3966931, 3966947, 3966962, 3966977, 3966991, 3967008, 3967024, 3967041, 3967058, 3967072, 3967086, 3967100, 3967114, 3967129, 3967144, 3967158, 3967172, 3967186, 3967200, 3967214, 3967228, 3967242, 3967256, 3967270, 3967284, 3967298, 3967315, 3967332, 3967349, 3967366, 3967383, 3967400, 3967414, 3967432, 3967472, 3967494, 3967519, 3967539, 3967553, 3967567, 3967581, 3967596, 3967610, 3967627, 3967641, 3967655, 3967669, 3967686, 3967701, 3967715, 3967813, 3967835, 3967849, 3967863, 3967877, 3967891, 3967912, 3967926, 3967940, 3967954, 3967969, 3967983, 3967997, 3968179, 3968201, 3968216, 3968232, 3968375, 3968549, 3968563, 3968613, 3968725, 3968739, 3968754, 3968769, 3968783, 3968797, 3968812, 3969411, 3969425, 3969439, 3969453, 3969468, 3969482, 3969496, 3969510, 3969524];
all_files[".DS_Store"] = [3601341, 3601457, 3601614, 3601622, 3682878, 3682900, 3683109, 3683116, 3683131, 3683159, 3683837, 3683838, 3683864, 3685165, 3685689, 3686006, 3686154, 3686208, 3686658, 3686951, 3688568, 3691304, 3691654, 3691706, 3698223, 3702806, 3703841, 3705589, 3707517, 3709434, 3709601, 3712204, 3712575, 3713471, 3714040, 3723182, 3723186, 3723577, 3723619, 3723697, 3724289, 3724323, 3724354, 3724644, 3724666, 3724687, 3724711, 3724929, 3729720, 3729721, 3729808, 3729859, 3745259, 3745417, 3749212, 3749214, 3752731, 3754225, 3754282, 3754697, 3754725, 3758418, 3762019, 3762050, 3762076, 3762135, 3762484, 3764339, 3767112, 3767162, 3770129, 3770205, 3770401, 3782075, 3782082, 3782103, 3782110, 3782128, 3782144, 3782158, 3782227, 3782297, 3782335, 3782453, 3782531, 3782575, 3782681, 3782800, 3782843, 3782912, 3782939, 3782994, 3785013, 3785271, 3786663, 3787204, 3787259, 3787266, 3788923, 3790797, 3790803, 3790941, 3790974, 3791013, 3791036, 3791053, 3791056, 3791205, 3792915, 3793142, 3793522, 3793765, 3799643, 3799796, 3804461, 3804592, 3804679, 3804763, 3804843, 3804857, 3804863, 3804891, 3804983, 3805631, 3806138, 3806264, 3806518, 3807440, 3807461, 3807473, 3816174, 3832254, 3834259, 3834271, 3834289, 3834708, 3835089, 3835661, 3835780, 3836513, 3836635, 3836990, 3837258, 3837281, 3838040, 3842299, 3842361, 3842362, 3842443, 3843321, 3843712, 3844005, 3845137, 3845205, 3848494, 3848643, 3850301, 3851318, 3851539, 3851581, 3851586, 3851718, 3851749, 3855131, 3856267, 3856405, 3856600, 3856617, 3856733, 3856789, 3856825, 3857691, 3857694, 3857714, 3858011, 3858087, 3858201, 3858261, 3858427, 3858440, 3858451, 3858466, 3858484, 3858512, 3858518, 3858632, 3858647, 3859178, 3859226, 3859817, 3859860, 3860031, 3860078, 3862433, 3862466, 3862493, 3862556, 3862629, 3862669, 3862785, 3863120, 3863137, 3863143, 3863189, 3863190, 3863298, 3863402, 3863624, 3863912, 3863919, 3868043, 3868103, 3937674, 3937883, 3939101, 3953451, 3966103, 3966148, 3966208, 3971417, 3972095, 3972176, 4000541, 4001581, 4001584, 4013248, 4073121, 4097129, 4124083, 4140856, 4205726, 4208195, 4208198, 4219015, 4219018, 4219025, 4219165, 4220286, 4221936, 4221956, 4222034, 4222073, 4222114, 4222208, 4222241, 4222369, 4222372, 4222417, 4222458, 4222533, 4222554, 4222608, 4222677, 4222688, 4222706, 4222777, 4222893, 4222992, 4223033, 4223088, 4223161, 4243924, 4244119, 4244333, 4245043, 4245045, 4245051, 4245057];
all_files[".emacs"] = [3601342, 4243585];
all_files[".gitconfig"] = [3601343];
all_files[".iterm2_shell_integration.bash"] = [3601344];
all_files[".julia_history"] = [3601345];
all_files[".lesshst"] = [3601346];
all_files[".profile"] = [3601347, 4243588];
all_files[".python_history"] = [3601348];
all_files[".pythonhistory"] = [3601349];
all_files[".rnd"] = [3601350];
...

The whole file ends up being about 90MB (at the moment). Time to load on my 4-year-old MacBook Pro with Google Chrome is 502ms, which is completely reasonable.


问:
Program returning undefined variable (python)
trying to get the following code to work, it still returns that the variable is undefined when the user enters an integer to try and assign a gender. How would you fix this?

```<code>#define the function for the physical characteristics question
def physical_characteristics_question (question, answer1, answer2, answer3) :
    print (question)
    print ('1. ' + answer1)
    print ('2. ' + answer2)
    print ('3. ' + answer3)

    while True:
        variable = (input('Please enter a number: '))
        while True:
        #repeats question if a type other than integer is entered
            try:
                int(variable)
                break
            except ValueError:
                variable = 0
                continue

        #repeats question if a number out of range is entered
        if int(variable) >= 1 and int(variable) <= 3:
            break

    return int(variable)

physical_characteristics_question ("What is your gender?", 'male', 'female', 'other')

if (variable) == 1:
    gender = 'male'
elif (variable) == 2:
    gender = 'female'
else:
    gender = 'other'
</code>```

Thanks in adavance!

答:
Your function physical_characteriscs_question isn't returning its results to any variable. Try doing this:

```<code>variable = physical_characteristics_question ("What is your gender?", 'male', 'female', 'other')
</code>```

Body:
trying to get the following code to work, it still returns that the variable is undefined when the user enters an integer to try and assign a gender. How would you fix this?

#define the function for the physical characteristics question
def physical_characteristics_question (question, answer1, answer2, answer3) :
    print (question)
    print ('1. ' + answer1)
    print ('2. ' + answer2)
    print ('3. ' + answer3)

    while True:
        variable = (input('Please enter a number: '))
        while True:
        #repeats question if a type other than integer is entered
            try:
                int(variable)
                break
            except ValueError:
                variable = 0
                continue

        #repeats question if a number out of range is entered
        if int(variable) >= 1 and int(variable) <= 3:
            break

    return int(variable)

physical_characteristics_question ("What is your gender?", 'male', 'female', 'other')

if (variable) == 1:
    gender = 'male'
elif (variable) == 2:
    gender = 'female'
else:
    gender = 'other'

Thanks in adavance!

Body:
Your function physical_characteriscs_question isn't returning its results to any variable. Try doing this:

variable = physical_characteristics_question ("What is your gender?", 'male', 'female', 'other')


问:
How to set the MediaBox values with iText
I want to change the mediabox entries of each page of my pdf.

https://i.imgur.com/mSqoIch.png

Is there a way to do that with iText so that the following values will be used

```<code>mediaBox[0] = 0
mediaBox[1] = 0
mediaBox[2] = 595.22
mediaBox[0] = 842
</code>```

答:
Could solve this by setting the mediaboxes like this</p>

```<code> File outputPdf = File.createTempFile("moveMediabox", ".pdf");
 PdfReader reader = new PdfReader(ByteSource.wrap(inputPdfBytes).openBufferedStream());
 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdf));
 int numberOfPages = reader.getNumberOfPages();

 for (int i = 1; i <= numberOfPages; i++) {
        PdfDictionary pagedict = reader.getPageN(i);
        PdfArray mediabox = pagedict.getAsArray(PdfName.MEDIABOX);
        int x = mediabox.getAsNumber(0).intValue();
        int y = mediabox.getAsNumber(1).intValue();
        if (x != 0 && y != 0){
            isChanged = true;
            mediabox.set(0, new PdfNumber(0));
            mediabox.set(1, new PdfNumber(0));
            mediabox.set(2, new PdfNumber(mediabox.getAsNumber(2).intValue() - x));
            mediabox.set(3, new PdfNumber(mediabox.getAsNumber(3).intValue() - y));
        }
        else{
            LOG.info("no need to repair media box, already at x:0 y:0");
        }
    }
</code>```

Body:
I want to change the mediabox entries of each page of my pdf.

https://i.imgur.com/mSqoIch.png

Is there a way to do that with iText so that the following values will be used

mediaBox[0] = 0
mediaBox[1] = 0
mediaBox[2] = 595.22
mediaBox[0] = 842

Body:
Could solve this by setting the mediaboxes like this

 File outputPdf = File.createTempFile("moveMediabox", ".pdf");
 PdfReader reader = new PdfReader(ByteSource.wrap(inputPdfBytes).openBufferedStream());
 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPdf));
 int numberOfPages = reader.getNumberOfPages();

 for (int i = 1; i <= numberOfPages; i++) {
        PdfDictionary pagedict = reader.getPageN(i);
        PdfArray mediabox = pagedict.getAsArray(PdfName.MEDIABOX);
        int x = mediabox.getAsNumber(0).intValue();
        int y = mediabox.getAsNumber(1).intValue();
        if (x != 0 && y != 0){
            isChanged = true;
            mediabox.set(0, new PdfNumber(0));
            mediabox.set(1, new PdfNumber(0));
            mediabox.set(2, new PdfNumber(mediabox.getAsNumber(2).intValue() - x));
            mediabox.set(3, new PdfNumber(mediabox.getAsNumber(3).intValue() - y));
        }
        else{
            LOG.info("no need to repair media box, already at x:0 y:0");
        }
    }


问:
ion-spinner while waiting for music to load
In my music app, I have a "click" function that makes an http request and plays the .mp3 file from the server. My problem is that sometimes it takes a while for the app to get the audio from the server that is why I added an ion-spinner. I would like the spinner to show up only while the audio is loading and then disappear.

Home.html

```<code><ion-card-content (click)="play(sound)">
      <div class="wrapper">
      <ion-spinner class="color-green" name="{{ sound.spinner }}"></ion-spinner>
      <img src="{{ sound.imageUrl }}" />
      </div>

    </ion-card-content>
</code>```

Home.ts

```<code>/* Plays a sound, pausing other playing sounds if necessary */
  play(sound) {

console.log(sound)
if(this.media) {
  this.media.pause();
}
this.media = new Audio(sound.file);
this.media.load();
this.media.play();
 }
</code>```

答:
In Home.ts add the below code

```<code><ion-card-content (click)="play(sound)">
      <div class="wrapper">
      <ion-spinner class="color-green" [name]="sound.spinner" [paused]="toggleSpinner"></ion-spinner>
      <img src="{{ sound.imageUrl }}" />
      </div>

    </ion-card-content>
</code>```

In constructor

```<code>toggleSpinner= false

 play(sound) {
    toggleSpinner= true
 ......
 }
</code>```

Body:
In my music app, I have a "click" function that makes an http request and plays the .mp3 file from the server. My problem is that sometimes it takes a while for the app to get the audio from the server that is why I added an ion-spinner. I would like the spinner to show up only while the audio is loading and then disappear.

Home.html

<ion-card-content (click)="play(sound)">

      <ion-spinner class="color-green" name="{{ sound.spinner }}"></ion-spinner>

    </ion-card-content>

Home.ts

/* Plays a sound, pausing other playing sounds if necessary */
  play(sound) {

console.log(sound)
if(this.media) {
  this.media.pause();
}
this.media = new Audio(sound.file);
this.media.load();
this.media.play();
 }

Body:
In Home.ts add the below code

<ion-card-content (click)="play(sound)">
      <div class="wrapper">
      <ion-spinner class="color-green" [name]="sound.spinner" [paused]="toggleSpinner"></ion-spinner>
      <img src="{{ sound.imageUrl }}" />
      </div>

    </ion-card-content>

In constructor

toggleSpinner= false

 play(sound) {
    toggleSpinner= true
 ......
 }


问:
More simplified explanation of chain.from_iterable and chain() of itertools
Can you give a more simplified explanation of these two methods chain() and chain.from_iterable from itertools?

I have searched the knowledge base and as well the python documentation but i got confused.

I am new to python that's why I am asking a more simplified explanation regarding these.

Thanks!

答:
You can chain sequences to make a single sequence:

```<code>>>> from itertools import chain

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> list(chain(a, b))
[1, 2, 3, 'a', 'b', 'c']
</code>```

If a and b are in another sequence, instead of having to unpack them and pass them to chain you can pass the whole sequence to from_iterable:

```<code>>>> c = [a, b]
>>> list(chain.from_iterable(c))
[1, 2, 3, 'a', 'b', 'c']
</code>```

It creates a sequence by iterating over the sub-sequences of your main sequence. This is sometimes called flattening a list. If you want to flatten lists of lists of lists, you'll have to code that yourself. There are plenty of questions and answers about that on Stack Overflow.

Body:
You can chain sequences to make a single sequence:

>>> from itertools import chain

>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> list(chain(a, b))
[1, 2, 3, 'a', 'b', 'c']

If a and b are in another sequence, instead of having to unpack them and pass them to chain you can pass the whole sequence to from_iterable:

>>> c = [a, b]
>>> list(chain.from_iterable(c))
[1, 2, 3, 'a', 'b', 'c']

It creates a sequence by iterating over the sub-sequences of your main sequence. This is sometimes called flattening a list. If you want to flatten lists of lists of lists, you'll have to code that yourself. There are plenty of questions and answers about that on Stack Overflow.


问:
How do you get the 'this' variable defined in a vuejs component unit test
I am trying to use mocha-webpack in an npm script to test a vuejs component. I am mocking the vuex store like this in the test:

```<code>const vm = new Vue({
        template: '<div><test></test></div>',
        store: new Vuex.Store(mockedStore),
        components: {
            'test': TestItems
        }
    }).$mount()
</code>```

I call a method on the component to test such as:

```<code>vm.$options.components.test.methods.foo()
</code>```

In the component I have code that accesses the store such as:

```<code>this.$store.commit('bar', data)
</code>```

The problem is when it gets to this point I get this error:

```<code>'Cannot read property \'commit\' of undefined' undefined undefined
</code>```

I verified that 'this' is undefined in this context. When I run the app, 'this' is defined and has '$store'. How can I make it work in the unit test context?

答:
You're calling the foo method of the test component without an instance of test. Try doing something like this:

```<code>const vm = new Vue({
  template: '<div><test ref="test"></test></div>',
  store: new Vuex.Store(mockedStore),
  components: {
    'test': TestItems
  }
}).$mount()
</code>```

```<code>vm.$refs.test.foo()
</code>```

foo will be called with vm.$refs.test as this.

Body:
I am trying to use mocha-webpack in an npm script to test a vuejs component. I am mocking the vuex store like this in the test:

const vm = new Vue({
        template: '
<test></test>
',
        store: new Vuex.Store(mockedStore),
        components: {
            'test': TestItems
        }
    }).$mount()

I call a method on the component to test such as:

vm.$options.components.test.methods.foo()

In the component I have code that accesses the store such as:

this.$store.commit('bar', data)

The problem is when it gets to this point I get this error:

'Cannot read property \'commit\' of undefined' undefined undefined

I verified that 'this' is undefined in this context. When I run the app, 'this' is defined and has '$store'. How can I make it work in the unit test context?

Body:
You're calling the foo method of the test component without an instance of test. Try doing something like this:

const vm = new Vue({
  template: '<div><test ref="test"></test></div>',
  store: new Vuex.Store(mockedStore),
  components: {
    'test': TestItems
  }
}).$mount()

vm.$refs.test.foo()

foo will be called with vm.$refs.test as this.


问:
Is this design possible with ConstraintLayout?
I was playing around with ConstraintLayout and I can't guess how to do this simple design using only a ConstraintLayout.

Simple design

Each TextView is centered with its image.

Each image is separated with the previous image with a fixed margin.

All views, treated like a group, are centered horizontally.

I have implemented the design using RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="4dp">

        <RelativeLayout
            android:id="@+id/androidALayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/androidAIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidATV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android A"
                android:layout_below="@id/androidAIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidBLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidALayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidBIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidBTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android B"
                android:layout_below="@id/androidBIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidCLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidBLayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidCIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidCTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android C"
                android:layout_below="@id/androidCIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidDLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidCLayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidDIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidDTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android D"
                android:layout_below="@id/androidDIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

    </RelativeLayout>
</RelativeLayout>```

Is this possible?

答:
I've found the solution: Group views in ConstraintLayout to treat them as a single view

Using chains, multiple views could be treated like a group.

Body:
I was playing around with ConstraintLayout and I can't guess how to do this simple design using only a ConstraintLayout.

Simple design

Each TextView is centered with its image.

Each image is separated with the previous image with a fixed margin.

All views, treated like a group, are centered horizontally.

I have implemented the design using RelativeLayout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="4dp">

        <RelativeLayout
            android:id="@+id/androidALayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/androidAIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidATV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android A"
                android:layout_below="@id/androidAIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidBLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidALayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidBIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidBTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android B"
                android:layout_below="@id/androidBIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidCLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidBLayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidCIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidCTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android C"
                android:layout_below="@id/androidCIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/androidDLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/androidCLayout"
            android:layout_marginLeft="32dp">

            <ImageView
                android:id="@+id/androidDIV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:srcCompat="@mipmap/ic_launcher"
                android:layout_centerHorizontal="true"/>

            <TextView
                android:id="@+id/androidDTV"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Android D"
                android:layout_below="@id/androidDIV"
                android:layout_marginTop="4dp"
                android:layout_centerHorizontal="true"/>
        </RelativeLayout>

    </RelativeLayout>
</RelativeLayout>

Is this possible?


问:
How can i hide the status bar in the browser?
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

```<code><a href="http://www.sell.com/?referrer=225"
   onMouseOver="window.status='http://www.sell.com';
               return true" onMouseOut="window.status=''">Click here</a>
</code>```

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)

答:
You can set the text of the status bar using javascript with window.status attribute. E.g. http://www.htmlite.com/JS017.php

If you REALLY need, to disable the status bar in a browser, you can get a copy of an open-source browser code base, remove all code for the status bar and redistribute it to your users, but I doubt this is what you mean/need.

Why do you need to hide the link in the status bar? A security issue with not wanting to expose the URL could be dealt with in another way.

Body:
I have a simple question, how can I hide a link in the status bar in my browser.

I've tried with this:

Click here

(Taken from a tutorial)
But it doesn't work, if somebody would help me, I would be very happy! ;-)


问:
How to use variable CSS selector
Does anyone know how I can use a variable CSS selector? For example, I want my CSS to grab a table id attribute that's variable... something like:

```<code><table id="table_1">
    <thead>
    </thead>
    <tbody>
    </tbody>
</table>

<table id="table_2">
    <thead>
    </thead>
    <tbody>
    </tbody>
</table>

<table id="table_3">
    <thead>
    </thead>
    <tbody>
    </tbody>
</table>
</code>```

Now I want to grab the tables by their id:

```<code>table#[INSERT VARIABLE TABLE ID HERE]{
  margin: 0 auto;
  border-collapse: collapse;
  font-family: Agenda-Light, sans-serif;
  font-weight: 100;
  background: #333; color: #fff;
  text-rendering: optimizeLegibility;
  border-radius: 5px;
}
</code>```

Thanks in advance!

答:
If all tables have same css you could use a class instead of id.

It is not possible to iterate or do other kind of logic in css. To use variables you could use css pre processors like sass or less, but you would have to define every variable "by hand".

Title: How to use variable CSS selector

Body:
Does anyone know how I can use a variable CSS selector? For example, I want my CSS to grab a table id attribute that's variable... something like:

Now I want to grab the tables by their id:

table#[INSERT VARIABLE TABLE ID HERE]{
  margin: 0 auto;
  border-collapse: collapse;
  font-family: Agenda-Light, sans-serif;
  font-weight: 100;
  background: #333; color: #fff;
  text-rendering: optimizeLegibility;
  border-radius: 5px;
}

Thanks in advance!


问:
OData property with internal setter -- like UpdateDate
I have a model with a class called "Animal".

The "Animal" class has several properties but let's focus on the following properties:

CreateDate

CreateUser

In the "Animal" class I can get the CreateDate to work by doing the following:

```<code>[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }
</code>```

This lets me generate the CreateDate in the database by setting the default value in the database as "GetDate()".

When an outside caller tries to "set" the CreateDate field on the OData service, it ignores the data being passed.

This makes it a "read only" property for outside callers.

I need to do something similar to the CreateUser except I need to set the CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name on the OData server.

If I try a private set then the OData service does not expose the property at all.

If I try a public set then the outside caller can change the property.

In the "Animal" constructor I have set the internal _CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

I'm not sure how to set it on the server side.

答:
Here is what I got to work.

In the model I have the following:

```<code>public string CreateUser { get; set; }

[NotMapped]
public string CreateUserName
{
    get
    {
        return CreateUser;
    }
    set
    {
        CreateUser = CreateUser ?? System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }
}
</code>```

And then in the WebApiConfig I had the following:

```<code>builder.EntitySet<Animal>("Animals"));
builder.EntityType<Animal>().Ignore(p => p.CreateUser); // hide CreateUser
builder.StructuralTypes.First(t => t.ClrType == typeof(Animal))
    .AddProperty(typeof(Animal).GetProperty(nameof(Animal.CreateUserName))); // show CreateUserName
</code>```

Body:
I have a model with a class called "Animal".

The "Animal" class has several properties but let's focus on the following properties:

CreateDate

CreateUser

In the "Animal" class I can get the CreateDate to work by doing the following:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreateDate { get; set; }

This lets me generate the CreateDate in the database by setting the default value in the database as "GetDate()".

When an outside caller tries to "set" the CreateDate field on the OData service, it ignores the data being passed.

This makes it a "read only" property for outside callers.

I need to do something similar to the CreateUser except I need to set the CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name on the OData server.

If I try a private set then the OData service does not expose the property at all.

If I try a public set then the outside caller can change the property.

In the "Animal" constructor I have set the internal _CreateUser = System.Threading.Thread.CurrentPrincipal.Identity.Name

I'm not sure how to set it on the server side.

Body:
Here is what I got to work.

In the model I have the following:

public string CreateUser { get; set; }

[NotMapped]
public string CreateUserName
{
    get
    {
        return CreateUser;
    }
    set
    {
        CreateUser = CreateUser ?? System.Threading.Thread.CurrentPrincipal.Identity.Name;
    }
}

And then in the WebApiConfig I had the following:

builder.EntitySet<Animal>("Animals"));
builder.EntityType<Animal>().Ignore(p => p.CreateUser); // hide CreateUser
builder.StructuralTypes.First(t => t.ClrType == typeof(Animal))
    .AddProperty(typeof(Animal).GetProperty(nameof(Animal.CreateUserName))); // show CreateUserName


问:
MySQL select optimization
A table with a few Million rows, something like this:

```<code>my_table (
  `CONTVISITID` bigint(20) NOT NULL AUTO_INCREMENT,
  `NODE_ID` bigint(20) DEFAULT NULL,
  `CONT_ID` bigint(20) DEFAULT NULL,
  `NODE_NAME` varchar(50) DEFAULT NULL,
  `CONT_NAME` varchar(100) DEFAULT NULL,
  `CREATE_TIME` datetime DEFAULT NULL,
  `HITS` bigint(20) DEFAULT NULL,
  `UPDATE_TIME` datetime DEFAULT NULL,
  `CLIENT_TYPE` varchar(20) DEFAULT NULL,
  `TYPE` bigint(1) DEFAULT NULL,
  `PLAY_TIMES` bigint(20) DEFAULT NULL,
  `FIRST_PUBLISH_TIME` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`CONTVISITID`),
  KEY `cont_visit_contid` (`CONT_ID`),
  KEY `cont_visit_createtime` (`CREATE_TIME`),
  KEY `cont_visit_publishtime` (`FIRST_PUBLISH_TIME`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=57676834 DEFAULT CHARSET=utf8
</code>```

I had a query that I have managed to optimize to the following departing from a flat select:

```<code>SELECT a.cont_id, SUM(a.hits)
FROM  (
SELECT cont_id,hits,type,first_publish_time
FROM my_table
where create_time > '2017-03-10 00:00:00'
AND first_publish_time>1398310263000
AND type=1) as a group by a.cont_id
order by sum(HITS) DESC LIMIT 10;
</code>```

Can this be further optimized?

Edit:
I started with a FLAT select like I mentioned before, what I mean by flat select not to have a composite select like my current one. Instead of the single select that someone responded with. A single select is twice slower, so not viable in my case.

Edit2: I have a DBA friend who suggested me to change the query to this:

```<code>SELECT a.cont_id, SUM(a.hits)
FROM  (
 SELECT cont_id,hits
 FROM my_table
 where create_time > '2017-03-10 00:00:00'
  AND first_publish_time>1398310263000
  AND type=1) as a group by a.cont_id
order by sum(HITS) DESC LIMIT 10;
</code>```

As I do not need the fields extra (type,first_publish_time) and the TMP table is smaller, this makes the query faster about about 1/4 total time of the fastest version I have. He also suggested to add a composite index between (create_time, cont_id, hits). He says with this index I will get really good performance, but I have not done that as this is a production DB and the alter might affect replication. I will post results once done.

答:
```<code>INDEX(type, first_publish_time)
INDEX(type, create_time)
</code>```

Then do

```<code>SELECT cont_id, SUM(hits) AS tot_hits
    FROM my_table
    where create_time > '2017-03-10 00:00:00'
      AND first_publish_time > 1398310263000
      AND type = 1
    group by cont_id
    order by tot_hits DESC
    LIMIT 10;
</code>```

Start the index with any = filters (type, in this case); then you get one chance to us a range.

The reason for 2 indexes -- The Optimizer will look at statistics and decide which look better based on the values given.

Consider shrinking the BIGINTs (8 bytes) to some smaller INT type.  Saving space will help speed, especially if the table is too big to be cached.

For further discussion, please provide EXPLAIN SELECT ...;.

Title: MySQL select optimization

Body:
A table with a few Million rows, something like this:

my_table (
  `CONTVISITID` bigint(20) NOT NULL AUTO_INCREMENT,
  `NODE_ID` bigint(20) DEFAULT NULL,
  `CONT_ID` bigint(20) DEFAULT NULL,
  `NODE_NAME` varchar(50) DEFAULT NULL,
  `CONT_NAME` varchar(100) DEFAULT NULL,
  `CREATE_TIME` datetime DEFAULT NULL,
  `HITS` bigint(20) DEFAULT NULL,
  `UPDATE_TIME` datetime DEFAULT NULL,
  `CLIENT_TYPE` varchar(20) DEFAULT NULL,
  `TYPE` bigint(1) DEFAULT NULL,
  `PLAY_TIMES` bigint(20) DEFAULT NULL,
  `FIRST_PUBLISH_TIME` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`CONTVISITID`),
  KEY `cont_visit_contid` (`CONT_ID`),
  KEY `cont_visit_createtime` (`CREATE_TIME`),
  KEY `cont_visit_publishtime` (`FIRST_PUBLISH_TIME`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=57676834 DEFAULT CHARSET=utf8

I had a query that I have managed to optimize to the following departing from a flat select:

SELECT a.cont_id, SUM(a.hits)
FROM  (
SELECT cont_id,hits,type,first_publish_time
FROM my_table
where create_time > '2017-03-10 00:00:00'
AND first_publish_time>1398310263000
AND type=1) as a group by a.cont_id
order by sum(HITS) DESC LIMIT 10;

Can this be further optimized?

Edit:
I started with a FLAT select like I mentioned before, what I mean by flat select not to have a composite select like my current one. Instead of the single select that someone responded with. A single select is twice slower, so not viable in my case.

Edit2: I have a DBA friend who suggested me to change the query to this:

SELECT a.cont_id, SUM(a.hits)
FROM  (
 SELECT cont_id,hits
 FROM my_table
 where create_time > '2017-03-10 00:00:00'
  AND first_publish_time>1398310263000
  AND type=1) as a group by a.cont_id
order by sum(HITS) DESC LIMIT 10;

As I do not need the fields extra (type,first_publish_time) and the TMP table is smaller, this makes the query faster about about 1/4 total time of the fastest version I have. He also suggested to add a composite index between (create_time, cont_id, hits). He says with this index I will get really good performance, but I have not done that as this is a production DB and the alter might affect replication. I will post results once done.

Body:
INDEX(type, first_publish_time)
INDEX(type, create_time)

Then do

SELECT cont_id, SUM(hits) AS tot_hits
    FROM my_table
    where create_time > '2017-03-10 00:00:00'
      AND first_publish_time > 1398310263000
      AND type = 1
    group by cont_id
    order by tot_hits DESC
    LIMIT 10;

Start the index with any = filters (type, in this case); then you get one chance to us a range.

The reason for 2 indexes -- The Optimizer will look at statistics and decide which look better based on the values given.

Consider shrinking the BIGINTs (8 bytes) to some smaller INT type.  Saving space will help speed, especially if the table is too big to be cached.

For further discussion, please provide EXPLAIN SELECT ...;.


问:
SPFx breakpoints and debugging from Visual Studio Code instead from Chrome
I am trying to find a way to debug my local SPFx workbench from Visual Studio Code instead from Chrome, but I could not find any guides on how to attach the Chrome to Visual Studio Code and hit a breakpoint in my react typescript webpart (web app). Are there any good guides on how to do it?

This may be something trivial, but I am new to the react-gulp-vs code world and in the past, it was relatively easy to debug javascript with Visual Studio and IExplorer and I am wondering if easy setup exists with Visual Studio Code as well.

Thanks!

答:
Quick update on this. @gruss is right about the Debugger for Chrome, but I wanted to go one step further and create a guide.

The official documents from the Office Dev team here:
https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode

I found very useful article here:
http://www.eliostruyf.com/how-to-debug-your-sharepoint-framework-web-part

I also created one here:
http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code

Gist with the launch.json config here:
https://gist.github.com/VelinGeorgiev/4a7b77ced7198df0a3898420d46f3405

The config pasted here for quick reference:

```<code>// Use Chrome browser to debug SharePoint Framework React webpart with Visual Studio Code on Windows
// - Install "Debugger for Chrome" extension
// - Add this configuration to the launch.json
// - Close all Chrome browser active instances
// - Start the SPFx nodejs server by executing "gulp serve"
// - Go to VS Code debug view (top menu -> View -> Debug)
// - Hit the play (start debugging) button
// Happy debugging!
// Full guides
// http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code
// https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "SPFx Local",
            "type": "chrome",
            "request": "launch",
            "url": "https://localhost:4321/temp/workbench.html",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/sites/<your_site>/SitePages/<your_webpart_page>.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online Workbench",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/_layouts/workbench.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        }
    ]
}
</code>```

Please let me know if any issues.

Body:
Quick update on this. @gruss is right about the Debugger for Chrome, but I wanted to go one step further and create a guide.

The official documents from the Office Dev team here:
https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode

I found very useful article here:
http://www.eliostruyf.com/how-to-debug-your-sharepoint-framework-web-part

I also created one here:
http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code

Gist with the launch.json config here:
https://gist.github.com/VelinGeorgiev/4a7b77ced7198df0a3898420d46f3405

The config pasted here for quick reference:

// Use Chrome browser to debug SharePoint Framework React webpart with Visual Studio Code on Windows
// - Install "Debugger for Chrome" extension
// - Add this configuration to the launch.json
// - Close all Chrome browser active instances
// - Start the SPFx nodejs server by executing "gulp serve"
// - Go to VS Code debug view (top menu -> View -> Debug)
// - Hit the play (start debugging) button
// Happy debugging!
// Full guides
// http://blog.velingeorgiev.pro/how-debug-sharepoint-framework-webpart-visual-studio-code
// https://dev.office.com/sharepoint/docs/spfx/debug-in-vscode
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "SPFx Local",
            "type": "chrome",
            "request": "launch",
            "url": "https://localhost:4321/temp/workbench.html",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/sites/<your_site>/SitePages/<your_webpart_page>.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        },
        {
            "name": "SPFx Online Workbench",
            "type": "chrome",
            "request": "launch",
            "url": "https://<your_tenant>.sharepoint.com/_layouts/workbench.aspx",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../src/*": "${webRoot}/src/*",
                "webpack:///../../../../../src/*": "${webRoot}/src/*"
            },
            "runtimeArgs": [
                "--remote-debugging-port=9222"
            ]
        }
    ]
}

Please let me know if any issues.


问:
Execute program as normal user (while being root)
I'm working on Debian 8 (Jessie) (64 bits). I want to run program as normal user, without creating and switching accounts to normal user.

I am running the main program from bash script:

```<code>screen ./run
</code>```

where run contains:

```<code>#!/bin/bash
ulimit -c unlimited
while true; do ./tfs --log-file "output.txt" "error.txt" | tee out.txt; done
</code>```

I want to run the 'tfs' as normal user

答:
```<code>sudo -u username
</code>```

is the command you are looking for.

Body:
I'm working on Debian 8 (Jessie) (64 bits). I want to run program as normal user, without creating and switching accounts to normal user.

I am running the main program from bash script:

screen ./run

where run contains:

#!/bin/bash
ulimit -c unlimited
while true; do ./tfs --log-file "output.txt" "error.txt" | tee out.txt; done

I want to run the 'tfs' as normal user

Body:
sudo -u username

is the command you are looking for.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
I found ++ to be fascinating in high school.

Everyone else knew Basic, Pascal, etc.  But i++ was code!   And code that only I knew!

And such tiny changes could have very important effects:
++i is different in many important ways from i++.
And ++ translates so directly all the way down to machine code.  So by learning this, I had direct access to the CORE of the MACHINE.  Imagine the power!

Learning about this made me want to learn all the other strange operations and  corners of the C language.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

OwnerDisplayName: Aaron


问:
Trying to get a simple php form to fire
I shouldnt even be in HTML/CSS, but here I am trying to incorporate a php modal contact form into my site...

I'm trying to get all of a demo form's functionality into my footer page (and then I'll restyle everything.)

http://danux.me/sections/footer_modal.html

I'm trying to get "email me" to fire ideally, but am settling now for just the Demo button to fire the popup form.

I also uploaded the demo form I'm pulling code from, just to make sure it works on my site. (It does.)

http://danux.me/contact/

Any guesses as to what I'm doing wrong?

答:
Your first link is in a different folder, yet the url for $.get points to the same relative file. Which isn't there.

So in contact.js needs to have

```<code> $.get("../contact/data/contact.php", function(data){
</code>```

I obviously cant test this. And it looks like there is some redesign in folderstructure coming up.

Title: Trying to get a simple php form to fire

Body:
Your first link is in a different folder, yet the url for $.get points to the same relative file. Which isn't there.

So in contact.js needs to have

 $.get("../contact/data/contact.php", function(data){

I obviously cant test this. And it looks like there is some redesign in folderstructure coming up.


问:
getting NaN when trying to cast string to int
I'm getting some very weird results here. I'm trying to convert a string into a integer. Consider the following code below.

```<code>           //Send back to client.
            io.emit('returned message', {
                'message': message,
                'chatid': chatid,
                'userid': userid
            });
            console.log("Returning the data to chat " + chatid);
</code>```

Which is sending data back to client, the console log looks like this:

Returning the data to the chat '5'

and in the client I have

```<code>alert(typeof msg.chatid);
alert(msg.chatid)
var test = Number(msg.chatid);
alert(typeof test)
alert(test);
</code>```

Which produces the following results

String and '5'
  Number and NaN

Please note I've tried Number() and parseInt()

However, trying to code in Jsfiddle, it works fine. I have no idea why I'm getting NaN. Any ideas?

var num = '5';

alert(Number(num));```

答:
try using parseInt().

var num = '5';

alert(parseInt(num));```

Body:
I'm getting some very weird results here. I'm trying to convert a string into a integer. Consider the following code below.

           //Send back to client.
            io.emit('returned message', {
                'message': message,
                'chatid': chatid,
                'userid': userid
            });
            console.log("Returning the data to chat " + chatid);

Which is sending data back to client, the console log looks like this:

Returning the data to the chat '5'

and in the client I have

alert(typeof msg.chatid);
alert(msg.chatid)
var test = Number(msg.chatid);
alert(typeof test)
alert(test);

Which produces the following results

String and '5'
  Number and NaN

Please note I've tried Number() and parseInt()

However, trying to code in Jsfiddle, it works fine. I have no idea why I'm getting NaN. Any ideas?

var num = '5';

alert(Number(num));


问:
aws lambda reject file upload
I created the below aws lambda function and set the trigger on all S3 upload events on my target bucket. The function attempt to reject file uploads greater than 2000000 bytes. The error message was logged, but neither context.fail('upload rejected') or context.fail(new Error('upload rejected')) did not prevent the fail upload. How to reject file upload, or in general, "reject/stop" an event with aws lambda?

//// nodejs aws lambda code: /////

```<code>exports.handler = (event, context, callback) => {
    var MAX_FILE_SIZE = 2000000;
    var msg = '';
    console.log('Received event:', JSON.stringify(event, null, 2));
    if (event.Records && event.Records.length && event.Records.length>0 && event.Records[0].s3 && event.Records[0].s3.object
        && event.Records[0].s3.object.size && event.Records[0].s3.object.size > MAX_FILE_SIZE) {
        msg = 'File ' + event.Records[0].s3.object.key + ' rejected, file size ' + event.Records[0].s3.object.size
            + ' is greater than ' + MAX_FILE_SIZE + ' bytes.';
        console.log(msg);
        var err = new Error(msg);
        callback(err, {'disposition':'STOP_RULE'});
        context.fail(err);
    } else {
        msg = 'Upload succeeded.';
        console.log(msg);
        callback(null, msg);
        context.succeed(msg);
    }

};
</code>```

答:
You can't do that if your lambda is triggered by s3 notification, simply because in that case it is not controlling the file upload in any way. It is simply called to do some processing  based on file upload. If you want to control the file upload then your uploading should happen via the lambda function

What you can actually do in your current situation is that you can delete the file if you see that the size is greater than your required limit, but you cannot prevent the file from getting upload

Title: aws lambda reject file upload

Body:
I created the below aws lambda function and set the trigger on all S3 upload events on my target bucket. The function attempt to reject file uploads greater than 2000000 bytes. The error message was logged, but neither context.fail('upload rejected') or context.fail(new Error('upload rejected')) did not prevent the fail upload. How to reject file upload, or in general, "reject/stop" an event with aws lambda?

//// nodejs aws lambda code: /////

exports.handler = (event, context, callback) => {
    var MAX_FILE_SIZE = 2000000;
    var msg = '';
    console.log('Received event:', JSON.stringify(event, null, 2));
    if (event.Records && event.Records.length && event.Records.length>0 && event.Records[0].s3 && event.Records[0].s3.object
        && event.Records[0].s3.object.size && event.Records[0].s3.object.size > MAX_FILE_SIZE) {
        msg = 'File ' + event.Records[0].s3.object.key + ' rejected, file size ' + event.Records[0].s3.object.size
            + ' is greater than ' + MAX_FILE_SIZE + ' bytes.';
        console.log(msg);
        var err = new Error(msg);
        callback(err, {'disposition':'STOP_RULE'});
        context.fail(err);
    } else {
        msg = 'Upload succeeded.';
        console.log(msg);
        callback(null, msg);
        context.succeed(msg);
    }

};


问:
Jupyter notebook only runs in python [root]
My question actually has two parts. So I just started to learn python language and downloaded Anaconda.
My friend recommended me to use Jupyter since it's relatively easy to use for beginners.
1) He told me to firstly type

'conda upgrade jupyter' in the Anaconda prompt (Btw I'm using Python 2.7)

and then I shall be able to run Jupyter by typing in:
'jupyter'

However, the prompt only gives me:

```<code>**(C:\Users\Kester\Anaconda2) C:\Users\Kester>jupyter
usage: jupyter-script.py [-h] [--version] [--config-dir] [--data-dir]
                     [--runtime-dir] [--paths] [--json]
                     [subcommand]
jupyter-script.py: error: one of the arguments --version subcommand --config-dir --data-dir --runtime-dir --paths is required**
</code>```

So I use the second method to run the Jupyter
I typed 'jupyter notebook' to open Jupyter.

2) But this time I got another problem, which is that only Python[root] is available when creating a new notebook. On the other hand, the terminal is not accessible, too.
Unaccessible Terminal and Python [root] only
I tried the method of removing nbsignature file under the jupyter folder. But it simply doesn't work.
Any Help please?

答:
You just need enter in Terminal: </p>

```<code>jupyter notebook
</code>```

Body:
My question actually has two parts. So I just started to learn python language and downloaded Anaconda.
My friend recommended me to use Jupyter since it's relatively easy to use for beginners.
1) He told me to firstly type

'conda upgrade jupyter' in the Anaconda prompt (Btw I'm using Python 2.7)

and then I shall be able to run Jupyter by typing in:
'jupyter'

However, the prompt only gives me:

**(C:\Users\Kester\Anaconda2) C:\Users\Kester>jupyter
usage: jupyter-script.py [-h] [--version] [--config-dir] [--data-dir]
                     [--runtime-dir] [--paths] [--json]
                     [subcommand]
jupyter-script.py: error: one of the arguments --version subcommand --config-dir --data-dir --runtime-dir --paths is required**

So I use the second method to run the Jupyter
I typed 'jupyter notebook' to open Jupyter.

2) But this time I got another problem, which is that only Python[root] is available when creating a new notebook. On the other hand, the terminal is not accessible, too.
Unaccessible Terminal and Python [root] only
I tried the method of removing nbsignature file under the jupyter folder. But it simply doesn't work.
Any Help please?

Body:
You just need enter in Terminal:

jupyter notebook


问:
Heroku always executes the dependancies check and slows down the push process
I am using the free version of heroku server. When ever i push to the heroku, I always get:

```<code>Gemfile detected, running Bundler version 1.0.0
</code>```

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!

答:
Run bundle install locally to make sure you have a Gemfile.lock and add that to your git repo.

```<code>$ bundle install
$ git add Gemfile.lock
$ git commit -a -m "adding gemfile lock"
$ git push heroku
</code>```

I've noticed sometimes that my deploys don't get all my dependencies if they are already satisfied, but that's not always the case because you're not necessarily deploying to the same place every time.

Body:
I am using the free version of heroku server. When ever i push to the heroku, I always get:

Gemfile detected, running Bundler version 1.0.0

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!

Body:
Run bundle install locally to make sure you have a Gemfile.lock and add that to your git repo.

$ bundle install
$ git add Gemfile.lock
$ git commit -a -m "adding gemfile lock"
$ git push heroku

I've noticed sometimes that my deploys don't get all my dependencies if they are already satisfied, but that's not always the case because you're not necessarily deploying to the same place every time.


问:
Can't read larger than 1kb in java
I have a question about dealing with large file in java.

I work on Eclipse neon, on Mac Pro. and I want to read .txt files in Java, the files size is in MB or GM.
I search on google and I have read all the question here in stackoverflow, and I try the the ways to reading the files.
I tried the
FileReader and BufferedReader , also I tried FileInputStream
when I read file equal or less than 100 KB, eclipse is ok and it read all the file.
But if the file in MG or more than 100 KB,eclipse hanging and I must restart it.
I don't know what is the problem, Is it in my device or what?
I really get confused of that, because all the ways I tried say it can read file with 1MG in some second. And with me it doesn't.
Is there any API or anything that I can use it, to guarantee read whole file.
Please, any one have same problem, give me an advice.

This is the code:

```<code> FileReader fileReader1 =  new FileReader("/Users/Desktop/i/36.txt");
        BufferedReader br = new BufferedReader(fileReader1);
          String line ;
            while ((line = br.readLine()) != null) {
                token+=line+" ";
            }
System.out.println(token);
</code>```

also I tried this:

```<code>List<String> lines = Files.readAllLines(Paths.get(fileName),
                    StandardCharsets.UTF_8);

            for (String line : lines) {
                System.out.println(line);
            }
</code>```

答:
The first is slurping the whole file into a single variable (never use string concatenation in a loop; use a StringBuilder) and probably crushing your machine under GC load.

The second one should work, but it might take a while on a larger file; I'm surprised there's not a stream version of it. Run in the debugger and find if there's a line that's taking forever.

Title: Can't read larger than 1kb in java

Body:
I have a question about dealing with large file in java.

I work on Eclipse neon, on Mac Pro. and I want to read .txt files in Java, the files size is in MB or GM.
I search on google and I have read all the question here in stackoverflow, and I try the the ways to reading the files.
I tried the
FileReader and BufferedReader , also I tried FileInputStream
when I read file equal or less than 100 KB, eclipse is ok and it read all the file.
But if the file in MG or more than 100 KB,eclipse hanging and I must restart it.
I don't know what is the problem, Is it in my device or what?
I really get confused of that, because all the ways I tried say it can read file with 1MG in some second. And with me it doesn't.
Is there any API or anything that I can use it, to guarantee read whole file.
Please, any one have same problem, give me an advice.

This is the code:

 FileReader fileReader1 =  new FileReader("/Users/Desktop/i/36.txt");
        BufferedReader br = new BufferedReader(fileReader1);
          String line ;
            while ((line = br.readLine()) != null) {
                token+=line+" ";
            }
System.out.println(token);

also I tried this:

List<String> lines = Files.readAllLines(Paths.get(fileName),
                    StandardCharsets.UTF_8);

            for (String line : lines) {
                System.out.println(line);
            }


问:
Rendering Layouts with Backbone.js
If you were to build a single page web application (SPWA) using Backbone.js and jQuery with--for example--two controllers that each required a unique page layouts, how would you render the layout?

ControllerA is a three column layout.

ControllerB is a two column layout.

The default route activates ControllerA.Welcome() -- the initial rendering.

Both controllers have different views rendered within their columns that take advantage of all the Backbone.js model/view goodness.

The Problem

When the user requests a route mapped to ControllerB, the entire page layout needs to change to no longer use the ControllerA layout. This would hide ControllerA's layout and show ControllerB's layout -- or, render the layout if not already in the DOM.

My First Thought

Would you use a Backbone.js view to render the layout, and then, render each column with it's model-bound views?

My Second Thought

Would you add a setup/layout method to your controller that used jQuery to render the layout and then allow the action responsible for the route do it's thing? Using jQuery within the controller feels a little off to me, but, I want the controller to be responsible for ensuring the right layout is visible for it's routes.

Here is a snippet for my second thought:

```<code>var Controller = Backbone.Controller.extend
({
    routes :
    {
       "" : "welcome" // default action
    }
    /** Constructor **/
    ,initialize: function(options)
    {
        console.log('Workspace initialized');
    }
    // LAYOUT
    ,renderLayout : function ()
    {
        console.log('Rendering Layout.');
        var $ = window.$;
        var layout = require('js/layout/app/big_menu');
        $(layout.parent).html(layout.html);
    }
    // ACTIONS
    /** Default Action **/
    ,welcome : function ()
    {
        this.renderLayout();
        console.log('Do the whole model/view thing...');
    }
});
</code>```

Thank You

Thanks for taking the time to respond. I appreciate it!

答: I tend to agree with Julien -- it's nice to keep your layouts as stateless as possible. Everything is always laid out on the page, in skeleton form, at least. When the particular layout or configuration needs to be displayed, you lazily-render its contents, and display that portion of the UI with CSS. Mutually-exclusive CSS classes are useful for this, things like: "projects-open", "documents-open", "notes-open".</p>

Title: Rendering Layouts with Backbone.js

Body:
If you were to build a single page web application (SPWA) using Backbone.js and jQuery with--for example--two controllers that each required a unique page layouts, how would you render the layout?

ControllerA is a three column layout.

ControllerB is a two column layout.

The default route activates ControllerA.Welcome() -- the initial rendering.

Both controllers have different views rendered within their columns that take advantage of all the Backbone.js model/view goodness.

The Problem

When the user requests a route mapped to ControllerB, the entire page layout needs to change to no longer use the ControllerA layout. This would hide ControllerA's layout and show ControllerB's layout -- or, render the layout if not already in the DOM.

My First Thought

Would you use a Backbone.js view to render the layout, and then, render each column with it's model-bound views?

My Second Thought

Would you add a setup/layout method to your controller that used jQuery to render the layout and then allow the action responsible for the route do it's thing? Using jQuery within the controller feels a little off to me, but, I want the controller to be responsible for ensuring the right layout is visible for it's routes.

Here is a snippet for my second thought:

var Controller = Backbone.Controller.extend
({
    routes :
    {
       "" : "welcome" // default action
    }
    /** Constructor **/
    ,initialize: function(options)
    {
        console.log('Workspace initialized');
    }
    // LAYOUT
    ,renderLayout : function ()
    {
        console.log('Rendering Layout.');
        var $ = window.$;
        var layout = require('js/layout/app/big_menu');
        $(layout.parent).html(layout.html);
    }
    // ACTIONS
    /** Default Action **/
    ,welcome : function ()
    {
        this.renderLayout();
        console.log('Do the whole model/view thing...');
    }
});

Thank You

Thanks for taking the time to respond. I appreciate it!


问:
Why is sign of DC and AC coefficients opposite of normal signed binary numbers?
I am very confused here. Here are some excerpts from ITU T.81;

From section Annex F section F.1.2.1.1 for DC coefficients in scan data:

"When DIFF is positive, the SSSS low order bits of DIFF are appended.
  When DIFF is negative, the SSSS low order bits of (DIFF – 1) are
  appended. Note that the most significant bit of the appended bit
  sequence is 0 for negative differences and 1 for positive
  differences."

Very similar to this in same Annex F end of section F.1.2.2.1 for AC coefficients in scan data:

"The format for the additional bits is the same as in the coding of
  the DC coefficients. The value of SSSS gives the number of additional
  bits required to specify the sign and precise amplitude of the
  coefficient. The additional bits are either the low-order SSSS bits of
  ZZ(K) when ZZ(K) is positive or the low-order SSSS bits of ZZ(K) – 1
  when ZZ(K) is negative."

Q1: It says "Note that the most significant bit of the appended bit sequence is 0 for negative differences and 1 for positive differences" but isn't this opposite of how signed numbers work? If the most significant bit is 1 that means we have a negative number, else we have positive number. But here this simple rule is reversed!?

Q2. In both cases we write ZZ(K) if it is positive and ZZ(K)-1 if it is negative. Why do we write ZZ(K)-1 if that ZZ(K) is negative?? I cannot understand this from the documentation.

Q3. Is the sign bit itself actually extra from the number of bits specified in SSSS?

These three things are seriously troubling me and I would be very thankful if you could answer them.

答:
If the most significant bit is 1 that means we have a negative number, else we have positive number. But here this simple rule is reversed!?

Because you are dealing with variable length data, there is no sign bit. The length works in conjunction with the bit values.

If you have length=1, bits=1 the resulting value is 1, just as if it were encoded in a full signed byte. The rule is not being reversed.

Q2. In both cases we write ZZ(K) if it is positive and ZZ(K)-1 if it is negative. Why do we write ZZ(K)-1 if that ZZ(K) is negative?

That is just the chosen way of encoding negative numbers. In the normal 4-byte encoding of -1 you would have the binary value

1111 1111 1111 1111 1111 1111 1111 1111

requiring 32-bits to encode.

Instead it gets encoded with a length and a single bit: Length=1, Bits=0.

For zero, you just have Length=0, Bits=0.

In this type of variable length encoding, either the positive value or the negative values had to be flipped to distinguish between them. They happened to choose to flip the negative.

Q3. Is the sign bit itself actually extra from the number of bits specified in SSSS?

There is no sign bit in this encoding.