问:
"Package should contain a content type part [M1.13]"
I am attempting to write to an Excel file however I keep getting the error:

Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

From what I understand I am missing a jar file.

Can anyone help me identify which file it is?

P.S. I am using Netbeans.

```<code>import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nicholaskissaun
 */

public class Tester {

    public static void main (String args \[\])throws FileNotFoundException, IOException, InvalidFormatException{
        int RowCount = 7, iChoice;
        String sChoice;
        XSSFSheet s;
        XSSFRow row1;
        XSSFWorkbook wb;
        XSSFCell r1c1, r1c2, r1c8, r1Episodes;

        FileInputStream fis = new FileInputStream("/Users/nicholaskissaun/Google Drive/Grade 11_12/Computer Science/Java/Term1/src/IA/Profiles/Becky/ShowDetails.xlsx");
        wb = new XSSFWorkbook(fis);
        s = wb.getSheetAt(0);

    }

}
</code>```

答:
Use file extension to handle WorkSheet Type

```<code>  String inputFilename = new File(path).getName();

                    switch (inputFilename.substring(inputFilename.lastIndexOf(".") + 1,
                            inputFilename.length())) {
                        case "xls":
                            return readXLS(path);

                        case "xlsx":
                            return readXLSX(path);
                        default:
                            Log.e(TAG, "No XLS file chosen");
                            return "Please select valid \"Excel\" File\"";
                    }
</code>```

For XLSX file: use XSSFWorkbook & XSSFSheet

```<code>    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

    XSSFSheet sheet = workbook.getSheetAt(0);
</code>```

For XLS file: use HSSFWorkbook & HSSFSheet

```<code>    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(path)));

    HSSFSheet sheet = workbook.getSheetAt(0);
</code>```

Body:
I am attempting to write to an Excel file however I keep getting the error:

Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

From what I understand I am missing a jar file.

Can anyone help me identify which file it is?

P.S. I am using Netbeans.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nicholaskissaun
 */

public class Tester {

    public static void main (String args \[\])throws FileNotFoundException, IOException, InvalidFormatException{
        int RowCount = 7, iChoice;
        String sChoice;
        XSSFSheet s;
        XSSFRow row1;
        XSSFWorkbook wb;
        XSSFCell r1c1, r1c2, r1c8, r1Episodes;

        FileInputStream fis = new FileInputStream("/Users/nicholaskissaun/Google Drive/Grade 11_12/Computer Science/Java/Term1/src/IA/Profiles/Becky/ShowDetails.xlsx");
        wb = new XSSFWorkbook(fis);
        s = wb.getSheetAt(0);

    }

}

Body:
Use file extension to handle WorkSheet Type

  String inputFilename = new File(path).getName();

                    switch (inputFilename.substring(inputFilename.lastIndexOf(".") + 1,
                            inputFilename.length())) {
                        case "xls":
                            return readXLS(path);

                        case "xlsx":
                            return readXLSX(path);
                        default:
                            Log.e(TAG, "No XLS file chosen");
                            return "Please select valid \"Excel\" File\"";
                    }

For XLSX file: use XSSFWorkbook & XSSFSheet

    XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));

    XSSFSheet sheet = workbook.getSheetAt(0);

For XLS file: use HSSFWorkbook & HSSFSheet

    HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(path)));

    HSSFSheet sheet = workbook.getSheetAt(0);


来源: stackexchange

问:
JOptionPane.showInputDialog
I've been wondering about what is wrong with my code

```<code>String s = JOptionPane.showInputDialog(null,"Enter discount type");
                if(s == "PWD"){
                    dis = 0.25;
                }
                else{
                    dis = 0;
                    JOptionPane.showMessageDialog(null, s);
                }
</code>```

when I run my program, it performs the code in the 'else' block instead of doing what is in the 'if' block. Thanks!

答:
== calling a reference similarity

and .equals() check the value similarity so its better to use a (s.equals("PWD"))

ContentLicense: CC BY-SA 3.0

Title: JOptionPane.showInputDialog

Body:
I've been wondering about what is wrong with my code

String s = JOptionPane.showInputDialog(null,"Enter discount type");
                if(s == "PWD"){
                    dis = 0.25;
                }
                else{
                    dis = 0;
                    JOptionPane.showMessageDialog(null, s);
                }

when I run my program, it performs the code in the 'else' block instead of doing what is in the 'if' block. Thanks!


问:
Checking XML Document befor upload to server via php
I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.

I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.

The upload is completly realized in php.

Someone have an idea for me?

Edit:

```<code>var fileInput;

window.onload = function() {
    fileInput = document.getElementById('file_input');
};

function getNodes() {
    var anzNodes = fileInput.getElementsByTagName("node").length;
    return anzNodes;
}

function getEdges() {
    var anzEdges = fileInput.getElementsByTagName("edge").length;
    return anzEdges;
}

function fillForm() {
    document.getElementById("nodes").value = getNodes();
    document.getElementById("edges").value = getEdges();
}
</code>```

So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?

答:
I found the answer and will provide it for completeness.

My Javascript part:

```<code>var openFile = function (event) {
    var input = event.target;
    var reader = new FileReader();

    reader.onload = function () {
        var anzEdges = (reader.result.match(/<edge/g) || []).length;
        var anzNodes = (reader.result.match(/<node/g) || []).length;
        document.getElementById("nodes").value = anzNodes;
        document.getElementById("edges").value = anzEdges;
    };
    reader.readAsText(input.files[0]);
};
</code>```

and the relevant html-code:

```<code><input type="file" onchange="openFile(event)" name="file_upload" size="60"><br>
<input type="number" id="nodes" name="nodes" min="2" readonly><br>
<input type="number" id="edges" name="edges" min="1" readonly>
</code>```

Body:
I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.

I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.

The upload is completly realized in php.

Someone have an idea for me?

Edit:

var fileInput;

window.onload = function() {
    fileInput = document.getElementById('file_input');
};

function getNodes() {
    var anzNodes = fileInput.getElementsByTagName("node").length;
    return anzNodes;
}

function getEdges() {
    var anzEdges = fileInput.getElementsByTagName("edge").length;
    return anzEdges;
}

function fillForm() {
    document.getElementById("nodes").value = getNodes();
    document.getElementById("edges").value = getEdges();
}

So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?

Body:
I found the answer and will provide it for completeness.

My Javascript part:

var openFile = function (event) {
    var input = event.target;
    var reader = new FileReader();

    reader.onload = function () {
        var anzEdges = (reader.result.match(/<edge/g) || []).length;
        var anzNodes = (reader.result.match(/<node/g) || []).length;
        document.getElementById("nodes").value = anzNodes;
        document.getElementById("edges").value = anzEdges;
    };
    reader.readAsText(input.files[0]);
};

and the relevant html-code:

<input type="file" onchange="openFile(event)" name="file_upload" size="60"><br>
<input type="number" id="nodes" name="nodes" min="2" readonly><br>
<input type="number" id="edges" name="edges" min="1" readonly>


问:
Elasticsearch return context of the result (10 lines before and after the hits)
When querying elasticsearch, only hit documents will be returned. How can I get the context of the hits, which, say, 10 documents before and after the hits?

For example, I have inserted 5 logs into elasticsearch:

```<code>{"log": "a"}
{"log": "b"}
{"log": "c"}
{"log": "d"}
{"log": "e"}
</code>```

I have searched "query": { "match": { "log": "e" } }, and es will return the 5th document. However, I may want the previous 4 logs for debugging, can es return the context?

答:
Maybe my answer may not be a complete answer for you but I want to share my opinion to solve this problem.

Firstly, you want to get results like grep application after and before feature. As far as I know, Elasticsearch can find the documents according to terms matched with documents and it does not think about nearest documents according to order of documents. In my opinion, you can solve this issue with two method. First one is populating relative data to a document while ingesting, second is executing second query to find relative data.

For first method, you will have unnecessary duplicate data and this will be cause performance problems or need more storage, cpu or ram, etc. But you can fetch your data and relative ones with one query. To handle this, you can use https://www.elastic.co/guide/en/logstash/current/plugins-codecs-multiline.html filter of logstash while ingest your logs to Elasticsearch.

For second method, you will be so cool :). Nothing will change on your ingesting part but you should change representation part of your application. On the other hand, with ElasticStack 5.4 on Kibana there is a new feature for this, whicsh is Document Context. You can easily reach documents surrounding a specific document. And I have not try yet but I guess, it could be the same as the second method.

Update:

I have checked the Kibana Surrounding Documents feature and it uses search_after api.

Body:
When querying elasticsearch, only hit documents will be returned. How can I get the context of the hits, which, say, 10 documents before and after the hits?

