问:
angular dirpagination - get current page
I use dirpagination in my angular app to have pagination for my search results. I'm trying to create a dynamic title for the page based on search words and selected page.

```<code><h2 class="page-title">{{app.set_page_title()}} - page {{app.pagination.current}}</h2>
</code>```

The problem is I can't get the current page from dirpagination. Any idea how to do it?

Update:

```<code>  <div class="search-item"
       dir-paginate="item in app.get_results() | itemsPerPage: app.items_per_page">
    <div class="item">
      Lorem ipsum item
    </div>
  </div>
  <div class="pull-left pagination-controls">
    <dir-pagination-controls></dir-pagination-controls>
  </div>
</code>```

And this is my app structure:

```<code>angular.module('searchApp',
               ['ngRoute','angularUtils.directives.dirPagination'])
  .controller('searchController', function($scope, $rootScope, $location) {
    var app = this;

    app.set_page_title = function() {
      // Set the page title
      return "Bla bla";
    }

  });
</code>```

答:
Solved with:
- in my controller:

```<code>app.current_page = 1;
</code>```

and then in my template:

```<code><h2 class="page-title">{{app.set_page_title()}} - page {{app.current_page}}</h2>

<div class="search-item" dir-paginate="item in app.get_results() | itemsPerPage: app.items_per_page" current-page="app.current_page">
</code>```

Body:
I use dirpagination in my angular app to have pagination for my search results. I'm trying to create a dynamic title for the page based on search words and selected page.

{{app.set_page_title()}} - page {{app.pagination.current}}

The problem is I can't get the current page from dirpagination. Any idea how to do it?

Update:

      Lorem ipsum item

    <dir-pagination-controls></dir-pagination-controls>

And this is my app structure:

angular.module('searchApp',
               ['ngRoute','angularUtils.directives.dirPagination'])
  .controller('searchController', function($scope, $rootScope, $location) {
    var app = this;

    app.set_page_title = function() {
      // Set the page title
      return "Bla bla";
    }

  });

Body:
Solved with:
- in my controller:

app.current_page = 1;

and then in my template:

<h2 class="page-title">{{app.set_page_title()}} - page {{app.current_page}}</h2>

<div class="search-item" dir-paginate="item in app.get_results() | itemsPerPage: app.items_per_page" current-page="app.current_page">


来源: stackexchange

问:
Execute parser methods wihout the main method
When I try to invoke parserAction()  method  inside an another servlet class  I'm getting a blank array. I cant print the nouns inside my servlet. But inside this class with the MAIN METHOD noun array is printing correctly. What is the reason for this ?

```<code>    package com.books.servlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import com.sun.corba.se.impl.orb.ParserAction;

import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;

public class ParserTest {

    public static Set<String> nounPhrases = new HashSet<>();

    public String line = "I need the java book";

    public void getNounPhrases(Parse p) {
        if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
                || p.getType().equals("NNPS")) {
            nounPhrases.add(p.getCoveredText());
            // System.out.println(p.getCoveredText());
        }

        for (Parse child : p.getChildren()) {
            getNounPhrases(child);

        }
    }

    public  void parserAction() throws Exception {
        InputStream is = new FileInputStream("en-parser-chunking.bin");
        ParserModel model = new ParserModel(is);
        Parser parser = ParserFactory.create(model);
        Parse topParses[] = ParserTool.parseLine(line, parser, 1);
        for (Parse p : topParses) {
            // p.show();
            getNounPhrases(p);
        }
    }

      public static void main(String[] args) throws Exception {
          new ParserTest().parserAction();
          System.out.println("List of Noun Parse : "+nounPhrases);

         }

    }
</code>```

Below is my sample servlet class. It shows me a blank array with []

```<code>    public class test extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 .......
 .......
 .......
ParserTest pt = new ParserTest();
 pt.parserAction();

 System.out.println("List of Noun Parse : "+pt.nounPhrases);
 System.out.println("List of Noun Parse : "+ParserTest.nounPhrases);
}
}
</code>```

Here I need to extract nouns without executing a main method. Since I'm developing a web application. I need to show these extracted nouns inside one of my servlet class.

答:
You need to write what you want in the response, for example by doing:

```<code>response.getWriter().println("Whatever you want to write in the response");
</code>```

But first I would suggest to read some good Java books as your code is not very good, also servlets are an old way of doing Java web application, nowadays people use other technologies, like templates using JSP or JSF, JAX-RS for REST applications, JAX-WS for SOAP applications, ...

ContentLicense: CC BY-SA 3.0

Body:
When I try to invoke parserAction()  method  inside an another servlet class  I'm getting a blank array. I cant print the nouns inside my servlet. But inside this class with the MAIN METHOD noun array is printing correctly. What is the reason for this ?

    package com.books.servlet;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import com.sun.corba.se.impl.orb.ParserAction;

import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;

public class ParserTest {

    public static Set<String> nounPhrases = new HashSet<>();

    public String line = "I need the java book";

    public void getNounPhrases(Parse p) {
        if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
                || p.getType().equals("NNPS")) {
            nounPhrases.add(p.getCoveredText());
            // System.out.println(p.getCoveredText());
        }

        for (Parse child : p.getChildren()) {
            getNounPhrases(child);

        }
    }

    public  void parserAction() throws Exception {
        InputStream is = new FileInputStream("en-parser-chunking.bin");
        ParserModel model = new ParserModel(is);
        Parser parser = ParserFactory.create(model);
        Parse topParses[] = ParserTool.parseLine(line, parser, 1);
        for (Parse p : topParses) {
            // p.show();
            getNounPhrases(p);
        }
    }

      public static void main(String[] args) throws Exception {
          new ParserTest().parserAction();
          System.out.println("List of Noun Parse : "+nounPhrases);

         }

    }

Below is my sample servlet class. It shows me a blank array with []

    public class test extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 .......
 .......
 .......
ParserTest pt = new ParserTest();
 pt.parserAction();

 System.out.println("List of Noun Parse : "+pt.nounPhrases);
 System.out.println("List of Noun Parse : "+ParserTest.nounPhrases);
}
}

Here I need to extract nouns without executing a main method. Since I'm developing a web application. I need to show these extracted nouns inside one of my servlet class.

Body:
You need to write what you want in the response, for example by doing:

response.getWriter().println("Whatever you want to write in the response");

But first I would suggest to read some good Java books as your code is not very good, also servlets are an old way of doing Java web application, nowadays people use other technologies, like templates using JSP or JSF, JAX-RS for REST applications, JAX-WS for SOAP applications, ...


问:
How do I know an item is a directory while looping over zipfile in Python?
Doing something like this:

```<code>from zipfile import ZipFile

#open zip file
zipfile = ZipFile('Photo.zip')

#iterate zip contents
for zipinfo in zipfile.filelist:
    #do something
    filepath, filename = path.split(zipinfo.filename)
</code>```

How do I know if zipinfo is a file or a directory?

答:
Starting with Python 3.6 there is a ZipInfo.is_dir() method.

```<code>with zipfile.ZipFile(zip_file) as archive:
    for file in archive.namelist():
        file_info = archive.getinfo(file)
        if file_info.is_dir():
            # do something
</code>```

See the Python 3.6 docs for details.

ContentLicense: CC BY-SA 4.0

Body:
Doing something like this:

from zipfile import ZipFile

#open zip file
zipfile = ZipFile('Photo.zip')

#iterate zip contents
for zipinfo in zipfile.filelist:
    #do something
    filepath, filename = path.split(zipinfo.filename)

How do I know if zipinfo is a file or a directory?

Body:
Starting with Python 3.6 there is a ZipInfo.is_dir() method.

with zipfile.ZipFile(zip_file) as archive:
    for file in archive.namelist():
        file_info = archive.getinfo(file)
        if file_info.is_dir():
            # do something

See the Python 3.6 docs for details.


问:
CSS Text Shadow Opacity
I have some text with the following css:

```<code>.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0 1px 0 black;
}
</code>```

As you can see, it has a black shadow.

Question

Is it possible to make the shadow opaque?

Thanks

答:
Use of rgba(0,0,0,0.2); or hsla(0,0%,0%,0.2)

```<code> .text-description-header {
        font-size: 250%;
        color: white;
        text-shadow: 0 1px 0 rgba(0,0,0,0.2);
}
</code>```

Title: CSS Text Shadow Opacity

Body:
I have some text with the following css:

.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0 1px 0 black;
}

As you can see, it has a black shadow.

Question

Is it possible to make the shadow opaque?

Thanks

Body:
Use of rgba(0,0,0,0.2); or hsla(0,0%,0%,0.2)

 .text-description-header {
        font-size: 250%;
        color: white;
        text-shadow: 0 1px 0 rgba(0,0,0,0.2);
}


问:
Cursor returns null when getting filepath from URI
```<code>Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();
</code>```

cursor.getString(columnIndex) Returns Null
Where as the selectedImage is not null.

Any suggestion on how I can create file from URI?

答:
Cursor returns null when getting filepath from URI

