问:
exclude html attributes in str_replace
so i'm trying to do the usual replacing each instance of a company name in wordpress, and i've run into an issue where on occasion (usually in the href of links) it's breaking links.

code i'm using (includes a filter for ACF custom fields)

```<code>    //Replace the word lunch with a span
function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'lunch!' => '<span class="lunch">lunch!</span>',
        'Lunch!' => '<span class="lunch">lunch!</span>',
        'LUNCH!' => '<span class="lunch">lunch!</span>'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');
</code>```

Is there a way to only replace it outside of stuff like href tags? i've looked into stuff like DOM parses but i'm not sure if there's a simpler method- it doesn't seem to cause grief in any other instances so i'm not sure that pre=processing the entire HMTL and looking for the word is appropriate. I did wonder about searching for the string including a space before and after it, but i wasn't sure how to include leading / trailing spaces, and it felt a bit bodge-y?
Thanks in advance!
Pete

答:
ok, so in this instance, which is quite specific, i've found the following code works well enough. added trailing / leading spaces in the initial matching parameters, and also variants to find it directly after html tags including with a space.
less elegant, but sufficient for the purpose here. </p>

```<code>function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' Lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' LUNCH! ' => ' <span class="lunch">lunch!</span> ',
        // used at end of lines
        ' lunch!' => ' <span class="lunch">lunch!</span>',
        ' Lunch!' => ' <span class="lunch">lunch!</span>',
        ' LUNCH!' => ' <span class="lunch">lunch!</span>',
        // used inside html tags like headers
        '>lunch!' => '><span class="lunch">lunch!</span>',
        '>Lunch!' => '><span class="lunch">lunch!</span>',
        '>LUNCH!' => '><span class="lunch">lunch!</span>',
        //used directly after html tags
        '> lunch!' => '> <span class="lunch">lunch!</span>',
        '> Lunch!' => '> <span class="lunch">lunch!</span>',
        '> LUNCH!' => '> <span class="lunch">lunch!</span>',
        //exclude alt tags on images, title attributes etc
        '"lunch!' => '"lunch!',
        'lunch!"' => 'lunch!"',
        '"Lunch!' => '"lunch!',
        'Lunch!"' => 'lunch!"'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');
</code>```

Title: exclude html attributes in str_replace

Body:
so i'm trying to do the usual replacing each instance of a company name in wordpress, and i've run into an issue where on occasion (usually in the href of links) it's breaking links.

code i'm using (includes a filter for ACF custom fields)

    //Replace the word lunch with a span