For example, I have inserted 5 logs into elasticsearch:

{"log": "a"}
{"log": "b"}
{"log": "c"}
{"log": "d"}
{"log": "e"}

I have searched "query": { "match": { "log": "e" } }, and es will return the 5th document. However, I may want the previous 4 logs for debugging, can es return the context?


问:
Can't get access token in Xcode Swift Facebook login SDK
I'm trying to test Facebook SDK login in my app but keep getting this error. I see a dialog which accepts my email and password to login and then tells me I have already accepted the app. I should see a message "Logged in but I only see the error below. How can I test the Facebook SDK in the Xcode iOS simulator. I tested this on an iPhone with an alert to display the access token but got the same result. It will always present "User cancelled login".

```<code>-canOpenURL: failed for URL: "fbauth2:/" - error: The operation couldn’t be completed. (OSStatus error -10814.) User cancelled login.
</code>```

Here is my code.

```<code>func signInWithFacebook(button: UIButton) {

    let loginManager = LoginManager()

    loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in

        switch loginResult {

        case .failed(let error):

            let alertController: UIAlertController = UIAlertController(title: "Login error", message: error as? String, preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print(error)

        case .cancelled:

            let alertController: UIAlertController = UIAlertController(title: "Login cancelled", message: "User cancelled login", preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("User cancelled login.")

        case .success(let grantedPermissions, let declinedPermissions, let accessToken):

            print(grantedPermissions)

            print(declinedPermissions)

            print(accessToken)

            let alertController: UIAlertController = UIAlertController(title: "Login success", message: String(describing: accessToken), preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("Logged in")
        }
    }
}
</code>```

On the first pass, I got the Facebook login dialog but thereafter I just see a dialog saying I have already authorized my app with an OK button.

```<code>let accessToken = AccessToken.current
</code>```

in viewDidLoad() returns nil always. I need to get an accessToken so i can send it to an API and test the response.

答:
mb for fb login only better use FacebookLogin

token here:

```<code>FBSDKAccessToken.current().tokenString
</code>```

Body:
I'm trying to test Facebook SDK login in my app but keep getting this error. I see a dialog which accepts my email and password to login and then tells me I have already accepted the app. I should see a message "Logged in but I only see the error below. How can I test the Facebook SDK in the Xcode iOS simulator. I tested this on an iPhone with an alert to display the access token but got the same result. It will always present "User cancelled login".

-canOpenURL: failed for URL: "fbauth2:/" - error: The operation couldn’t be completed. (OSStatus error -10814.) User cancelled login.

Here is my code.

func signInWithFacebook(button: UIButton) {

    let loginManager = LoginManager()

    loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in

        switch loginResult {

        case .failed(let error):

            let alertController: UIAlertController = UIAlertController(title: "Login error", message: error as? String, preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print(error)

        case .cancelled:

            let alertController: UIAlertController = UIAlertController(title: "Login cancelled", message: "User cancelled login", preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("User cancelled login.")

        case .success(let grantedPermissions, let declinedPermissions, let accessToken):

            print(grantedPermissions)

            print(declinedPermissions)

            print(accessToken)

            let alertController: UIAlertController = UIAlertController(title: "Login success", message: String(describing: accessToken), preferredStyle: .alert)

            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in }

            alertController.addAction(okAction)

            self.present(alertController, animated: true, completion: nil)

            print("Logged in")
        }
    }
}

On the first pass, I got the Facebook login dialog but thereafter I just see a dialog saying I have already authorized my app with an OK button.

let accessToken = AccessToken.current

in viewDidLoad() returns nil always. I need to get an accessToken so i can send it to an API and test the response.

Body:
mb for fb login only better use FacebookLogin

token here:

FBSDKAccessToken.current().tokenString


问:
HTML Form Library for PHP 5
I am looking for a QuickForm replacement. QF has performance issues with, for example, many options in combobox. I would also like something more object oriented, like Zend_Form, but without decorators and so much bloat. Of course it should also be warning with E_STRICT. Any recommendations?

答: Also you may take a look at phorms and its somewhat newer fork</p>

OwnerDisplayName: Anonymous Coward

Title: HTML Form Library for PHP 5

ContentLicense: CC BY-SA 2.5


问:
system io file not found exception/ error handling
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

```<code>using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }
</code>```

答:
RTFM?

Read Directory.GetFiles method

It says that you will get the DirectoryNotfound exception if the specified path is not found. Obviously folder 'C:\Temp\first_project\first_project\bin\Debug\12345' does not exist.

Proper code would be:

```<code>string hely = ...
try
{
    string[] files = Directory.GetFiles(hely);
    ProcessFiles(files);
}
catch (DirectoryNotFoundException exc)
{
    Console.WriteLine(exc.Message);
}
</code>```

If you don't know how to react on exceptions read MSDN about exception handling

Body:
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }

Body:
RTFM?

Read Directory.GetFiles method

It says that you will get the DirectoryNotfound exception if the specified path is not found. Obviously folder 'C:\Temp\first_project\first_project\bin\Debug\12345' does not exist.

Proper code would be:

string hely = ...
try
{
    string[] files = Directory.GetFiles(hely);
    ProcessFiles(files);
}
catch (DirectoryNotFoundException exc)
{
    Console.WriteLine(exc.Message);
}

If you don't know how to react on exceptions read MSDN about exception handling


问:
Why it isnt it possible to do Set <Object> = new TreeSet <String>
Question: Why it isnt it possible to do Set <Object> = new TreeSet <String>? Why do I need to add ? extends.

Feeling like it is a set of objects and not one entity so it can get any type of collection, but the right side of the equation knows only to understand collection of strings

答:
To a Set<Object> you can add instances of Integer, String or any other reference type.

To a TreeSet<String> you can only add instances of String.

Therefore the compiler doesn't allow assigning a TreeSet<String> to a Set<Object>, since it would allow you to add any reference type to a TreeSet that should only hold Strings.


问:
how to add zeros for integer variable
I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.

ex:

int value = 23;

I want to use it like this ;

0023

Thanks in advance

答:
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.

If you need a 4 digit value always, use the .ToString formatting to add leading 0's.

```<code>int value = 23;
var result = value.ToString("0000");
</code>```

or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.

```<code>int value = 23;
var result = "00" + value.ToString();
</code>```

Title: how to add zeros for integer variable

Body:
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.

If you need a 4 digit value always, use the .ToString formatting to add leading 0's.

int value = 23;
var result = value.ToString("0000");

or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.

int value = 23;
var result = "00" + value.ToString();


问:
Navigating pages in jquery,Ajax
I'm new in jquery and ajax, i just want to open all my navigation links in one page. I also divided my page in three division. 1st page is in html i.e. welcome.html and rest all are in jsp. simply program takes two numbers, performs arithmetic operations on server (i wrote the servlet for each operation) side and send result back to jsp. At first it opens on same page but when i click on calculate button it goes on next page. if anybody have this solution using ajax or jquery plz let me know .

答: It's probably because the calculate button submits the form. Try calculating the value with JQuery/AJAX.</p>

Title: Navigating pages in jquery,Ajax


问:
How do i add text before footer in wordpress?
text just before the footer. I'm not a coder so please help me out and suggest me how to do it?</p>

答:
There are many way to add text or whatever in footer,

You can find the template file belongs to this page and then find
footer file which is included using "get_footer()" in the last of
template file and modify this footer file as you want.

Another method is to use hook
use wp_footer() hook in your functions.php

```<code>function add_footer_text_function() {
    echo '<p>Text in Footer<strong>Company name</strong></p>';
}
add_action( 'wp_footer', 'add_footer_text_function');
</code>```

As you said you are not a coder then use Custom Headers and
Footers plugin using this you can modify footer of your website.

Body:
There are many way to add text or whatever in footer,

You can find the template file belongs to this page and then find
footer file which is included using "get_footer()" in the last of
template file and modify this footer file as you want.

Another method is to use hook
use wp_footer() hook in your functions.php

function add_footer_text_function() {
    echo '<p>Text in Footer<strong>Company name</strong></p>';
}
add_action( 'wp_footer', 'add_footer_text_function');

As you said you are not a coder then use Custom Headers and
Footers plugin using this you can modify footer of your website.


问:
Including files when writing Wordpress admin options page for a plugin
So I've written a couple of classes in separate php files to help me with API calls that I want to make when a user fills in a form on the plugin options page.
I've also got a config file with some variables I want to include on the options page.
The issue I'm having is that when I require the files, they seem to be including okay because there's no fatal error, but none of the variables or classes are available to use in the function I hook to the action 'admin_menu'.

