问:
Why does using a different type of session affect whether or not the variables are initialized in tensorflow?
I am trying to run a classifier on the MNIST dataset.  I know that I need to initialize a session in order to do this correctly.

But, the other thing I want to do is print out the values when I'm running the training iterations on the neural network.

so, I try to print out the line print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})) to print out the values of these variables.  the following code is runnable if you have tensorflow installed:

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

data_dir='/tmp/tensorflow/mnist/input_data'

mnist = input_data.read_data_sets(data_dir, one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy =    tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# sess = tf.InteractiveSession()
sess = tf.Session()
tf.global_variables_initializer().run()

# Train
for k in range(1000):
    # print loss function at each iteration
    if k%100 == 0 and k!=0:
        print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}))
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
</code>```

I have two related problems about this. The problem is when I try to run this by initializing my session using sess = tf.Session() I get a FailedPredictionError:

```<code>FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_14
     [[Node: Variable_14/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_14"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_14)]]
</code>```

Then, I try to do this using instead of Session() I use sess = tf.InteractiveSession() (which you can see is the line above it).  When I do that, it works, but it is printing None instead of the actual value of the loss function.

My two questions are:

Why does the type of Session I am using affect whether or not the variable is initialized?

Why is the line for printing print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) print None instead of the actual value of the loss function at that training step?  I want to observe the loss function changing across iterations.

答:
The right way to initialize variables in a session like the following:

```<code>sess = tf.Session()
sess.run(tf.global_variables_initializer()) # or tf.global_variables_initializer().run(sess = sess)

#or

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
</code>```

You might wonder what is the difference.

Because when you use tf.InteractiveSession() to create a session, this InteractiveSession installs itself as the default session on construction. That means you can directly call operation.run() to run this operation with this session.

But If you are using tf.Session(), you need to explicitly point out which session to use when run a operation. So If you use tf.Session(), the code in your question is broken as the global variables initializer is not bound with your session. This is your first question.

The second question is because you are not understand well how tensorflow works. The results of sess.run() just return what the operations return. And operation .minimize() won't return what you expect. If you want to get the loss, the code should like the following:

```<code>if k%100 == 0 and k!=0:
    print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys}))
</code>```

Attention, because I can't test your code, so there may be some mistakes, comment me if you want.

Body:
I am trying to run a classifier on the MNIST dataset.  I know that I need to initialize a session in order to do this correctly.

But, the other thing I want to do is print out the values when I'm running the training iterations on the neural network.

so, I try to print out the line print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})) to print out the values of these variables.  the following code is runnable if you have tensorflow installed:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

data_dir='/tmp/tensorflow/mnist/input_data'

mnist = input_data.read_data_sets(data_dir, one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.matmul(x, W) + b

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

cross_entropy =    tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# sess = tf.InteractiveSession()
sess = tf.Session()
tf.global_variables_initializer().run()

# Train
for k in range(1000):
    # print loss function at each iteration
    if k%100 == 0 and k!=0:
        print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}))
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

I have two related problems about this. The problem is when I try to run this by initializing my session using sess = tf.Session() I get a FailedPredictionError:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value Variable_14
     [[Node: Variable_14/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_14"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_14)]]

Then, I try to do this using instead of Session() I use sess = tf.InteractiveSession() (which you can see is the line above it).  When I do that, it works, but it is printing None instead of the actual value of the loss function.

My two questions are:

Why does the type of Session I am using affect whether or not the variable is initialized?

Why is the line for printing print(sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) print None instead of the actual value of the loss function at that training step?  I want to observe the loss function changing across iterations.

Body:
The right way to initialize variables in a session like the following:

sess = tf.Session()
sess.run(tf.global_variables_initializer()) # or tf.global_variables_initializer().run(sess = sess)

#or

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

You might wonder what is the difference.

Because when you use tf.InteractiveSession() to create a session, this InteractiveSession installs itself as the default session on construction. That means you can directly call operation.run() to run this operation with this session.

But If you are using tf.Session(), you need to explicitly point out which session to use when run a operation. So If you use tf.Session(), the code in your question is broken as the global variables initializer is not bound with your session. This is your first question.

The second question is because you are not understand well how tensorflow works. The results of sess.run() just return what the operations return. And operation .minimize() won't return what you expect. If you want to get the loss, the code should like the following:

if k%100 == 0 and k!=0:
    print(sess.run(cross_entropy, feed_dict={x: batch_xs, y_: batch_ys}))

Attention, because I can't test your code, so there may be some mistakes, comment me if you want.


来源: stackexchange

问:
Java parse String containing integers and multiple delimiters
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

```<code>"1,25,3-6,14,16-19"
</code>```

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

```<code>1,3,4,5,6,14,16,17,18,19,25
</code>```

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

```<code>List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}
</code>```

答:
You can use String#split() twice to handle your input string.  First split by comma, which leaves us with either an individual number, or an individual range of numbers.  Then, in the case of range, split again by dash to obtain the starting and ending numbers of that range.  We can iterate over that range, adding each number to our list.

```<code>String input = "1,25,3-6,14,16-19";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();

for (String part : parts) {
    if (part.contains("-")) {
        String[] range = part.split("-");
        int start = Integer.parseInt(range[0]);
        int end = Integer.parseInt(range[1]);

        for (int i=start; i <= end; ++i) {
            list.add(i);
        }
    }
    else {
        int value = Integer.parseInt(part);
        list.add(value);
    }
}
</code>```

This generated the following list of numbers:

```<code>1,25,3,4,5,6,14,16,17,18,19
</code>```

Demo here:

Rextester

ContentLicense: CC BY-SA 3.0

Body:
Here is an example String, which contains 2 delimiters used for parsing the String to integers:

"1,25,3-6,14,16-19"

The integers in the aforementioned string have to be parsed and added to ArrayList cotaining integers. So the ArrayList has to contain:

1,3,4,5,6,14,16,17,18,19,25

The values in the original string are never mentioned twice. So, there are no crossing sections. Below you can see the incomplete code I wrote so far, but I think that I'm going in a completely wrong direction and there should be an easier way to solve the parsing.

List<Integer> temp = new ArrayList<>();
Scanner s = new Scanner(System.in);
String str = s.nextLine();
char[] strCh = str.toCharArray();
for (int j = 0; j < strCh.length; j++) {
    char c = strCh[j];
    String number = "";
    char operator = 'n';
    if (Character.isDigit(c)) {
        do {
            number += c;
            j++;
            if (j != strCh.length - 1)
                c = strCh[j];
           } while (j < strCh.length && Character.isDigit(c));
    } else if (c == ',') {
        operator = ',';
        temp.add(Integer.parseInt(number));
        number = "";
    } else if (c == '-') {
        //still not sure
    }
}

Body:
You can use String#split() twice to handle your input string.  First split by comma, which leaves us with either an individual number, or an individual range of numbers.  Then, in the case of range, split again by dash to obtain the starting and ending numbers of that range.  We can iterate over that range, adding each number to our list.

String input = "1,25,3-6,14,16-19";
String[] parts = input.split(",");
List<Integer> list = new ArrayList<>();

for (String part : parts) {
    if (part.contains("-")) {
        String[] range = part.split("-");
        int start = Integer.parseInt(range[0]);
        int end = Integer.parseInt(range[1]);

        for (int i=start; i <= end; ++i) {
            list.add(i);
        }
    }
    else {
        int value = Integer.parseInt(part);
        list.add(value);
    }
}

This generated the following list of numbers:

1,25,3,4,5,6,14,16,17,18,19

Demo here:

Rextester


问:
Node - EJS - Display toastjs message
I'm trying to display a toast message using the library ToastrJS. The message display okay. The problem is that I'm not finding a way to pass the error message. I use connect-flash to do flash-messages, and then I wanna pass the message to the toaster.

My EJS code:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%=title%></title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/stylesheets/nav-bar.css">
    <link rel="stylesheet" href="<%=style%>">
    <link rel="stylesheet" href="/js/aos.css">
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
      <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
  </head>
  <body >
    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Joobber</a>
        </div>
        <div class="collapse navbar-collapse" id="myNavbar">
          <ul class="nav navbar-nav">
            <li class=""><a href="#">Home</a></li>
            <li><a href="#">Ver todas as vagas</a></li>
            <li><a href="#">Vagas por categoria:</a></li>

          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="#"><span class="glyphicon glyphicon-user"></span> Ainda não está cadastrado?</a></li>
            <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Logar</a></li>
          </ul>
        </div>
      </div>
    </nav>

    <% if(success.length > 0){ %>
      <script>
        toastr.success('WANNA USE THE ERROR MESSAGE VARIABLE HERE!!!!')
      </script>
    <% } %>

    <script type="text/javascript" src="js/aos.js">

    </script>
    <script type="text/javascript">
    AOS.init({
      offset: 200,
      duration: 600,
      easing: 'ease-in-sine',
      delay: 100,
      });
    </script>
</code>```