A Uri is not a file. A Uri does not have to point to a file, let alone a file on the filesystem that you can access.

Any suggestion on how I can create file from URI?

Use ContentResolver and openInputStream() to get an InputStream on the content identified the Uri. Ideally, just use that InputStream directly. If, for some reason, you truly need a file:

Create a FileOutputStream on some file that you control (e.g., in getCacheDir())

Copy the bytes from the InputStream to the FileOutputStream

Use the file that you just created, deleting it when you are done

Body:
Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            // Get the cursor
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            // Move to first row
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            imgDecodableString = cursor.getString(columnIndex);
            cursor.close();

cursor.getString(columnIndex) Returns Null
Where as the selectedImage is not null.

Any suggestion on how I can create file from URI?


问:
increment is not happening in for loop in c
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

```<code>#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main
</code>```

And this is the output:

```<code>year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000
</code>```

I made this program in Eclipse, in ubuntu mate.

答:
You're using integer division when you do 10/100, so rather than returning 0.1, it's actually truncating to 0. Thus, you're setting popatend to zero every loop (popatend = pop * 0), and effectively adding zero to pop every time.

To fix this, you could either cast or change the types ofpop and popatend, or use 10f/100f.

Body:
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main

And this is the output:

year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000

I made this program in Eclipse, in ubuntu mate.


问:
How to edit category.php template so it will display all post of specific category?
I have a simple wordpres category post loop in category.php template like this :

```<code><?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $postid = get_the_ID();?>
</code>```

How to change post limit ? Because now i get only ten posts per category. I'm using one template for all categories. I'm new to wordpres and trying to make my first custom template :)

答:
To display all posts on a category template you have override its default display per posts which is 10. Please refer following code:

```<code>$args = array('posts_per_page' => -1);
$the_query = new WP_Query($args);

while ( $the_query->have_posts() ) {
    $the_query->the_post();
    /** Your code here **/
}
</code>```

Displaying all the posts on a template is not a good practice, instead I will recommend to display 10 posts per page and show pagination.

Reference for Pagination: https://codex.wordpress.org/Pagination

Body:
I have a simple wordpres category post loop in category.php template like this :

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); $postid = get_the_ID();?>

How to change post limit ? Because now i get only ten posts per category. I'm using one template for all categories. I'm new to wordpres and trying to make my first custom template :)

Body:
To display all posts on a category template you have override its default display per posts which is 10. Please refer following code:

$args = array('posts_per_page' => -1);
$the_query = new WP_Query($args);

while ( $the_query->have_posts() ) {
    $the_query->the_post();
    /** Your code here **/
}

Displaying all the posts on a template is not a good practice, instead I will recommend to display 10 posts per page and show pagination.

Reference for Pagination: https://codex.wordpress.org/Pagination


问:
Call actual function from blur()
I'm trying to write some jquery that will call a function when an object is blurred.  Because of some of the requirement in my underlying code, I need to call a function, like this:

```<code>$("object").blur(myFunction());
</code>```

instead of like this:

```<code>$("object").blur(function() {
  //do stuff
});
</code>```

Unfortunately, binding the blur event using the first method doesn't work.  It actually runs the method on page load, and then never binds the function.  What am I doing wrong here?

I've set up a jsfiddle that demonstrates my problem, if it helps you visualize. http://jsfiddle.net/WskKJ/

答:
```<code>$("object").blur(myFunction);
</code>```

dont use () when u pass a delegate

ContentLicense: CC BY-SA 2.5

Title: Call actual function from blur()

Body:
I'm trying to write some jquery that will call a function when an object is blurred.  Because of some of the requirement in my underlying code, I need to call a function, like this:

$("object").blur(myFunction());

instead of like this:

$("object").blur(function() {
  //do stuff
});

Unfortunately, binding the blur event using the first method doesn't work.  It actually runs the method on page load, and then never binds the function.  What am I doing wrong here?

I've set up a jsfiddle that demonstrates my problem, if it helps you visualize. http://jsfiddle.net/WskKJ/

Body:
$("object").blur(myFunction);

dont use () when u pass a delegate


问:
Can I use the feature plugin today for my installable app only?
I want to start modularizing my project but haven't worked out the use-cases for my instant app yet. Can I start refactoring my code using com.android.feature plugin for my installable app today and build my instant app later when I'm ready with product features that I want to ship as an instant app.</p>

答: Yes, You can. In fact it is good to start refactoring your code from now if your are planning to make an instant version of your app in future. Till then you can use feature module as a library .aar in your application module. And when you decide to make an instant app just add that feature module to instant app. That's it. It's Always good to do it now than later on.</p>


问:
Adding multiple tree Branches and leafs in javafx
hi i post this question before but didn't get any answer.  Adding tree Branches and leafs in TreeView

i need help, Please have a look at code,

```<code>public class Main extends Application
{
    private BorderPane border;
    @Override
    public void start(Stage primaryStage)
    {
        border = new BorderPane();
        Scene scene = new Scene(border,200,200);
        primaryStage.setTitle("BorderPane");
        primaryStage.setScene(scene);
        primaryStage.show();

        TreeItem<String> tree = new TreeItem<String>("Root");
        TreeItem<String> item1 = new TreeItem<String>("Branch");
        item1.getChildren().add(new TreeItem<String>("Leaf"));
        item1.setExpanded(true);
        tree.setExpanded(true);
        tree.getChildren().addAll(item1);
        TreeView<String> treeView  = new TreeView<String>(tree);

        treeView.setEditable(true);
        treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
            @Override
            public TreeCell<String> call(TreeView<String> arg0) {
                return new AddMenuTreeCell();
            }
        });

        VBox vbox =new VBox(2);
        vbox.setPadding(new Insets(5));
        VBox.setVgrow(treeView, Priority.ALWAYS);
        vbox.getChildren().addAll(treeView);
        border.setLeft(vbox);
    }

    private static class AddMenuTreeCell extends TextFieldTreeCell<String> {
        private ContextMenu menu = new ContextMenu();
        private TextField textField;
        public AddMenuTreeCell() {

            MenuItem addItem1 = new MenuItem("Insert Branch");
            MenuItem addItem2 = new MenuItem("Insert Leaf");
            menu.getItems().addAll(addItem1,addItem2);
            addItem1.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    TreeItem<String> newBranch =
                            new TreeItem<String>("Brunch");
                                getTreeItem().getChildren().add(newBranch);
                }
            });
            addItem2.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    TreeItem<String> newLeaf =
                            new TreeItem<String>("leaf");
                                getTreeItem().getChildren().add(newLeaf);
                }
            });
        }

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
                    if (!empty && getTreeItem().getParent() == null){
                        setContextMenu(menu);
                    }
                }
        }
}
</code>```

With this user can add multiple Branches and Leafs.

But the problem is, if user add a Branch it should be like "Branch1" next added branch should be "Branch2", "Branch3",...... same for leafs added in any branch have their numbers.

So that later on user can assign different task to different branches and leafs.

Thank you!

答:
Replace AddMenuTreeCell class to below code and try now</p>

```<code>private static class AddMenuTreeCell extends TextFieldTreeCell<String> {
    private ContextMenu menu = new ContextMenu();
    private TextField textField;
    int i = 1, j = 1;

    public AddMenuTreeCell() {
        MenuItem addItem1 = new MenuItem("Insert Branch");
        MenuItem addItem2 = new MenuItem("Insert Leaf");
        menu.getItems().addAll(addItem1, addItem2);

        addItem1.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {

                TreeItem<String> newBranch = new TreeItem<String>("Brunch" + i);
                getTreeItem().getChildren().add(newBranch);
                i++;
            }
        });
        addItem2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                TreeItem<String> newLeaf = new TreeItem<String>("leaf" + j);
                getTreeItem().getChildren().add(newLeaf);
                j++;
            }
        });
        setContextMenu(menu);
    }
}
</code>```

Body:
hi i post this question before but didn't get any answer.  Adding tree Branches and leafs in TreeView

i need help, Please have a look at code,