```<code>require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/config.php');
require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/license.php');
require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/member.php');

function product_dyno_plugin_menu() {
    add_options_page( 'Product Dyno Options', 'Product Dyno',
    'manage_options', 'activate-plugin-with-product-dyno',
    'product_dyno_options' );
}
add_action( 'admin_menu', 'product_dyno_plugin_menu' );

function product_dyno_options() {

    $license = new License();

    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo '<div class="wrap">';
    echo '<h2>Activate plugin '.$PLUGIN_NAME.'</h2>';
    echo '</div>';

    .......
</code>```

$PLUGIN_NAME is required from config.php and I'm getting the error that the variable is undefined.

Strangely, the class does seem to be included because variables used within the constructor of the class which are also included from config.php are also returning as undefined.

I'm assuming it's something to do with the headers already being sent or the order of the wp actions but I really can't work it out and I can't find a similar issue on any forums!

Any pointers would be hugely appreciated!

答:
I think, $Plugin_name is defined in config.php file, all values define in this file are unavailable in a procedural function.

There's two way to grab data on your function :

Use global

use new config() (if the config.php stands in a class)

To use global : at the top of product_dyno_options(), add global $PLUGIN_NAME;.

If config.php is in a class, use the same way you use for licence. In the function

```<code>$config = new config ();
</code>```

Then call it like this where you want after :

```<code>$config->plugin_name;
</code>```

Hope it helps

Body:
So I've written a couple of classes in separate php files to help me with API calls that I want to make when a user fills in a form on the plugin options page.
I've also got a config file with some variables I want to include on the options page.
The issue I'm having is that when I require the files, they seem to be including okay because there's no fatal error, but none of the variables or classes are available to use in the function I hook to the action 'admin_menu'.

require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/config.php');
require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/license.php');
require_once( plugin_dir_path( __DIR__ ) . 'product-dyno/member.php');

function product_dyno_plugin_menu() {
    add_options_page( 'Product Dyno Options', 'Product Dyno',
    'manage_options', 'activate-plugin-with-product-dyno',
    'product_dyno_options' );
}
add_action( 'admin_menu', 'product_dyno_plugin_menu' );