I also have connect-flash configured and used some locals variables to set the specific kind of message

```<code>app.use(flash());
var sessionFlash = function(req, res, next) {
    res.locals.currentUser = req.user;
    res.locals.error = req.flash('error');
    res.locals.success = req.flash('success');
    next();

}
app.use(sessionFlash)
</code>```

And then, my routes:

```<code>const express = require('express')
const router = express.Router()
const indexControllers = require('../controllers/indexControllers')

router.get('/', indexControllers.HomePage)

router.get('/signup', indexControllers.Signup)

router.get('/test', (req, res)=>{
  req.flash('success', 'user succesfulyl registered')
  res.redirect('/')
})

module.exports = router;
</code>```

答:
If you want to display toastr with error and message using one sentence then using toastr.info. If not, better off separating between success and error message to have clearer context. And use it like this:</p>

```<code><% if(success.length > 0){ %>
  <script>
    toastr.success(`${success[0]}`)
  </script>
<% } %>
<% if(error.length > 0){ %>
  <script>
    toastr.error(`${error[0]}`)
  </script>
<% } %>
</code>```

Title: Node - EJS - Display toastjs message

Body:
I'm trying to display a toast message using the library ToastrJS. The message display okay. The problem is that I'm not finding a way to pass the error message. I use connect-flash to do flash-messages, and then I wanna pass the message to the toaster.

My EJS code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><%=title%></title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/stylesheets/nav-bar.css">
    <link rel="stylesheet" href="<%=style%>">
    <link rel="stylesheet" href="/js/aos.css">

      <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

          </button>
          Joobber

Home

Ver todas as vagas

Vagas por categoria:

 Ainda não está cadastrado?

 Logar

    <% if(success.length > 0){ %>

    <% } %>

I also have connect-flash configured and used some locals variables to set the specific kind of message

app.use(flash());
var sessionFlash = function(req, res, next) {
    res.locals.currentUser = req.user;
    res.locals.error = req.flash('error');
    res.locals.success = req.flash('success');
    next();

}
app.use(sessionFlash)

And then, my routes:

const express = require('express')
const router = express.Router()
const indexControllers = require('../controllers/indexControllers')

router.get('/', indexControllers.HomePage)

router.get('/signup', indexControllers.Signup)

router.get('/test', (req, res)=>{
  req.flash('success', 'user succesfulyl registered')
  res.redirect('/')
})

module.exports = router;

Body:
If you want to display toastr with error and message using one sentence then using toastr.info. If not, better off separating between success and error message to have clearer context. And use it like this:

<% if(success.length > 0){ %>
  <script>
    toastr.success(`${success[0]}`)
  </script>
<% } %>
<% if(error.length > 0){ %>
  <script>
    toastr.error(`${error[0]}`)
  </script>
<% } %>


问:
Regular Expression (REGEX) to match : or . or '
i want to use regex to check if i have ' or . or :

i should add ? before it

for example

Rue de l'etrang

should be like this

Rue de l?'etrang

or

Rue de l'etrang: nancy

should be like this

Rue de l?'etrang?: nancy

答:
You can use this simple regex : </p>

```<code>'|\.
</code>```

Body:
You can use this simple regex :

'|\.


问:
Retrieving data from database for update
I want to retrieve data from my database for editing by user and I don't know where I'm going wrong...

The codes below are supposed to return the information from the database in json format and insert them into existing textboxes for user edit...

My problem is that, when the update button is clicked, nothing works... there is no response from the browser...

Please help... I'm new to all of this

Code to retrieve data from database (fetch.php):

```<code><?php
$connect= mysqli_connect("localhost", "Eben", "Pass1234", "stageupgh");

if (isset($_POST['item_id'])) {
    $output= array();
    $procedure= "
        CREATE PROCEDURE whereItem(IN item_id int(11))
        BEGIN
            SELECT * FROM items WHERE item_id= item_id;
        END;
    ";
    if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereItem")) {
        if (mysqli_query($connect, $procedure)) {
            $query=  "CALL whereItem(".$_POST['item_id'].")";
            $result= mysqli_query($connect, $query);
            while ($row= mysqli_fetch_array($result)) {
                $output["itemName"]= $row["name"];
                $output['itemDescription']= $row["description"];
                $output['stock']= $row["in_stock"];
                $output['price']= $row["price"];
            }
            echo json_encode($output);
        }
    }
}
</code>```

?>

itemAction.php:

```<code><?php
if (isset($_POST["action"])) {
    $output= '';
    $connect= mysqli_connect("localhost", "Eben", "Pass1234", "stageupgh");

    if ($_POST["action"]=="Add") {
        $itemName= mysqli_real_escape_string($connect, $_POST["itemName"]);
        $itemDescription= mysqli_real_escape_string($connect, $_POST["itemDescription"]);
        $stock= mysqli_real_escape_string($connect, $_POST["stock"]);
        $price= mysqli_real_escape_string($connect, $_POST["price"]);

        $procedure= "
            CREATE PROCEDURE insertItem(IN name varchar(100), description varchar(250), in_stock int(11), price decimal(6,2))
            BEGIN
                INSERT INTO items(name, description, in_stock, price) VALUES (name, description, in_stock, price);
            END
        ";
        if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS insertItem")) {
            if(mysqli_query($connect, $procedure)){
                $query= "CALL insertItem('".$itemName."', '".$itemDescription."','".$stock."','".$price."')";
                mysqli_query($connect, $query);
                echo "Data Inserted";
            }
        }
    }

    if (isset($_POST['action'])=="Edit") {
        $itemName= mysqli_real_escape_string($connect, $_POST["itemName"]);
        $itemDescription= mysqli_real_escape_string($connect, $_POST["itemDescription"]);
        $stock= mysqli_real_escape_string($connect, $_POST["stock"]);
        $price= mysqli_real_escape_string($connect, $_POST["price"]);

        $procedure= "
            CREATE PROCEDURE updateItem(IN item_id int(11), name varchar(100), description  varchar(250), in_stock int(11), price decimal(6,2))
            BEGIN
                UPDATE items SET name= itemName, description= itemDescription, in_stock= stock, price= price WHERE item_id= item_id;
            END;
        ";
        if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateUser")) {
            if (mysqli_query($connect, $procedure)) {
                $query= "CALL updateUser('".$_POST['item_id']."', '".$itemName."', '".$itemDescription."',, '".$stock."', '".$price."')";
                mysqli_query($connect, $query);
                echo "Data Updated";
            }
        }
    }
}
</code>```

?>

Main body:

```<code><div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label class="sr-only">Item Name:</label>
                                    <input type="text" class="form-control" placeholder="Name" id="itemName" name="itemName" required data-validation-required-message="Please enter the item's." autofocus="true">
                                    <p class="text-danger help-block"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label class="sr-only">Description</label>
                                    <input type="text" class="form-control" placeholder="Item Description" id="itemDescription" name="itemDescription" required data-validation-required-message="Please enter the item's description.">
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label class="sr-only">In Stock</label>
                                    <input type="text" class="form-control" placeholder="In Stock" id="stock" name="stock" required data-validation-required-message="How many items are available">
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <div class="row control-group">
                                <div class="form-group col-xs-12 floating-label-form-group controls">
                                    <label class="sr-only">Price (Gh &#x20b5:)</label>
                                    <input type="text" class="form-control" placeholder="Unit Price (Gh &#x20b5:)" id="price" name="price" required data-validation-required-message="How many items are available">
                                    <p class="help-block text-danger"></p>
                                </div>
                            </div>
                            <br>
                            <div id="success"></div>
                            <div class="row">
                                <div class="form-group col-xs-12">
                                    <input type="hidden" name="item_id" id="item_id">
                                    <button type="button" name="action" id="action" class="btn btn-success btn-lg" style="float: right; margin-right: 20px;">Add</button>
                                </div>
                            </div>
</code>```

Script:

```<code><script type="text/javascript">

$(document).ready(function(){
    fetchItems();
    function fetchItems(){
        var action= "select";
        $.ajax({
            url: "itemSelect.php",
            method: "POST",
            data:{action:action},
            success: function(data){
                $('#itemName').val('');
                $('#itemDescription').val('');
                $('#stock').val('');
                $('#price').val('');
                $('#action').val("Add");
                $('#result').html(data);
            }
        })
    }
    $('#action').click(function(){
        var itemName= $('#itemName').val();
        var itemDescription= $('#itemDescription').val();
        var stock= $('#stock').val();
        var price= $('#price').val();
        var item_id= $('#itemId').val();
        var action= $('#action').text();

        if (itemName!='' && itemDescription!='' && stock!='' && price!='') {
            $.ajax({
                url: "itemAction.php",
                method: "POST",
                data:{itemName:itemName, itemDescription:itemDescription, stock:stock, price:price, item_id:item_id, action:action},
                success:function(data){
                    alert(data);
                    fetchItems();
                }
            });
        }else{
            alert("All fields are required");
        }
    });
    $(document).on('click', '.update', function(){
        var item_id= $(this).attr("#item_id");
        $.ajax({
            url: "fetch.php",
            method: "POST",
            data:{item_id:item_id},
            dataType:"json",
            success:function(data){
                $action('#action').text("Edit");
                $('#itemId').val(item_id);
                $('#itemName').val(data.itemName);
                $('#itemDescription').val(data.itemDescription);
                $('#stock').val(data.stock);
                $('#price').val(data.price);
            }
        });
    });
});
</code>```

Thanks

答: First ensure that you are connecting to the database successfully. Write some code that will connect to the database, query and echo to the screen when you press the submit button. If this works then one debug item can be checked off you list.</p>

Body:
I want to retrieve data from my database for editing by user and I don't know where I'm going wrong...

The codes below are supposed to return the information from the database in json format and insert them into existing textboxes for user edit...

My problem is that, when the update button is clicked, nothing works... there is no response from the browser...

Please help... I'm new to all of this

Code to retrieve data from database (fetch.php):

<?php
$connect= mysqli_connect("localhost", "Eben", "Pass1234", "stageupgh");

if (isset($_POST['item_id'])) {
    $output= array();
    $procedure= "
        CREATE PROCEDURE whereItem(IN item_id int(11))
        BEGIN
            SELECT * FROM items WHERE item_id= item_id;
        END;
    ";
    if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereItem")) {
        if (mysqli_query($connect, $procedure)) {
            $query=  "CALL whereItem(".$_POST['item_id'].")";
            $result= mysqli_query($connect, $query);
            while ($row= mysqli_fetch_array($result)) {
                $output["itemName"]= $row["name"];
                $output['itemDescription']= $row["description"];
                $output['stock']= $row["in_stock"];
                $output['price']= $row["price"];
            }
            echo json_encode($output);
        }
    }
}

?>

itemAction.php:

<?php
if (isset($_POST["action"])) {
    $output= '';
    $connect= mysqli_connect("localhost", "Eben", "Pass1234", "stageupgh");

    if ($_POST["action"]=="Add") {
        $itemName= mysqli_real_escape_string($connect, $_POST["itemName"]);
        $itemDescription= mysqli_real_escape_string($connect, $_POST["itemDescription"]);
        $stock= mysqli_real_escape_string($connect, $_POST["stock"]);
        $price= mysqli_real_escape_string($connect, $_POST["price"]);

        $procedure= "
            CREATE PROCEDURE insertItem(IN name varchar(100), description varchar(250), in_stock int(11), price decimal(6,2))
            BEGIN
                INSERT INTO items(name, description, in_stock, price) VALUES (name, description, in_stock, price);
            END
        ";
        if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS insertItem")) {
            if(mysqli_query($connect, $procedure)){
                $query= "CALL insertItem('".$itemName."', '".$itemDescription."','".$stock."','".$price."')";
                mysqli_query($connect, $query);
                echo "Data Inserted";
            }
        }
    }

    if (isset($_POST['action'])=="Edit") {
        $itemName= mysqli_real_escape_string($connect, $_POST["itemName"]);
        $itemDescription= mysqli_real_escape_string($connect, $_POST["itemDescription"]);
        $stock= mysqli_real_escape_string($connect, $_POST["stock"]);
        $price= mysqli_real_escape_string($connect, $_POST["price"]);

        $procedure= "
            CREATE PROCEDURE updateItem(IN item_id int(11), name varchar(100), description  varchar(250), in_stock int(11), price decimal(6,2))
            BEGIN
                UPDATE items SET name= itemName, description= itemDescription, in_stock= stock, price= price WHERE item_id= item_id;
            END;
        ";
        if (mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateUser")) {
            if (mysqli_query($connect, $procedure)) {
                $query= "CALL updateUser('".$_POST['item_id']."', '".$itemName."', '".$itemDescription."',, '".$stock."', '".$price."')";
                mysqli_query($connect, $query);
                echo "Data Updated";
            }
        }
    }
}

?>

Main body:

                                    Item Name:
                                    <input type="text" class="form-control" placeholder="Name" id="itemName" name="itemName" required data-validation-required-message="Please enter the item's." autofocus="true">

                                    Description
                                    <input type="text" class="form-control" placeholder="Item Description" id="itemDescription" name="itemDescription" required data-validation-required-message="Please enter the item's description.">

                                    In Stock
                                    <input type="text" class="form-control" placeholder="In Stock" id="stock" name="stock" required data-validation-required-message="How many items are available">

                                    Price (Gh &#x20b5:)
                                    <input type="text" class="form-control" placeholder="Unit Price (Gh &#x20b5:)" id="price" name="price" required data-validation-required-message="How many items are available">

                                    <input type="hidden" name="item_id" id="item_id">
                                    <button type="button" name="action" id="action" class="btn btn-success btn-lg" style="float: right; margin-right: 20px;">Add</button>

Script:


问:
Cruft code. IoC to the rescue
In question about usefulness of IoC Container, the winning submitter mentioned that with an IoC container you can take this:

```<code>public class UglyCustomer : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            string oldValue = _firstName;
            _firstName = value;
            if(oldValue != value)
                OnPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            string oldValue = value;
            _lastName = value;
            if(oldValue != value)
                OnPropertyChanged("LastName");
        }
    }
}
</code>```

to this:

```<code>var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());
</code>```

Questions:

Which magic IoC container provides this goodness?

An example implementing this?

Any downsides?

In a project with complex dependencies, will I be crying when I try to apply data binding to these objects?

答:
To do this in a generic way (i.e. a single piece of code implementing INotifyPropertyChanged
for any class) use a proxy. There are lots of implementations around to do this with Castle.DynamicProxy or LinFu or Unity. These proxy libraries have good support in IoC containers, for example DynamicProxy has good integration with Castle Windsor and Unity interception  (or whatever it's called) has obviously good integration with the Unity container.</p>

ContentLicense: CC BY-SA 2.5

Title: Cruft code. IoC to the rescue

Body:
In question about usefulness of IoC Container, the winning submitter mentioned that with an IoC container you can take this:

public class UglyCustomer : INotifyPropertyChanged
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            string oldValue = _firstName;
            _firstName = value;
            if(oldValue != value)
                OnPropertyChanged("FirstName");
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            string oldValue = value;
            _lastName = value;
            if(oldValue != value)
                OnPropertyChanged("LastName");
        }
    }
}

to this:

var bindingFriendlyInstance = IoC.Resolve<Customer>(new NotifyPropertyChangedWrapper());

Questions:

Which magic IoC container provides this goodness?

An example implementing this?

Any downsides?

In a project with complex dependencies, will I be crying when I try to apply data binding to these objects?