function replace_text_wps($text){
    $replace = array(
        // 'WORD TO REPLACE' => 'REPLACE WORD WITH THIS'
        'lunch!' => 'lunch!',
        'Lunch!' => 'lunch!',
        'LUNCH!' => 'lunch!'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}

add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');

Is there a way to only replace it outside of stuff like href tags? i've looked into stuff like DOM parses but i'm not sure if there's a simpler method- it doesn't seem to cause grief in any other instances so i'm not sure that pre=processing the entire HMTL and looking for the word is appropriate. I did wonder about searching for the string including a space before and after it, but i wasn't sure how to include leading / trailing spaces, and it felt a bit bodge-y?
Thanks in advance!
Pete

Body:
ok, so in this instance, which is quite specific, i've found the following code works well enough. added trailing / leading spaces in the initial matching parameters, and also variants to find it directly after html tags including with a space.
less elegant, but sufficient for the purpose here.

function replace_text_wps($text){
    $replace = array(
        // used mid-line
        ' lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' Lunch! ' => ' <span class="lunch">lunch!</span> ',
        ' LUNCH! ' => ' <span class="lunch">lunch!</span> ',
        // used at end of lines
        ' lunch!' => ' <span class="lunch">lunch!</span>',
        ' Lunch!' => ' <span class="lunch">lunch!</span>',
        ' LUNCH!' => ' <span class="lunch">lunch!</span>',
        // used inside html tags like headers
        '>lunch!' => '><span class="lunch">lunch!</span>',
        '>Lunch!' => '><span class="lunch">lunch!</span>',
        '>LUNCH!' => '><span class="lunch">lunch!</span>',
        //used directly after html tags
        '> lunch!' => '> <span class="lunch">lunch!</span>',
        '> Lunch!' => '> <span class="lunch">lunch!</span>',
        '> LUNCH!' => '> <span class="lunch">lunch!</span>',
        //exclude alt tags on images, title attributes etc
        '"lunch!' => '"lunch!',
        'lunch!"' => 'lunch!"',
        '"Lunch!' => '"lunch!',
        'Lunch!"' => 'lunch!"'
    );
    $text = str_replace(array_keys($replace), $replace, $text);
    return $text;
}
add_filter('the_content', 'replace_text_wps');
add_filter('the_excerpt', 'replace_text_wps');
add_filter('the_title', 'replace_text_wps');
add_filter('acf_the_content', 'replace_text_wps');


来源: stackexchange

问:
VBA code that finds first row in column with integers and stores rownum as variable
I know this is really simple but I am new to VBA and I really don't know what I am doing

```<code>Dim StartRow As Range
Dim Sht As Worksheet
Dim TotalRows As Long
Dim StartCell As Integer

Set StartRow = Sht.Range("J7").End(xlDown)  'I just need to create a variable for the first
' row with numerical figures in column J and then use this as a starting point for my
' data in column D as well.
</code>```

In the end I want VBA code that will select two ranges (one in column D and one in J) but where the starting point between the two will be the same, but it will be different across spreadsheets, hence the End(XlDown) function.  The range just needs to select all the data going down until it his the #N A N A signs.

ContentLicense: CC BY-SA 3.0

Body:
I know this is really simple but I am new to VBA and I really don't know what I am doing

Dim StartRow As Range
Dim Sht As Worksheet
Dim TotalRows As Long
Dim StartCell As Integer

Set StartRow = Sht.Range("J7").End(xlDown)  'I just need to create a variable for the first
' row with numerical figures in column J and then use this as a starting point for my
' data in column D as well.

In the end I want VBA code that will select two ranges (one in column D and one in J) but where the starting point between the two will be the same, but it will be different across spreadsheets, hence the End(XlDown) function.  The range just needs to select all the data going down until it his the #N A N A signs.

Body: range("j7:j100").SpecialCells(xlCellTypeConstants,xlnumbers).Cells(1,1).row


问:
Iterate using Object key and findIndex failed
```<code>{
  "June": [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John"
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}
</code>```

I have above object and within it it has array of object, I tried to check within 'June', is there any is_new, but failed?

```<code>const has_any_is_new = Object.keys(arr).map(obj =>
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);
</code>```

答:
You have one map too much. arr[obj] already refers to the "June" array of objects, so obj2 has the .is_new property but no map method. Use

```<code>const obj = { "June": […] };
const news = Object.keys(obj).map(key =>
    [key, obj[key].some(o => o.is_new)]
); // an array of month-boolean-tuples
</code>```

or

```<code>const has_any_is_new = Object.keys(obj).some(key =>
    obj[key].some(o => o.is_new)
); // a boolean whether any month has a new entry
</code>```

Body:
{
  "June": [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John"
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

I have above object and within it it has array of object, I tried to check within 'June', is there any is_new, but failed?

const has_any_is_new = Object.keys(arr).map(obj =>
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);

Body:
You have one map too much. arr[obj] already refers to the "June" array of objects, so obj2 has the .is_new property but no map method. Use

const obj = { "June": […] };
const news = Object.keys(obj).map(key =>
    [key, obj[key].some(o => o.is_new)]
); // an array of month-boolean-tuples

or

const has_any_is_new = Object.keys(obj).some(key =>
    obj[key].some(o => o.is_new)
); // a boolean whether any month has a new entry


问:
PHP build json from a dynamic number of arrays
I have a dynamic number of pages in my web project. It depends on data from the database. I may have 1 page or 10 pages. I put the data selected on each page in session, and finally want to build an array. At the moment I am building JSON from 4 arrays. (In session all the keys are level + int in ascending order. If session x is missing I don't have any data on 6+ levels)

```<code>$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();

if (isset($_SESSION['level1'])) {
    $level1 = $_SESSION['level1'];
}
//the same for 3 more levels in session

$array = array(
    "first"  => ($level1),
    "second" => ($level2),
    "third"  => ($level3),
    "fourth" => ($level4)
);

json_encode($array);
</code>```

Example of output of the json_encode($array):

```<code>{"first":["1","2"],"second":["4","6","8","9"],"third":["13","14","17","18"],"fourth":["33","34","35","36"]}
</code>```

I tried to check how would json_encode work with array_push(), but I get an array of JSON objects instead of a single json object.

```<code>$result = array();
array_push($result, ["key1" => $_SESSION["level1"]]);
array_push($result, ["key2" => $_SESSION["level2"]]);
array_push($result, ["key3" => $_SESSION["level3"]]);

echo json_encode($result);
</code>```

and the output:

```<code>[{"key1":["1","2"]},{"key2":["4","5","6"]},{"key3":["13","14","15"]}]
</code>```

I will make everything iteratively, but I want to know if it is possible to make a single JSON object instead of array of JSONs. Thanks!

答:
You can just add the keys to the array without any need for a function.</p>

```<code>$result = array();
$result["key1"] = $_SESSION["level1"];
$result["key2"] = $_SESSION["level2"];
$result["key3"] = $_SESSION["level3"];

echo json_encode($result);
</code>```

Body:
I have a dynamic number of pages in my web project. It depends on data from the database. I may have 1 page or 10 pages. I put the data selected on each page in session, and finally want to build an array. At the moment I am building JSON from 4 arrays. (In session all the keys are level + int in ascending order. If session x is missing I don't have any data on 6+ levels)

$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();

if (isset($_SESSION['level1'])) {
    $level1 = $_SESSION['level1'];
}
//the same for 3 more levels in session

$array = array(
    "first"  => ($level1),
    "second" => ($level2),
    "third"  => ($level3),
    "fourth" => ($level4)
);

json_encode($array);

Example of output of the json_encode($array):

{"first":["1","2"],"second":["4","6","8","9"],"third":["13","14","17","18"],"fourth":["33","34","35","36"]}

I tried to check how would json_encode work with array_push(), but I get an array of JSON objects instead of a single json object.

$result = array();
array_push($result, ["key1" => $_SESSION["level1"]]);
array_push($result, ["key2" => $_SESSION["level2"]]);
array_push($result, ["key3" => $_SESSION["level3"]]);

echo json_encode($result);

and the output:

[{"key1":["1","2"]},{"key2":["4","5","6"]},{"key3":["13","14","15"]}]

I will make everything iteratively, but I want to know if it is possible to make a single JSON object instead of array of JSONs. Thanks!

Body:
You can just add the keys to the array without any need for a function.

$result = array();
$result["key1"] = $_SESSION["level1"];
$result["key2"] = $_SESSION["level2"];
$result["key3"] = $_SESSION["level3"];

echo json_encode($result);


问:
I am trying to create a JSP Page with frames
I am trying to create a JSP page which will contain multiple section. Each section will contain data fetched from data base using servlet. I tried using frame and have put frame src ="servlet" and in servlet data is being fetched and forward that to jsp which I want to be displayed inside the frame?? Anyone having some idea for this.</p>

答:
I often want to achieve similar things and do so by setting attributes on the HttpServletRequest object.

Servlet:

```<code>User user = userBean.getUser(231);
Job job = user.getJob();

request.setAttribute("user",user);
request.setAttribute("job",job);

request.getRequestDispatcher( url ).forward(request, response);
</code>```

JSP Page

```<code><div id="section1">
    ${user.name}
    ${user.age}
</div>

<div id="section2">
    ${job.title}
    ${job.wage}
</div>
</code>```

Notes

Frame is an old HTML Element and not compatible with HTML5
I've used divs in my example, but you could use HTML5 Section to provide more smeantic meaning.

Hope I've understood your problem and this helps.

Good luck

Adam

Body:
I often want to achieve similar things and do so by setting attributes on the HttpServletRequest object.

Servlet:

User user = userBean.getUser(231);
Job job = user.getJob();

request.setAttribute("user",user);
request.setAttribute("job",job);

request.getRequestDispatcher( url ).forward(request, response);

JSP Page

<div id="section1">
    ${user.name}
    ${user.age}
</div>

<div id="section2">
    ${job.title}
    ${job.wage}
</div>

Notes

Frame is an old HTML Element and not compatible with HTML5
I've used divs in my example, but you could use HTML5 Section to provide more smeantic meaning.

Hope I've understood your problem and this helps.

Good luck

Adam


问:
Filling ComboBox in JavaFX From DataBase
i have this class

```<code>public class FXMLstudentregisterController implements Initializable {

@FXML
private JFXTextField usernametxt;
@FXML
private JFXTextField nomtxt;
@FXML
private JFXTextField prenomtxt;
@FXML
private JFXTextField emailtxt;
@FXML
private JFXTextField passwordhinttxt;
@FXML
private JFXPasswordField passwordtxt;
@FXML
private static  JFXComboBox<String> filierecb ;
@FXML
private JFXButton registerbtn;
@FXML
private JFXComboBox<Integer> promocb = new JFXComboBox<>();;
@FXML
private AnchorPane rootpane;
AnchorPane pane;
/**
 * Initializes the controller class.
 */
           static  Filiere f;
               static  Promotion p;
           static  Student s;
@FXML
private Label lbl;
@Override
public void initialize(URL url, ResourceBundle rb) {
    fillpromo();
    try {
        filierecb =  new JFXComboBox<>();
         ArrayList ar =       service.ConnectServer.getStub().oneColumnQuery("select * from filiere");
        ObservableList<String> a = (ObservableList<String>)   FXCollections.observableArrayList(ar);
        filierecb.getItems().clear();
        filierecb.setItems(a);
    } catch (RemoteException ex) {
        Logger.getLogger(FXMLstudentregisterController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@FXML
private void register(ActionEvent event) throws IOException {
    try {
        String nom = nomtxt.getText();
    String prenom = prenomtxt.getText();
    String username = usernametxt.getText();
    String email = emailtxt.getText();
    String password = passwordtxt.getText();
    String passhint = passwordhinttxt.getText();
    f = new Filiere(filierecb.getSelectionModel().getSelectedItem());
    p = new Promotion(promocb.getSelectionModel().getSelectedItem());
    s = new Student(email, nom, prenom, password, username, passhint);
        if (service.ConnectServer.getStub().registerStudent(s, f, p) != 0 ) {
           pane =  FXMLLoader.load(getClass().getResource("/Login/FXMLLogin.fxml"));
        rootpane.getChildren().setAll(pane);
        }else{
            System.out.println("error");
        }

    } catch (RemoteException ex) {
        Logger.getLogger(FXMLstudentregisterController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void fillpromo(){

     DateFormat df  = new SimpleDateFormat("YYYY");
    Date d = new Date();
    String y = df.format(d);
    int yy = Integer.parseInt(y);
    ArrayList<Integer> year = new ArrayList<>();
   year.add(yy);
   year.add(yy-1);

    for (Integer integer : year) {
        Promotion pro =new Promotion(integer);
        promocb.getItems().addAll(pro.getPromotion());
    }

}}
</code>```

And AS you see it's should fill the combobox " filierecb " with the data from the arraylist but when i execute the code nothing shows up and the combo is empty not exception is shown .

答:
i see you have a few bad practices, for example i don't know why is static the ComboBox, then you have to use instead of ArrayList its interface the List<"Content"> with generic type. The bug i think comes from the filierecb =  new JFXComboBox<>(); line, because you have an .fxml file which contains the ComboBox so you don't have to re-instantiate the ComboBox, on the other had you don't have to cast the observableArrayList() to ObservableList for me this code works fine:

```<code>package stackoverflow;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class TestController implements Initializable {

    @FXML
    private ComboBox<String> comboBox;

    @Override public void initialize(URL location, ResourceBundle resources) {
        List<String> strings = new ArrayList<>();
        strings.add("Test1");
        strings.add("Test2");
        comboBox.setItems(FXCollections.observableArrayList(strings));
    }

}
</code>```

And here is my .fxml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.ComboBox?>
<BorderPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.65"
        xmlns:fx="http://javafx.com/fxml/1" fx:controller="stackoverflow.TestController">
<top>
    <ComboBox fx:id="comboBox"/>
</top>
</code>```

I see you are using JFXComboBox, but I don`t think there is any difference regarding to this problem.

Body:
i have this class

public class FXMLstudentregisterController implements Initializable {

@FXML
private JFXTextField usernametxt;
@FXML
private JFXTextField nomtxt;
@FXML
private JFXTextField prenomtxt;
@FXML
private JFXTextField emailtxt;
@FXML
private JFXTextField passwordhinttxt;
@FXML
private JFXPasswordField passwordtxt;
@FXML
private static  JFXComboBox<String> filierecb ;
@FXML
private JFXButton registerbtn;
@FXML
private JFXComboBox<Integer> promocb = new JFXComboBox<>();;
@FXML
private AnchorPane rootpane;
AnchorPane pane;
/**
 * Initializes the controller class.
 */
           static  Filiere f;
               static  Promotion p;
           static  Student s;
@FXML
private Label lbl;
@Override
public void initialize(URL url, ResourceBundle rb) {
    fillpromo();
    try {
        filierecb =  new JFXComboBox<>();
         ArrayList ar =       service.ConnectServer.getStub().oneColumnQuery("select * from filiere");
        ObservableList<String> a = (ObservableList<String>)   FXCollections.observableArrayList(ar);
        filierecb.getItems().clear();
        filierecb.setItems(a);
    } catch (RemoteException ex) {
        Logger.getLogger(FXMLstudentregisterController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

@FXML
private void register(ActionEvent event) throws IOException {
    try {
        String nom = nomtxt.getText();
    String prenom = prenomtxt.getText();
    String username = usernametxt.getText();
    String email = emailtxt.getText();
    String password = passwordtxt.getText();
    String passhint = passwordhinttxt.getText();
    f = new Filiere(filierecb.getSelectionModel().getSelectedItem());
    p = new Promotion(promocb.getSelectionModel().getSelectedItem());
    s = new Student(email, nom, prenom, password, username, passhint);
        if (service.ConnectServer.getStub().registerStudent(s, f, p) != 0 ) {
           pane =  FXMLLoader.load(getClass().getResource("/Login/FXMLLogin.fxml"));
        rootpane.getChildren().setAll(pane);
        }else{
            System.out.println("error");
        }

    } catch (RemoteException ex) {
        Logger.getLogger(FXMLstudentregisterController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void fillpromo(){

     DateFormat df  = new SimpleDateFormat("YYYY");
    Date d = new Date();
    String y = df.format(d);
    int yy = Integer.parseInt(y);
    ArrayList<Integer> year = new ArrayList<>();
   year.add(yy);
   year.add(yy-1);

    for (Integer integer : year) {
        Promotion pro =new Promotion(integer);
        promocb.getItems().addAll(pro.getPromotion());
    }

}}

And AS you see it's should fill the combobox " filierecb " with the data from the arraylist but when i execute the code nothing shows up and the combo is empty not exception is shown .

Body:
i see you have a few bad practices, for example i don't know why is static the ComboBox, then you have to use instead of ArrayList its interface the List<"Content"> with generic type. The bug i think comes from the filierecb =  new JFXComboBox<>(); line, because you have an .fxml file which contains the ComboBox so you don't have to re-instantiate the ComboBox, on the other had you don't have to cast the observableArrayList() to ObservableList for me this code works fine:

package stackoverflow;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class TestController implements Initializable {

    @FXML
    private ComboBox<String> comboBox;

    @Override public void initialize(URL location, ResourceBundle resources) {
        List<String> strings = new ArrayList<>();
        strings.add("Test1");
        strings.add("Test2");
        comboBox.setItems(FXCollections.observableArrayList(strings));
    }

}

And here is my .fxml file:

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.ComboBox?>
<BorderPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.65"
        xmlns:fx="http://javafx.com/fxml/1" fx:controller="stackoverflow.TestController">
<top>
    <ComboBox fx:id="comboBox"/>
</top>

I see you are using JFXComboBox, but I don`t think there is any difference regarding to this problem.


问:
PHP nested ternary if condition
```<code><?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>
</code>```

for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?

答:
Set the priority </p>

```<code>    <?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ( ($var > 6) ? "gr than 6" : "not gr than 2 or 6" );
?>
</code>```

Title: PHP nested ternary if condition

Body:
<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>

for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?

Body:
Set the priority

    <?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ( ($var > 6) ? "gr than 6" : "not gr than 2 or 6" );
?>


问:
How to resolve language file URL for Jquery datatables in ASP.NET
In my ASP.NET app I am using Jquery datatables plugin like this:

```<code>    <script type="text/javascript">
      $('#grdData').DataTable({
          "language": { "url": "Scripts/json/table-language.json" }
      });
   </script>
</code>```

when running this on localhost it works fine and it fetches the json file.
But in production I get a 404 not found error.
I guess it somehow relates to relative path...
any ideas on how to fix the path so it would work?

答:
I found the problem.
It was related to IIS, I needed to add Mime Type of .json extension and it did the trick.</p>

Body:
In my ASP.NET app I am using Jquery datatables plugin like this:

when running this on localhost it works fine and it fetches the json file.
But in production I get a 404 not found error.
I guess it somehow relates to relative path...
any ideas on how to fix the path so it would work?


问:
Replace empty alt tag on  tag
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

```<code>preg_match_all('/<img[^>]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }
</code>```

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

答:
Please try it below:

```<code>function img_title_in_alt($full_img_tag){

    $doc = new DOMDocument();
    $doc->loadHTML($full_img_tag);
    $imageTags = $doc->getElementsByTagName('img');

    foreach($imageTags as $tag) {

        if($tag->getAttribute('src')!==''){
            return '<img src="'.$tag->getAttribute('src').'" width="'.$tag->getAttribute('width').'" height="'.$tag->getAttribute('height').'" alt="'.$tag->getAttribute('title').'" title="'.$tag->getAttribute('title').'" />';
        }
    }
}
</code>```

Now call the function with your full html tag of image. See the example:

```<code>$image = '<img src="assets/img/test.png" alt="" title="I\'am a title tag" width="100" height="100" />';

print img_title_in_alt($image);
</code>```

Let me know if you do not understand anything.

Title: Replace empty alt tag on <img> tag

Body:
I would like to replace my empty alt tags on images in a string. I have a string that contains all the text for a curtain page. In the text are also images, and a lot of them have empty tags (old data), but most of the time they do have title tags.
For example:

What I wish to have:

So:
I need to find all the images in my string, loop trough the images, find title tags, find alt tags, and replace the empty alt tags with the title tags that do have a value.

This is what i tried:

preg_match_all('/]+>/i',$return, $text);
if(isset($text)) {
            foreach( $text as $itemImg ) {
                foreach( $itemImg as $item ) {
                    $array = array();
                    preg_match( '/title="([^"]*)"/i', $item, $array );
                    if(isset($array[1])) {
                        //So $array[1] is a title tag, now what?
                    }
                }

            }
        }

I don't know have to complete the code, and I think there must be a easier fix for this. Suggestions?

Body:
Please try it below:

function img_title_in_alt($full_img_tag){

    $doc = new DOMDocument();
    $doc->loadHTML($full_img_tag);
    $imageTags = $doc->getElementsByTagName('img');

    foreach($imageTags as $tag) {

        if($tag->getAttribute('src')!==''){
            return '<img src="'.$tag->getAttribute('src').'" width="'.$tag->getAttribute('width').'" height="'.$tag->getAttribute('height').'" alt="'.$tag->getAttribute('title').'" title="'.$tag->getAttribute('title').'" />';
        }
    }
}

Now call the function with your full html tag of image. See the example:

$image = '<img src="assets/img/test.png" alt="" title="I\'am a title tag" width="100" height="100" />';

print img_title_in_alt($image);

Let me know if you do not understand anything.


问:
Hibernate 5 issue with JDK 9
I have a Hibernate 5 project that perfectly builds and runs on Java 8. I tried to test it on JDK 9 ea build 171.
Since it is a huge project and have other dependencies I had to add java.xml.bind module to the JVM configuration for tests:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <argLine>--add-modules java.xml.bind</argLine>
    </configuration>
</plugin>
</code>```

There were other issues that I could resolve but if used aggregated module java.se.ee(as recommended):

```<code><argLine>--add-modules java.se.ee</argLine>
</code>```

I got an exception :

```<code>java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:374)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
</code>```

I couldn't even understand why it happened because JTA library(with SystemException class) is in the class-path when tests were running.

Any suggestions on how to fix this?

答:
Java SE defines a small subset of JTA. It doesn't include javax.transaction.SystemException as that exception is in the Java EE version of JTA, not the Java SE subset.

When you run with --add-modules java.se.ee then it causes the modules shared between Java SE and Java EE to be resolved, this includes the the java.transaction module. Any attempt to load a type in the javax.transaction package will be loaded from the java.transaction module but since this module only has a small subset of JTA then javax.transaction.SystemException will not be found.

If you drop --add-modules java.se.ee from your command line then you'll find that javax.transaction.SystemException can be loaded, as it's on the class path. So if you only need JAXB (module java.xml.bind) then specify that module to --add-modules, not the "java.se.ee" aggregator that will cause all modules shared with Java EE to be resolved.

Title: Hibernate 5 issue with JDK 9

Body:
I have a Hibernate 5 project that perfectly builds and runs on Java 8. I tried to test it on JDK 9 ea build 171.
Since it is a huge project and have other dependencies I had to add java.xml.bind module to the JVM configuration for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <argLine>--add-modules java.xml.bind</argLine>
    </configuration>
</plugin>

There were other issues that I could resolve but if used aggregated module java.se.ee(as recommended):

<argLine>--add-modules java.se.ee</argLine>

I got an exception :

java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:374)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)

I couldn't even understand why it happened because JTA library(with SystemException class) is in the class-path when tests were running.

Any suggestions on how to fix this?


问:
Private vs Public variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         public int numberTwo = 12;

         static void yo()
         {
             public int numberThree = 12;
             private int numberFour = 12;
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne, numberTwo, numberThree and numberFour in this code excerpt?

答: numberOne and numberTwo are public instance variables in heap.  They can be accessed directly inside of an object who has an instance of the hithere object.  numberThree and numberFour cannot be accessed this way as they are not instance variables and are encapsulated within the scope of the function yo and stored in it respective stack.</p>

ContentLicense: CC BY-SA 2.5

Title: Private vs Public variables

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         public int numberTwo = 12;

         static void yo()
         {
             public int numberThree = 12;
             private int numberFour = 12;
         }
    }
}

Can someone tell me the difference between the variables numberOne, numberTwo, numberThree and numberFour in this code excerpt?


答:
The solution is to use parentheses to group your operators and also alter the order of the conditions a bit:

```<code>echo $current = ($var > 2) ?
    (($var > 6) ? "gr than 6" : "gr than 2") :
    "not gr than 2 or 6 (smaller than 2)";
</code>```

The problem in your version is that by default it gets grouped like this:

```<code>echo $current = (($var > 2) ? "gr than 2" : ($var > 6)) ?
  "gr than 6" :
  "not gr than 2 or 6";
</code>```

Which is equal to:

```<code>echo $current = ("gr than 2") ?
  "gr than 6" :
  "not gr than 2 or 6";
</code>```

Title: PHP nested ternary if condition

Body:
The solution is to use parentheses to group your operators and also alter the order of the conditions a bit:

echo $current = ($var > 2) ?
    (($var > 6) ? "gr than 6" : "gr than 2") :
    "not gr than 2 or 6 (smaller than 2)";

The problem in your version is that by default it gets grouped like this:

echo $current = (($var > 2) ? "gr than 2" : ($var > 6)) ?
  "gr than 6" :
  "not gr than 2 or 6";

Which is equal to:

echo $current = ("gr than 2") ?
  "gr than 6" :
  "not gr than 2 or 6";


问:
Error installing visual studio service pack 1
I am trying to install visual studio 2008 service pack 1

I am got following error with visual studio Just-In-Time debugger

Error-An Handled Exception ('System.TypeLoadException') occurred in ServiceModelReg.exe[900]

Can you help me out

Thanks

答:
Go to Services

Disable IIS admin service while installing it..


问:
Apache rewrite condition for subdomain and URL including numbers
I have a website and I want to 404 all incoming traffic from subdomain like sub.example.de but not www.example.de and not example.de

like this (Apache - Rewrite dynamic subdomains and URL parameters)

```<code>RewriteCond %{HTTP_HOST} !^www\.example\.de$ [NC]
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]+)\.example\.de$ [NC]
RewriteRule ^(.*)$ - [L,R=404]
</code>```

However when the requested URI is like this /go/12345, I don't want he rule to apply no matter if there is a subdomain or not.

答:
You can use this rule with a negative pattern inRewriteRule:

```<code>RewriteCond %{HTTP_HOST} !^www\.example\.de$ [NC]
RewriteCond %{HTTP_HOST} ^[a-zA-Z0-9]+\.example\.de$ [NC]
RewriteRule !^go/12345/?$ - [L,R=404,NC]
</code>```

Body:
I have a website and I want to 404 all incoming traffic from subdomain like sub.example.de but not www.example.de and not example.de

like this (Apache - Rewrite dynamic subdomains and URL parameters)

RewriteCond %{HTTP_HOST} !^www\.example\.de$ [NC]
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]+)\.example\.de$ [NC]
RewriteRule ^(.*)$ - [L,R=404]

However when the requested URI is like this /go/12345, I don't want he rule to apply no matter if there is a subdomain or not.

Body:
You can use this rule with a negative pattern inRewriteRule:

RewriteCond &#37;{HTTP_HOST} !^www\.example\.de$ [NC]
RewriteCond %{HTTP_HOST} ^[a-zA-Z0-9]+\.example\.de$ [NC]
RewriteRule !^go/12345/?$ - [L,R=404,NC]


问:
COBOL analysis using Excel sheet. Need script to locate paragraphs
I have copied a COBOL program in to Excel sheet. I want write a macro and assign keys. So when I press the assigned keys it should do the following thing. For example, when the cursor is at the row PERFORM 001-PARA-ADD it should store the row value (line no 2) in a variable and copy only para name 001-PARA-ADD and add . at the end of the string and strip out the other characters in the line and search for string 001-PARA-ADD. and move the control to the line 7 where the string 001-PARA-ADD. is present and when I press the keys again it should comeback to the initial location line 2.

Please tell me if it possible. Please let me know if more details need about the requirement.

```<code> IF A > B
345    PERFORM 001-PARA-ADD 12345
     IF A < B
        PERFORM 002-PARA-SUB
     END-IF
    END-IF
    001-PARA-ADD.
       COMPUTE A = A+B.
    .
    002-PARA-SUB.
       COMPUTE B = B-A.
    .
</code>```

Image of the program:

答:
Try to connect dots with these:

I have copied a COBOL program in to Excel sheet. I want write a macro and assign keys. So when I press the assigned keys it should do the following thing. For example, when the cursor is at the row PERFORM 001-PARA-ADD it should store the row value (line no 2) in a variable

```<code>   strValue = ActiveCell.Value
   Sheets("Sheet2").Range("A1") = ActiveCell.Address 'save your cell address into a scratch sheet
</code>```

and copy only para name  001-PARA-ADD

```<code>   arrayValue = Split(strValue, " ")
   For Each val In arrayValue
        If Instr(val, "PARA") > 0 Then
            strPara = val
            Goto ProcessNext
        End If
   Next

   ProcessNext:
</code>```

and add . at the end of the string

```<code>   strPara = strPara & "."
</code>```

and strip out the other characters in the line

```<code>   strPara = Trim(strPara)
</code>```

and search for string 001-PARA-ADD. and move the control to the line 7 where the string 001-PARA-ADD. is present

```<code>get the code from this link <https://stackoverflow.com/questions/11813720/search-a-string-in-a-worksheet-in-vba>!
</code>```

and when I press the keys again it should comeback to the initial location line 2.

```<code>   'create another macro for this
   ActiveSheet.Range(Sheets("Sheet2").Range("A1").Value).Activate
</code>```

Body:
I have copied a COBOL program in to Excel sheet. I want write a macro and assign keys. So when I press the assigned keys it should do the following thing. For example, when the cursor is at the row PERFORM 001-PARA-ADD it should store the row value (line no 2) in a variable and copy only para name 001-PARA-ADD and add . at the end of the string and strip out the other characters in the line and search for string 001-PARA-ADD. and move the control to the line 7 where the string 001-PARA-ADD. is present and when I press the keys again it should comeback to the initial location line 2.

Please tell me if it possible. Please let me know if more details need about the requirement.

 IF A > B
345    PERFORM 001-PARA-ADD 12345
     IF A < B
        PERFORM 002-PARA-SUB
     END-IF
    END-IF
    001-PARA-ADD.
       COMPUTE A = A+B.
    .
    002-PARA-SUB.
       COMPUTE B = B-A.
    .

Image of the program:

Body:
Try to connect dots with these:

I have copied a COBOL program in to Excel sheet. I want write a macro and assign keys. So when I press the assigned keys it should do the following thing. For example, when the cursor is at the row PERFORM 001-PARA-ADD it should store the row value (line no 2) in a variable

   strValue = ActiveCell.Value
   Sheets("Sheet2").Range("A1") = ActiveCell.Address 'save your cell address into a scratch sheet

and copy only para name  001-PARA-ADD

   arrayValue = Split(strValue, " ")
   For Each val In arrayValue
        If Instr(val, "PARA") > 0 Then
            strPara = val
            Goto ProcessNext
        End If
   Next

   ProcessNext:

and add . at the end of the string

   strPara = strPara & "."

and strip out the other characters in the line

   strPara = Trim(strPara)

and search for string 001-PARA-ADD. and move the control to the line 7 where the string 001-PARA-ADD. is present

get the code from this link <https://stackoverflow.com/questions/11813720/search-a-string-in-a-worksheet-in-vba>!

and when I press the keys again it should comeback to the initial location line 2.

   'create another macro for this
   ActiveSheet.Range(Sheets("Sheet2").Range("A1").Value).Activate


问:
Pull data from a closed workbook to a userform using Vlookup
In the following code, I copy a value from a closed-spreadsheet to a user-form, but it fails with error 1004.

"Unable to get the Vlookup propoerty".

My code is as follows:

```<code>If TextBox1.Value = "" Then
   MsgBox "Enter Employee Number", vbExclamation, "Error Message"

   Exit Sub

End If

Set wb = Workbooks.Open("Z:\PROD  - Production related info\QUALITY\KAIZEN TEAM\Weekly Rejects\Dropdown_List_Database\Dropdown_Lists.xlsx")

Dim myRange As Range
Set myRange = Worksheets("Users").Range("A2:F1000")

UserForm1.TextBox2.Value =
Application.WorksheetFunction.VLookup(UserForm1.TextBox1.Value, myRange, 2, False)
</code>```

答:
VLookup will raise an error, when called via the Application.WorksheetFunction object, if it cannot find the value you are looking for.  You can handle this by adding error trapping to your function:

Test Data

```<code>Row/Col     A   B
1           x   XXX
2           y   YYY
3           z   ZZZ
</code>```

Example A

```<code>Public Sub XX()
On Error Resume Next    ' Ignore errors.  WARNING: Will ignore **all** errors.
Dim result As Variant   ' Holds result of vlookup.

    ' Can find value, no error.
    result = Application.WorksheetFunction.VLookup("x", Range("Sheet1!A1:B3"), 2, False)
    MsgBox result

    ' Cannot find value, raises an error.
    result = Application.WorksheetFunction.VLookup("a", Range("Sheet1!A1:B3"), 2, False)

    ' Check for error.
    ' 1004 = cannot find value.
    ' Make sure you handle all other errors.
    If Err.Number = 1004 Then

        MsgBox "Cannot find value"
        Err.Clear
    Else

        MsgBox Err.Description
        Err.Clear
    End If
End Sub
</code>```

An alternative approach allows you to call VLookup directly.  This method does not require error trapping:

Example B

```<code>Dim Result As Variant

' Value XXX wrote to Result.
Result = [Vlookup("x", Sheet1!A1:B3, 2, False)]

' Value Error 2042 wrote to Result.
Result = [Vlookup("a", Sheet1!A1:B3, 2, False)]
</code>```

I prefer the second approach.  Ignoring errors can make it hard to debug your code later.

For more on using VLookup via VBA I'd recommend reading this blog post.

Body:
In the following code, I copy a value from a closed-spreadsheet to a user-form, but it fails with error 1004.

"Unable to get the Vlookup propoerty".

My code is as follows:

If TextBox1.Value = "" Then
   MsgBox "Enter Employee Number", vbExclamation, "Error Message"

   Exit Sub

End If

Set wb = Workbooks.Open("Z:\PROD  - Production related info\QUALITY\KAIZEN TEAM\Weekly Rejects\Dropdown_List_Database\Dropdown_Lists.xlsx")

Dim myRange As Range
Set myRange = Worksheets("Users").Range("A2:F1000")

UserForm1.TextBox2.Value =
Application.WorksheetFunction.VLookup(UserForm1.TextBox1.Value, myRange, 2, False)

Body:
VLookup will raise an error, when called via the Application.WorksheetFunction object, if it cannot find the value you are looking for.  You can handle this by adding error trapping to your function:

Test Data

Row/Col     A   B
1           x   XXX
2           y   YYY
3           z   ZZZ

Example A

Public Sub XX()
On Error Resume Next    ' Ignore errors.  WARNING: Will ignore **all** errors.
Dim result As Variant   ' Holds result of vlookup.

    ' Can find value, no error.
    result = Application.WorksheetFunction.VLookup("x", Range("Sheet1!A1:B3"), 2, False)
    MsgBox result

    ' Cannot find value, raises an error.
    result = Application.WorksheetFunction.VLookup("a", Range("Sheet1!A1:B3"), 2, False)

    ' Check for error.
    ' 1004 = cannot find value.
    ' Make sure you handle all other errors.
    If Err.Number = 1004 Then

        MsgBox "Cannot find value"
        Err.Clear
    Else

        MsgBox Err.Description
        Err.Clear
    End If
End Sub

An alternative approach allows you to call VLookup directly.  This method does not require error trapping:

Example B

Dim Result As Variant

' Value XXX wrote to Result.
Result = [Vlookup("x", Sheet1!A1:B3, 2, False)]

' Value Error 2042 wrote to Result.
Result = [Vlookup("a", Sheet1!A1:B3, 2, False)]

I prefer the second approach.  Ignoring errors can make it hard to debug your code later.

For more on using VLookup via VBA I'd recommend reading this blog post.


问:
Check that the file is not binary in pre receive hook
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

```<code>my @new_file_list =  `git diff --name-only $old..$new`;;
</code>```

I get a size of every file, by looping:

```<code>foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;
</code>```

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

答:
Perl has a number of file test operators which will tell you various things about a file (you're already using -s). These include the following (taken from the documentation):

-T  File is an ASCII or UTF-8 text file (heuristic guess).

-B  File is a "binary" file (opposite of -T).

It's worth emphasising that this is just a heuristic. Perl examines the start of the file and checks what proportion of the characters appear to be printable.

So you can use these in your code like this:

```<code>if (-B $filename) {
  # file is (probably) binary
}
</code>```

Body:
In my git pre-recieve hook on server side I get a list of files in commit by using this command:

my @new_file_list =  `git diff --name-only $old..$new`;;

I get a size of every file, by looping:

foreach $file (@new_file_list)
{
  $size = `git cat-file -s $new:$file`;

By using what command can I get a boolean variable, that will define, if the file in the commit is binary?
So I have a filename in the input, and $old $new revisions, what command can define, if the file is binary?

Thanks in advance.

Body:
Perl has a number of file test operators which will tell you various things about a file (you're already using -s). These include the following (taken from the documentation):

-T  File is an ASCII or UTF-8 text file (heuristic guess).

-B  File is a "binary" file (opposite of -T).

It's worth emphasising that this is just a heuristic. Perl examines the start of the file and checks what proportion of the characters appear to be printable.

So you can use these in your code like this:

if (-B $filename) {
  # file is (probably) binary
}


问:
google mock - save EXPECT_CALL then re-use and change clauses
Let's say you have this:

```<code>EXPECT_CALL(MockClass_obj, f1(55)).Times(1);
// use the expectation
// ...

// Now clear it
Mock::VerifyAndClear(&MockClass_obj)
</code>```

Is it possible to
1) Save the expectation

AND

2) Re-use it later and change the clauses?

From here I know it's possible to save expectations but there's nowhere else that expounds on what else can be done.

Referring to the above code, I want to do something like:

```<code>Expecatation exp1 = EXPECT_CALL(MockClass_obj, f1(55)).Times(1);
// use the expectation
// ...

// Now clear it
Mock::VerifyAndClear(&MockClass_obj)

// Somehow modify exp1 to change the cardinality or any of the clauses
// so that I can make the test immediately readable and convey that it's very much related to the one above":

// Instead of this:
EXPECT_CALL(MockClass_obj, f1(55)).Times(0);

// I wanna do something like
exp1.Times(0)
</code>```

答:
No, it is not possible in the way described in question. The Expectation class is just to be used in After clause and nothing else - by google-mock design you cannot do anything else with it.

But, with proper encapsulation - you might achieve the goal, like:

```<code>::testing::Expectation expectF1For55(::testing::Cardinality cardinality)
{
    EXPECT_CALL(MockClass_obj, f1(55)).Times(cardinality);
}
</code>```

And use:

```<code>auto exp1 = expectF1For55(Exactly(1));
// ...

// ...
expectF1For55(Exactly(0));
</code>```

However I bet, the question is more general than just to cover this very example.

E.g. you can encapsulate entire Expectation - whatever you need - like:

```<code>class F1Expectation
{
public:
    F1Expectation(MockClass&);
    Expectation expect(int arg, ::testing::Cardinality cardinality = Exaclty(1))
    {
       m_arg = arg;
       return EXPECT_CALL(obj, f1(m_arg)).Times(cardinality);
    }
    Expectation expect(::testing::Cardinality cardinality)
    {
       return EXPECT_CALL(obj, f1(55)).Times(cardinality);
    }
private:
    MockClass& obj;
    Matcher<int> m_arg = _;
};
</code>```

And use:

```<code>F1Expectation exp1(MockClass_obj);
exp1.expect(1);
// ...

// ...
exp1.expect(0);
</code>```

Body:
Let's say you have this:

EXPECT_CALL(MockClass_obj, f1(55)).Times(1);
// use the expectation
// ...

// Now clear it
Mock::VerifyAndClear(&MockClass_obj)

Is it possible to
1) Save the expectation

AND

2) Re-use it later and change the clauses?

From here I know it's possible to save expectations but there's nowhere else that expounds on what else can be done.

Referring to the above code, I want to do something like:

Expecatation exp1 = EXPECT_CALL(MockClass_obj, f1(55)).Times(1);
// use the expectation
// ...

// Now clear it
Mock::VerifyAndClear(&MockClass_obj)

// Somehow modify exp1 to change the cardinality or any of the clauses
// so that I can make the test immediately readable and convey that it's very much related to the one above":

// Instead of this:
EXPECT_CALL(MockClass_obj, f1(55)).Times(0);

// I wanna do something like
exp1.Times(0)

Body:
No, it is not possible in the way described in question. The Expectation class is just to be used in After clause and nothing else - by google-mock design you cannot do anything else with it.

But, with proper encapsulation - you might achieve the goal, like:

::testing::Expectation expectF1For55(::testing::Cardinality cardinality)
{
    EXPECT_CALL(MockClass_obj, f1(55)).Times(cardinality);
}

And use:

auto exp1 = expectF1For55(Exactly(1));
// ...

// ...
expectF1For55(Exactly(0));

However I bet, the question is more general than just to cover this very example.

E.g. you can encapsulate entire Expectation - whatever you need - like:

class F1Expectation
{
public:
    F1Expectation(MockClass&);
    Expectation expect(int arg, ::testing::Cardinality cardinality = Exaclty(1))
    {
       m_arg = arg;
       return EXPECT_CALL(obj, f1(m_arg)).Times(cardinality);
    }
    Expectation expect(::testing::Cardinality cardinality)
    {
       return EXPECT_CALL(obj, f1(55)).Times(cardinality);
    }
private:
    MockClass& obj;
    Matcher<int> m_arg = _;
};

And use:

F1Expectation exp1(MockClass_obj);
exp1.expect(1);
// ...

// ...
exp1.expect(0);


问:
create a temporary file with a specified name in java
I have a Byte[] array that i want to put it's content into a temporary file .

I have tryied to do it like this

```<code>try {
            tempFile = File.createTempFile("tmp", null);
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(sCourrier.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

but i want that I specify the filename by myself so not generated by the jvm

答:
You can directly give the location and file name or You can access local filesystem and find the temp directory

```<code> String tempDir=System.getProperty("java.io.tmpdir");
</code>```

you can use temp directory and your custom file name.

```<code>public static void main(String[] args) {
    try {
        String tempDir=System.getProperty("java.io.tmpdir");
        String sCourrier ="sahu";
        File file = new File(tempDir+"newfile.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(sCourrier.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Body:
I have a Byte[] array that i want to put it's content into a temporary file .

I have tryied to do it like this

try {
            tempFile = File.createTempFile("tmp", null);
            FileOutputStream fos = new FileOutputStream(tempFile);
            fos.write(sCourrier.getBody());
        } catch (IOException e) {
            e.printStackTrace();
        }

but i want that I specify the filename by myself so not generated by the jvm

Body:
You can directly give the location and file name or You can access local filesystem and find the temp directory

 String tempDir=System.getProperty("java.io.tmpdir");

you can use temp directory and your custom file name.

public static void main(String[] args) {
    try {
        String tempDir=System.getProperty("java.io.tmpdir");
        String sCourrier ="sahu";
        File file = new File(tempDir+"newfile.txt");
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(sCourrier.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }


问:
How to give custom size to PdfSharp generated Pdf
I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.

```<code>            pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }
</code>```

Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.

答:
If I'm not mistaken, PageSize.A3 is not an enum but Rectangle value. So instead of passing predefined Rectangle you can provide your own, for example:

new Rectangle(1191, 842) // for album A3

new Rectangle(842, 595) // for album A4

and so on...

Body:
I was trying to generate a pdf from HTML which containing a table using PdfSharp and HTMLRenderer. The following shows the code.

            pdf = PdfGenerator.GeneratePdf(html, PageSize.A3);

            byte[] fileContents = null;
            using (MemoryStream stream = new MemoryStream())
            {
                pdf.Save(stream, true);
                fileContents = stream.ToArray();
                return new FileStreamResult(new MemoryStream(fileContents.ToArray()), "application/pdf");
            }

Is there any possibility for me to provide a custom size to the PDF and change the orientation of the page. I am using a memory stream to show the PDF directly on the browser display.


问:
How to split a routes.js that grows too large to be easily maintained?
I'm using node and express to create a rest api. I followed a tutorial where all the routes and its logic are saved in a routes.js file like this:

SERVER JS:

```<code>var express = require('express');
var app = express();

(...)

require('./app/routes.js')(app, port, express);
</code>```

ROUTES.JS

```<code>module.exports = function(app, port, express) {

  var apiRoutes = express.Router();

(...)

//Sample route

  apiRoutes.get('/userfiles', function(req, res) {
    UserFile.find({ owner: req.decoded.user.email }, function(err, filesList) {
      if (err)
        return done(err);
      res.json({ success: true, files: filesList });
    });
  });
</code>```

My problem is twofold:

1 - Routes can easily contain code thats 150 lines long, some of them far longer. It doesn't feel clean to have route declarations and the logic grouped together. Is it a good practice to do something like this instead?

```<code>apiRoutes.post('/randomRoute', function(req, res) {
    return res.json(functionThatContainsTheActualCode(req));
  });
</code>```

(and then have an functionThatContainsTheActualCode function with all the logic in a different file).

2 - I have middleware that applies to some functions (for example, some routes are only accessible for logged in users and those routes go through an authentication middleware). Currently way I do it is declaring public routes before the middleware declaration and private routes after, which feels incredibly hacky. How can I separate public and private routes (and the middleware itself) in different files?

答:
Problem 1:

We need to go deeper.

Change the route file to just require the actual router logic.

routes.js

```<code>// where app = express();
module.exports = (app) => {
    // index.js happens to be a file exporting the router.
    app.use('/', require('./index'));

    // this is basically the idea. Create a separate file for the actual logic.
    app.use('/route', require('.path/to/file'));
};
</code>```

and in file.js

```<code>const express = require('express'),
    router    = express.Router();

router.verb('/path/', (req, res, next) => {
   // do whatever
});

// this is required
module.exports = router;
</code>```

Problem 2:
Middleware is basically a function taking in request, response, next as 3 params, doing something with the request and either sending out a response or moving on to the next middleware. That's why you need to call next if you want to move to next middleware in the chain.

Now all you need is a file that exports a function which takes request, response, next as params.
    // lets call this auth.js
    module.exports = function(req, res, next) {

```<code>    // do logic

    if () {
        return res.send(); // or res.somethingThatSendsOutAHttpResponse()
    }

   // next middelware
    next();
};
</code>```

Since express routes are also middlewares, (mind blown), you can mount them top down.
To authenticate a route, just put the auth.js middleware on top of that route.

```<code>router.get('/', require('./auth'));
router.get('/', require('./log'));
router.get('/', (req, res, next) => {
    // yolo
});
</code>```

Now since this is web dev, you still got problems.
Now all your boring database queries are scattered everywhere.
Fear not, you can solve it, by, guess, creating another file.

```<code>apiRoutes.get('/userfiles', function(req, res) {
    const userFile = require('/path/to/model/with/userfile/methods/exported/out');

    // do something with userFile's methods
  });
</code>```

Body:
I'm using node and express to create a rest api. I followed a tutorial where all the routes and its logic are saved in a routes.js file like this:

SERVER JS:

var express = require('express');
var app = express();

(...)

require('./app/routes.js')(app, port, express);

ROUTES.JS

module.exports = function(app, port, express) {

  var apiRoutes = express.Router();

(...)

//Sample route

  apiRoutes.get('/userfiles', function(req, res) {
    UserFile.find({ owner: req.decoded.user.email }, function(err, filesList) {
      if (err)
        return done(err);
      res.json({ success: true, files: filesList });
    });
  });

My problem is twofold:

1 - Routes can easily contain code thats 150 lines long, some of them far longer. It doesn't feel clean to have route declarations and the logic grouped together. Is it a good practice to do something like this instead?

apiRoutes.post('/randomRoute', function(req, res) {
    return res.json(functionThatContainsTheActualCode(req));
  });

(and then have an functionThatContainsTheActualCode function with all the logic in a different file).

2 - I have middleware that applies to some functions (for example, some routes are only accessible for logged in users and those routes go through an authentication middleware). Currently way I do it is declaring public routes before the middleware declaration and private routes after, which feels incredibly hacky. How can I separate public and private routes (and the middleware itself) in different files?

Body:
Problem 1:

We need to go deeper.

Change the route file to just require the actual router logic.

routes.js

// where app = express();
module.exports = (app) => {
    // index.js happens to be a file exporting the router.
    app.use('/', require('./index'));

    // this is basically the idea. Create a separate file for the actual logic.
    app.use('/route', require('.path/to/file'));
};

and in file.js

const express = require('express'),
    router    = express.Router();

router.verb('/path/', (req, res, next) => {
   // do whatever
});

// this is required
module.exports = router;

Problem 2:
Middleware is basically a function taking in request, response, next as 3 params, doing something with the request and either sending out a response or moving on to the next middleware. That's why you need to call next if you want to move to next middleware in the chain.

Now all you need is a file that exports a function which takes request, response, next as params.
    // lets call this auth.js
    module.exports = function(req, res, next) {

    // do logic

    if () {
        return res.send(); // or res.somethingThatSendsOutAHttpResponse()
    }

   // next middelware
    next();
};

Since express routes are also middlewares, (mind blown), you can mount them top down.
To authenticate a route, just put the auth.js middleware on top of that route.

router.get('/', require('./auth'));
router.get('/', require('./log'));
router.get('/', (req, res, next) => {
    // yolo
});

Now since this is web dev, you still got problems.
Now all your boring database queries are scattered everywhere.
Fear not, you can solve it, by, guess, creating another file.

apiRoutes.get('/userfiles', function(req, res) {
    const userFile = require('/path/to/model/with/userfile/methods/exported/out');

    // do something with userFile's methods
  });


问:
How can I insert rows into a table for each date from periods described in another table?
Given a table alpha, with the following structure:

```<code>id INT
period_start DATE
period_end DATE
</code>```

And a table beta:

```<code>id INT
alpha_id INT
day DATE
</code>```

For each row in table alpha, I would like to insert rows into table beta, filling beta.day for each date between alpha.period_start and alpha.period_end.

For example:

```<code>id | period_start | period_end
1  | 2017-01-01   | 2017-01-03
</code>```

Would be translated into:

```<code>id | alpha_id | day
1  | 1        | 2017-01-01
2  | 1        | 2017-01-02
3  | 1        | 2017-01-03
</code>```

Ideas?

答:
This works, but it's really inefficient. You can tweak it if you know for sure that periods are not going to be longer than a certain amount of days (the one below allows for ridiculously large periods: 99999 days, if I'm not mistaken).

```<code>insert into beta(alpha_id, day)
select
    a1.id, selected_date
from
    alpha a1 join
    (select id, selected_date from
        (select id, adddate(@period_start, t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4,
            (select @period_start := min(period_start), @period_end := max(period_end) from alpha) init,
            (select id from alpha a3) id) v
    where selected_date <= @period_end) days on a1.id = days.id
where
    selected_date between
        (select
            period_start
        from
            alpha a4
        where a1.id = a4.id) and
        (select
            period_end
        from
            alpha a5
        where a1.id = a5.id)
</code>```

Personally, I'd work with procedures: more efficient, more readable... in sum, more elegant imho.

Anyway, hope it helps.

PS: I'm using an automatically incremented field for beta table's id.

Body:
Given a table alpha, with the following structure:

id INT
period_start DATE
period_end DATE

And a table beta:

id INT
alpha_id INT
day DATE

For each row in table alpha, I would like to insert rows into table beta, filling beta.day for each date between alpha.period_start and alpha.period_end.

For example:

id | period_start | period_end
1  | 2017-01-01   | 2017-01-03

Would be translated into:

id | alpha_id | day
1  | 1        | 2017-01-01
2  | 1        | 2017-01-02
3  | 1        | 2017-01-03

Ideas?

Body:
This works, but it's really inefficient. You can tweak it if you know for sure that periods are not going to be longer than a certain amount of days (the one below allows for ridiculously large periods: 99999 days, if I'm not mistaken).

insert into beta(alpha_id, day)
select
    a1.id, selected_date
from
    alpha a1 join
    (select id, selected_date from
        (select id, adddate(@period_start, t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
            (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4,
            (select @period_start := min(period_start), @period_end := max(period_end) from alpha) init,
            (select id from alpha a3) id) v
    where selected_date <= @period_end) days on a1.id = days.id
where
    selected_date between
        (select
            period_start
        from
            alpha a4
        where a1.id = a4.id) and
        (select
            period_end
        from
            alpha a5
        where a1.id = a5.id)

Personally, I'd work with procedures: more efficient, more readable... in sum, more elegant imho.

Anyway, hope it helps.

PS: I'm using an automatically incremented field for beta table's id.


问:
Checking if two strings are the same to stop inputs
Hello i'm needing to check if an extension in my program already exists and if it does to stop it from being inputted into the list of entries and pop up a dialog box. At the moment with the code below i can now no longer insert anything as everything is said to be the same. I feel like i'm making a basic idiotic mistake but i can't see it.</p>

```<code> private void addNewEntry()
{
    // TODO add code to create a new entry
    // should show appropriate error if unable to create the entry
    // update the UI
    // update the data file by calling updateDataFile
    String fileExtension, program;
    String repeatExtension;

    fileExtension = txtAddExtension.getText();
    if (!fileExtension.substring(0,1).equals("."))
        fileExtension = "." + fileExtension;
     repeatExtension = fileExtension;
    program = txtAddProgram.getText();

    if(fileExtension.equalsIgnoreCase(repeatExtension))
    {
        JOptionPane.showMessageDialog(txtList, "Matching extension", "Error", JOptionPane.ERROR_MESSAGE);

    }

    else
    {
    Association assoc = new Association(fileExtension, program);

    assocList.add(assoc);
    updateDataFile();

    try {
        doc.remove(0, doc.getLength());

        doc.insertString(doc.getLength(), "Entry added\n" + assoc.toString() + "\n", null);

    } catch (BadLocationException e) {

        e.printStackTrace();
    }

    listAll();
}

}
</code>```

答:
You are assigning repeatExtension to the same as fileExtension just before checking if they are equal so the check will always be true

```<code>     repeatExtension = fileExtension;
</code>```

Body:
Hello i'm needing to check if an extension in my program already exists and if it does to stop it from being inputted into the list of entries and pop up a dialog box. At the moment with the code below i can now no longer insert anything as everything is said to be the same. I feel like i'm making a basic idiotic mistake but i can't see it.

 private void addNewEntry()
{
    // TODO add code to create a new entry
    // should show appropriate error if unable to create the entry
    // update the UI
    // update the data file by calling updateDataFile
    String fileExtension, program;
    String repeatExtension;

    fileExtension = txtAddExtension.getText();
    if (!fileExtension.substring(0,1).equals("."))
        fileExtension = "." + fileExtension;
     repeatExtension = fileExtension;
    program = txtAddProgram.getText();

    if(fileExtension.equalsIgnoreCase(repeatExtension))
    {
        JOptionPane.showMessageDialog(txtList, "Matching extension", "Error", JOptionPane.ERROR_MESSAGE);

    }

    else
    {
    Association assoc = new Association(fileExtension, program);

    assocList.add(assoc);
    updateDataFile();

    try {
        doc.remove(0, doc.getLength());

        doc.insertString(doc.getLength(), "Entry added\n" + assoc.toString() + "\n", null);

    } catch (BadLocationException e) {

        e.printStackTrace();
    }

    listAll();
}

}

Body:
You are assigning repeatExtension to the same as fileExtension just before checking if they are equal so the check will always be true

     repeatExtension = fileExtension;


问:
Question about ASP.NET Code Behind model
I am thinking about the asp.net 2.0 code behind model.

After I drag a button onto my Default.aspx page, I got the following declaration in my Default.aspx.designer.cs file:

```<code>public partial class _Default {

    protected global::System.Web.UI.HtmlControls.HtmlForm form1;

    protected global::System.Web.UI.WebControls.Button Button1;
}
</code>```

And now it's OK for me to write the following code in Default.aspx.cs file:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Text = "clicked!";
}
</code>```

But I am wondering, what I got is nothing but a declaration of Button1 variable of Button type, it hasn't been instanciated, how could this code run without trigging a Null Reference Exception?

I think there must exist some code like this somewhere:

```<code>Button1 = new Button();
</code>```

But where is this code? When is this code executed? Who executes it?

Many thanks...

Update - 1 - 21:17 12/15/2010

I found 2 auto-generated file in a mysterious location C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\edd9f4a1\7f113408, they are:

```<code>App_Web_x_swwj6s.1.cs
App_Web_x_swwj6s.0.cs
</code>```

I found code like below in the App_Web_x_swwj6s.0.cs file:

```<code>        private global::System.Web.UI.WebControls.Button @__BuildControlButton1()
         {
            global::System.Web.UI.WebControls.Button @__ctrl;
            @__ctrl = new global::System.Web.UI.WebControls.Button();
            //....
            this.Button1 = @__ctrl;
            return @__ctrl;
          }
</code>```

And this method is invoked in the below code:

```<code>private global::System.Web.UI.HtmlControls.HtmlForm @__BuildControlform1()
{
  //....
  global::System.Web.UI.WebControls.Button @__ctrl1;

  @__ctrl1 = this.@__BuildControlButton1();
  //......
}
</code>```

And finally the above code is invoked in the following method:

```<code>protected override void FrameworkInitialize()
</code>```

So I believed that the FrameworkInitialize() method is the one who did the dirty job of bind the control reference to a control instance.

To prove this, I intentionally wrote the following code in my code-behind file:

```<code>protected override void FrameworkInitialize()
{
    this.Button1 = null;
}
</code>```

I hope there would be a Null Reference Exception when I click the button, but strange enough, the whole web site run smoothly.

Is it true that all the controls I declared in the aspx file are created with the FrameworkInitialize() method? Why there's no Null Reference Exception in the above scenario?

Many thanks again.

Update - 2 - 21:43 12/15/2010

I think I may find the explanation, I checked the final page class generated by ASP.NET with .NET reflector. Its deriving relation is like this:

default_aspx class (The ultimate class representing the page)<--- _Default class (the code behind class) <--- System.Web.UI.Page

And in the default_aspx class, I found this:

```<code>protected override void FrameworkInitialize()
{
    base.FrameworkInitialize();  // Button1=null is executed here.
    this.__BuildControlTree(this); // Here Button1 is STILL set to an instance.
    base.AddWrappedFileDependencies(__fileDependencies);
    base.Request.ValidateInput();
}
</code>```

So, this could explain why my intention to set the Button1 to null failed.

Now, my question is, does the FrameworkInitialize() method has to be called at the very beginning of a page's life cycle so that we could use the control on the page afterwards.

Update - 3 - 3:45 PM 12/16/2010

From here:

Once the HTTP page handler class is
  fully identified, the ASP.NET run time
  calls the handler's ProcessRequest
  method to process the request.
  Normally, there is no need to change
  the implementation of the method as it
  is provided by the Page class.

This implementation begins by calling
  the method FrameworkInitialize, which
  builds the controls tree for the page.
  The method is a protected and virtual
  member of the TemplateControl
  class—the class from which Page itself
  derives. Any dynamically generated
  handler for an .aspx resource
  overrides FrameworkInitialize. In this
  method, the whole control tree for the
  page is built.

A bounty is started for your precious comments. :)

答:
The page and its controls (including your button in this case) are instantiated by the webforms "view engine" before the OnLoad, etc events are fired.

Otherwise, you'd have to have an ISAPI filter or similar device intercept requests and create the page object and its controls before any events were fired. This is what the ASP.NET ISAPI DLL does, I think.

I haven't tried this, but you may be able to set a break point in the page's constructor to see the ::Controls[] list before anything is created, which I would expect to be empty (but the page life cycle link I've provided below will have a better explanation).

See this link or this one.

Body:
I am thinking about the asp.net 2.0 code behind model.

After I drag a button onto my Default.aspx page, I got the following declaration in my Default.aspx.designer.cs file:

public partial class _Default {

    protected global::System.Web.UI.HtmlControls.HtmlForm form1;

    protected global::System.Web.UI.WebControls.Button Button1;
}

And now it's OK for me to write the following code in Default.aspx.cs file:

protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Text = "clicked!";
}

But I am wondering, what I got is nothing but a declaration of Button1 variable of Button type, it hasn't been instanciated, how could this code run without trigging a Null Reference Exception?

I think there must exist some code like this somewhere:

Button1 = new Button();

But where is this code? When is this code executed? Who executes it?

Many thanks...

Update - 1 - 21:17 12/15/2010

I found 2 auto-generated file in a mysterious location C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\edd9f4a1\7f113408, they are:

App_Web_x_swwj6s.1.cs
App_Web_x_swwj6s.0.cs

I found code like below in the App_Web_x_swwj6s.0.cs file:

        private global::System.Web.UI.WebControls.Button @__BuildControlButton1()
         {
            global::System.Web.UI.WebControls.Button @__ctrl;
            @__ctrl = new global::System.Web.UI.WebControls.Button();
            //....
            this.Button1 = @__ctrl;
            return @__ctrl;
          }

And this method is invoked in the below code:

private global::System.Web.UI.HtmlControls.HtmlForm @__BuildControlform1()
{
  //....
  global::System.Web.UI.WebControls.Button @__ctrl1;

  @__ctrl1 = this.@__BuildControlButton1();
  //......
}

And finally the above code is invoked in the following method:

protected override void FrameworkInitialize()

So I believed that the FrameworkInitialize() method is the one who did the dirty job of bind the control reference to a control instance.

To prove this, I intentionally wrote the following code in my code-behind file:

protected override void FrameworkInitialize()
{
    this.Button1 = null;
}

I hope there would be a Null Reference Exception when I click the button, but strange enough, the whole web site run smoothly.

Is it true that all the controls I declared in the aspx file are created with the FrameworkInitialize() method? Why there's no Null Reference Exception in the above scenario?

Many thanks again.

Update - 2 - 21:43 12/15/2010

I think I may find the explanation, I checked the final page class generated by ASP.NET with .NET reflector. Its deriving relation is like this:

default_aspx class (The ultimate class representing the page)<--- _Default class (the code behind class) <--- System.Web.UI.Page

And in the default_aspx class, I found this:

protected override void FrameworkInitialize()
{
    base.FrameworkInitialize();  // Button1=null is executed here.
    this.__BuildControlTree(this); // Here Button1 is STILL set to an instance.
    base.AddWrappedFileDependencies(__fileDependencies);
    base.Request.ValidateInput();
}

So, this could explain why my intention to set the Button1 to null failed.

Now, my question is, does the FrameworkInitialize() method has to be called at the very beginning of a page's life cycle so that we could use the control on the page afterwards.

Update - 3 - 3:45 PM 12/16/2010

From here:

Once the HTTP page handler class is
  fully identified, the ASP.NET run time
  calls the handler's ProcessRequest
  method to process the request.
  Normally, there is no need to change
  the implementation of the method as it
  is provided by the Page class.

This implementation begins by calling
  the method FrameworkInitialize, which
  builds the controls tree for the page.
  The method is a protected and virtual
  member of the TemplateControl
  class—the class from which Page itself
  derives. Any dynamically generated
  handler for an .aspx resource
  overrides FrameworkInitialize. In this
  method, the whole control tree for the
  page is built.

A bounty is started for your precious comments. :)


问:
JQUERY: How to reduce code if i have multiple fields that i control validation
For example i have 3 function that i control the keydown of each field; at the end i control the same so i want to put the 3 fields with code 1 time only.</p>

```<code>ens_q_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_q_cal.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_t_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});
</code>```

答:
Create a function:

```<code>function validate(event) {
  if (event.shiftKey == true) {
            event.preventDefault();
        }

        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

        } else {
            event.preventDefault();
        }

        if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
            event.preventDefault();
}
</code>```

And pass it to the event:

```<code>ens_t_frio.keydown(validate);
</code>```

Do the same thing for other inputs.

Body:
For example i have 3 function that i control the keydown of each field; at the end i control the same so i want to put the 3 fields with code 1 time only.

ens_q_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_q_cal.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_t_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

Body:
Create a function:

function validate(event) {
  if (event.shiftKey == true) {
            event.preventDefault();
        }

        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

        } else {
            event.preventDefault();
        }

        if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
            event.preventDefault();
}

And pass it to the event:

ens_t_frio.keydown(validate);

Do the same thing for other inputs.


问:
Liferay IDE Alternatives
I am using Liferay Developer Studio for theme development and as a frontend developer, I am not impress with the tool's performance.

Below are few reasons I am looking for alternative IDE, compatible for Liferay development.

It occupies more than 75% of the memory

It slower down the whole system

I cannot use chat application while running IDE as to switch from one app to another takes irrelevant time

I use to build theme through CLI. Sometime I need to close the IDE or else it gives runtime error and doesn't build the theme.

I am sure there are many others too faced same issues, which actually makes the development slower. This question is not against the Liferay of course, it's a great enterprise level CMS tool. But yes looking for alternate IDE with best compatibility for the purpose.

Thanks in advance.

答:
You can use Gulp and Yo to generate, build and deploy your theme or layout  , and you can use Notepad ++ as editor.

Please refere to those links :

1 - LIFERAY theme generator

2 - Gulp Tasks

Title: Liferay IDE Alternatives


问:
Where is the angular-cli package directory?
I'm trying to create a new Angular CLI project stub as instructed in the IntelliJ docs here Generating an Angular application stub using Angular CLI. One of the mandatory fields asks for the Angular CLI package directory.

I have no idea what this is or where to find this.

答:
As it's written in https://www.jetbrains.com/help/idea/2017.1/using-angular.html#d461255e133, you need to install angular-cli module first: npm install -g @angular/cli.

Once the package is installed, specify a path to it in Angular CLI field. In your environment, it should be smth like C:\Users\andyrh3\AppData\Roaming\npm\node_modules\@angular\cli


问:
Using Angular to authenticate users API
I am building a web application in Angular ( Im new to Angular).

I building a form to pass new user info to the third party software via API end point.

to post data I need to pass name(new user) email(new user) user_key(mine) and api_key (changes evry hour)

To get the new api_key I need to Post

```<code>POST: https://pi.pardot.com/api/login/version/3
message body: email=<email>&password=<password>&user_key=<user_key>
</code>```

and this returns

```<code><rsp stat="ok" version="1.0">
    <api_key><api_key here></api_key>
</rsp>
</code>```

Once I have the new Key I can pass it with the form post to post data.

Question

I think Ill need to have a function that runs before the Posting of data that dose the post to get the new api_keyand changes the api_key variable on my new user post.

so the main question is how do I do this with angular, I have added my current post controller bellow that post the new user data.

My controller

```<code>// submit button controller POST
// =============================================================================
FirstModule.controller('formController', function ($scope, $http) {
    $scope.formData = {};

    $scope.processForm = function (Fname, Lname, email) {
        var data = {
            Fname: $scope.formData.Fname,
            Lname: $scope.formData.Lname,
            email: $scope.formData.email,
            api_key: 'changes every hr', //needs to be dynamic
            user_key: 'my key'
        };

//Call the services
        $http.post('https://some api.com/api/prospect/version/4/do/create', JSON.stringify(data)).then(function (response) {
            if (response.data)
                $scope.formData = "Post Data Submitted Successfully!";

        }, function (response) {
            $scope.formData = "Post Data Submitted Failed";
            $scope.statusval = response.status;
            $scope.statustext = response.statusText;
            $scope.headers = response.headers();
        });
    };
});
</code>```

My form

```<code><form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2"
                  ng-submit="processForm()"
                  ng-click="postdata(formData)">

                <!-- our nested state views will be injected here -->
                <div id="form-views" ui-view></div>
            </form>
</code>```

So this part is Ok, but how do I run a function before this runs so I get the latest api_key ? and more importantly how can I do it safe ?

The API is Pardot

For security should I place all; API request on a backed script maybe node ?

答: you can try to use app.run() and write the function in that. app.run() will always run before your controller. Here is one link you can check AngularJS app.run() documentation?</p>

Title: Using Angular to authenticate users API

Body:
I am building a web application in Angular ( Im new to Angular).

I building a form to pass new user info to the third party software via API end point.

to post data I need to pass name(new user) email(new user) user_key(mine) and api_key (changes evry hour)

To get the new api_key I need to Post

POST: https://pi.pardot.com/api/login/version/3
message body: email=<email>&password=<password>&user_key=<user_key>

and this returns

<rsp stat="ok" version="1.0">
    <api_key><api_key here></api_key>
</rsp>

Once I have the new Key I can pass it with the form post to post data.

Question

I think Ill need to have a function that runs before the Posting of data that dose the post to get the new api_keyand changes the api_key variable on my new user post.

so the main question is how do I do this with angular, I have added my current post controller bellow that post the new user data.

My controller

// submit button controller POST
// =============================================================================
FirstModule.controller('formController', function ($scope, $http) {
    $scope.formData = {};

    $scope.processForm = function (Fname, Lname, email) {
        var data = {
            Fname: $scope.formData.Fname,
            Lname: $scope.formData.Lname,
            email: $scope.formData.email,
            api_key: 'changes every hr', //needs to be dynamic
            user_key: 'my key'
        };

//Call the services
        $http.post('https://some api.com/api/prospect/version/4/do/create', JSON.stringify(data)).then(function (response) {
            if (response.data)
                $scope.formData = "Post Data Submitted Successfully!";

        }, function (response) {
            $scope.formData = "Post Data Submitted Failed";
            $scope.statusval = response.status;
            $scope.statustext = response.statusText;
            $scope.headers = response.headers();
        });
    };
});

My form

<form name="myForm" id="signup-form" class="col-sm-8 col-sm-offset-2"
                  ng-submit="processForm()"
                  ng-click="postdata(formData)">

            </form>

So this part is Ok, but how do I run a function before this runs so I get the latest api_key ? and more importantly how can I do it safe ?

The API is Pardot

For security should I place all; API request on a backed script maybe node ?


答: Have the argument of keydown as a separate function and then just pass it instead. You can also use forEach if your fields are in an array</p>

Title: JQUERY: How to reduce code if i have multiple fields that i control validation


问:
Converting <select></option> in  links (Ajax)
My ajax script is working fine with this:

```<code><head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","y.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>
</code>```

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

```<code><div onchange="showUser(this.value)">
<a value="1" href="">1</a>
<a value="2" href="">2</a>
<a value="3" href="">3</a>
</div>
</code>```

How to change them? I need them for pagination.

答:
```<code><div class="paging">
                <a value="1" href="#" >1</a>
                <a value="2" href="#" >2</a>
                <a value="3" href="#" >3</a>
            </div>
     <script>
        $('.paging').find('a').click(function () {
            alert($(this).attr("value"));
        });

        </script>
</code>```

Body:
My ajax script is working fine with this:

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

1
2
3

How to change them? I need them for pagination.