public class Main extends Application
{
    private BorderPane border;
    @Override
    public void start(Stage primaryStage)
    {
        border = new BorderPane();
        Scene scene = new Scene(border,200,200);
        primaryStage.setTitle("BorderPane");
        primaryStage.setScene(scene);
        primaryStage.show();

        TreeItem<String> tree = new TreeItem<String>("Root");
        TreeItem<String> item1 = new TreeItem<String>("Branch");
        item1.getChildren().add(new TreeItem<String>("Leaf"));
        item1.setExpanded(true);
        tree.setExpanded(true);
        tree.getChildren().addAll(item1);
        TreeView<String> treeView  = new TreeView<String>(tree);

        treeView.setEditable(true);
        treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
            @Override
            public TreeCell<String> call(TreeView<String> arg0) {
                return new AddMenuTreeCell();
            }
        });

        VBox vbox =new VBox(2);
        vbox.setPadding(new Insets(5));
        VBox.setVgrow(treeView, Priority.ALWAYS);
        vbox.getChildren().addAll(treeView);
        border.setLeft(vbox);
    }

    private static class AddMenuTreeCell extends TextFieldTreeCell<String> {
        private ContextMenu menu = new ContextMenu();
        private TextField textField;
        public AddMenuTreeCell() {

            MenuItem addItem1 = new MenuItem("Insert Branch");
            MenuItem addItem2 = new MenuItem("Insert Leaf");
            menu.getItems().addAll(addItem1,addItem2);
            addItem1.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    TreeItem<String> newBranch =
                            new TreeItem<String>("Brunch");
                                getTreeItem().getChildren().add(newBranch);
                }
            });
            addItem2.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent arg0) {
                    TreeItem<String> newLeaf =
                            new TreeItem<String>("leaf");
                                getTreeItem().getChildren().add(newLeaf);
                }
            });
        }

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
                    if (!empty && getTreeItem().getParent() == null){
                        setContextMenu(menu);
                    }
                }
        }
}

With this user can add multiple Branches and Leafs.

But the problem is, if user add a Branch it should be like "Branch1" next added branch should be "Branch2", "Branch3",...... same for leafs added in any branch have their numbers.

So that later on user can assign different task to different branches and leafs.

Thank you!

Body:
Replace AddMenuTreeCell class to below code and try now

private static class AddMenuTreeCell extends TextFieldTreeCell<String> {
    private ContextMenu menu = new ContextMenu();
    private TextField textField;
    int i = 1, j = 1;

    public AddMenuTreeCell() {
        MenuItem addItem1 = new MenuItem("Insert Branch");
        MenuItem addItem2 = new MenuItem("Insert Leaf");
        menu.getItems().addAll(addItem1, addItem2);

        addItem1.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {

                TreeItem<String> newBranch = new TreeItem<String>("Brunch" + i);
                getTreeItem().getChildren().add(newBranch);
                i++;
            }
        });
        addItem2.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                TreeItem<String> newLeaf = new TreeItem<String>("leaf" + j);
                getTreeItem().getChildren().add(newLeaf);
                j++;
            }
        });
        setContextMenu(menu);
    }
}


答:
Specify the color in RGBA (Red,Green,Blue,Alpha)

Where Alpha is the opacity (0 - 1)

Something like:

```<code>text-shadow: 0 1px 0 rgba(0,0,0,0.5);
</code>```

For half transparent black shadow.

Title: CSS Text Shadow Opacity

Body:
Specify the color in RGBA (Red,Green,Blue,Alpha)

Where Alpha is the opacity (0 - 1)

Something like:

text-shadow: 0 1px 0 rgba(0,0,0,0.5);

For half transparent black shadow.


问:
why data is not inserting to database?
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

```<code><html>
<head>
    <title>create menu</title>
</head>
<h1 align="center">create menu</h1>
<h2 align="center">Dont create more than 7 menu</h2><br/><br/>
<form method="post">
    <table border="2px" width="500px">
        <tr>
            <th colspan="2" align="center">create menu</th>
        </tr>
        <tr>
            <td align="right">menu name</td>
            <td><input type="text" name="menu"></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" name="submit" value="create"></td>
        </tr>
    </table>
</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "<h1 align='center'>DATA INSERTED</h1>";
    }
    else{
        echo "<h1>data not inserted</h1>";
    }
}
?>
</code>```

where am i wrong please help data is not inserting to database

答:
you can do like this, for your php code</p>

<p>```</p>

<code><?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "coupons";

try{

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query=$conn->prepare("INSERT INTO menu( item) VALUES( :menu)");
    $query->bindParam(':menu',$menu);
    $menu=$_POST['menu'];

    $query->execute();

    echo "<h1 align='center'>DATA INSERTED</h1>";
        }
    catch(PDOException $e)
        {
    // roll back the transaction if something failed
    $conn->rollback();
    echo "Error: " . $e->getMessage();
    echo "<h1>data not inserted</h1>";
        }

    $conn = null;
    ?>
</code>```

Title: why data is not inserting to database?

Body:
i am using php for inserting data in in mysql database. i am new to php and also mysql please help

    <title>create menu</title>

create menu

Dont create more than 7 menu

<form method="post">

            create menu

            menu name
            <input type="text" name="menu">

            <input type="submit" name="submit" value="create">

</form>
<?php
mysql_connect("localhost","root","");
mysql_select_db("coupons");
if(isset($_POST['submit'])){
    $menu=$_POST['menu'];
    $query = "insert into menu(item) values ('$menu')";
    if(mysql_query($query)){
        echo "
DATA INSERTED
";
    }
    else{
        echo "
data not inserted
";
    }
}
?>

where am i wrong please help data is not inserting to database

Body:
you can do like this, for your php code

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "coupons";

try{

    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query=$conn->prepare("INSERT INTO menu( item) VALUES( :menu)");
    $query->bindParam(':menu',$menu);
    $menu=$_POST['menu'];

    $query->execute();

    echo "<h1 align='center'>DATA INSERTED</h1>";
        }
    catch(PDOException $e)
        {
    // roll back the transaction if something failed
    $conn->rollback();
    echo "Error: " . $e->getMessage();
    echo "<h1>data not inserted</h1>";
        }

    $conn = null;
    ?>


问:
Foreach loop in CodeIgniter
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

```<code>class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}
</code>```

This is my model file:

```<code><?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}
</code>```

this is my view:

```<code><?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>
</code>```

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

答:
You have to pass $data with the view. </p>

```<code>$this->load->view('allecadeaus',$data);
</code>```

Title: Foreach loop in CodeIgniter

Body:
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}

This is my model file:

<?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

Body:
You have to pass $data with the view.

$this->load->view('allecadeaus',$data);


问:
How to convert all arguments to dictionary in python
I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

```<code>func(arg1, arg2, arg3=value3, arg4=value4)
</code>```

should return one dictionary like this:

```<code>{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }
</code>```

答:
You can use locals() or vars():

```<code>def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}
</code>```

However if you only use *args you will not be able to differentiate them using locals():

```<code>def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}
</code>```

Body:
I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }

Body:
You can use locals() or vars():

def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}

However if you only use *args you will not be able to differentiate them using locals():

def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}


问:
Form Authentication with wrong credentials leads to HTTP 405 (Method Not Allowed)
I have a Spring web application which should be protected by Form Authentication (I cannot use Spring Security for some reasons).

If I request a protected resource I will be redirected to the login form and can enter the credentials. When the credentials are correct, I will be redirected to the requestet resource. Everything like it should be.

But when I enter wrong credentials I get a HTTP 405 message, not the error page. Why?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Authentication</web-resource-name>
            <url-pattern>/test/auth/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>users</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.html</form-login-page>
            <form-error-page>/loginerror.html</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <role-name>users</role-name>
    </security-role>

</web-app>
```

<p><strong>login.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

<form method="post" action="j_security_check">
    <table>
        <tr>
            <td colspan="2">Please type in your user name and password</td>
        </tr>
        <tr>
            <td>Name:</td>
            <td><input type="text" name="j_username" width="40"/></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name="j_password" /></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Login" /></td>
        </tr>
    </table>
</form>

</body>
</html>
</code>```

loginerror.html

<!DOCTYPE html>

error!

```

<p><strong>Log</strong></p>

<pre class="lang-none prettyprint-override"><code>WARN [http-nio-8080-exec-79] o.s.web.servlet.PageNotFound: Request method 'POST' not supported
</code>```

Controller

@RestController
@RequestMapping("/test")
public class TestController {