问:
drop down list combo box excel
I have a searchable combo box with suggestions to select from as I type letters in it (vba below). However i want to be able to click the arrow of the combo box (if i don't type anything else in it of course) and see the entire drop down list. For some reason the code below does not show me the entire list if I click the arrow.

Any suggestions much appreciated.

```<code>    Dim ws As Worksheet
    Dim x, dict
    Dim i As Long
    Dim str As String
    Set ws = Sheets("Lists")
    x = ws.Range("Listing").value
    Set dict = CreateObject("Scripting.Dictionary")
    str = Me.cbo1.value
    If str <> "" Then
     For i = 1 To UBound(x, 1)
    If InStr(LCase(x(i, 1)), LCase(str)) > 0 Then
        dict.Item(x(i, 1)) = ""
    End If
    Next i
     Me.cbo1.List = dict.keys
   Else
    Me.cbo1.List = x
   End If
   Me.cbo1.DropDown
</code>```

答:
What you want is that if the arrow is clicked when nothing is yet selected or written in the combo by the user, to show all the items of the list, which you load from the named range "Listing" without any filtering.

To do so, add this event handler to your userform's code:

```<code>Private Sub Cbo1_DropButtonClick()
  'If Len(Trim(cbo1.text)) = 0 Then
  If Trim(cbo1.text) = "type here" Then
    cbo1.List = Sheets("Lists").Range("Listing").Value
    Exit Sub
  End If

  ' Your code to add only items that match the characters typed by the user
  ' ...
End Sub
</code>```

Title: drop down list combo box excel

Body:
I have a searchable combo box with suggestions to select from as I type letters in it (vba below). However i want to be able to click the arrow of the combo box (if i don't type anything else in it of course) and see the entire drop down list. For some reason the code below does not show me the entire list if I click the arrow.

Any suggestions much appreciated.

    Dim ws As Worksheet
    Dim x, dict
    Dim i As Long
    Dim str As String
    Set ws = Sheets("Lists")
    x = ws.Range("Listing").value
    Set dict = CreateObject("Scripting.Dictionary")
    str = Me.cbo1.value
    If str <> "" Then
     For i = 1 To UBound(x, 1)
    If InStr(LCase(x(i, 1)), LCase(str)) > 0 Then
        dict.Item(x(i, 1)) = ""
    End If
    Next i
     Me.cbo1.List = dict.keys
   Else
    Me.cbo1.List = x
   End If
   Me.cbo1.DropDown

Body:
What you want is that if the arrow is clicked when nothing is yet selected or written in the combo by the user, to show all the items of the list, which you load from the named range "Listing" without any filtering.

To do so, add this event handler to your userform's code:

Private Sub Cbo1_DropButtonClick()
  'If Len(Trim(cbo1.text)) = 0 Then
  If Trim(cbo1.text) = "type here" Then
    cbo1.List = Sheets("Lists").Range("Listing").Value
    Exit Sub
  End If

  ' Your code to add only items that match the characters typed by the user
  ' ...
End Sub


问:
Send POST data in Android
I'm trying to send POST data in Android. On internet I find some codes with Apache, but the codes were deprecated.

I need to send the values bellow to my web service and than register on PostgreSQL

```<code>edtName = (EditText) findViewById(R.id.edtName);
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtLogin = (EditText) findViewById(R.id.edtLogin);
edtPassword = (EditText) findViewById(R.id.edtPassword);
</code>```

If someone knows how to do that, can be with GSON or not.

答:
Use Retrofit with Gson.
Add those libraries to your gradle

```<code>compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
</code>```

First create a singleton class with the retrofit instance

```<code>public class Api {

    public static final String BASE_URL = "http://yourApiBaseUrl.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getInstance(){
        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

Then define your model, I assume is something like this:

```<code>public class User {

    @SerializedName("Name")
    private String name;

    @SerializedName("Email")
    private String email;

    @SerializedName("Login")
    private String login;

    @SerializedName("Password")
    private String password;

    public User(...){
         //Constructor
    }

}
</code>```

After that, you are ready to create your calls to the api. Create an interface to define the methods of your api. I assume your post method return the posted user. You will send all the data encapsulated in the user model, inside the body of the http request:

```<code>public interface UserService {

    @POST("yourPostUrl")
    Call<User> postUser(@Body User user);

}
</code>```

Now it's time to do the POST. Create a method where you want to perform the post, just like this:

```<code>private void postUser(String edtName, String edtEmail, String edtLogin, String edtPassword){

        UserService service = Api.getInstance().create(UserService.class);
        Call<User> userCall = service.postUser(new User(edtName, edtEmail, edtLogin, edtPassword));
        userCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {

                }
            }
            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
}
</code>```

And that's all, hope it helps.

For more information visit the retrofit website and read the tutorial.

Title: Send POST data in Android

Body:
I'm trying to send POST data in Android. On internet I find some codes with Apache, but the codes were deprecated.

I need to send the values bellow to my web service and than register on PostgreSQL

edtName = (EditText) findViewById(R.id.edtName);
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtLogin = (EditText) findViewById(R.id.edtLogin);
edtPassword = (EditText) findViewById(R.id.edtPassword);

If someone knows how to do that, can be with GSON or not.

Body:
Use Retrofit with Gson.
Add those libraries to your gradle

compile 'com.google.code.gson:gson:2.8.0'
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'

First create a singleton class with the retrofit instance

public class Api {

    public static final String BASE_URL = "http://yourApiBaseUrl.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getInstance(){
        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Then define your model, I assume is something like this:

public class User {

    @SerializedName("Name")
    private String name;

    @SerializedName("Email")
    private String email;

    @SerializedName("Login")
    private String login;

    @SerializedName("Password")
    private String password;

    public User(...){
         //Constructor
    }

}

After that, you are ready to create your calls to the api. Create an interface to define the methods of your api. I assume your post method return the posted user. You will send all the data encapsulated in the user model, inside the body of the http request:

public interface UserService {

    @POST("yourPostUrl")
    Call<User> postUser(@Body User user);

}

Now it's time to do the POST. Create a method where you want to perform the post, just like this:

private void postUser(String edtName, String edtEmail, String edtLogin, String edtPassword){

        UserService service = Api.getInstance().create(UserService.class);
        Call<User> userCall = service.postUser(new User(edtName, edtEmail, edtLogin, edtPassword));
        userCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {

                }
            }
            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
}

And that's all, hope it helps.

For more information visit the retrofit website and read the tutorial.


问:
SSL Handshake failure Java
I was learning SSL communications and I came across this issue. I am writing a simple client which tries to handshake with a local apache server. The server is https enabled. I added the server certificates to all possible trust stores (the one in jdk & the one used by the program also). But the handshake status is never reaching FINISHED. It is stuck at NEED_TASK status continuously
I get a sun.security.ssl.Handshaker$DelegatedTask at the first entry into loop. Thereafter the status is NEED_TASK and the task is null.
. Where is my understanding wrong \ flaw with the below code ?

Note  : I took the code from the following tutorial :

http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#KRB

The handshake code which is stuck at NEED_TASK status is below :

```<code>void doHandshake(SocketChannel socketChannel, SSLEngine engine,
            ByteBuffer myNetData, ByteBuffer peerNetData) throws Exception {

        // Create byte buffers to use for holding application data
        int appBufferSize = engine.getSession().getApplicationBufferSize();
        ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize);
        ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize);
        // Begin handshake
        engine.beginHandshake();
        SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();
        int i=0;
        // Process handshaking message
        while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
            hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
            i++;
            switch (hs) {

            case NEED_UNWRAP:
                // Receive handshaking data from peer
                if (socketChannel.read(peerNetData) < 0) {
                    // The channel has reached end-of-stream
                }

                // Process incoming handshaking data
                peerNetData.flip();
                SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
                peerNetData.compact();
                hs = res.getHandshakeStatus();

                // Check status
                switch (res.getStatus()) {
                case OK :
                    // Handle OK status
                    break;

                // Handle other status: BUFFER_UNDERFLOW, BUFFER_OVERFLOW, CLOSED

                }
                break;

            case NEED_WRAP :
                // Empty the local network packet buffer.
                myNetData.clear();

                // Generate handshaking data
                res = engine.wrap(myAppData, myNetData);
                hs = res.getHandshakeStatus();

                // Check status
                switch (res.getStatus()) {
                case OK :
                    myNetData.flip();

                    // Send the handshaking data to peer
                    while (myNetData.hasRemaining()) {
                        socketChannel.write(myNetData);
                    }
                    break;

                // Handle other status:  BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED

                }
                break;

            case NEED_TASK :
                Runnable task =engine.getDelegatedTask();
                if(task!= null) {
                    //task.run();
                    new Thread(task).start();
                }// Handle blocking tasks

                break;

            // Handle other status:  // FINISHED or NOT_HANDSHAKING

            }
        }
        // Processes after handshaking

    }
</code>```

Any help would be appreciated.

答:
The problem was my incomplete understanding of engine.getHandShakeStatus() method.

I changed the above code to

```<code> case NEED_TASK :
            Runnable task =engine.getDelegatedTask();
            if(task!= null) {
                //task.run();
               new Thread(task).start();
            }
            hs = engine.getHandshakeStatus();
            break;