function product_dyno_options() {

    $license = new License();

    if ( !current_user_can( 'manage_options' ) )  {
        wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
    }
    echo '
';
    echo '
Activate plugin '.$PLUGIN_NAME.'
';
    echo '
';

    .......

$PLUGIN_NAME is required from config.php and I'm getting the error that the variable is undefined.

Strangely, the class does seem to be included because variables used within the constructor of the class which are also included from config.php are also returning as undefined.

I'm assuming it's something to do with the headers already being sent or the order of the wp actions but I really can't work it out and I can't find a similar issue on any forums!

Any pointers would be hugely appreciated!

Body:
I think, $Plugin_name is defined in config.php file, all values define in this file are unavailable in a procedural function.

There's two way to grab data on your function :

Use global

use new config() (if the config.php stands in a class)

To use global : at the top of product_dyno_options(), add global $PLUGIN_NAME;.

If config.php is in a class, use the same way you use for licence. In the function

$config = new config ();

Then call it like this where you want after :

$config->plugin_name;

Hope it helps


问:
Problems running code with Python IDLE
I have been attempting to work an iCreate, roomba without a vacuum cleaner attached using Python 2.7.1 and have created working code. When I type each line in by hand it works perfectly, however when putting all the code in together it stalls and does not operate.

```<code>import Create
import VideoCapture
from PIL import Image, Imagechops
import os
robot = Create.Create(3)
camera = VideoCapture.Device(0, 1)
(rgb_red, rgb_green, rgb_blue) = (0, 0, 0)
red = Image.open("Red.jpeg")
(redr, redg, redb) = red.getpixel((0, 0))
blue = Image.open("Blue.jpeg")
(bluer, blueg, blueb) = blue.getpixel((0, 0))
green = Image.open("Green.jpeg")
(greenr, greeng, greenb) = green.getpixel((0, 0))
yellow = Image.open("Yellow.jpeg")
(yellowr, yellowg, yellowb) = yellow.getpixel((0, 0))
camera.getImage(0, 0, 'tl')
camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
pic = Image.open("CurrentPicture.jpeg")
(rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
os.remove("C:\Python27\CurrentPicture.jpeg")
while 0 == 0:
    if((rgb_red - redr) < (rgb_green - greeng)) and ((rgb_red - redr) < (rgb_blue - blueb)):
        robot.stop()
    elif((rgb_blue - blueb) < (rgb_green - greeng)) and ((rgb_blue - blueb) < (rgb_red - redr)):
        robot.turn(45, 40)
    elif((rgb_green - greeng) < (rgb_red - redr)) and ((rgb_green - greeng) < (rgb_blue - blueb)):
        robot.move(50, 50)
    camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
    pic = Image.open("CurrentPicture.jpeg")
    (rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
    os.remove("C:\Python27\CurrentPicture.jpeg")
</code>```

Are there any issues with IDLE for running multiple lines and just not working, I am not terribly sure what I should be asking. It is just that nothing happens when I run that entire block together but line by line entering works.

-Any help is greatly appreciated.

答:
Instead if pasting the code into IDLE, save it into a file, and run it like this:

python yourfile.py

while 0 == 0: You might want while True: instead.

red = Image.open("Red.jpeg")
(redr, redg, redb) = red.getpixel((0, 0)) is a very complex way of saying RED = (255, 0, 0)

Title: Problems running code with Python IDLE

Body:
I have been attempting to work an iCreate, roomba without a vacuum cleaner attached using Python 2.7.1 and have created working code. When I type each line in by hand it works perfectly, however when putting all the code in together it stalls and does not operate.

import Create
import VideoCapture
from PIL import Image, Imagechops
import os
robot = Create.Create(3)
camera = VideoCapture.Device(0, 1)
(rgb_red, rgb_green, rgb_blue) = (0, 0, 0)
red = Image.open("Red.jpeg")
(redr, redg, redb) = red.getpixel((0, 0))
blue = Image.open("Blue.jpeg")
(bluer, blueg, blueb) = blue.getpixel((0, 0))
green = Image.open("Green.jpeg")
(greenr, greeng, greenb) = green.getpixel((0, 0))
yellow = Image.open("Yellow.jpeg")
(yellowr, yellowg, yellowb) = yellow.getpixel((0, 0))
camera.getImage(0, 0, 'tl')
camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
pic = Image.open("CurrentPicture.jpeg")
(rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
os.remove("C:\Python27\CurrentPicture.jpeg")
while 0 == 0:
    if((rgb_red - redr) < (rgb_green - greeng)) and ((rgb_red - redr) < (rgb_blue - blueb)):
        robot.stop()
    elif((rgb_blue - blueb) < (rgb_green - greeng)) and ((rgb_blue - blueb) < (rgb_red - redr)):
        robot.turn(45, 40)
    elif((rgb_green - greeng) < (rgb_red - redr)) and ((rgb_green - greeng) < (rgb_blue - blueb)):
        robot.move(50, 50)
    camera.saveSnapshot('CurrentPicture.jpeg', 0, 0, 'tl')
    pic = Image.open("CurrentPicture.jpeg")
    (rgb_red, rgb_green, rgb_blue) = pic.getpixel((0, 0))
    os.remove("C:\Python27\CurrentPicture.jpeg")

Are there any issues with IDLE for running multiple lines and just not working, I am not terribly sure what I should be asking. It is just that nothing happens when I run that entire block together but line by line entering works.

-Any help is greatly appreciated.


问:
How does ComponentScan work?
@ComponentScan will give you a list of all the classes with the @Component annotation in a package (or @Service/@Repository). To do this I imagine they use reflection to enumerate all the classes in a package and find the ones with that annotation.

However according to other StackOverflow answers you can not reliably enumerate all the classes in a package due to how the ClassLoaderworks. So how does @ComponentScan seemingly manage to accomplish this?

答:
@ComponentScan works differently. Workflow is put shortly this:

Find all .class files in same folder and all subfolders

Read .class file and wrap it into Resource object

Check if class has annotations that will make it good candidate

If class is good candidate, create bean from it.

Classes from Spring source code to look:

ComponentScanAnnotationParser

AnnotationConfigUtils

ClassPathBeanDefinitionScanner

BeanDefinitionReaderUtils

DefaultListableBeanFactory

Title: How does ComponentScan work?


问:
How to disable Apache caching in Apache-XAMPP?
I am having this weird problem with my XAMPP-Apache.
I am making an log-in system where form is posted to redirect.php page.
I updated the redirect.php and but still it is showing me the same old result.
There is not even a single line to redirect(header fn call) it to another page but still it redirects to home.php page as it was doing in older script.
I tried clearing cache of my browser and changing the browser for testing but didn't work...I even tried rebooting the server but no change.
Please help me through....</p>

答:
Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

```<code><filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>
</code>```

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control:
  private, x-gzip-ok="" > to prevent caching of ads by proxies and
  clients. From
  http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

Body:
Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control:
  private, x-gzip-ok="" > to prevent caching of ads by proxies and
  clients. From
  http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.


问:
How to achieve Android's getViewById in iOS?
IOS's IBOutlet is fine in most scenarios. But consider this:

I have a UITableview which contains 2 types of custom cells, both cells have the same subviews (1 image view and 2 labels), only the 2 types layout differently. Now how do I reference these subviews in my code?

I could, of course, define 2 subclasses of UITableViewCell, and use IBOutlet to reference them. But that sounds not very elegant, as behavior-wise, they are exactly the same.

Android has a getViewById function. In iOS, can I get a subview from a view with some identifier?

答:
You can give tag values to these subviews and you can get these subviews by using viewWithTag function. For example in swift for say label with tag 100 you can use</p>

```<code>    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
    let label = cell.viewWithTag(100) as? UILabel
    label?.text = "label from tag"
</code>```

Body:
You can give tag values to these subviews and you can get these subviews by using viewWithTag function. For example in swift for say label with tag 100 you can use

    let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
    let label = cell.viewWithTag(100) as? UILabel
    label?.text = "label from tag"


问:
Intercepting WebView
Let if web page is bound to WebView, then is it possible to capture
the data that user is entering in the data fields of the web page?

In other words my activity need to intercept and interpret what is happening in
webview.... Is it possible?

答: Make the web page contain a submit-button, which activates Javascript, that accesses a JavaScript API that your application exposes. This way, you can make your web page communicate the data directly to your Android Java code.</p>

Title: Intercepting WebView


问:
Is there an inverse to Git's octopus merge?
Git has a much-touted(?) octopus-merge capability that can merge many heads into one.

But is there something that would do just the opposite, make several simultaneous branches out of one node?

Let's assume that I have a bunch of code for a project, and I just started using Git. Some of the features are complete in that project, others are still work-in-progress. What I'd want is to get those unfinished features moved into their own respective and separate branch, and have the master as 'complete' as possible, with no unfinished code.

Now, I could of course do all of this in single steps: Create a "unfinished feature #1" branch, and delete the files from the master that are specific to that feature. Then I'd re-branch the master into "unfinished feature #2" and again remove feature #2 specific files from the master, but also from the first branch. And thus the workload increases for each split I do.

Is there something that would help me in such a scenario?

答:
Since you just started using Git, it would be easier to start again and only commit your 'complete' code to the Master branch. Then checkout a new branch from the master for a feature and commit that 'unfinished' feature code on its own branch. Repeat for each feature branch. </p>

<p>You have to partition the code into features and 'complete' anyway, so use that to set up your repository. </p>

OwnerDisplayName: wolfie

Body:
Since you just started using Git, it would be easier to start again and only commit your 'complete' code to the Master branch. Then checkout a new branch from the master for a feature and commit that 'unfinished' feature code on its own branch. Repeat for each feature branch.

You have to partition the code into features and 'complete' anyway, so use that to set up your repository.

OwnerDisplayName: Paul


问:
creating .htaccess
I am developing a project with Struts2. I use jsp for web-side. I use MySQL database for my application and I installed wamp server for it. My urls are like localhost/xxx?name.action?blablabla... instead of this I wanna redirect urls. For example instead of name.action on my url I wanna use localhost/name or something like that. Also with .htaccess I wanna send data over it as like name.action?Id=$1... for my action at Struts2 side. However I couldn't redirect the urls, I couldn't define document root properly and .htaccess file. What should I do, can you explain it step by step?

Thanks.

答: If using a current version of struts2, 2.2.1 you should set up your application as per: http://struts.apache.org/2.2.1/docs/create-struts-2-web-application-using-maven-to-manage-artifacts-and-to-build-the-application.html please search the page for "web.xml Servlet Filter" once this is done "name" and "name.action" are both valid mappings to the "name" action. As for url parameters this is automatically taken care of with struts form tags.  The basic tutorials and tag reference examples on the struts.apache.org web site.  Document root is normally set up via IDE from project name, further when you compile typically the IDE will create a WAR, when deploying the WAR via a web interface for your application server / web container changing the document root is normally one of the visible fields during installation. So that is easily configurable on a per installation basis.  </p>

Title: creating .htaccess


问:
How to implement such use case by Java Concurrency Lock
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

```<code>public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}
</code>```

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

答:
An update on the below ReadWriteLock sample, we have to acquire locks before starting the read/write operations. As I don't have permission to edit the sample, posting a new answer.</p>

```<code>import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        Lock writeLock = lock.writeLock();
        try {
            writeLock.lock();
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            writeLock.unlock();
        }
    }

    public String getKey1() {
        Lock readLock = lock.readLock();
        try {
            readLock.lock();
            if (flag1.get()) {
                // doing something for key 1
                key1 = getFromFile();
                flag1.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }

    public String getKey2() {
        Lock readLock = lock.readLock();
        try {
            readLock.lock();
            if (flag2.get()) {
                // doing something for key 1
                key2 = getFromFile();
                flag2.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }
}
</code>```

Body:
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

Body:
An update on the below ReadWriteLock sample, we have to acquire locks before starting the read/write operations. As I don't have permission to edit the sample, posting a new answer.

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test {

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        Lock writeLock = lock.writeLock();
        try {
            writeLock.lock();
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            writeLock.unlock();
        }
    }

    public String getKey1() {
        Lock readLock = lock.readLock();
        try {
            readLock.lock();
            if (flag1.get()) {
                // doing something for key 1
                key1 = getFromFile();
                flag1.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }

    public String getKey2() {
        Lock readLock = lock.readLock();
        try {
            readLock.lock();
            if (flag2.get()) {
                // doing something for key 1
                key2 = getFromFile();
                flag2.set(false);
            }
            return key1;
        } finally {
            readLock.unlock();
        }
    }
}


问:
How to use specific version Python in Conda environment
I have Anaconda 3 installed and I also created a new environment with Python 2.7. </p>

<p>How can I now use this Python 2.7? Like how can I use it run/write some code in it? </p>

答:
Once you have created your new environment with conda create, you can switch to it by

unix:

```<code>source activate py27
</code>```

windows:

```<code>activate snowflakes
</code>```

For more information please refer to the documention.

Body:
I have Anaconda 3 installed and I also created a new environment with Python 2.7.

How can I now use this Python 2.7? Like how can I use it run/write some code in it?

Body:
Once you have created your new environment with conda create, you can switch to it by

unix:

source activate py27

windows:

activate snowflakes

For more information please refer to the documention.


问:
Liferay 7 GA3 wizard
When i started liferay 7 GA3 for the first time, the browser on my laptop automatically opened the wizard with user and database configuration. I left the default values (which is hypersoning database) and moved forward to the portal.
I now want to connect my liferay istance to a mysql database. I have changed this line in the portal-setup-wizard.properties:

setup.wizard.enabled from "no" to "yes"

But when i restart liferay the wizard do not show anymore.

Is there any other configuration i have to write in liferay files to make the wizard to show again? Or maybe i have to configure the database manually?

答: In portal-setup-wizard.properties remove the line setup.wizard.enabled=false. The property takes only one value i.e false to tell the setup not to start the basic configuration wizard. The absence of setup.wizard.enabled in  portal-setup-wizard.properties will again trigger the basic configuration wizard.

Title: Liferay 7 GA3 wizard


问:
"Message": "Authorization has been denied for this request." OWIN middleware
I added Token based authentication to my OWIN middleware and can generate the token. But while using, the token for an API call with Authorize attribute I always get "Authorization has been denied for this request." It works fine though without Authorize attribute. Here is my startup.cs and controller method. Any thoughts , what is wrong?

startup.cs

```<code>    public void Configuration(IAppBuilder app)
            {
                var issuer = ConfigurationManager.AppSettings["issuer"];
                var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    Provider = new SimpleAuthProvider(),
                    AccessTokenFormat = new JwtFormat(issuer)
                });
                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { "*" },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
                container = BuildDI();
                var config = new HttpConfiguration();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                app.UseCors(CorsOptions.AllowAll);
                app.UseSerilogRequestContext("RequestId");
                app.UseAutofacMiddleware(container);
                app.UseAutofacWebApi(config);
                app.UseWebApi(config);
                RegisterShutdownCallback(app, container);
            }

 public class SimpleAuthProvider: OAuthAuthorizationServerProvider
        {
            public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                if (context.UserName != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Rejected();
                    return Task.FromResult<object>(null);
                }

                var ticket = new AuthenticationTicket(SetClaimsIdentity(context), new AuthenticationProperties());
                context.Validated(ticket);

                return Task.FromResult<object>(null);
            }

            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                return identity;
            }
        }
</code>```

API Controller Method:

```<code> [HttpGet]
        [Route("sampleroute")]
        [Authorize]
        public async Task<HttpResponseMessage> GetSamples(string search)
        {
            try
            {

                HttpResponseMessage response;
                using (HttpClient client = new HttpClient(Common.CreateHttpClientHandler()))
                {
                     response = await client.GetAsync("test url");
                }
                var result = response.Content.ReadAsStringAsync().Result;
                Samples[] sampleArray = JsonConvert.DeserializeObject<Samples[]>(result);
                var filteredSamples = sampleArray .ToList().Where(y => y.NY_SampleName.ToUpper().Contains(search.ToUpper())).Select(n=>n);
                log.Information("<==========Ended==========>");
                return  Request.CreateResponse(HttpStatusCode.OK,filteredSamples);

            }
            catch (Exception ex)
            {
                log.Error($"Error occured while pulling the Samples:  {ex.ToString()}");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }
</code>```

答:
From what I understood, you need to add the header: Authorization: Bearer "token".
If you have not modified the default implementation of the authorization request the steps are these:

Register user at the endpoint:

```<code>/api/Account/Register
</code>```

Post to /token the following items:

grant_type: password

username: "the username you registered"

password: "the password you registered for the user"

You will receive a token in the Response

Copy that token and create a Request to the method you secured with the [Authorize] filter of type:

```<code> Authorization: Bearer "the_token_you_copied_earlier"
</code>```

Needless to say, it could be pretty easy for you if you used Postman or Fiddler to make and receive Requests because it shows you how everything works.

Body:
I added Token based authentication to my OWIN middleware and can generate the token. But while using, the token for an API call with Authorize attribute I always get "Authorization has been denied for this request." It works fine though without Authorize attribute. Here is my startup.cs and controller method. Any thoughts , what is wrong?

startup.cs

    public void Configuration(IAppBuilder app)
            {
                var issuer = ConfigurationManager.AppSettings["issuer"];
                var secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["secret"]);
                app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AllowInsecureHttp = true,
                    TokenEndpointPath = new PathString("/token"),
                    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                    Provider = new SimpleAuthProvider(),
                    AccessTokenFormat = new JwtFormat(issuer)
                });
                app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { "*" },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });
                container = BuildDI();
                var config = new HttpConfiguration();
                config.Formatters.XmlFormatter.UseXmlSerializer = true;
                config.MapHttpAttributeRoutes();
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));
                config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
                app.UseCors(CorsOptions.AllowAll);
                app.UseSerilogRequestContext("RequestId");
                app.UseAutofacMiddleware(container);
                app.UseAutofacWebApi(config);
                app.UseWebApi(config);
                RegisterShutdownCallback(app, container);
            }

 public class SimpleAuthProvider: OAuthAuthorizationServerProvider
        {
            public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {

                if (context.UserName != context.Password)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect");
                    context.Rejected();
                    return Task.FromResult<object>(null);
                }

                var ticket = new AuthenticationTicket(SetClaimsIdentity(context), new AuthenticationProperties());
                context.Validated(ticket);

                return Task.FromResult<object>(null);
            }

            public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
            {
                context.Validated();
                return Task.FromResult<object>(null);
            }

            private static ClaimsIdentity SetClaimsIdentity(OAuthGrantResourceOwnerCredentialsContext context)
            {
                var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ExternalBearer);
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                return identity;
            }
        }