    private final static Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        printAuth();
        return "test";
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.GET)
    public String testAuth() {
        printAuth();
        return "testAuth";
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.GET)
    public String testAuth2() {
        printAuth();
        return "testAuth2";
    }

    private void printAuth() {
        Principal principal = request.getUserPrincipal();
        LOG.debug("Request: " + request);
        LOG.debug("Principal: " + principal);
        LOG.debug("Principal name :" + principal.getName());
        LOG.debug("User in Role 'users': " + request.isUserInRole("users"));
    }

}
```

Update:

I tried the same authentication with a spimple "non Spring" application and it works fine. So I assume that the Spring servlet "catches" the request somehow. Is it possible to avoid that?

答:
From wiki:

405 Method Not Allowed: A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

All you have to do is to change your controller RequestMethod from GET to POST

You can't Post an HTTP form + try to handle it using GET method.

something like this:

```<code>@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test() {
      ...
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.POST)
    public String testAuth() {
      ...
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.POST)
    public String testAuth2() {
       ...
    }

}
</code>```

According to your image:

You are obviously trying to POST your form to this URL: /test/auth

And according to your controller code:

```<code>@RequestMapping(value = "/auth/test", method = RequestMethod.GET)
public String testAuth() {
    printAuth();
    return "testAuth";
}
</code>```

You are using GET and it's wrong to do, Try to change it to POST.

Body:
I have a Spring web application which should be protected by Form Authentication (I cannot use Spring Security for some reasons).

If I request a protected resource I will be redirected to the login form and can enter the credentials. When the credentials are correct, I will be redirected to the requestet resource. Everything like it should be.

But when I enter wrong credentials I get a HTTP 405 message, not the error page. Why?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Authentication</web-resource-name>
            <url-pattern>/test/auth/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>users</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.html</form-login-page>
            <form-error-page>/loginerror.html</form-error-page>
        </form-login-config>
    </login-config>

    <security-role>
        <role-name>users</role-name>
    </security-role>

</web-app>

login.html

<!DOCTYPE html>

<form method="post" action="j_security_check">

            Please type in your user name and password

            Name:
            <input type="text" name="j_username" width="40"/>

            Password:
            <input type="password" name="j_password" />

            <input type="submit" value="Login" />

</form>

loginerror.html

<!DOCTYPE html>

error!

Log

WARN [http-nio-8080-exec-79] o.s.web.servlet.PageNotFound: Request method 'POST' not supported

Controller

@RestController
@RequestMapping("/test")
public class TestController {

    private final static Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        printAuth();
        return "test";
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.GET)
    public String testAuth() {
        printAuth();
        return "testAuth";
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.GET)
    public String testAuth2() {
        printAuth();
        return "testAuth2";
    }

    private void printAuth() {
        Principal principal = request.getUserPrincipal();
        LOG.debug("Request: " + request);
        LOG.debug("Principal: " + principal);
        LOG.debug("Principal name :" + principal.getName());
        LOG.debug("User in Role 'users': " + request.isUserInRole("users"));
    }

}

Update:

I tried the same authentication with a spimple "non Spring" application and it works fine. So I assume that the Spring servlet "catches" the request somehow. Is it possible to avoid that?

Body:
From wiki:

405 Method Not Allowed: A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

All you have to do is to change your controller RequestMethod from GET to POST

You can't Post an HTTP form + try to handle it using GET method.

something like this:

@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test() {
      ...
    }

    @RequestMapping(value = "/auth/test", method = RequestMethod.POST)
    public String testAuth() {
      ...
    }

    @RequestMapping(value = "/auth/test2", method = RequestMethod.POST)
    public String testAuth2() {
       ...
    }

}

According to your image:

You are obviously trying to POST your form to this URL: /test/auth

And according to your controller code:

@RequestMapping(value = "/auth/test", method = RequestMethod.GET)
public String testAuth() {
    printAuth();
    return "testAuth";
}

You are using GET and it's wrong to do, Try to change it to POST.


问:
Account Locked in API Manager Store & Publisher 2.1.0
Is there a way to lock a user's account after a certain number of failed login attempts to the API Store and API Publisher? I already check at FAQ API Manager, but then the documentation redirect to Identity Server files.

Its there any method on how to solve this issues?

Thank You.

答:
You should first install following Identity Feature in WSO2 API Manager.

Account Recovery and Credential Management

version :  5.7.5

Then you will get the identity-mgt.properties file in your /repository/conf/identity directory.

By changing the following property value to the preferred number you can achive the account locking after several attempts.

Authentication.Policy.Account.Lock.On.Failure.Max.Attempts=0

Note :
To install the above feature,

Login to Management Console of API Manager 2.1.0 (httpso://localhost:9443/carbon)

Go to Configure > Features > Repository Management and add the following repository.
http://product-dist.wso2.com/p2/carbon/releases/wilkes/

Then search for "Account Recovery and Credential Management Feature".

Select and install the version 5.7.5 as below.

Restart the Server.


问:
Sparklyr: Use group_by and then concatenate strings from rows in a group
I am trying to use the group_by() and mutate() functions in sparklyr to concatenate rows in a group.

Here is a simple example that I think should work but doesn't:

```<code>library(sparkylr)
d <- data.frame(id=c("1", "1", "2", "2", "1", "2"),
             x=c("200", "200", "200", "201", "201", "201"),
             y=c("This", "That", "The", "Other", "End", "End"))
d_sdf <- copy_to(sc, d, "d")
d_sdf %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))
</code>```

What I'd like it to produce is:

```<code>Source: local data frame [6 x 3]
Groups: id, x [4]

# A tibble: 6 x 3
      id      x         y
  <fctr> <fctr>     <chr>
1      1    200 This That
2      1    200 This That
3      2    200       The
4      2    201 Other End
5      1    201       End
6      2    201 Other End
</code>```

I get the following error:

```<code>Error: org.apache.spark.sql.AnalysisException: missing ) at 'AS' near '' '' in selection target; line 1 pos 42
</code>```

Note that the using the same code on a data.frame works fine:

```<code>d %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))
</code>```

答:
Spark sql doesn't like it if you use aggregate functions without aggregating, hence the reason why this works in dplyr with an ordinary dataframe but not in a SparkDataFrame- sparklyr translates your commands to an sql statement. You can observe this going wrong if you look at the second bit in the error message:

```<code>== SQL ==
SELECT `id`, `x`, CONCAT_WS(' ', `y`, ' ' AS "collapse") AS `y`
</code>```

paste gets translated to CONCAT_WS. concat however would paste columns together.

A better equivalent would be collect_list and collect_set, but they produce list outputs.

But you can build on that:

If you do not want to have the same row replicated in your result you can use summarise, collect_list, and paste:

```<code>res <- d_sdf %>%
      group_by(id, x) %>%
      summarise( yconcat =paste(collect_list(y)))
</code>```

result:

```<code>Source:     lazy query [?? x 3]
Database:   spark connection master=local[8] app=sparklyr local=TRUE
Grouped by: id

     id     x         y
  <chr> <chr>     <chr>
1     1   201       End
2     2   201 Other End
3     1   200 This That
4     2   200       The
</code>```

you can join this back onto your original data if you do want to have your rows replicated:

```<code>d_sdf %>% left_join(res)
</code>```

result:

```<code>Source:     lazy query [?? x 4]
Database:   spark connection master=local[8] app=sparklyr local=TRUE

     id     x     y   yconcat
  <chr> <chr> <chr>     <chr>
1     1   200  This This That
2     1   200  That This That
3     2   200   The       The
4     2   201 Other Other End
5     1   201   End       End
6     2   201   End Other End
</code>```

Body:
I am trying to use the group_by() and mutate() functions in sparklyr to concatenate rows in a group.

Here is a simple example that I think should work but doesn't:

library(sparkylr)
d <- data.frame(id=c("1", "1", "2", "2", "1", "2"),
             x=c("200", "200", "200", "201", "201", "201"),
             y=c("This", "That", "The", "Other", "End", "End"))
d_sdf <- copy_to(sc, d, "d")
d_sdf %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))

What I'd like it to produce is:

Source: local data frame [6 x 3]
Groups: id, x [4]

# A tibble: 6 x 3
      id      x         y
  <fctr> <fctr>     <chr>
1      1    200 This That
2      1    200 This That
3      2    200       The
4      2    201 Other End
5      1    201       End
6      2    201 Other End

I get the following error:

Error: org.apache.spark.sql.AnalysisException: missing ) at 'AS' near '' '' in selection target; line 1 pos 42

Note that the using the same code on a data.frame works fine:

d %>% group_by(id, x) %>% mutate( y = paste(y, collapse = " "))

Body:
Spark sql doesn't like it if you use aggregate functions without aggregating, hence the reason why this works in dplyr with an ordinary dataframe but not in a SparkDataFrame- sparklyr translates your commands to an sql statement. You can observe this going wrong if you look at the second bit in the error message:

== SQL ==
SELECT `id`, `x`, CONCAT_WS(' ', `y`, ' ' AS "collapse") AS `y`

paste gets translated to CONCAT_WS. concat however would paste columns together.

A better equivalent would be collect_list and collect_set, but they produce list outputs.

But you can build on that:

If you do not want to have the same row replicated in your result you can use summarise, collect_list, and paste:

res <- d_sdf %>%
      group_by(id, x) %>%
      summarise( yconcat =paste(collect_list(y)))

result:

Source:     lazy query [?? x 3]
Database:   spark connection master=local[8] app=sparklyr local=TRUE
Grouped by: id

     id     x         y
  <chr> <chr>     <chr>
1     1   201       End
2     2   201 Other End
3     1   200 This That
4     2   200       The

you can join this back onto your original data if you do want to have your rows replicated:

d_sdf %>% left_join(res)

result:

Source:     lazy query [?? x 4]
Database:   spark connection master=local[8] app=sparklyr local=TRUE

     id     x     y   yconcat
  <chr> <chr> <chr>     <chr>
1     1   200  This This That
2     1   200  That This That
3     2   200   The       The
4     2   201 Other Other End
5     1   201   End       End
6     2   201   End Other End


答:
You are looking for locals()

```<code>def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}
</code>```

Output:

```<code>{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}
</code>```

Title: How to convert all arguments to dictionary in python

Body:
You are looking for locals()

def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

Output:

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}


问:
How to create multi item template with wizard
I'd like to be able to add many files (C#, XAML) at a time with parameters that I can fill in a form like Visual Studio's wizard.

The usage would be like:

Right-click on a project containing following structure:

Controllers

DAOS

Views

Choose add -> new item and select "MyCompanyTemplate"

Then a form would ask for say classname, time and appleType.

Once this form filled with classname=AAA, time=12:00 and appleType=Gravenstein, the result would be :

Controllers/AAAController.cs

namespace Controllers
{
    public class AAAController
    {
        private const string appleType = "Gravenstein";

        public AAAController() { }

        //// Whatever I need in this class
    }
}
```