</code>```

And now it finished the handshake

Title: SSL Handshake failure Java

Body:
I was learning SSL communications and I came across this issue. I am writing a simple client which tries to handshake with a local apache server. The server is https enabled. I added the server certificates to all possible trust stores (the one in jdk & the one used by the program also). But the handshake status is never reaching FINISHED. It is stuck at NEED_TASK status continuously
I get a sun.security.ssl.Handshaker$DelegatedTask at the first entry into loop. Thereafter the status is NEED_TASK and the task is null.
. Where is my understanding wrong \ flaw with the below code ?

Note  : I took the code from the following tutorial :

http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/JSSERefGuide.html#KRB

The handshake code which is stuck at NEED_TASK status is below :

void doHandshake(SocketChannel socketChannel, SSLEngine engine,
            ByteBuffer myNetData, ByteBuffer peerNetData) throws Exception {

        // Create byte buffers to use for holding application data
        int appBufferSize = engine.getSession().getApplicationBufferSize();
        ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize);
        ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize);
        // Begin handshake
        engine.beginHandshake();
        SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();
        int i=0;
        // Process handshaking message
        while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
            hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
            i++;
            switch (hs) {

            case NEED_UNWRAP:
                // Receive handshaking data from peer
                if (socketChannel.read(peerNetData) < 0) {
                    // The channel has reached end-of-stream
                }

                // Process incoming handshaking data
                peerNetData.flip();
                SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
                peerNetData.compact();
                hs = res.getHandshakeStatus();

                // Check status
                switch (res.getStatus()) {
                case OK :
                    // Handle OK status
                    break;

                // Handle other status: BUFFER_UNDERFLOW, BUFFER_OVERFLOW, CLOSED

                }
                break;

            case NEED_WRAP :
                // Empty the local network packet buffer.
                myNetData.clear();

                // Generate handshaking data
                res = engine.wrap(myAppData, myNetData);
                hs = res.getHandshakeStatus();

                // Check status
                switch (res.getStatus()) {
                case OK :
                    myNetData.flip();

                    // Send the handshaking data to peer
                    while (myNetData.hasRemaining()) {
                        socketChannel.write(myNetData);
                    }
                    break;

                // Handle other status:  BUFFER_OVERFLOW, BUFFER_UNDERFLOW, CLOSED

                }
                break;

            case NEED_TASK :
                Runnable task =engine.getDelegatedTask();
                if(task!= null) {
                    //task.run();
                    new Thread(task).start();
                }// Handle blocking tasks

                break;

            // Handle other status:  // FINISHED or NOT_HANDSHAKING

            }
        }
        // Processes after handshaking

    }

Any help would be appreciated.

Body:
The problem was my incomplete understanding of engine.getHandShakeStatus() method.

I changed the above code to

 case NEED_TASK :
            Runnable task =engine.getDelegatedTask();
            if(task!= null) {
                //task.run();
               new Thread(task).start();
            }
            hs = engine.getHandshakeStatus();
            break;

And now it finished the handshake


问:
how to return createdatroute location?
I'm attempting to create a record like so:

```<code>[Route("", Name = "CreateAccount")]
[HttpPost]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account)
{

    var response = await _accountService.Create(account);

    return CreatedAtRoute(
        routeName: "GetAccount",????);
}
</code>```

The creation of the record succeeds; however. I'm not sure how to return a CreatedAtRoute object?

This is my GET controller method:

```<code>[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
    var query = Request.RequestUri.PathAndQuery.Split('/')[2];
    var response = _accountService.Get(query);

    if (!response.Result.IsSuccessStatusCode)
    {
        return NotFound();
    }

    var readAsAsync = response.Result.Content.ReadAsAsync<object>();
    if (readAsAsync == null)
    {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}
</code>```

as you can see the controller does not accept any parameters, rather we get the parameters from Request.RequestUri.PathAndQuery

After creating a record, how do we return a valid CreatedAtRoute result?

答:
One thing you can try is to pass route values as an object. The framework should convert them (route values) to query string.

```<code>[HttpPost]
[Route("", Name = "CreateAccount")]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account) {

    var response = await _accountService.Create(account);

    var model = await response.Content.ReadAsAsync<MyModel>();

    return CreatedAtRoute(
        routeName: "GetAccount",
        routeValues: new { id = model.Id, name = model.Name }, // can include other properties
        content: model);
}
</code>```

That should set the location header in the 201 response with something like

```<code>LOCATION: http://localhost/api/accounts?id=5&name=JDoe
</code>```

Title: how to return createdatroute location?

Body:
I'm attempting to create a record like so:

[Route("", Name = "CreateAccount")]
[HttpPost]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account)
{

    var response = await _accountService.Create(account);

    return CreatedAtRoute(
        routeName: "GetAccount",????);
}

The creation of the record succeeds; however. I'm not sure how to return a CreatedAtRoute object?

This is my GET controller method:

[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
    var query = Request.RequestUri.PathAndQuery.Split('/')[2];
    var response = _accountService.Get(query);

    if (!response.Result.IsSuccessStatusCode)
    {
        return NotFound();
    }

    var readAsAsync = response.Result.Content.ReadAsAsync<object>();
    if (readAsAsync == null)
    {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
}

as you can see the controller does not accept any parameters, rather we get the parameters from Request.RequestUri.PathAndQuery

After creating a record, how do we return a valid CreatedAtRoute result?

Body:
One thing you can try is to pass route values as an object. The framework should convert them (route values) to query string.

[HttpPost]
[Route("", Name = "CreateAccount")]
public async Task<IHttpActionResult> CreateAccount([FromBody] JObject account) {

    var response = await _accountService.Create(account);

    var model = await response.Content.ReadAsAsync<MyModel>();

    return CreatedAtRoute(
        routeName: "GetAccount",
        routeValues: new { id = model.Id, name = model.Name }, // can include other properties
        content: model);
}

That should set the location header in the 201 response with something like

LOCATION: http://localhost/api/accounts?id=5&name=JDoe


问:
Printing a warning message over multiple lines
I am trying to print a warning message that is a little long and includes 2 variable calls. Here's my code: </p>

```<code>warning( 'MATLAB:questionable_argument', ...
           'the arguments dt (%d) and h (%d) are sub-optimal. Consider increasing nt or decreasing nx.', ...
           dt, h )
</code>```

<p>Obviously, the line of text extends to the right when viewing the MATLAB code. How can I break it so it wraps nicely? I've tried multiple things but keep getting syntax errors. </p>

答:
A more simple version than EBH had provided is as shown:</p>

```<code>str1 = 'text 1';
str2 = 'text 2';
str3 = 'etc.';
str = sprintf('\n%s \n%s \n%s \n',str1,str2,str3);
warning(str)
</code>```

Body:
I am trying to print a warning message that is a little long and includes 2 variable calls. Here's my code:

warning( 'MATLAB:questionable_argument', ...
           'the arguments dt (%d) and h (%d) are sub-optimal. Consider increasing nt or decreasing nx.', ...
           dt, h )

Obviously, the line of text extends to the right when viewing the MATLAB code. How can I break it so it wraps nicely? I've tried multiple things but keep getting syntax errors.

Body:
A more simple version than EBH had provided is as shown:

str1 = 'text 1';
str2 = 'text 2';
str3 = 'etc.';
str = sprintf('\n%s \n%s \n%s \n',str1,str2,str3);
warning(str)


问:
Angucomplete Alt : Getting "No Results Found" before the server response is obtained
I am trying to initiate a request after 3 characters but once 3 characters are typed I am getting the No records found error and after that I can find the service call get completed but nothing is shown in auto complete(only the error message under the autocomplete dropdown).What am I missing here?

HTML code:

```<code>       <angucomplete-alt id="angu_{{$index}}"
                                      placeholder="Search people"
                                      remote-api-handler="search"
                                      remote-url-data-field="results"
                                      title-field="fullName"
                                      minlength="3"
                                      input-class="form-control form-control-small"
                                      selected-object="selected"
                                      selected-object-data="$index"
                                      clear-selected="true"/>