API Controller Method:

 [HttpGet]
        [Route("sampleroute")]
        [Authorize]
        public async Task<HttpResponseMessage> GetSamples(string search)
        {
            try
            {

                HttpResponseMessage response;
                using (HttpClient client = new HttpClient(Common.CreateHttpClientHandler()))
                {
                     response = await client.GetAsync("test url");
                }
                var result = response.Content.ReadAsStringAsync().Result;
                Samples[] sampleArray = JsonConvert.DeserializeObject<Samples[]>(result);
                var filteredSamples = sampleArray .ToList().Where(y => y.NY_SampleName.ToUpper().Contains(search.ToUpper())).Select(n=>n);
                log.Information("<==========Ended==========>");
                return  Request.CreateResponse(HttpStatusCode.OK,filteredSamples);

            }
            catch (Exception ex)
            {
                log.Error($"Error occured while pulling the Samples:  {ex.ToString()}");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.ToString());
            }
        }

Body:
From what I understood, you need to add the header: Authorization: Bearer "token".
If you have not modified the default implementation of the authorization request the steps are these:

Register user at the endpoint:

/api/Account/Register

Post to /token the following items:

grant_type: password

username: "the username you registered"

password: "the password you registered for the user"

You will receive a token in the Response

Copy that token and create a Request to the method you secured with the [Authorize] filter of type:

 Authorization: Bearer "the_token_you_copied_earlier"

Needless to say, it could be pretty easy for you if you used Postman or Fiddler to make and receive Requests because it shows you how everything works.


问:
Can a MVC 5 project change browser level zoom?
I have a MVC 5 app, and I need to have a default zoom out. I don't want to use JavaScript or CSS.

Does such a way exist to change zoom level across all browsers?

答:
```<code>  <html>
        <body>
            <div id="sampleDiv" style="width: 100px; background-color: Gray;">
                Zoom Me
            </div>
            <button onclick="sampleDiv.style.zoom='300%'">Zoom 300%</button>
            <button onclick="sampleDiv.style.zoom='200%'">Zoom 200%</button>
            <button onclick="sampleDiv.style.zoom='100%'">Zoom 100%</button>
        </body>
    </html>
</code>```


问:
Program in C crashes after the 2nd input is requested
I am new to the C language and I know there are a few Q&A out there about program crashes, but I think in this case my one is a bit specific and would prefer to make the question. I am attempting a Poker game and after running the program it crashes after I enter the "Y" or "N" command. I would appreciate any insights on how to solve this. Here's the code:</p>