<p>Daos/AAADao.cs</p>

<pre class="lang-cs prettyprint-override"><code>namespace Daos
{
    public class AAADao
    {

        public AAADao() { }

        public void Count()
        {
            var whatsthetime = "12:00";
            string s = "Not very inspired for this example";
        }
        //// Whatever I need in this class

    }
}
</code>```

Views/AAAView.xaml

Views/AAAView.xaml.cs

This is the kind of behavior we have when adding a new controller in ASP.Net MVC and choose to create the corresponding view, but with custom parameters added.

It must work with Visual Studio 2015 and/or 2017. I also have Resharper installed so any provided solution using this tool is welcome as well.

答:
The solution I found was to create a visual studio extension.

I use classes provided in Microsoft.VisualStudio.Shell.Package namespace to add files to my projects and basic txt files with string replacement as templates.

Body:
I'd like to be able to add many files (C#, XAML) at a time with parameters that I can fill in a form like Visual Studio's wizard.

The usage would be like:

Right-click on a project containing following structure:

Controllers

DAOS

Views

Choose add -> new item and select "MyCompanyTemplate"

Then a form would ask for say classname, time and appleType.

Once this form filled with classname=AAA, time=12:00 and appleType=Gravenstein, the result would be :

Controllers/AAAController.cs

namespace Controllers
{
    public class AAAController
    {
        private const string appleType = "Gravenstein";

        public AAAController() { }

        //// Whatever I need in this class
    }
}

Daos/AAADao.cs

namespace Daos
{
    public class AAADao
    {

        public AAADao() { }

        public void Count()
        {
            var whatsthetime = "12:00";
            string s = "Not very inspired for this example";
        }
        //// Whatever I need in this class

    }
}

Views/AAAView.xaml

Views/AAAView.xaml.cs

This is the kind of behavior we have when adding a new controller in ASP.Net MVC and choose to create the corresponding view, but with custom parameters added.

It must work with Visual Studio 2015 and/or 2017. I also have Resharper installed so any provided solution using this tool is welcome as well.


问:
Chain API http request that depends on response of previous request
I'm trying to implement chain http request that will be repeated X times and stop when there is no response from last request.

How it should work.

For example first I call

```<code>http://example.com/?skip=0
</code>```

and response is:

```<code>{
   skip=10
},
</code>```

than I call

```<code>http://example.com/?skip=10
...
http://example.com/?skip=20
</code>```

and on skip 20 response is

```<code>{
  "message" : "You reach the end"
}
</code>```

I need to stop there. But I have to repeat requests when I'm getting "skip" in response and repeat them on the way that I add skip into next request.

Thanks

答:
If you don't have too many calls then you could just chain them together as individual methods as below. This will allow you to alter the returned data and act on it at each stage: (i'm paraphrasing the code so apologies if it is not 100% syntactically correct)

```<code>$scope.call1 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call2(data);
    })
};

$scope.call2 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call3(data);
    })
};

$scope.call3 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        ...this is the end...
    })
};
</code>```

and kick it all off with a

```<code>$scope.call1(params);
</code>```

This will call each method in turn only after the previous one has finished.
If you do have lots (i.e. in a kind of for loop) then you would have to add them to a queueing type system.

Body:
I'm trying to implement chain http request that will be repeated X times and stop when there is no response from last request.

How it should work.

For example first I call

http://example.com/?skip=0

and response is:

{
   skip=10
},

than I call

http://example.com/?skip=10
...
http://example.com/?skip=20

and on skip 20 response is

{
  "message" : "You reach the end"
}

I need to stop there. But I have to repeat requests when I'm getting "skip" in response and repeat them on the way that I add skip into next request.

Thanks

Body:
If you don't have too many calls then you could just chain them together as individual methods as below. This will allow you to alter the returned data and act on it at each stage: (i'm paraphrasing the code so apologies if it is not 100% syntactically correct)

$scope.call1 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call2(data);
    })
};

$scope.call2 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        $scope.call3(data);
    })
};

$scope.call3 = function (values) {
   $.ajax({
        url: _url,
        method: 'GET'
    })
    .done(function (data) {
        ...do stuff with data...
        ...this is the end...
    })
};

and kick it all off with a

$scope.call1(params);

This will call each method in turn only after the previous one has finished.
If you do have lots (i.e. in a kind of for loop) then you would have to add them to a queueing type system.


问:
static content not caching in Asp.net MVC
I want to cache all my static content of mvc application.

I Added Web.config file like this in the Content folder

I got proper response header from my server.

Even after receiving the header with max-age attribute, The next Request to the server goes with Cache-Control:  no-cache

This again retrieve the whole data.

It is not caching.

I want to know What am i missing here. Thanks in advance.

答:
The no-cache in your screenshot is a request header not a response header.

It is likely being issued by your browser in response to you forcing a refresh (Control-F5). The browser is effectively saying 'please get me fresh data, I don't want the cached data'. The server-side can't control this - the client is the one making the request.

If you aren't forcing a refresh then you may have disabled your browser cache (e.g. https://stackoverflow.com/a/7000899/34092 ).

See also https://stackoverflow.com/a/14544664/34092 .


问:
Can I deploy multiple build versions using the same bamboo deployment plan?
I would like to create a single bamboo deployment plan to deploy multiple versions of an artifact.

Each supported version has a maintenance branch in git.

Bamboo supports the creation of a single build plan that can be applied to many branches.

Can this be transferred to the deployment project, in which the deployment would be identical, parameterized only by the version.

答:
Deployment plans are used for deploying artifacts, which are created by existing bamboo build jobs. So if you have bamboo build jobs, which create the different versions of your artifact, you can easily reuse your existing deployment plan.

I assuming a bamboo build plan (with multiple builds either due to updates or due to different branches, thus containing different versions of your software) and a working deployment plan.

You can then use your deployment plan and start a deployment by clicking on that cloud icon, select a release to deploy "Create new release from build result", choose the branch and/or correct build number of the build, give your child a meaningful name and deploy the newly created release of your software. However this mean, that at a given time you'll have only a single version deployed.

If you want to deploy multiple version simultaneously you should clone your existing environment of the deployment plan. Otherwise you wouln't be able to track which version (release) of your software is deployed.


问:
Advanced image editing off the web
I'm building an app in ASP.NET that will store some pictures of objects. The pictures will be uploaded by suppliers and downloaded by subscribers. In between, they will have to be edited before becoming available to subscribers.

The editing involves creating a cropping path tightly around the object in the picture, in which some advanced desktop image software will have to be used I suppose.

My problem is in exchanging pictures between my ASP.NET app and the desktop software in a manner that is easy and transparent for the user.

I've done some thinking and I've come up with:
- Manually downloading and uploading the image (Not much user friendly...)
- An image editing program that can upload to a web service (Haven't found yet...)
- Develop a plug-in for an image editing program (Too advanced...)

I'd appreciate any suggestions you may have, thank you!

答:
It sounds like you need some automation to move files between the web server and a file share. I am assuming that the number of images that need to be processed is pretty large, because if it's not, then the overhead of downloading/re-uploading each would not be that much.

So do the following:

1) Create an API for your web app that lists files that are available, or new files since some date/time, or files that have been marked as "new". The API should probably also allow marking a status on them (so you can tell it when you've finishing pulling something down, and it won't be offered again) if you don't want to trust date/time as an indicator of it being new.

2) Write an app (non-web) that runs on a schedule and uses this API to automatically download files to a shared filesystem area in your local network, and marks them as "downloaded"

The app should also monitor these files (the ones it downloaded & saved to your local share) for changes, and if changed, upload them back to your web app. To do this you may need to keep a database of filenames and modification dates/times.

This shouldn't be too hard to write in whatever language you are using for your web (assume c# or vb). By "API" I just mean, a web page that provides a list in a standardized format (e.g. json) that you can parse with your automation application, and another page that allows posting the file back for re-upload.

I'm assuming that the web server is not your own, or generally, you can't simply have it save the file uploads directly to some area where your image editors can access them. Otherwise you could just do that.

Title: Advanced image editing off the web


问:
for loop cycle showing always the last array value swift 3 after HTTP request
I already used another post to solver part of the problem,so now I am able to wait the end of the request. I made a http request with Almofire and parse the resulting JSON file. the code inside the myGroup.notify i think is correctly executed ater the request is completed (if I print allCards.count returns the correct value). Why if I put the for loop inside it is always showing the last card?

Thanks for any help

```<code>import UIKit
mport SwiftyJSON
import Alamofire