</code>```

Api remote handler

```<code>  $scope.search = function(str, timeoutPromise) {
   return $timeout(function () {
    $scope.input = {};
     $scope.input.userId = "";
     $scope.input.name = str;
     $scope.input.system = "";
     $scope.input.officeNumber = "";
     $scope.input.department= "";
     //  server call and get the response to $scope.organisationNames
        var promise = genericAPIService.doApiCall(url, appConstant.POST,
    JSON.stringify($scope.input));
            promise.then(
              function(payload) {
                  console.log(payload);
                 $scope.organisationNames = payload.data.result.data.List;
                 $scope.results = [];
                 $scope.organisationNames.forEach(function(organisation) {
                        if ((organisation.fullName.toLowerCase().indexOf(str.toString().toLowerCase()) >= 0)) {
                            $scope.results.push(organisation);
                        }
                    });
                 return scope.results;
              },
              function(errorPayload) {
                  $log.error('failure loading role json', errorPayload);
              }).finally(function(){
                    $scope.loading = false;
                });
}
},5000);
};
</code>```

Tried another version of the same:

```<code> <angucomplete-alt id="angu_{{$index}}"
                   placeholder="Search people"
                   selected-object="selectedBusiness"
                   selected-object-data="$index"
                   clear-selected="true"
                   input-class="form-control
                   form-control-small"
                   remote-api-handler="searchAPI"
                   remote-url-data-field="responseData.data"
                   title-field="fullName" minlength="3" />

   $scope.searchAPI = function (userInputString, timeoutPromise) {
   $scope.approversAndEndorsersInput = {};
   return $timeout(function () {
         $scope.approversAndEndorsersInput.userId = "";
         $scope.approversAndEndorsersInput.name = userInputString;
         $scope.approversAndEndorsersInput.system = "";
         $scope.approversAndEndorsersInput.officeNumber = "";
         $scope.approversAndEndorsersInput.department= "";
         return $http.post(appConstant.selfDomainName+appConstant.getApproversAndEndorsersList, JSON.stringify($scope.approversAndEndorsersInput), {timeout: timeoutPromise});

   }, 1000);
</code>```

}

答:
First Example

In your first example you never return the promise

```<code>var promise = genericAPIService.doApiCall(url, appConstant.POST, ...
</code>```

So the $timeout is never resolved with the response from the API

Return the promise at the end of the $timeout callback

Second Example

It looks like that you are not settings correctly the remote-url-data-field

Here's a plunker that I came with using your second example http://plnkr.co/edit/QsJFWh?p=preview and it works correctly, I have slightly altered the searchAPI method to show the last http response

When I misconfigured the remote-url-data-field, the response was made but the angucomplete read "No results found"

See the notes on the plunk, and try to configure it the way it works for you
If you can't bind the correct property, provide a response sample from your api, and we can come up with a solution

Using $timeout

The reason you are using $timeout to add a delay is not obvious, you do it in both examples. The only thing this does is to add an artificial delay of the given amount of time. If the reason is to add some debounce/delay to the input field triggering an API request, that won't cut it.

There is a pause property that can be configured with a delay in milliseconds that will ensure that the api will be called after this amount of time when the user has stopped typing.
You can see it on the plunker demo, the default value is 500
Since your custom service and $http (from the 2nd example) both return promises, you can directly return their result

Body:
I am trying to initiate a request after 3 characters but once 3 characters are typed I am getting the No records found error and after that I can find the service call get completed but nothing is shown in auto complete(only the error message under the autocomplete dropdown).What am I missing here?

HTML code:

       <angucomplete-alt id="angu_{{$index}}"
                                      placeholder="Search people"
                                      remote-api-handler="search"
                                      remote-url-data-field="results"
                                      title-field="fullName"
                                      minlength="3"
                                      input-class="form-control form-control-small"
                                      selected-object="selected"
                                      selected-object-data="$index"
                                      clear-selected="true"/>

Api remote handler

  $scope.search = function(str, timeoutPromise) {
   return $timeout(function () {
    $scope.input = {};
     $scope.input.userId = "";
     $scope.input.name = str;
     $scope.input.system = "";
     $scope.input.officeNumber = "";
     $scope.input.department= "";
     //  server call and get the response to $scope.organisationNames
        var promise = genericAPIService.doApiCall(url, appConstant.POST,
    JSON.stringify($scope.input));
            promise.then(
              function(payload) {
                  console.log(payload);
                 $scope.organisationNames = payload.data.result.data.List;
                 $scope.results = [];
                 $scope.organisationNames.forEach(function(organisation) {
                        if ((organisation.fullName.toLowerCase().indexOf(str.toString().toLowerCase()) >= 0)) {
                            $scope.results.push(organisation);
                        }
                    });
                 return scope.results;
              },
              function(errorPayload) {
                  $log.error('failure loading role json', errorPayload);
              }).finally(function(){
                    $scope.loading = false;
                });
}
},5000);
};

Tried another version of the same:

 <angucomplete-alt id="angu_{{$index}}"
                   placeholder="Search people"
                   selected-object="selectedBusiness"
                   selected-object-data="$index"
                   clear-selected="true"
                   input-class="form-control
                   form-control-small"
                   remote-api-handler="searchAPI"
                   remote-url-data-field="responseData.data"
                   title-field="fullName" minlength="3" />

   $scope.searchAPI = function (userInputString, timeoutPromise) {
   $scope.approversAndEndorsersInput = {};
   return $timeout(function () {
         $scope.approversAndEndorsersInput.userId = "";
         $scope.approversAndEndorsersInput.name = userInputString;
         $scope.approversAndEndorsersInput.system = "";
         $scope.approversAndEndorsersInput.officeNumber = "";
         $scope.approversAndEndorsersInput.department= "";
         return $http.post(appConstant.selfDomainName+appConstant.getApproversAndEndorsersList, JSON.stringify($scope.approversAndEndorsersInput), {timeout: timeoutPromise});

   }, 1000);

}

Body:
First Example

In your first example you never return the promise

var promise = genericAPIService.doApiCall(url, appConstant.POST, ...

So the $timeout is never resolved with the response from the API

Return the promise at the end of the $timeout callback

Second Example

It looks like that you are not settings correctly the remote-url-data-field

Here's a plunker that I came with using your second example http://plnkr.co/edit/QsJFWh?p=preview and it works correctly, I have slightly altered the searchAPI method to show the last http response

When I misconfigured the remote-url-data-field, the response was made but the angucomplete read "No results found"

See the notes on the plunk, and try to configure it the way it works for you
If you can't bind the correct property, provide a response sample from your api, and we can come up with a solution

Using $timeout

The reason you are using $timeout to add a delay is not obvious, you do it in both examples. The only thing this does is to add an artificial delay of the given amount of time. If the reason is to add some debounce/delay to the input field triggering an API request, that won't cut it.

There is a pause property that can be configured with a delay in milliseconds that will ensure that the api will be called after this amount of time when the user has stopped typing.
You can see it on the plunker demo, the default value is 500
Since your custom service and $http (from the 2nd example) both return promises, you can directly return their result


问:
Removing an item from a list
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

```<code>def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list
</code>```

答:
How about you check if the word is already in the list before appending it, like so:

```<code>def endwords(sent):
     wordList = []
     words = sent.split()
     for word in words:
         if "." in word and word not in wordList:
             wordList.append(word)
     return wordList
</code>```

You're trying to check if word == list, but that's seeing if the word is equal to the entire list. To check if an element is in a container in python, you can use the in keyword. Alternatively, to check if something is not in a container, you can use not in.

Another option is to use a set:

```<code>def endwords(sent):
     wordSet = set()
     words = sent.split()
     for word in words:
         if "." in word:
             wordSet.add(word)
     return wordSet
</code>```

And to make things a little cleaner, here is a version using set comprehension:

```<code>def endwords(sent):
    return {word for word in sent.split() if '.' in word}
</code>```

If you want to get a list out of this function, you can do so like this:

```<code>def endwords(sent):
    return list({word for word in sent.split() if '.' in word})
</code>```

Since you said in your question you want to check if the word ends with a '.', you probably also want to use the endswith() function like so:

```<code>def endwords(sent):
    return list({word for word in sent.split() if word.endswith('.')})
</code>```

ContentLicense: CC BY-SA 4.0

Title: Removing an item from a list

Body:
I would like to remove to ignore duplicates in my list. For example, let's say the function checks for words that end with a ''.'' and puts them in a list. I would like to make sure that duplicate words don't go in the list.

Here is what I have so far:

def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix
        if (word == list):
            list.remove(word)
    return list

Body:
How about you check if the word is already in the list before appending it, like so:

def endwords(sent):
     wordList = []
     words = sent.split()
     for word in words:
         if "." in word and word not in wordList:
             wordList.append(word)
     return wordList

You're trying to check if word == list, but that's seeing if the word is equal to the entire list. To check if an element is in a container in python, you can use the in keyword. Alternatively, to check if something is not in a container, you can use not in.

Another option is to use a set:

def endwords(sent):
     wordSet = set()
     words = sent.split()
     for word in words:
         if "." in word:
             wordSet.add(word)
     return wordSet

And to make things a little cleaner, here is a version using set comprehension:

def endwords(sent):
    return {word for word in sent.split() if '.' in word}

If you want to get a list out of this function, you can do so like this:

def endwords(sent):
    return list({word for word in sent.split() if '.' in word})

Since you said in your question you want to check if the word ends with a '.', you probably also want to use the endswith() function like so:

def endwords(sent):
    return list({word for word in sent.split() if word.endswith('.')})


问:
I want to change my ionic start page
I am working on the project but when I close the terminal, the project returns to the default screen when I come back.

My project files are as follows,
click for photo

I want to start templates/anasayfa.html every time the app is opened

But it always comes across
click for photo

答:
in ionic2+ you have to place all html files in seperate folders under pages folder. If you see your project there are two folders like home and list under pages folder. to create a new page use this command

```<code>ionic g page anasayfa
</code>```

it will create a folder with  four files (.html,.ts and .scss type files)

now to make it as root page, we need to change root page in app.component.ts file like this

```<code>rootPage:any = anasayfaPage;
</code>```

Title: I want to change my ionic start page

Body:
in ionic2+ you have to place all html files in seperate folders under pages folder. If you see your project there are two folders like home and list under pages folder. to create a new page use this command

ionic g page anasayfa

it will create a folder with  four files (.html,.ts and .scss type files)

now to make it as root page, we need to change root page in app.component.ts file like this

rootPage:any = anasayfaPage;


问:
Multiple enums in datomic
Is it possible to add multiple enums to an attribute in datomic ? Something like :

```<code>[{:artist/name "Leonard Cohen"
  :artist/countries  [:country/GR :country/CA] }
</code>```

In this case  I get something like
":db.error/not-an-attribute :country/GR is not an attribute"

However

```<code>[{:artist/name "Leonard Cohen"
  :artist/countries  :country/GR  }
</code>```

would work

答:
Please see the James Bond example in the Tupelo-Datomic library.  In short, when adding multiple enum attributes you need to wrap them in a set instead of a vector:

```<code>; Create some antagonists and load them into the db.  We can specify some of the
; attribute-value pairs at the time of creation, and add others later. Note that
; whenever we are adding multiple values for an attribute in a single step (e.g.
; :weapon/type), we must wrap all of the values in a set. Note that the set
; implies there can never be duplicate weapons for any one person.  As before,
; we immediately commit the new entities into the DB.
(td/transact *conn*
  (td/new-entity { :person/name "James Bond" :location "London"     :weapon/type #{ :weapon/gun :weapon/wit   } } )
  (td/new-entity { :person/name "M"          :location "London"     :weapon/type #{ :weapon/gun :weapon/guile } } )
  (td/new-entity { :person/name "Dr No"      :location "Caribbean"  :weapon/type    :weapon/gun                 } ))
</code>```

Title: Multiple enums in datomic

Body:
Is it possible to add multiple enums to an attribute in datomic ? Something like :

[{:artist/name "Leonard Cohen"
  :artist/countries  [:country/GR :country/CA] }

In this case  I get something like
":db.error/not-an-attribute :country/GR is not an attribute"

However

[{:artist/name "Leonard Cohen"
  :artist/countries  :country/GR  }

would work

Body:
Please see the James Bond example in the Tupelo-Datomic library.  In short, when adding multiple enum attributes you need to wrap them in a set instead of a vector:

; Create some antagonists and load them into the db.  We can specify some of the
; attribute-value pairs at the time of creation, and add others later. Note that
; whenever we are adding multiple values for an attribute in a single step (e.g.
; :weapon/type), we must wrap all of the values in a set. Note that the set
; implies there can never be duplicate weapons for any one person.  As before,
; we immediately commit the new entities into the DB.
(td/transact *conn*
  (td/new-entity { :person/name "James Bond" :location "London"     :weapon/type #{ :weapon/gun :weapon/wit   } } )
  (td/new-entity { :person/name "M"          :location "London"     :weapon/type #{ :weapon/gun :weapon/guile } } )
  (td/new-entity { :person/name "Dr No"      :location "Caribbean"  :weapon/type    :weapon/gun                 } ))


问:
VisitId between (different) date range for each user
For each fullvisitorId, i'm trying to get all visitId between date_1 and date_2. which is of-course differ for each user.

Can anyone give any pointers how I can go about doing this?

for example:

user_1: i'd like all visitId between 1st & 20th June

user_2: i'd like all visitId between 12th & 27th June
... and so son

date_1 and date_2 correspond to important actions (Event hits) they took on the site. Download Trial & Purchase

Thanks in advance for any leads in this.

答:
One possible way of solving this is using analytical functions. As an example:

```<code>#standardSQL
WITH data AS(
  select '1' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event2' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '4' as visitid, '20170523' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL

  select '2' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '2' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event2' as eventCategory) as eventInfo)] hits UNION ALL
  select '2' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits union all

  select '3' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '3' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL
  select '3' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits
)

SELECT
  user,
  visitid,
  date
FROM(
  SELECT
    user,
    visitid,
    date,
    MIN(CASE WHEN hits.eventInfo.eventCategory = 'event1' THEN date END) OVER(PARTITION BY user) min_date,
MAX(CASE WHEN hits.eventInfo.eventCategory = 'event2' THEN date END) OVER(PARTITION BY user) max_date
FROM data,
UNNEST(hits) hits
)
WHERE date BETWEEN min_date AND max_date
</code>```

Where data is a simulation of your ga_sessions data (I named 'fullvisitorid' as 'user').

This makes the assumption that a given user can have distinct events for date 1 and date 2 (so it's taking the MIN and MAX respectively) and it assumes that you are saving the event in the eventCategory field (given that your event of "Download" and "Purchase" are defined in the session level, I recommend you use the customDimensions field instead of the hits.eventInfo.eventCategory one).

Other than analytical functions, you can also work with ARRAYs and STRUCTs of the Standard SQL version:

```<code>SELECT
  user,
  ARRAY(SELECT AS STRUCT visitid, date FROM UNNEST(user_data) WHERE date BETWEEN min_date AND max_date) user_data
FROM(
  SELECT
    user,
    ARRAY_AGG((SELECT AS STRUCT visitid, date)) user_data,
    MIN(CASE WHEN EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE hits.eventInfo.eventCategory = 'event1') then date END) min_date,
    MAX(CASE WHEN EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE hits.eventInfo.eventCategory = 'event2') THEN date END) max_date
FROM data
GROUP BY user
)
WHERE ARRAY_LENGTH(ARRAY(SELECT AS STRUCT visitid, date FROM UNNEST(user_data) WHERE date BETWEEN min_date AND max_date)) > 0
</code>```

If the assumptions I made are not aligned with your data you can adapt these techniques to query for what you want. You can also use the simulated data for testing purposes (as well as adapting it to better suit your dataset).

Body:
One possible way of solving this is using analytical functions. As an example:

#standardSQL
WITH data AS(
  select '1' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event2' as eventCategory) as eventInfo)] hits UNION ALL
  select '1' as user, '4' as visitid, '20170523' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL

  select '2' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '2' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event2' as eventCategory) as eventInfo)] hits UNION ALL
  select '2' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits union all

  select '3' as user, '1' as visitid, '20170520' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('event1' as eventCategory) as eventInfo)] hits UNION ALL
  select '3' as user, '2' as visitid, '20170521' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits UNION ALL
  select '3' as user, '3' as visitid, '20170522' as date, ARRAY<STRUCT<hitNumber INT64, eventInfo STRUCT<eventCategory STRING> >> [STRUCT(1 as hitNumber, STRUCT('' as eventCategory) as eventInfo)] hits
)

SELECT
  user,
  visitid,
  date
FROM(
  SELECT
    user,
    visitid,
    date,
    MIN(CASE WHEN hits.eventInfo.eventCategory = 'event1' THEN date END) OVER(PARTITION BY user) min_date,
MAX(CASE WHEN hits.eventInfo.eventCategory = 'event2' THEN date END) OVER(PARTITION BY user) max_date
FROM data,
UNNEST(hits) hits
)
WHERE date BETWEEN min_date AND max_date

Where data is a simulation of your ga_sessions data (I named 'fullvisitorid' as 'user').

This makes the assumption that a given user can have distinct events for date 1 and date 2 (so it's taking the MIN and MAX respectively) and it assumes that you are saving the event in the eventCategory field (given that your event of "Download" and "Purchase" are defined in the session level, I recommend you use the customDimensions field instead of the hits.eventInfo.eventCategory one).

Other than analytical functions, you can also work with ARRAYs and STRUCTs of the Standard SQL version:

SELECT
  user,
  ARRAY(SELECT AS STRUCT visitid, date FROM UNNEST(user_data) WHERE date BETWEEN min_date AND max_date) user_data
FROM(
  SELECT
    user,
    ARRAY_AGG((SELECT AS STRUCT visitid, date)) user_data,
    MIN(CASE WHEN EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE hits.eventInfo.eventCategory = 'event1') then date END) min_date,
    MAX(CASE WHEN EXISTS(SELECT 1 FROM UNNEST(hits) hits WHERE hits.eventInfo.eventCategory = 'event2') THEN date END) max_date
FROM data
GROUP BY user
)
WHERE ARRAY_LENGTH(ARRAY(SELECT AS STRUCT visitid, date FROM UNNEST(user_data) WHERE date BETWEEN min_date AND max_date)) > 0

If the assumptions I made are not aligned with your data you can adapt these techniques to query for what you want. You can also use the simulated data for testing purposes (as well as adapting it to better suit your dataset).


问:
mysql string contained within a search string
What I need seems simple, but I haven't been able to pull it off so far. Maybe it's just these late hours, or maybe it's not that simple after all, I don't know any more :)
So, here's the thing. I want to be able to check whether the search string from my site contains any of the fields from a particular column in my database. So, it would be the opposite of the usual one:

```<code>mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$search}%'
");
</code>```

which looks for the fields with values where the search string is contained.

What would be the easiest way, using some regular expressions or...?

Thanks a bunch!

答:
your query is also good as you want.
but still you can try this.

You can search your string by using MATCH() AGAINST() statement in mysql.

```<code>mysql_query("SELECT * FROM table_name WHERE MATCH(field11,field12) AGAINST ('searchstring')");

Here your field must be having Fulltext datatype.
</code>```

This may work good.

Thanks.

Body:
What I need seems simple, but I haven't been able to pull it off so far. Maybe it's just these late hours, or maybe it's not that simple after all, I don't know any more :)
So, here's the thing. I want to be able to check whether the search string from my site contains any of the fields from a particular column in my database. So, it would be the opposite of the usual one:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$search}%'
");

which looks for the fields with values where the search string is contained.

What would be the easiest way, using some regular expressions or...?

Thanks a bunch!

Body:
your query is also good as you want.
but still you can try this.

You can search your string by using MATCH() AGAINST() statement in mysql.

mysql_query("SELECT * FROM table_name WHERE MATCH(field11,field12) AGAINST ('searchstring')");

Here your field must be having Fulltext datatype.

This may work good.

Thanks.


问:
Fixed div on left of container, full height of container (but not of page) using CSS
I want the following layout in my page:

The header and footer are always visible. The gray area is an article tag. The green and dark red areas are both inside a nav tag. The dark red has a fixed width, and is going to be used as a handle to resize the green navigation panel (it will be very narrow, of course, and I'll use JavaScript for the resizing). Both the gray and green areas must have their own scrollbars.

That's the HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>CSS template</title>
</head>
<body>
<header>Header</header>
<main>
<nav>
    <div class='navcont'>
        <p>nav1</p>
        <p>nav2 with longer line just to make sure if everything is working as intended</p>
    </div>
    <div class='handle'>Handle</div>
</nav>
<article>
    <p>Article</p>
</article>
</main>
<footer>Footer</footer>
</body>
</html>
</code>```

That's the CSS:

```<code>html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#C0C0C0;
    width:80%;
    overflow:auto;
    padding:10px;
}
nav {
    width:20%;
    height:auto;
    overflow:hidden;
}
.navcont {
    background:#00FF00;
    width:auto;
}
.handle {
    background:#800000;
    float:right;
    width:30px;
}
footer {
    text-align:center;
}
</code>```

And a running example: https://jsfiddle.net/etwphhc8/

I tried many different solutions, from many different questions/answers here, but still haven't make it work as intended. So, how can I achieve the wanted layout using CSS?

答:
Try to write:</p>

```<code>  .navcont {
      background:#00FF00;
      width:auto;
      height: 100%;
}
</code>```

Body:
I want the following layout in my page:

The header and footer are always visible. The gray area is an article tag. The green and dark red areas are both inside a nav tag. The dark red has a fixed width, and is going to be used as a handle to resize the green navigation panel (it will be very narrow, of course, and I'll use JavaScript for the resizing). Both the gray and green areas must have their own scrollbars.

That's the HTML:

<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS template</title>

Header

nav1

nav2 with longer line just to make sure if everything is working as intended

Handle

Article

Footer

That's the CSS:

html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#C0C0C0;
    width:80%;
    overflow:auto;
    padding:10px;
}
nav {
    width:20%;
    height:auto;
    overflow:hidden;
}
.navcont {
    background:#00FF00;
    width:auto;
}
.handle {
    background:#800000;
    float:right;
    width:30px;
}
footer {
    text-align:center;
}

And a running example: https://jsfiddle.net/etwphhc8/

I tried many different solutions, from many different questions/answers here, but still haven't make it work as intended. So, how can I achieve the wanted layout using CSS?

Body:
Try to write:

  .navcont {
      background:#00FF00;
      width:auto;
      height: 100%;
}


问:
Centralizing RecyclerView with LinearLayoutManager
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>
</code>```

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

答:
Please check your public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType), if you write like that:

```<code>@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(mLayoutInflater.inflate(R.layout.your_item_layout, null));
}
</code>```

this will make your FrameLayout disabled and CardView will be the itemView of your ViewHolder, So you should change as follow:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new ViewHolder(mLayoutInflater.inflate(R.layout.your_item_layout, parent, false));
}

Hope Help you.

Body:
I am trying to centralize a RecyclerView list in the screen. Its going to be a single list, so I will use the LinearLayoutManager (LLM).
However using the LLM its not centralizing the items, and it looks like this on the landscape mode:

The XML code looks like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recipe_card"
        android:layout_gravity="center"
        android:layout_width="400dp"
        android:layout_height="186dp"
        style="@style/CardViewStyle">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/recipe_image"
                android:layout_width="120dp"
                android:layout_height="163dp"
                app:srcCompat="@mipmap/ic_pan"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                app:layout_constraintLeft_toLeftOf="parent"
                tools:layout_editor_absoluteY="3dp" />

            <TextView
                android:id="@+id/recipe_name"
                android:layout_width="250dp"
                android:layout_height="119dp"
                android:text="TextView"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:layout_marginTop="16dp" />

            <TextView
                android:id="@+id/recipe_servings"
                android:layout_width="164dp"
                android:layout_height="32dp"
                android:text="TextView"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toBottomOf="@+id/recipe_name"
                app:layout_constraintBottom_toBottomOf="parent"
                android:layout_marginBottom="8dp"
                app:layout_constraintLeft_toRightOf="@+id/recipe_image"
                android:layout_marginLeft="94dp"
                app:layout_constraintVertical_bias="0.0" />
        </android.support.constraint.ConstraintLayout>

    </android.support.v7.widget.CardView>

</FrameLayout>

On the Android Studio's Preview, it looks fine, but on the app, it does not.
I manage to fix it by changing the LLM for a GridLayoutManager with only one column. But it looks ugly.

Does anyone knows what is going on?
Thanks.

Body:
Please check your public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType), if you write like that:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(mLayoutInflater.inflate(R.layout.your_item_layout, null));
}

this will make your FrameLayout disabled and CardView will be the itemView of your ViewHolder, So you should change as follow:

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new ViewHolder(mLayoutInflater.inflate(R.layout.your_item_layout, parent, false));
}

Hope Help you.


问:
Captures in C# regexes
This code is supposed to convert the value of img src to a local path.

```<code>var matches = Regex.Replace(html, "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)",
  (match)=> {
    return string.Format("{0}{1}{2}",
      match.Captures[0],
      HostingEnvironment.MapPath("~/" + match.Captures[1]),
      match.Captures[2]);
});
</code>```

It matches the whole image tag correctly but there's only one capture. I thought the parentheses delimited captures but it doesn't seem to be working like that.

How should I have written this to get three captures, the middle one being the path?

答:
Try using the Groups Property instead of Captures, like so:</p>

```<code>var matches = Regex.Replace("<img src=\"dsa\"/>", "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)",
    (match)=> {
        return string.Format("{0}{1}{2}",
            match.Groups[1],
            HostingEnvironment.MapPath("~/" + match.Groups[2]),
            match.Groups[3]);
        });
</code>```

Title: Captures in C# regexes

Body:
This code is supposed to convert the value of img src to a local path.

var matches = Regex.Replace(html, "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)",
  (match)=> {
    return string.Format("{0}{1}{2}",
      match.Captures[0],
      HostingEnvironment.MapPath("~/" + match.Captures[1]),
      match.Captures[2]);
});

It matches the whole image tag correctly but there's only one capture. I thought the parentheses delimited captures but it doesn't seem to be working like that.

How should I have written this to get three captures, the middle one being the path?

Body:
Try using the Groups Property instead of Captures, like so:

var matches = Regex.Replace("<img src=\"dsa\"/>", "(<[ ]*img[^s]+src=[\"'])([^\"']*)([\"'][^/]*/>)",
    (match)=> {
        return string.Format("{0}{1}{2}",
            match.Groups[1],
            HostingEnvironment.MapPath("~/" + match.Groups[2]),
            match.Groups[3]);
        });


答:
You can add a sample judge for the question.</p>

```<code>def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            if word not in list:
                list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix

    return list
</code>```

Title: Removing an item from a list

Body:
You can add a sample judge for the question.

def endwords(sent):
    list = []
    words = sent.split()
    for word in words:
        if "." in word:
            if word not in list:
                list.append(word)
        # bottom if statment does not work for some reason. thats the one i am trying to fix

    return list