```<code>#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE 1

void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand(int cardRank[], int cardSuit[], int finalRank[],
                  int finalSuit[], int ranksinHand[],
                  int suitsinHand[]);
int analyzeHand(int ranksinHand[], int suitsinHand[]);

main(void) {
    int bet;
    int bank = 100;
    int i;
    int cardRank[5];
    int cardSuit[5];

    int finalRank[5];
    int finalSuit[5];
    int ranksinHand[13];
    int suitsinHand[4];
    int winnings;
    time_t t;
    char suit, rank, stillPlay;

    //print greeting
    printGreeting();

    // plays a new hand of draw poker

    do {
        bet = getBet();
        srand(time(&t));
        getFirstHand(cardRank, cardSuit);
        printf("Your five cards: \n");

        for (i=0; i<5; i++) {
            suit = getSuit(cardSuit[i]);
            rank = getRank(cardRank[i]);
            printf("Card #%d: %c%c\n", i+1, rank, suit);
        }

        for (i=0; i<4; i++) {
            suitsinHand[i] = 0;
        }

        for (i=0; i<13; i++) {
            ranksinHand[i] = 0;
        }

        getFinalHand(cardRank, cardSuit, finalRank, finalSuit,
                     ranksinHand, suitsinHand);

        printf("Your final five cards: \n");
        for (i = 0; i < 5; i++) {
            suit = getSuit(finalSuit[i]);
            rank = getRank(finalRank[i]);
            printf("Card #%d: %c%c\n", i+1, rank, suit);
        }

        winnings = analyzeHand(ranksinHand, suitsinHand);
        printf("You won %d!\n", bet*winnings);
        bank = bank - bet + (bet*winnings);
        printf("\nYour bank is now %d.\n", bank);
        printf("\nDo you want to play again? ");
        scanf(" %c", &stillPlay);
    } while (toupper(stillPlay) == 'Y');

    return 0;
}

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

// Print a quick greeting as well as tell the users the value
// of different winning hands

void printGreeting() {

    printf("Here are the rules: \n");
    printf("You start with 100 credits, and you make a bet from ");
    printf("1 to 5 credits. \n");
    printf("You are dealt 5 cards, and then you choose which ");
    printf("cards to keep ");
    printf("or discard.\n");
    printf("You want to make the best possible hand. \n");
    printf("\nHere is the table for winnings (assuming a ");
    printf("bet of 1 credit):");
    printf("\nPair\t\t\t\t1 credit");
    printf("\nTwo Pairs\t\t\t2 credits");
    printf("\nThree Pairs\t\t\t3 credits");
    printf("\nStraight\t\t\t4 credits");
    printf("\nFlush\t\t\t\t5 credits");
    printf("\nFull House\t\t\t8 credits");
    printf("\nFour of a Kind\t\t\t10 credits");
    printf("\nStraight Flush\t\t\t20 credits");
    printf("\n\nHave Fun!!\n\n");
}

// Function to deal the first five cards

void getFirstHand(int cardRank[], int cardSuit[]) {
    int i, j;
    int cardDup;

    for (i=0; i < 5; i++) {
        cardDup = 0;
        do {
            cardRank[i] = (rand() %13);
            cardSuit[i] = (rand() %4);

            for (j=0; j < i; j++) {
                if ((cardRank[i] == cardRank[j]) &&
                    (cardSuit[i] == cardSuit[j])) {
                    cardDup = 1;
                }
            }
        } while (cardDup == 1);
    }
}

// Function that changes the Suit integer value to a character
// representing the suit

char getSuit(int suit) {
    switch (suit) {
    case 0:
        return('c');
    case 1:
        return('d');
    case 2:
        return('h');
    case 3:
        return('s');
    }
}

// Function that changes the rank integer value to a character
// representing the rank

char getRank(int rank) {
    switch (rank) {
    case 0:
        return('A');
    case 1:
        return('2');
    case 2:
        return('3');
    case 3:
        return('4');
    case 4:
        return('5');
    case 5:
        return('6');
    case 6:
        return('7');
    case 7:
        return('8');
    case 8:
        return('9');
    case 9:
        return('T');
    case 10:
        return('J');
    case 11:
        return('Q');
    case 12:
        return('K');
    }
}

// Function to get the user's bet, between 1 and 5

int getBet() {
    int bet;

    do {
        printf("How much do you want to bet? (Enter a number ");
        printf("1 to 5, or 0 to quit the game):");
        scanf(" %d", &bet);

        if (bet >= 1 && bet <= 5) {
            return(bet);
        } else if (bet == 0) {
            exit(1);
        } else {
            printf("\n\nPlease enter a bet from 1-5 or ");
            printf("0 to quit the game. \n");
        }
    } while ((bet < 0) || (bet > 5));
}

// Last function reviews the final hand and determines the value of
// the hand

int analyzeHand(int ranksinHand[], int suitsinHand[]) {
    int num_consec = 0;
    int i, rank, suit;
    int straight = FALSE;
    int flush = FALSE;
    int four = FALSE;
    int three = FALSE;
    int pairs = FALSE;

    for (suit = 0; suit < 4; suit ++)
        if (suitsinHand[suit] == 5)
            flush = TRUE;
    rank = 0;
    while (ranksinHand[rank] == 0)
        rank++;
    for (; rank < 13 && ranksinHand[rank]; rank++)
        num_consec++;
    if (num_consec == 5) {
        straight = TRUE;
    }
    for (rank = 0; rank < 13; rank++) {
        if (ranksinHand[rank] == 4)
            four = TRUE;
        if (ranksinHand[rank] == 3)
            three = TRUE;
        if (ranksinHand[rank] == 2)
            pairs++;
    }

    if (straight && flush) {
        printf("Straight Flush\n\n");
        return(20);
    } else if (four) {
        printf("Four of a Kind\n\n");
        return(10);
    } else if (three && pairs == 1) {
        printf("Full House\n\n");
        return(8);
    } else if (flush) {
        printf("Flush\n\n");
        return(5);
    } else if (straight) {
        printf("Straight\n\n");
        return(4);
    } else if (three) {
        printf("Three of a Kind\n\n");
        return(3);
    } else if (pairs == 2) {
        printf("Two Pairs\n\n");
        return(2);
    } else if (pairs == 1) {
        printf("Pair\n\n");
        return(1);
    } else {
        printf("High Card\n\n");
        return(0);
    }
}

void getFinalHand(int cardRank[], int cardSuit[], int finalRank[],
                  int finalSuit[], int ranksinHand[],
                  int suitsinHand[]) {
    int i, j, cardDup;
    char suit, rank, ans;

    for(i=0; i < 5; i++) {
        suit = getSuit(cardSuit[i]);
        rank = getRank(cardRank[i]);
        printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
        printf("\nPlease answer (Y/N): ");
        scanf(" %c", ans);
        if (toupper(ans) == 'Y') {
            finalRank[i] = cardRank[i];
            finalSuit[i] = cardSuit[i];
            ranksinHand[finalRank[i]]++;
            suitsinHand[finalSuit[i]]++;
            continue;
        } else if (toupper(ans) == 'N') {
            cardDup = 0;
            do {
                cardDup = 0;
                finalRank[i] = (rand() % 13);
                finalSuit[i] = (rand() % 4);

                for (j=0; j < 5; j++) {
                    if ((finalRank[i] == finalRank[j]) &&
                        (finalSuit[i] == finalSuit[j])) {
                        cardDup = 1;
                    }
                }
            } while (cardDup == 1);
            ranksinHand[finalRank[i]]++;
            suitsinHand[finalSuit[i]]++;
        }
    }
}
</code>```

答:
You have forgot & inside scanf in line number 276, So use this:

```<code>scanf(" %c", &ans);
</code>```

instead of

```<code>scanf(" %c", ans);
</code>```

Body:
I am new to the C language and I know there are a few Q&A out there about program crashes, but I think in this case my one is a bit specific and would prefer to make the question. I am attempting a Poker game and after running the program it crashes after I enter the "Y" or "N" command. I would appreciate any insights on how to solve this. Here's the code:

#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE 1

void printGreeting();
int getBet();
char getSuit(int suit);
char getRank(int rank);
void getFirstHand(int cardRank[], int cardSuit[]);
void getFinalHand(int cardRank[], int cardSuit[], int finalRank[],
                  int finalSuit[], int ranksinHand[],
                  int suitsinHand[]);
int analyzeHand(int ranksinHand[], int suitsinHand[]);

main(void) {
    int bet;
    int bank = 100;
    int i;
    int cardRank[5];
    int cardSuit[5];

    int finalRank[5];
    int finalSuit[5];
    int ranksinHand[13];
    int suitsinHand[4];
    int winnings;
    time_t t;
    char suit, rank, stillPlay;

    //print greeting
    printGreeting();

    // plays a new hand of draw poker

    do {
        bet = getBet();
        srand(time(&t));
        getFirstHand(cardRank, cardSuit);
        printf("Your five cards: \n");

        for (i=0; i<5; i++) {
            suit = getSuit(cardSuit[i]);
            rank = getRank(cardRank[i]);
            printf("Card #%d: %c%c\n", i+1, rank, suit);
        }

        for (i=0; i<4; i++) {
            suitsinHand[i] = 0;
        }

        for (i=0; i<13; i++) {
            ranksinHand[i] = 0;
        }

        getFinalHand(cardRank, cardSuit, finalRank, finalSuit,
                     ranksinHand, suitsinHand);

        printf("Your final five cards: \n");
        for (i = 0; i < 5; i++) {
            suit = getSuit(finalSuit[i]);
            rank = getRank(finalRank[i]);
            printf("Card #%d: %c%c\n", i+1, rank, suit);
        }

        winnings = analyzeHand(ranksinHand, suitsinHand);
        printf("You won %d!\n", bet*winnings);
        bank = bank - bet + (bet*winnings);
        printf("\nYour bank is now %d.\n", bank);
        printf("\nDo you want to play again? ");
        scanf(" %c", &stillPlay);
    } while (toupper(stillPlay) == 'Y');

    return 0;
}

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

// Print a quick greeting as well as tell the users the value
// of different winning hands

void printGreeting() {

    printf("Here are the rules: \n");
    printf("You start with 100 credits, and you make a bet from ");
    printf("1 to 5 credits. \n");
    printf("You are dealt 5 cards, and then you choose which ");
    printf("cards to keep ");
    printf("or discard.\n");
    printf("You want to make the best possible hand. \n");
    printf("\nHere is the table for winnings (assuming a ");
    printf("bet of 1 credit):");
    printf("\nPair\t\t\t\t1 credit");
    printf("\nTwo Pairs\t\t\t2 credits");
    printf("\nThree Pairs\t\t\t3 credits");
    printf("\nStraight\t\t\t4 credits");
    printf("\nFlush\t\t\t\t5 credits");
    printf("\nFull House\t\t\t8 credits");
    printf("\nFour of a Kind\t\t\t10 credits");
    printf("\nStraight Flush\t\t\t20 credits");
    printf("\n\nHave Fun!!\n\n");
}

// Function to deal the first five cards