class ViewController: UIViewController {
//variables Declaration
var allCard = [Card]()
let allCardsHTTP: String = "https://omgvamp-hearthstone-v1.p.mashape.com/cards?mashape-key="

override func viewDidLoad() {
    super.viewDidLoad()
    let myGroup = DispatchGroup()

    //get HTTp request with Alamofire

    myGroup.enter()
    Alamofire.request(allCardsHTTP, method: .get).responseJSON {
         response in
         if response.result.isSuccess {
             let jsonCards : JSON = JSON(response.result.value!)
             print("success")
             self.updateJSONCards(json: jsonCards)
          }
        else {
             print("error")
         }
         myGroup.leave()
    }

    myGroup.notify(queue: .main) {
         //Updte UI here
         print(self.allCard[10].name) //This is Working

         for card in self.allCard {
            if card.cardsSet == "Basic" {
                print(card.name)
            }
        } //For loop always showing last card ???

    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: - JSON Parsing

//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         var card = Card()
         card.cardsSet = set
         if json[set].count != 0 {
            for i in 0...json[set].count - 1 {
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }
</code>```

}

答:
You are creating the Card instance at the wrong place.

Before the inner repeat loop you are creating one instance and appending the same instance to the allCard array. If Card is a class (reference semantics) all occurrences of that instance contain the same data (the last loop item).

Put the two lines in the repeat loop.

```<code>//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         if !json[set].isEmpty {
            for i in 0..<json[set].count {
                let card = Card()
                card.cardsSet = set
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }
</code>```

Body:
I already used another post to solver part of the problem,so now I am able to wait the end of the request. I made a http request with Almofire and parse the resulting JSON file. the code inside the myGroup.notify i think is correctly executed ater the request is completed (if I print allCards.count returns the correct value). Why if I put the for loop inside it is always showing the last card?

Thanks for any help

import UIKit
mport SwiftyJSON
import Alamofire

class ViewController: UIViewController {
//variables Declaration
var allCard = [Card]()
let allCardsHTTP: String = "https://omgvamp-hearthstone-v1.p.mashape.com/cards?mashape-key="

override func viewDidLoad() {
    super.viewDidLoad()
    let myGroup = DispatchGroup()

    //get HTTp request with Alamofire

    myGroup.enter()
    Alamofire.request(allCardsHTTP, method: .get).responseJSON {
         response in
         if response.result.isSuccess {
             let jsonCards : JSON = JSON(response.result.value!)
             print("success")
             self.updateJSONCards(json: jsonCards)
          }
        else {
             print("error")
         }
         myGroup.leave()
    }

    myGroup.notify(queue: .main) {
         //Updte UI here
         print(self.allCard[10].name) //This is Working

         for card in self.allCard {
            if card.cardsSet == "Basic" {
                print(card.name)
            }
        } //For loop always showing last card ???

    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: - JSON Parsing

//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         var card = Card()
         card.cardsSet = set
         if json[set].count != 0 {
            for i in 0...json[set].count - 1 {
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }

}

Body:
You are creating the Card instance at the wrong place.

Before the inner repeat loop you are creating one instance and appending the same instance to the allCard array. If Card is a class (reference semantics) all occurrences of that instance contain the same data (the last loop item).

Put the two lines in the repeat loop.

//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
    //create the cards
     for (set, value) in json {
         if !json[set].isEmpty {
            for i in 0..<json[set].count {
                let card = Card()
                card.cardsSet = set
                card.name = json[set][i]["name"].stringValue
                allCard.append(card)
             }
         }
         else {
             print("The set \(set) has no cards")
         }
     }
  }


问:
Cannot change checkbox color API 19
I'm trying to change checkbox color on Api <21 like this:

```<code><android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:id="@+id/chSave"
            android:checked="false"
            android:layout_centerVertical="true"
            app:buttonTint="@android:color/white"
            android:layout_toRightOf="@id/txtterms" />
</code>```

also tried setting theme like this:

```<code><style name="checkBoxStyle" parent="Theme.AppCompat">
    <item name="colorAccent">#ffffff</item>
    <item name="android:textColorSecondary">#ffffff</item>
</style>

<android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:id="@+id/chSave"
            android:checked="false"
            android:layout_centerVertical="true"
            app:theme="@style/checkBoxStyle"
            app:buttonTint="@android:color/white"
            android:layout_toRightOf="@id/txtterms" />
</code>```

and also tried with just CheckBox without appcompat.

Layout is in DialogFragment, tried changing it to AppCompatDialogFragment, changing theme to appcompat but none of it helped.

Using custom drawable is a last resort.
So is there any other chance to achieve this?

答:
I just ran a test on an app with minimum api 16 and this worked, though you see it filled in with the color when checked="true", when it is false, only the borders are red.</p>

```<code><android.support.v7.widget.AppCompatCheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        app:buttonTint="@color/colorRed"/>
</code>```

Title: Cannot change checkbox color API 19

Body:
I'm trying to change checkbox color on Api <21 like this:

<android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:id="@+id/chSave"
            android:checked="false"
            android:layout_centerVertical="true"
            app:buttonTint="@android:color/white"
            android:layout_toRightOf="@id/txtterms" />

also tried setting theme like this:

<android.support.v7.widget.AppCompatCheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:id="@+id/chSave"
            android:checked="false"
            android:layout_centerVertical="true"
            app:theme="@style/checkBoxStyle"
            app:buttonTint="@android:color/white"
            android:layout_toRightOf="@id/txtterms" />

and also tried with just CheckBox without appcompat.

Layout is in DialogFragment, tried changing it to AppCompatDialogFragment, changing theme to appcompat but none of it helped.

Using custom drawable is a last resort.
So is there any other chance to achieve this?

Body:
I just ran a test on an app with minimum api 16 and this worked, though you see it filled in with the color when checked="true", when it is false, only the borders are red.

<android.support.v7.widget.AppCompatCheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        app:buttonTint="@color/colorRed"/>


问:
Get word that is surrounded by [tag] in brackets[/tag]
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

```<code>$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";
</code>```

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

```<code>$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "<a href='$url'>\$0</a>",
                                $e->innertext,
                                1
                            );
</code>```

答:
This should work -

```<code>preg_match_all('/\[tag\](.*?)\[\/tag\]/', $string, $match);
</code>```

Output

```<code>Array
(
    [0] => Array
        (
            [0] => [tag]world[/tag]
            [1] => [tag]fine[/tag]
        )

    [1] => Array
        (
            [0] => world
            [1] => fine
        )

)
</code>```

Code

Body:
I would like to get a list of words, that is surrounded by a BBCode-like "tag".

E.g.:

$string = "Hello [tag]world[/tag], how [notag]are[/notag] you today? I am [tag]fine[/tag].";

This should return an array like this:

world

fine

because both are surrounded by [tag], but "are" should not be added, because it is surrounded by another tag.

At the moment I try to check and replace the findings this way:

$e->innertext = preg_replace(
                                '/\b' . preg_quote( "[tag]".$text."[/tag]", "/" ) . '\b/i',
                                "\$0",
                                $e->innertext,
                                1
                            );

Body:
This should work -

preg_match_all('/\[tag\](.*?)\[\/tag\]/', $string, $match);

Output

Array
(
    [0] => Array
        (
            [0] => [tag]world[/tag]
            [1] => [tag]fine[/tag]
        )

    [1] => Array
        (
            [0] => world
            [1] => fine
        )

)

Code


问:
Read/write XML with C#/.NET
What are the best functions, practices, and/or techniques to read/write XML with C#/.NET?</p>

答:
If you are working with .NET 3.5, LINQ to XML is certainly a very good way to interact with XML.

MSDN Link

Title: Read/write XML with C#/.NET

OwnerDisplayName: Jason Miesionczek


问:
Overlay two bitmaps and rub out the top one
I'm having trouble trying to create a screen where I have two bitmaps (one on top of the other so it's totally obscuring the lower one) and "rub out" the top one so it reveals the bottom one under the path of the finger. I realise I may need 3 separate layers (bottom image, top image and then a custom view that handles the finger tracking) but I can't find a method of manipulating the middle layer from the custom view. Can anyone offer some advice on how I might do this? </p>

答: You should do the whole thing in one View, see this SO question and its answer for more info and links.</p>


问:
On [PRIMARY] and [OTHERS] and obscure option [SORT_IN_TEMPDB]
I read this post
What does ON [PRIMARY] mean?

and I wonder how I can get the text "PRIMARY" or any other file group names in use by using SQL scripts.
I also look into the syntax of CREATE table and see SORT_IN_TEMPDB and try searching for it with queries in MS SMS but can't find where it is either.

答:
```<code>select OBJECT_NAME(p.object_id) as obj_name, fg.name as fg
from sys.partitions p inner join sys.allocation_units au
        on au.container_id = p.hobt_id
     inner join sys.filegroups fg
        on fg.data_space_id = au.data_space_id
</code>```

SORT_IN_TEMPDB is the CREATE INDEX option: CREATE INDEX (Transact-SQL)

SORT_IN_TEMPDB = { ON | OFF } Applies to: SQL Server 2008 through SQL
  Server 2017 and Azure SQL Database. Specifies whether to store
  temporary sort results in tempdb. The default is OFF. ON The
  intermediate sort results that are used to build the index are stored
  in tempdb. This may reduce the time required to create an index if
  tempdb is on a different set of disks than the user database. However,
  this increases the amount of disk space that is used during the index
  build.

Body:
select OBJECT_NAME(p.object_id) as obj_name, fg.name as fg
from sys.partitions p inner join sys.allocation_units au
        on au.container_id = p.hobt_id
     inner join sys.filegroups fg
        on fg.data_space_id = au.data_space_id

SORT_IN_TEMPDB is the CREATE INDEX option: CREATE INDEX (Transact-SQL)

SORT_IN_TEMPDB = { ON | OFF } Applies to: SQL Server 2008 through SQL
  Server 2017 and Azure SQL Database. Specifies whether to store
  temporary sort results in tempdb. The default is OFF. ON The
  intermediate sort results that are used to build the index are stored
  in tempdb. This may reduce the time required to create an index if
  tempdb is on a different set of disks than the user database. However,
  this increases the amount of disk space that is used during the index
  build.


问:
How to apply SSO with an existing login screen and a trusted second website
We use IdentityServer3 (IdSvr3) for authorization/authentication. We want to offer the ability for our end user (or resource owner: RO) to log in (log through) to a second trusted website (site B) without login in to site B also, after they have already logged in to an initial website (site A). Site B administers a different set of resources for the RO. It is important that the RO is not redirected to the IdSvr3 login/consent screen. A possible approach I found so far is: inside site A an access token is created by calling RequestResourceOwnerPasswordAsync (passing username and password plus scope = "openid ..."). This access token is send to site B with which the RO can be authenticated. Site B retrieves the user info by calling the connect/userinfo endpoint. I want to know if this is a correct approach/flow. We assume that the RO will always enter site A first, not site B.
Thanks in advance for taking your time to think with me about this.</p>

答:
what you can do here is to send a authorize request to identity server for Site B Scope and request id_token or reference token. Make sure while sending the authorize request to idsrv you are using prompt=none, this way you will get the access_token without showing a consent to the user again if the user is already logged-in to site A.
Below example is doing the same from a JS file. In  Site A you can refer to this script file and execute the script using IIFE.

```<code> function getIdentityServerURL() {
    var url = global.appSettings.identityServerURL
                        + "/connect/authorize?client_id=siteB&response_type=id_token token&redirect_uri="
                        + global.appSettings.siteBUrl + "/Main/SsoCallback&scope=siteBscope openid email roles&prompt=none&nonce="
                        + genNonce();
    return encodeURI(url);
}
</code>```

The code above will redirect you to SsoCallback page where you can create a virtual iframe and post the token back to site B after reducing the result from authorize request. Refer to code below.

```<code><script type="text/javascript">
var identityresult = window.location.hash.split('&').reduce(function (result, item) {
    var parts = item.split('=');
    result[parts[0]] = parts[1];
    return result;
}, {});

window.parent.postMessage(identityresult, '*');
</code>```

your script can listen to postmessage event. Hope this helps.

Body:
what you can do here is to send a authorize request to identity server for Site B Scope and request id_token or reference token. Make sure while sending the authorize request to idsrv you are using prompt=none, this way you will get the access_token without showing a consent to the user again if the user is already logged-in to site A.
Below example is doing the same from a JS file. In  Site A you can refer to this script file and execute the script using IIFE.

 function getIdentityServerURL() {
    var url = global.appSettings.identityServerURL
                        + "/connect/authorize?client_id=siteB&response_type=id_token token&redirect_uri="
                        + global.appSettings.siteBUrl + "/Main/SsoCallback&scope=siteBscope openid email roles&prompt=none&nonce="
                        + genNonce();
    return encodeURI(url);
}

The code above will redirect you to SsoCallback page where you can create a virtual iframe and post the token back to site B after reducing the result from authorize request. Refer to code below.

<script type="text/javascript">
var identityresult = window.location.hash.split('&').reduce(function (result, item) {
    var parts = item.split('=');
    result[parts[0]] = parts[1];
    return result;
}, {});

window.parent.postMessage(identityresult, '*');

your script can listen to postmessage event. Hope this helps.


问:
SQL to find a string in another string
I have 2 tables:

tblFoo:

```<code>Id | MessageId | SenderName
</code>```

tblBar:

```<code>MessageId | Name
</code>```

I need to update all the rows in tblFoo with the MessageId from tblBar where SenderName starts with Name. e.g.

tblFoo:

```<code>Id     | MessageId | SenderName
-------+-----------+--------------------
365175 | NULL      | x.y.z.abc.def.ghi
535646 | NULL      | a.b.c.fjdkf.dsfjdsf:a
535647 | NULL      | a.b.c.sdjskfj.dsfjds:b
</code>```

tblBar:

```<code>MessageId                             | Name
--------------------------------------+--------
9B30FCD1-F063-4B7F-887B-65288C3681D3  | x.y.z
56FBEF0F-8C29-4614-8894-4F64A515659A  | a.b.c
</code>```

So in tblFoo Id=365175 would end up with MessageId = 9B30FCD1-F063-4B7F-887B-65288C3681D3 and Id=535646 would end up with MessageId = 56FBEF0F-8C29-4614-8894-4F64A515659A and Id=535647 would also end up with MessageId=
56FBEF0F-8C29-4614-8894-4F64A515659A

So far I have

```<code>begin transaction
    update tblFoo
    set MessageId =
    (
        select MessageId
        from tblBar
        where [Name] ???
    );
    rollback transaction
</code>```

I can't do

```<code>where [Name] like
</code>```

as [Name] is a substring of SenderName.

Or do I need to use a temp table?

答:
You can use the inner join as below.</p>

```<code>update foo set messageid = br.messageid
from
tblFoo foo
inner join
tblBar br
on foo.senderName like ltrim(br.Name) + '%'
</code>```

Title: SQL to find a string in another string

Body:
I have 2 tables:

tblFoo:

Id | MessageId | SenderName

tblBar:

MessageId | Name

I need to update all the rows in tblFoo with the MessageId from tblBar where SenderName starts with Name. e.g.

tblFoo:

Id     | MessageId | SenderName
-------+-----------+--------------------
365175 | NULL      | x.y.z.abc.def.ghi
535646 | NULL      | a.b.c.fjdkf.dsfjdsf:a
535647 | NULL      | a.b.c.sdjskfj.dsfjds:b

tblBar:

MessageId                             | Name
--------------------------------------+--------
9B30FCD1-F063-4B7F-887B-65288C3681D3  | x.y.z
56FBEF0F-8C29-4614-8894-4F64A515659A  | a.b.c

So in tblFoo Id=365175 would end up with MessageId = 9B30FCD1-F063-4B7F-887B-65288C3681D3 and Id=535646 would end up with MessageId = 56FBEF0F-8C29-4614-8894-4F64A515659A and Id=535647 would also end up with MessageId=
56FBEF0F-8C29-4614-8894-4F64A515659A

So far I have

begin transaction
    update tblFoo
    set MessageId =
    (
        select MessageId
        from tblBar
        where [Name] ???
    );
    rollback transaction

I can't do

where [Name] like

as [Name] is a substring of SenderName.

Or do I need to use a temp table?

Body:
You can use the inner join as below.

update foo set messageid = br.messageid
from
tblFoo foo
inner join
tblBar br
on foo.senderName like ltrim(br.Name) + '%'


问:
increment is not happening in for loop in c
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

```<code>#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main
</code>```

And this is the output:

```<code>year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000
</code>```

I made this program in Eclipse, in ubuntu mate.

答: and you have (year = 1; year <= 10; year++), which year here never serve as a factor in the calculation, that's why.

Body:
I had written a program in C in which the population of a town increases by 10% each year, but the variable pop is not incrementing in the for loop.

This is my code:

#include <stdio.h>

int main() { // B main
    int pop = 100000, year, popatend;
    printf("\nyear\t\t\tpopulation\n\n");
    for (year = 1; year <= 10; year++) { // B loop
        popatend = pop * (10 / 100);
        pop = pop + popatend;

        printf("%d\t\t\t %d\n", year, pop);
    } // B loop
} // B main

And this is the output:

year            population

   1             100000
   2             100000
   3             100000
   4             100000
   5             100000
   6             100000
   7             100000
   8             100000
   9             100000
  10             100000

I made this program in Eclipse, in ubuntu mate.


问:
How to get XPath for data table with two td and it should be clickable at once?
```<code><div class="dataTables_scrollBody" style="position: relative; overflow: auto; height: 370px; width: 100%; min-height: 0px;">
<table id="offer_create" class="display article-list ranklist_drag table table-bordered dataTable no-footer" aria-describedby="offer_create_info" role="grid" style="position: absolute; top: 0px; left: 0px; width: 100%;" width="100%" cellspacing="0">
<thead>
<tbody>
<tr class="odd" role="row">

    <td>test1</td>
    <td>test2</td>
</tr>
</code>```

How to get XPath and its in data table to be clickable at once?

Check for image data table looks like this:

答:
```<code>WebElement htmltable=driver.findElement(By.xpath("//*[@id='main']/table[1]/tbody"));
List<WebElement> rows=htmltable.findElements(By.tagName("tr"));

for(int rnum=0;rnum<rows.size();rnum++)
{
List<WebElement> columns=rows.get(rnum).findElements(By.tagName("th"));
System.out.println("Number of columns:"+columns.size());

for(int cnum=0;cnum<columns.size();cnum++)
{
System.out.println(columns.get(cnum).getText());
}
}

Note: <tr> represent your row name and <th> represent your column name here.
</code>```

Body:
    test1
    test2

How to get XPath and its in data table to be clickable at once?

Check for image data table looks like this:


问:
How to properly use Git. Using CodeIgniter w/ DEVELOPMENT, TESTING, and PRODUCTION servers
Basically, I have a file index.php which should be different in each server. The file indicates which server it is on.

It has something like this:

On the DEVELOPMENT environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
</code>```

On the TESTING environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing');
</code>```

On the PRODUCTION environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');
</code>```

What's the proper way to maintain these files on each server without Git touching it?

I've added the file to .gitignore now, and I've untracked it using git rm --cached index.php then git push origin master for TESTING server and stable for PRODUCTION server.

答:
With Apache you can set CI_ENV like @sintakonte's answer. With nginx and php-fpm you can set CI_ENV like this:

```<code>location ~ \.php {
    ....
    fastcgi_param CI_ENV production;
}
</code>```

And leave the index.php file as default.

Cheers.

Body:
Basically, I have a file index.php which should be different in each server. The file indicates which server it is on.

It has something like this:

On the DEVELOPMENT environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

On the TESTING environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing');

On the PRODUCTION environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');

What's the proper way to maintain these files on each server without Git touching it?

I've added the file to .gitignore now, and I've untracked it using git rm --cached index.php then git push origin master for TESTING server and stable for PRODUCTION server.

Body:
With Apache you can set CI_ENV like @sintakonte's answer. With nginx and php-fpm you can set CI_ENV like this:

location ~ \.php {
    ....
    fastcgi_param CI_ENV production;
}

And leave the index.php file as default.

Cheers.


问:
R incorrect y-axis in ggplots geom_bar()
I have a dataframe with Wikipedia edits, with information about the number of edit for the user (1st edit, 2nd edit and so on), the timestamp when the edit was made, and how many words were added.

In the actual dataset, I have up to 20.000 edits per user and in some edits, they add up to 30.000 words.

However, here is a downloadable small example dataset to exemplify my problem. The header looks like this:

I am trying to plot the distribution of added words across the Edit Progression and across time. If I use the regular R barplot, i works just like expected:

barplot(UserFrame3$NoOfAdds,UserFrame3$EditNo)

But I want to do it in ggplot for nicer graphics and more customizing options.

If I plot this as a scatterplot, I get the same result:

ggplot(data = UserFrame3, aes(x = UserFrame3$EditNo, y = UserFrame3$NoOfAdds))  + geom_point(size = 0.1)

Same for a linegraph:

ggplot(data = UserFrame3, aes(x = UserFrame3$EditNo, y = UserFrame3$NoOfAdds)) +geom_line(size = 0.1)

But when I try to plot it as a bargraph in ggplot, I get this result:

ggplot(data = UserFrame3, aes(x = UserFrame3$EditNo, y = UserFrame3$NoOfAdds)) + geom_bar(stat = "identity", position = "dodge")

There appear to be a lot more holes on the X-axis and the maximum is nowhere close to where it should be (y = 317).

I suspect that ggplot somehow groups the bars and uses means instead of the actual values despite the "dodge" parameter? How can I avoid this? and how would I go about plotting the time progression as a bargraph aswell without ggplot averaging over multiple edits?

答:
You should expect more x-axis "holes" using bars as compared with lines. Lines connect the zero values together, bars do not.

I used geom_col with your data download, it looks as expected:

```<code>UserFrame3 %>%
  ggplot(aes(EditNo, NoOfAdds)) + geom_col()
</code>```

Body:
You should expect more x-axis "holes" using bars as compared with lines. Lines connect the zero values together, bars do not.

I used geom_col with your data download, it looks as expected:

UserFrame3 %>%
  ggplot(aes(EditNo, NoOfAdds)) + geom_col()


问:
how to accomplish the multiple bash script command in python script
When I run this two commands in Ubuntu terminal I get a variable value

1. source script.sh

2. echo $varname

Where scripts.sh contains the variable being defined which is than called with echo in step 2.

How do I accomplish the same in python script:
I have tried the following code

```<code>#!/bin/bash

import subprocess

command=['bash','-c','source ia_servers']
cmdout = subprocess.Popen(command, stdout=subprocess.PIPE)

filtercommand=['bash','-c','echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdin=cmdout.stdout, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)
</code>```

Description:
I first ran step 1 using subprocess and the result  of it fed as input to the step 2. I know there wont come any output in the first steps. But how do I accomplish this in python.

Or am I following the wrong way. If  there is another way to solve this problem

Primary Goal:

my purpose is to get the variable value being set in the bash scripts to my python codes.

答:
Every subprocess call spawns its own instance of shell. So, any shell variable set in source in first subprocess is lost immediately when the shell exits. The only way to get an access to those variables is to print them immediately from the same subprocess call, when source is called:</p>

```<code>import subprocess

filtercommand=['bash','-c','source ia_servers; echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)
</code>```

Body:
When I run this two commands in Ubuntu terminal I get a variable value

1. source script.sh

2. echo $varname

Where scripts.sh contains the variable being defined which is than called with echo in step 2.

How do I accomplish the same in python script:
I have tried the following code

#!/bin/bash

import subprocess

command=['bash','-c','source ia_servers']
cmdout = subprocess.Popen(command, stdout=subprocess.PIPE)

filtercommand=['bash','-c','echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdin=cmdout.stdout, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)

Description:
I first ran step 1 using subprocess and the result  of it fed as input to the step 2. I know there wont come any output in the first steps. But how do I accomplish this in python.

Or am I following the wrong way. If  there is another way to solve this problem

Primary Goal:

my purpose is to get the variable value being set in the bash scripts to my python codes.

Body:
Every subprocess call spawns its own instance of shell. So, any shell variable set in source in first subprocess is lost immediately when the shell exits. The only way to get an access to those variables is to print them immediately from the same subprocess call, when source is called:

import subprocess

filtercommand=['bash','-c','source ia_servers; echo $IA_SRV_cs68_64']
filtered = subprocess.Popen(filtercommand, stdout=subprocess.PIPE)

output, err = filtered.communicate()

print(output)


问:
How to tell a setup file to install to the Documents folder with Inno Setup compiler?
I'm trying to create a setup file using Inno Setup Compiler, and I want it to install to the Documents folder as it needs to create and then delete a file, something that it can't do if it installs to Program Files. I've tried using %userprofile%\Documents as that works in File Explorer, but that simply creates a folder called %userprofile% wherever the Setup.exe is, and  C:\Users\%username%\Documents simply creates the %username% folder in the Users folder. How do I get it to install into the Documents folder no matter where it is?

答:
You should use Inno Setup Shell Folder Constants to do this.

See more at Inno Setup Help.

Use ExpandConstant('{userdocs}') where you want to get path of Documents folder (For current user).

It will return "OS Drive:\Users\CurrentUser\Documents".

Eg:

```<code>MsgBox(ExpandConstant('{userdocs}'), mbInformation, MB_OK);
</code>```

For all users, you should replace userdocs with commondocs.

So, It will return "OS Drive:\Users\Public\Documents".

Body:
You should use Inno Setup Shell Folder Constants to do this.

See more at Inno Setup Help.

Use ExpandConstant('{userdocs}') where you want to get path of Documents folder (For current user).

It will return "OS Drive:\Users\CurrentUser\Documents".

Eg:

MsgBox(ExpandConstant('{userdocs}'), mbInformation, MB_OK);

For all users, you should replace userdocs with commondocs.

So, It will return "OS Drive:\Users\Public\Documents".


问:
how to create a dropdown list in iphone?
i did a view based application and it tat thr 3 buttons and when i click each different subviews are displayed for performing different actions.when i click 1st button it should show a textfield to enter the items---for this i should have a drop down list to list the items available so that user can select the items from there.if i use pickerview then how i should display it as it may occupy more screen space.and if there is any other method pls give me the code.

could anyone help me with clear codes to complete this task pls.

thanku

答: A drop-down list doesn't really fit in with the iOS interface.  I would recommend a UIPickerView that is presented from the bottom of the screen, like the keyboard.</p>