void getFirstHand(int cardRank[], int cardSuit[]) {
    int i, j;
    int cardDup;

    for (i=0; i < 5; i++) {
        cardDup = 0;
        do {
            cardRank[i] = (rand() %13);
            cardSuit[i] = (rand() %4);

            for (j=0; j < i; j++) {
                if ((cardRank[i] == cardRank[j]) &&
                    (cardSuit[i] == cardSuit[j])) {
                    cardDup = 1;
                }
            }
        } while (cardDup == 1);
    }
}

// Function that changes the Suit integer value to a character
// representing the suit

char getSuit(int suit) {
    switch (suit) {
    case 0:
        return('c');
    case 1:
        return('d');
    case 2:
        return('h');
    case 3:
        return('s');
    }
}

// Function that changes the rank integer value to a character
// representing the rank

char getRank(int rank) {
    switch (rank) {
    case 0:
        return('A');
    case 1:
        return('2');
    case 2:
        return('3');
    case 3:
        return('4');
    case 4:
        return('5');
    case 5:
        return('6');
    case 6:
        return('7');
    case 7:
        return('8');
    case 8:
        return('9');
    case 9:
        return('T');
    case 10:
        return('J');
    case 11:
        return('Q');
    case 12:
        return('K');
    }
}

// Function to get the user's bet, between 1 and 5

int getBet() {
    int bet;

    do {
        printf("How much do you want to bet? (Enter a number ");
        printf("1 to 5, or 0 to quit the game):");
        scanf(" %d", &bet);

        if (bet >= 1 && bet <= 5) {
            return(bet);
        } else if (bet == 0) {
            exit(1);
        } else {
            printf("\n\nPlease enter a bet from 1-5 or ");
            printf("0 to quit the game. \n");
        }
    } while ((bet < 0) || (bet > 5));
}

// Last function reviews the final hand and determines the value of
// the hand

int analyzeHand(int ranksinHand[], int suitsinHand[]) {
    int num_consec = 0;
    int i, rank, suit;
    int straight = FALSE;
    int flush = FALSE;
    int four = FALSE;
    int three = FALSE;
    int pairs = FALSE;

    for (suit = 0; suit < 4; suit ++)
        if (suitsinHand[suit] == 5)
            flush = TRUE;
    rank = 0;
    while (ranksinHand[rank] == 0)
        rank++;
    for (; rank < 13 && ranksinHand[rank]; rank++)
        num_consec++;
    if (num_consec == 5) {
        straight = TRUE;
    }
    for (rank = 0; rank < 13; rank++) {
        if (ranksinHand[rank] == 4)
            four = TRUE;
        if (ranksinHand[rank] == 3)
            three = TRUE;
        if (ranksinHand[rank] == 2)
            pairs++;
    }

    if (straight && flush) {
        printf("Straight Flush\n\n");
        return(20);
    } else if (four) {
        printf("Four of a Kind\n\n");
        return(10);
    } else if (three && pairs == 1) {
        printf("Full House\n\n");
        return(8);
    } else if (flush) {
        printf("Flush\n\n");
        return(5);
    } else if (straight) {
        printf("Straight\n\n");
        return(4);
    } else if (three) {
        printf("Three of a Kind\n\n");
        return(3);
    } else if (pairs == 2) {
        printf("Two Pairs\n\n");
        return(2);
    } else if (pairs == 1) {
        printf("Pair\n\n");
        return(1);
    } else {
        printf("High Card\n\n");
        return(0);
    }
}

void getFinalHand(int cardRank[], int cardSuit[], int finalRank[],
                  int finalSuit[], int ranksinHand[],
                  int suitsinHand[]) {
    int i, j, cardDup;
    char suit, rank, ans;

    for(i=0; i < 5; i++) {
        suit = getSuit(cardSuit[i]);
        rank = getRank(cardRank[i]);
        printf("Do you want to keep card #%d: %c%c", i+1, rank, suit);
        printf("\nPlease answer (Y/N): ");
        scanf(" %c", ans);
        if (toupper(ans) == 'Y') {
            finalRank[i] = cardRank[i];
            finalSuit[i] = cardSuit[i];
            ranksinHand[finalRank[i]]++;
            suitsinHand[finalSuit[i]]++;
            continue;
        } else if (toupper(ans) == 'N') {
            cardDup = 0;
            do {
                cardDup = 0;
                finalRank[i] = (rand() % 13);
                finalSuit[i] = (rand() % 4);

                for (j=0; j < 5; j++) {
                    if ((finalRank[i] == finalRank[j]) &&
                        (finalSuit[i] == finalSuit[j])) {
                        cardDup = 1;
                    }
                }
            } while (cardDup == 1);
            ranksinHand[finalRank[i]]++;
            suitsinHand[finalSuit[i]]++;
        }
    }
}

Body:
You have forgot & inside scanf in line number 276, So use this:

scanf(" %c", &ans);

instead of

scanf(" %c", ans);


问:
What case is better?
I have a list of MyClass:

```<code>struct MyClass {
     bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else
</code>```

What case of removing is better (c++ design and perfomance):

```<code>results.remove_if(
    std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));
</code>```

or

```<code>results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));
</code>```

or

```<code>struct RemoveFunctor {
   RemoveFunctor (int lifetime) : lifetime(lifetime) {}
   bool operator()(const MyClass & m) { return m.is_old_result(lifetime); }
private:
   int lifetime;
};
results.remove_if(RemoveFunctor(lifetime));
</code>```

and why?

P.S. Please, no lambda-function and no C++0x.

答:
With more suitable naming, such as "IsOldResult" or "ResultOlderThan", I would say that the final solution would be the most readable, as it is the one that most passes for prose:

```<code>results.remove_if(ResultOlderThan(lifetime));
</code>```

However, I would probably only go and write the functor if the algorithm it represented turned up in multiple contexts.  Writing a 5-line class that is physically removed from its single one-liner call site seems overly wasteful, to me.

Otherwise, the boost::bind option has my vote since it has the least additional fluff between it and std::bind2nd (_1 and std::mem_fun_ref, respectively).  In addition, boost::bind works for more cases in general, such as a case where you are not binding only one variable of a function that has only two parameters.

Title: What case is better?

Body:
I have a list of MyClass:

struct MyClass {
     bool is_old_result(int lifetime);
};
std::list<MyClass> results;
int lifetime = 50; // or something else

What case of removing is better (c++ design and perfomance):

results.remove_if(
    std::bind2nd(std::mem_fun_ref(&MyClass::is_old_result), lifetime));

or

results.remove_if(boost::bind(&MyClass::is_old_result, _1, lifetime));

or

struct RemoveFunctor {
   RemoveFunctor (int lifetime) : lifetime(lifetime) {}
   bool operator()(const MyClass & m) { return m.is_old_result(lifetime); }
private:
   int lifetime;
};
results.remove_if(RemoveFunctor(lifetime));

and why?

P.S. Please, no lambda-function and no C++0x.

Body:
With more suitable naming, such as "IsOldResult" or "ResultOlderThan", I would say that the final solution would be the most readable, as it is the one that most passes for prose:

results.remove_if(ResultOlderThan(lifetime));

However, I would probably only go and write the functor if the algorithm it represented turned up in multiple contexts.  Writing a 5-line class that is physically removed from its single one-liner call site seems overly wasteful, to me.

Otherwise, the boost::bind option has my vote since it has the least additional fluff between it and std::bind2nd (_1 and std::mem_fun_ref, respectively).  In addition, boost::bind works for more cases in general, such as a case where you are not binding only one variable of a function that has only two parameters.


问:
Angular router links not working in Html content
My app do have some content contributed by user from a richtext editor (froala), and the content might contain some internal reference to another page. I like to make those routerlink like switching page instead of opening another. However, it is not working neither as innerHtml nor froalaView directive.</p>

答:
I finally resolved it my own with reference to others, wannaa share for those who have the same question</p>

```<code>@ViewChild('articleContent', {read: ViewContainerRef})
articleContentRef: ViewContainerRef;
private injector: Injector;

constructor(
injector: Injector,
private compiler: Compiler,
) {
this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);
this.compiler = this.injector.get(Compiler);
this.init();
}

init() {
const compMetadata = new Component({
    selector: 'article-content',
    template: this.article.content,
});
const cmpClass = class DynamicComponent { };
const decoratedCmp = Component(compMetadata)(cmpClass);

const moduleMetaData = new NgModule({
    imports: [CommonModule, RouterModule], declarations: [decoratedCmp], entryComponents: [decoratedCmp]
});
const cmpModule = class DynamicHtmlModule { };
const decoratedModule = NgModule(moduleMetaData)(cmpModule);

const moduleFactory: NgModuleFactory<any> = this.compiler.compileModuleSync(decoratedModule);
const moduleRef: NgModuleRef<any> = moduleFactory.create(this.injector);

const injector = moduleRef.injector;

this.componentRef = this.articleContentRef.createComponent<any>(
  injector.get(ComponentFactoryResolver).resolveComponentFactory(decoratedCmp),
  0,
  injector);
}
</code>```

Body:
I finally resolved it my own with reference to others, wannaa share for those who have the same question

@ViewChild('articleContent', {read: ViewContainerRef})
articleContentRef: ViewContainerRef;
private injector: Injector;

constructor(
injector: Injector,
private compiler: Compiler,
) {
this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);
this.compiler = this.injector.get(Compiler);
this.init();
}

init() {
const compMetadata = new Component({
    selector: 'article-content',
    template: this.article.content,
});
const cmpClass = class DynamicComponent { };
const decoratedCmp = Component(compMetadata)(cmpClass);

const moduleMetaData = new NgModule({
    imports: [CommonModule, RouterModule], declarations: [decoratedCmp], entryComponents: [decoratedCmp]
});
const cmpModule = class DynamicHtmlModule { };
const decoratedModule = NgModule(moduleMetaData)(cmpModule);

const moduleFactory: NgModuleFactory<any> = this.compiler.compileModuleSync(decoratedModule);
const moduleRef: NgModuleRef<any> = moduleFactory.create(this.injector);

const injector = moduleRef.injector;

this.componentRef = this.articleContentRef.createComponent<any>(
  injector.get(ComponentFactoryResolver).resolveComponentFactory(decoratedCmp),
  0,
  injector);
}


问:
get nlargest values from multi index data frame
I have a data frame that looks like following image:

Here uid and id are indexes. This data frame was converted from a single index dataframe, so there are duplicate values for some columns. For each uid, all values for avg_diff are same, but different uid will have different values for this field. I want to get the largest 10 avg_diff values, with different uids.

Note: This is a huge data frame, so I am looking for the most optimized way.

答:
I think you can first remove duplicates by get_level_values and duplicated with boolean indexing, ~ is for invert boolean mask.

Then use DataFrame.nlargest or sort_values + head:

```<code>df = pd.DataFrame({'uid':[1,1,1,2,2,3,3], 'id':[2,3,4,5,6,1,3],
                   'avg_diff':[0.1,0.1,0.1,0.2,0.2,0.3,0.3]})
df = df.set_index('uid').set_index('id', drop=False, append=True)
print (df)
        avg_diff  id
uid id
1   2        0.1   2
    3        0.1   3
    4        0.1   4
2   5        0.2   5
    6        0.2   6
3   1        0.3   1
    3        0.3   3
</code>```

```<code>mask = df.index.get_level_values('uid').duplicated()
print (~mask)
[ True False False  True False  True False]

df = df[~mask].nlargest(2, 'avg_diff')
print (df)
        avg_diff  id
uid id
3   1        0.3   1
2   5        0.2   5
</code>```

Another solution:

```<code>mask = df.index.get_level_values('uid').duplicated()
print (~mask)
[ True False False  True False  True False]

df = df[~mask].sort_values('avg_diff', ascending=False).head(2)
print (df)

        avg_diff  id
uid id
3   1        0.3   1
2   5        0.2   5
</code>```

Body:
I think you can first remove duplicates by get_level_values and duplicated with boolean indexing, ~ is for invert boolean mask.

Then use DataFrame.nlargest or sort_values + head:

df = pd.DataFrame({'uid':[1,1,1,2,2,3,3], 'id':[2,3,4,5,6,1,3],
                   'avg_diff':[0.1,0.1,0.1,0.2,0.2,0.3,0.3]})
df = df.set_index('uid').set_index('id', drop=False, append=True)
print (df)
        avg_diff  id
uid id
1   2        0.1   2
    3        0.1   3
    4        0.1   4
2   5        0.2   5
    6        0.2   6
3   1        0.3   1
    3        0.3   3

mask = df.index.get_level_values('uid').duplicated()
print (~mask)
[ True False False  True False  True False]

df = df[~mask].nlargest(2, 'avg_diff')
print (df)
        avg_diff  id
uid id
3   1        0.3   1
2   5        0.2   5

Another solution:

mask = df.index.get_level_values('uid').duplicated()
print (~mask)
[ True False False  True False  True False]

df = df[~mask].sort_values('avg_diff', ascending=False).head(2)
print (df)

        avg_diff  id
uid id
3   1        0.3   1
2   5        0.2   5


问:
MongoDB search by nested dynamic sub field
Trying to find a way to reach to sub sub field which dynamic sub field in between. Not sure how to reach there. Looking for something like $ used for arrays.

My data structure looks like

```<code>  {
    _id: ObjectId("59355deee13f1a1260f17421"),
    product: {
      shirt: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17422"),
    product: {
      top: {
        color: "red"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17423"),
    product: {
      shoes: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17424"),
    product: {
      belt: {
        color: "brown7"
      }
    }
  },
</code>```

Looking for equivalent of

```<code>db.things.find({product.$.color: "black"})
</code>```

答:
Above mentioned document can be represented as an embedded document since all data belongs to common entity and facilitates conveniency in querying data from an embedded document using $elemMatch operator.Its representation should be as follows.

```<code>{
    "_id": ObjectId("59355deee13f1a1260f17421"),
    "product": [{
            "name": "shirt",
            "color": "black"
        },
        {
            "name": "top",
            "color": "red"
        },
        {
            "name": "shoes",
            "color": "black"
        },
        {
            "name": "belt",
            "color": "brown7"
        }
    ]
}
</code>```

According to description as mentioned in above question to fetch documents in which value of color field is black please try executing following query in MongoDB shell.

```<code>db.things.find({product:{$elemMatch:{color:'black'}}})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Trying to find a way to reach to sub sub field which dynamic sub field in between. Not sure how to reach there. Looking for something like $ used for arrays.

My data structure looks like

  {
    _id: ObjectId("59355deee13f1a1260f17421"),
    product: {
      shirt: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17422"),
    product: {
      top: {
        color: "red"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17423"),
    product: {
      shoes: {
        color: "black"
      }
    }
  },
  {
    _id: ObjectId("59355deee13f1a1260f17424"),
    product: {
      belt: {
        color: "brown7"
      }
    }
  },

Looking for equivalent of

db.things.find({product.$.color: "black"})

Body:
Above mentioned document can be represented as an embedded document since all data belongs to common entity and facilitates conveniency in querying data from an embedded document using $elemMatch operator.Its representation should be as follows.

{
    "_id": ObjectId("59355deee13f1a1260f17421"),
    "product": [{
            "name": "shirt",
            "color": "black"
        },
        {
            "name": "top",
            "color": "red"
        },
        {
            "name": "shoes",
            "color": "black"
        },
        {
            "name": "belt",
            "color": "brown7"
        }
    ]
}

According to description as mentioned in above question to fetch documents in which value of color field is black please try executing following query in MongoDB shell.

db.things.find({product:{$elemMatch:{color:'black'}}})


问:
Sitecore pages to plain htmls
We are planning to move websites hosted on Sitecore as plain htmls. I have tried all possible ways to convert them.

Is it possible to convert the Sitecore site in to HTMLs.

答: Depends on the websites, You lose a lot, personalisation, multivar testing, experience editor, content editor, analytics. And all build serverside logic, search, forms, tools. If there is only content in the website you can try a webscraper. Try http://www.httrack.com/ or https://websitedownloader.io/ or a simulair tool.</p>

Title: Sitecore pages to plain htmls


答:
According to your situation, the elegant solution is to define two cells with different layout in TableView in a Storyboard, or in two Xib files. And then, binding them to the same class.

The separated cell defined in Storyboard or Xib means the same thing in Android: separated layout XML files, which you want to access its sub view by getViewById.

Title: How to achieve Android's getViewById in iOS?

Body:
IOS's IBOutlet is fine in most scenarios. But consider this:

I have a UITableview which contains 2 types of custom cells, both cells have the same subviews (1 image view and 2 labels), only the 2 types layout differently. Now how do I reference these subviews in my code?

I could, of course, define 2 subclasses of UITableViewCell, and use IBOutlet to reference them. But that sounds not very elegant, as behavior-wise, they are exactly the same.

Android has a getViewById function. In iOS, can I get a subview from a view with some identifier?


问:
GROUP BY & ORDER BY - Ordering by a specific field
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

```<code>SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

```<code>SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

答: my guess is you should order the MAX(popularity) in descending order, try adding DESC at the end of the query.</p>

Body:
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!