问:
Why won't the variable echo?
I have a success page that displays some variables after a succesful transaction with Paypal (IPN).

It's all working great but I just can't figure out why the $email variable does not echo out. Is there something wrong with the query? I have triple checked all the column names.

I get this output:

```<code>OK
price-1.89

Notice: Undefined variable: payer_email in success.php on line 34
Email-
</code>```

Success.php

```<code> <?php
        include 'dbConfig.php';

        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        //Get payment information from PayPal
        $item_number= mysqli_real_escape_string($db, $_POST['item_number']);
        $txn_id= mysqli_real_escape_string($db, $_POST['txn_id']);
        $payment_gross= mysqli_real_escape_string($db, $_POST['payment_gross']);

        //Get product price from database
        $productResult = $db->query("SELECT price FROM products WHERE id = '".$item_number."'");
        $productRow = $productResult->fetch_assoc();
        $productPrice = $productRow['price'];

        if(!empty($txn_id) && $payment_gross == $productPrice){

          //Check if payment data exists with the same TXN ID.
            $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

           if($prevPaymentResult->num_rows > 0){

            //Get Email
            $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '".$txn_id."'");
        $row = $result->fetch_assoc();
        $email=$row['payer_email'];
           }
                echo "OK</br>";
                echo "Price-".$payment_gross."</br>";
                echo "Email-".$email."</br>";

            }else{

              echo '<h1>Error</h1>';
        }
        ?>
</code>```

答:
you can change

```<code>$email=$row['payer_email'];
</code>```

to

```<code>$email=!empty($row['payer_email']) ? $row['payer_email'] : '';
</code>```

thia error show because variable $row does not have key payer_email

Title: Why won't the variable echo?

Body:
I have a success page that displays some variables after a succesful transaction with Paypal (IPN).

It's all working great but I just can't figure out why the $email variable does not echo out. Is there something wrong with the query? I have triple checked all the column names.

I get this output:

OK
price-1.89

Notice: Undefined variable: payer_email in success.php on line 34
Email-

Success.php

 <?php
        include 'dbConfig.php';

        error_reporting(E_ALL);
        ini_set('display_errors', 1);

        //Get payment information from PayPal
        $item_number= mysqli_real_escape_string($db, $_POST['item_number']);
        $txn_id= mysqli_real_escape_string($db, $_POST['txn_id']);
        $payment_gross= mysqli_real_escape_string($db, $_POST['payment_gross']);

        //Get product price from database
        $productResult = $db->query("SELECT price FROM products WHERE id = '".$item_number."'");
        $productRow = $productResult->fetch_assoc();
        $productPrice = $productRow['price'];

        if(!empty($txn_id) && $payment_gross == $productPrice){

          //Check if payment data exists with the same TXN ID.
            $prevPaymentResult = $db->query("SELECT payment_id FROM payments WHERE txn_id = '".$txn_id."'");

           if($prevPaymentResult->num_rows > 0){

            //Get Email
            $result = $db->query("SELECT payer_email FROM payments WHERE txn_id = '".$txn_id."'");
        $row = $result->fetch_assoc();
        $email=$row['payer_email'];
           }
                echo "OK
";
                echo "Price-".$payment_gross."
";
                echo "Email-".$email."
";

            }else{

              echo '
Error
';
        }
        ?>

Body:
you can change

$email=$row['payer_email'];

to

$email=!empty($row['payer_email']) ? $row['payer_email'] : '';

thia error show because variable $row does not have key payer_email


来源: stackexchange

问:
Adding delay or something between hundred of promises
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

```<code>// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})
</code>```

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

答:
```<code>var Promise = require('bluebird');

function fetchData(objekt){
  return new Promise((resolve, reject) => {
      // api call and then
      resolve(data);
  })
}

function doRequest(){

 Promise.coroutine(function *(){
        yield Promise.map(arr, fetchData);
 })()
 .catch(err => {
    console.error(err);
  })
}
</code>```

A simple and shorter code with error handling.

ContentLicense: CC BY-SA 3.0

Body:
I'm using node for requesting app details from another website but the problem i'm facing is, it sends hundreds ( or maybe thousands ) of request, and then I get error and I receive nothing.

Read comments in code for info...

// I'm reading links from another file using 'fs'
fs.readFile('./google_apps/GAME_ACTION.json', 'utf8', function (err, data) {
    if (err) throw err;

    obj = JSON.parse(data);
    // creating a empty array
    var promiseStack = [];

    for (var index in obj['GAME_ACTION']) {
        var linksArray = obj['GAME_ACTION'][index];
        linksArray.forEach( function(link, index) {
            var appID = link.match(/id=.*/g)
            var instr = appID.toString();

            var appIDSliced = instr.slice(3)
            // Here appIDSliced is ID, which is sliced from a link
            // there are thousands on link in this file which I opened

            console.log('sending') // for testing purpose

            // here i'm pushing promises into that empty array
            // store.app({id: appIDSliced}) is a promise I guess because I can use .then() on it...
            // and store.app sends request to another website from which it receives an object in return.
            // (Variable store is from another file 'require()' above in my node app fie )
            promiseStack.push( store.app({id: appIDSliced}))

        });
    }

    // After pushing all promises into array, now i'm trying to resolve them using Promise.all
    Promise.all(promiseStack).then((responses) => {
        console.log("Dealing with responses")

        // Dealing with response (which is an object coming)
        responses.map(response => {
            var title = response.title
            var package_name = response.appId
            var appCategory = response.primaryGenre
            var appSize = parseFloat((response.size/1024)/1024).toFixed(2)
            var developerName = response.developer
            var developerWebsite = response.developerWebsite
            if (typeof developerWebsite == 'undefined') {
                developerWebsite = "N/A"
            }
            var appPrice = response.price
            var lastUpdated = response.updated
            var contentRating = response.contentRating
            if (typeof contentRating == 'undefined') {
                contentRating = "N/A"
            }
            var userRating = response.score
            if (typeof userRating == 'undefined') {
                userRating = "N/A"
            }
            var dataRow = [appID, title, package_name, appCategory, appSize, developerName, developerWebsite, appPrice, lastUpdated, contentRating, userRating]
            var dataToAdd = [dataRow];
            console.log("Appending now")

            // here i'm using google API to append that into my sheet on google
            authentication.authenticate().then((auth)=>{
                appendData(auth, dataToAdd);
            });
        })
    })
})

See the image below ... Those are the Errors I receive on my console
It keep logging 'sending' like for 80 secs and then I get error "UnhandledPromiseRejectionWarning" where I just get stuck for 2 mins and I keep pressing 'CTRL+C'.

Thanks.

Body:
var Promise = require('bluebird');

function fetchData(objekt){
  return new Promise((resolve, reject) => {
      // api call and then
      resolve(data);
  })
}

function doRequest(){

 Promise.coroutine(function *(){
        yield Promise.map(arr, fetchData);
 })()
 .catch(err => {
    console.error(err);
  })
}

A simple and shorter code with error handling.


问:
Unable to post using weibo Website statuses/share
So I am able to make a post on weibo account using statuses/upload but I am unable to make a post on weibo account using statuses/share.

Both takes access_token, status,pic as mandatory parameter with multipart / form-data.

And I am getting the following error

{"error":"text not find domain!","error_code":10017,"request":"/2/statuses/share.json"}

Now, I narrowed down the source of the exception to status field but I still couldn't solve it:

status field for statuses/share says 用户分享到微博的文本内容，必须做URLencode，内容不超过140个汉字，文本中不能包含“#话题词#”，同时文本中必须包含至少一个第三方分享到微博的网页URL，且该URL只能是该第三方（调用方）绑定域下的URL链接，绑定域在“我的应用 － 应用信息 － 基本应用信息编辑 － 安全域名”里设置。

In english : Users to share text content microblogging, must do URLencode, the content is not more than 140 characters, the text can not contain "# # topic word," while the text must contain at least one third-party web page URL to share micro-blog, and the URL is only URL links under the third party (the caller) binding domain, a binding domain in the "my Apps - application information - basic information editing application - security domain" in the settings.

status field for statuses/upload says 要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。

In English: To publish microblogging text content, must do URLencode, the content is not more than 140 characters.

So, status in statuses/share expects URL, but even though

I am URLencoding it

I have added a domain in security domain secion

I am passing the domain URL in it status.

it still gives me the above error.

So I am assuming status field is looking for some format which I missed. Anyone encountered and fixed such exception?

答:
Sorry for late answer. Hopefully this helps someone in the future.

Weibo API is very unclear regarding the accepted format of parameter it expects.

So, statuses/upload accepts a pic as a binary and status as a string, you can pass a URL in status and it will publish it just fine.

however, statuses/share also accepts a pic as a binary and status as a string, but status will accept URL if that URL domain is added as one of the security domain in application information of your Weibo Application.

Now here's what I doing wrong.

I was adding 'google.com', because the error message on that box says

"Please fill in the main domain name and secondary domain name..."

I later on decided to add the full URL 'www.google.com' and then it worked.

So when you try to save only 'google' in security domain, it won't allow you and will give you an error message. When you try to save 'google.com', it will let you save it but it won't be able to find any URL you provide like 'http://www.google.com' and will give you an error message when you try to send it with statuses/share. You have to save 'www.google.com' in security domain then only you will be able to pass 'http://www.google.com' in status parameter of statuses/share

Hopefully I am able to explain it clearly to those who comes here with this error.


问:
Adding Methods to Constructors
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/```
</div>
</div>
</p>

<p><strong>THIS IS WHAT I'VE DONE...</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3</code>```

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

答:
Firstly if you are considering your function carlike  as a constructor, then you must instantiate before you use, so that your code should be in object oriented way.

Answer to your question:

```<code>   var move = function() {
      this.loc++;
      console.log(this.loc);
    };

    var amy = new carlike({}, 1);
console.log(amy.move());
</code>```

No need to pass params in move function, since you are using it inside your carlike constructor there for move function will become method and all context of carlike is also available for it. Thus you can use loc from context of carlike constructor (this.loc)

Title: Adding Methods to Constructors

Body:
Refactor the carlike function in a way that allows us to use the method calling syntax with "dot access".

var carlike = function(obj, loc) {
  obj.loc = loc;
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);

/*
Here we want to call move with "dot access"

amy.move();
ben.move();
*/

THIS IS WHAT I'VE DONE...

var carlike = function(obj, loc) {
  obj.loc = loc;
  obj.move = move;//CHANGE#1
  return obj;
};

var move = function(car) {
  car.loc++;
};

var amy = carlike({}, 1);
var ben = carlike({}, 9);
amy.move();//CHANGE#2
ben.move();//CHANGE#3

BUT IT WON'T WORK IT'S HAVING ERROR REGARDING LOCATION VARIABLE WHICH WAS WORKING GOOD UNTIL!

Thank You in Advance ☺

Body:
Firstly if you are considering your function carlike  as a constructor, then you must instantiate before you use, so that your code should be in object oriented way.

Answer to your question:

   var move = function() {
      this.loc++;
      console.log(this.loc);
    };

    var amy = new carlike({}, 1);
console.log(amy.move());

No need to pass params in move function, since you are using it inside your carlike constructor there for move function will become method and all context of carlike is also available for it. Thus you can use loc from context of carlike constructor (this.loc)


问:
Setting a variable in JSP using a custom tag and passing it to a servlet
I have a custom tag like this <user:current-location msg="!{#locationName}"/> which works fine, but I want to assign it to a variable so I can pass the current location value to a servlet using a form.

I have tried setting the variable using <c:set var = 'location_id' scope = 'session' value = '<user:current-location msg="!{#locationName}">'/>

but when I do <c:out value = '${location_id}'/>, instead of printing out the name of the current location on the page, it just prints out  <user:current-location msg="!{#locationName}">  How can I get it to access what’s actually assigned to the variable?

If I can get that working, I would then like to do something like this in my form to be passed to the servlet in the post request <input type="radio" name="locationName" value="${location_id}" checked="checked">

I cannot use the old scriptlet syntax as this is deprecated.

答:
Try like this :</p>

```<code><c:set var = "location_id" scope ="session">
 <user:current-location msg="!{#locationName}"/>
</c:set>
</code>```

Body:
Try like this :

<c:set var = "location_id" scope ="session">
 <user:current-location msg="!{#locationName}"/>
</c:set>


问:
How to pass Poco::SharedPtr to a TimerCallback function?
I have created a Timer with Poco following the example:

```<code>TimerExample example;
Timer timer(250, 500);
timer.start(TimerCallback<TimerExample>(example, &TimerExample::onTimer));
</code>```

However I for my case TimerExample need to be a Poco::SharedPtr as

```<code>Poco::SharedPtr<TimerExample>TimerExample;
</code>```

The constructor of TimerCallback takes the following parameters :

```<code>TimerCallback(
     C & object,
     Callback method
);
</code>```

Where C is the template Class <TimerExample> for our case.

I'd like to know how to pass the Poco::SharedPtr  to the TimerCallback function in order to be consistent with the bullet from relevant poco guide 030-MemoryManagement.pdf where it is stated that:

Once you use SharedPtr for an object, never work with plain pointers
  to that object again.

答: As pointed out in the comment by vencik - you can't. As it currently stands, you can only pass in a reference to the object having the callback as member and you have to make sure it is valid during the lifetime of the TimerCallback instantiation - your callback can be SharedPtr that you can deref to pass in, but the TimerCallback will take its address and will know nothing about its sharing elsewhere.</p>

Body:
I have created a Timer with Poco following the example:

TimerExample example;
Timer timer(250, 500);
timer.start(TimerCallback<TimerExample>(example, &TimerExample::onTimer));

However I for my case TimerExample need to be a Poco::SharedPtr as

Poco::SharedPtr<TimerExample>TimerExample;

The constructor of TimerCallback takes the following parameters :

TimerCallback(
     C & object,
     Callback method
);

Where C is the template Class <TimerExample> for our case.

I'd like to know how to pass the Poco::SharedPtr  to the TimerCallback function in order to be consistent with the bullet from relevant poco guide 030-MemoryManagement.pdf where it is stated that:

Once you use SharedPtr for an object, never work with plain pointers
  to that object again.


问:
Django redirect views with parameter/context
I have register view in my django app, that redirects to the homepage:

```<code>def register(request):
   ...register...
   return redirect("/")

def homepage(request):
    users = User.objects.all().order_by('username')
    return render(request, 'index.html', {'users': users})
</code>```

I want to add variable new_user that would tell the homepage if user is new. I would pass variable from register view to the homepage view and than into the template where i would handle it:

```<code>{% if new_user %}
<h1>Welcome</h1>
{% endif %}
</code>```

But i dont know how to pass this variable from register view to homepage and than into the template.
Help is well appreciated!

答:
Try this hope this will help you.</p>

```<code>def register(request):
   ...register...
   users = User.objects.all().order_by('username')
   return redirect("/", {'users'=users })

def homepage(request,users):
</code>```

Body:
I have register view in my django app, that redirects to the homepage:

def register(request):
   ...register...
   return redirect("/")

def homepage(request):
    users = User.objects.all().order_by('username')
    return render(request, 'index.html', {'users': users})

I want to add variable new_user that would tell the homepage if user is new. I would pass variable from register view to the homepage view and than into the template where i would handle it:

{% if new_user %}

Welcome

{% endif %}

But i dont know how to pass this variable from register view to homepage and than into the template.
Help is well appreciated!

Body:
Try this hope this will help you.

def register(request):
   ...register...
   users = User.objects.all().order_by('username')
   return redirect("/", {'users'=users })

def homepage(request,users):


问:
How to speed-up Python PIL image filtering function
I have two grayscale pngs. These images have the same width and height.

For example:

I need to filter these images in the following way: when a pixel from image1 has a value different from 255 and the pixel in the same position has a value different from 255 I want to store both pixels in two separate images (imageFiltered1 and imageFiltered2). Then both filtered images will create a new image thanks to multiply from ImageChops.

This is the algorithm I pulled together:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image, ImageChops

def makeCustomMultiply(image1, image2):
    assert image1.size == image2.size

    imageFiltered1 = Image.new(size=image1.size, mode='L', color=255)
    imageFiltered2 = Image.new(size=image1.size, mode='L', color=255)

    for eachY in xrange(0, imageFiltered1.size[1]):
        for eachX in xrange(0, imageFiltered1.size[0]):
            pixel1 = image1.getpixel((eachX, eachY))
            pixel2 = image2.getpixel((eachX, eachY))

            if pixel1 == 255 or pixel2 == 255:
                imageFiltered1.putpixel((eachX, eachY), 255)
                imageFiltered2.putpixel((eachX, eachY), 255)
            else:
                imageFiltered1.putpixel((eachX, eachY), pixel1)
                imageFiltered2.putpixel((eachX, eachY), pixel2)

    combo = ImageChops.multiply(imageFiltered1, imageFiltered2)
    return combo

if __name__ == '__main__':

    image1 = Image.open('image1.png')
    image2 = Image.open('image2.png')

    myCustomMultiply = makeCustomMultiply(image1, image2)
    myCustomMultiply.save('myCustomMultiply.png')
</code>```

It is basically a multiply function where black/gray against white is not showed. Only gray to gray is then multiplied.

Can my code be improved somehow?
I would like to avoid the nested for loops which slow down my code quite a lot. This function has to be used hundreds of times each time I run my program.

Thanks

ouput :

答:
From the docs:

getpixel

  ...

  Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see load), or the getdata method.

Or, to speed up the pure Python part of your code, try to use PyPy

Body:
I have two grayscale pngs. These images have the same width and height.

For example:

I need to filter these images in the following way: when a pixel from image1 has a value different from 255 and the pixel in the same position has a value different from 255 I want to store both pixels in two separate images (imageFiltered1 and imageFiltered2). Then both filtered images will create a new image thanks to multiply from ImageChops.

This is the algorithm I pulled together:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image, ImageChops

def makeCustomMultiply(image1, image2):
    assert image1.size == image2.size

    imageFiltered1 = Image.new(size=image1.size, mode='L', color=255)
    imageFiltered2 = Image.new(size=image1.size, mode='L', color=255)

    for eachY in xrange(0, imageFiltered1.size[1]):
        for eachX in xrange(0, imageFiltered1.size[0]):
            pixel1 = image1.getpixel((eachX, eachY))
            pixel2 = image2.getpixel((eachX, eachY))

            if pixel1 == 255 or pixel2 == 255:
                imageFiltered1.putpixel((eachX, eachY), 255)
                imageFiltered2.putpixel((eachX, eachY), 255)
            else:
                imageFiltered1.putpixel((eachX, eachY), pixel1)
                imageFiltered2.putpixel((eachX, eachY), pixel2)

    combo = ImageChops.multiply(imageFiltered1, imageFiltered2)
    return combo

if __name__ == '__main__':

    image1 = Image.open('image1.png')
    image2 = Image.open('image2.png')

    myCustomMultiply = makeCustomMultiply(image1, image2)
    myCustomMultiply.save('myCustomMultiply.png')

It is basically a multiply function where black/gray against white is not showed. Only gray to gray is then multiplied.

Can my code be improved somehow?
I would like to avoid the nested for loops which slow down my code quite a lot. This function has to be used hundreds of times each time I run my program.

Thanks

ouput :


问:
Custom Page Templates in WordPress to show Content in specific layout
I want to create a custom page template in WordPress which shows Image Slideshow and then a video below it and finally some text - till now what I am able to do is play with sidebar, footer, header.

I can either remove them or keep them in my custom page templates but what I want to do is play with the page contents.

The Admin user should be able to see these sections in the Page Editor (WYSIWYG) when they choose the Template from the drop-down, so that they can accordingly add the correct content in correct place holders

Something like the attached screen-shot is showing

Is this possible in WordPress

答:
Yes! It's possible to implement this! you can use https://codecanyon.net/item/visual-composer-page-builder-for-wordpress/242431 or https://wordpress.org/plugins/siteorigin-panels/ plugin.

The first plugin allows you to create different page layout and save it. It also allows admin to choose page layout that admin has saved previously.

The second page builder plugin allows you to create template same way and allows admin to clone one page layout to another one.

Hope this will help you!


问:
How to feed inputs into a loaded Tensorflow model using C++
I want to create and train a model, export it and run inference in C++.

I'm following the tutorial listed here: https://www.tensorflow.org/tutorials/wide_and_deep

I'm also trying to use the SavedModel approach as described here since this is the canonical way to export TensorFlow graphs for serving:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md.

At the very end, I export the saved model as follows:

```<code>feature_spec = tf.contrib.layers.create_feature_spec_for_parsing(feature_columns)
serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec)
output = model.export_savedmodel(model_dir, serving_input_fn, as_text=True)
print('Model saved to {}'.format(output))
</code>```

I see the saved_model.pbtxt has the following signature definition.

```<code>signature_def {
  key: "serving_default"
  value {
    inputs {
      key: "inputs"
      value {
        name: "input_example_tensor:0"
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
  outputs {
  ...
</code>```

I can load the saved model on the C++ side

```<code>SavedModelBundle bundle;

const std::string graph_path = "models/1498572863";
const std::unordered_set<std::string> tags = {"serve"};

Status status = LoadSavedModel(session_options,
                        run_options, graph_path,
                        tags, &bundle);
</code>```

I'm stuck at the last part where I need to feed the input into this model.
The Run function expects the input parameter to be of the form: std::vector<std::pair<string, Tensor>>.

I would have expected this to be a vector of pairs where the key is the feature name used in the python code and the Tensor is multiple values for that feature.

However, it seems to expect the string to be "input_example_tensor".
I'm not sure how I'm supposed to now feed the model with different features using a single Tensor.

```<code>std::vector<string> output_tensor_names = {
"binary_logistic_head/_classification_output_alternatives/classes_tensor"};

// How do I create input_tensor?
status = bundle.session->Run({{"input_example_tensor", input_tensor}}
    output_tensor_names, {}, &outputs);
</code>```

Solution

I did something like this

```<code>tensorflow::Example example;
auto& tf_feature_map = *(example.mutable_features()->mutable_feature());

tf_feature_map["name"].mutable_int64_list()->add_value(15);
const std::string& serialized = example.SerializeAsString();
tensorflow::Input input({serialized});

status = bundle.session->Run({{"input_example_tensor", input.tensor()}}
    output_tensor_names, {}, &outputs);
</code>```

答:
Your model signature suggests that it is expecting a DT_STRING tensor as input. When using tensorflow::Example, this typically means that the protocol buffer needs to be serialized into a tensor with a string as the type of its elements.

To convert the tensorflow::Example object to a string, you can use the protocol buffer methods such as SerializeToString, SerializeAsString etc.

Hope that helps.

Body:
I want to create and train a model, export it and run inference in C++.

I'm following the tutorial listed here: https://www.tensorflow.org/tutorials/wide_and_deep

I'm also trying to use the SavedModel approach as described here since this is the canonical way to export TensorFlow graphs for serving:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md.

At the very end, I export the saved model as follows:

feature_spec = tf.contrib.layers.create_feature_spec_for_parsing(feature_columns)
serving_input_fn = input_fn_utils.build_parsing_serving_input_fn(feature_spec)
output = model.export_savedmodel(model_dir, serving_input_fn, as_text=True)
print('Model saved to {}'.format(output))

I see the saved_model.pbtxt has the following signature definition.

signature_def {
  key: "serving_default"
  value {
    inputs {
      key: "inputs"
      value {
        name: "input_example_tensor:0"
        dtype: DT_STRING
        tensor_shape {
          dim {
            size: -1
          }
        }
      }
    }
  outputs {
  ...

I can load the saved model on the C++ side

SavedModelBundle bundle;

const std::string graph_path = "models/1498572863";
const std::unordered_set<std::string> tags = {"serve"};

Status status = LoadSavedModel(session_options,
                        run_options, graph_path,
                        tags, &bundle);

I'm stuck at the last part where I need to feed the input into this model.
The Run function expects the input parameter to be of the form: std::vector<std::pair<string, Tensor>>.

I would have expected this to be a vector of pairs where the key is the feature name used in the python code and the Tensor is multiple values for that feature.

However, it seems to expect the string to be "input_example_tensor".
I'm not sure how I'm supposed to now feed the model with different features using a single Tensor.

std::vector<string> output_tensor_names = {
"binary_logistic_head/_classification_output_alternatives/classes_tensor"};

// How do I create input_tensor?
status = bundle.session->Run({{"input_example_tensor", input_tensor}}
    output_tensor_names, {}, &outputs);

Solution

I did something like this

tensorflow::Example example;
auto& tf_feature_map = *(example.mutable_features()->mutable_feature());

tf_feature_map["name"].mutable_int64_list()->add_value(15);
const std::string& serialized = example.SerializeAsString();
tensorflow::Input input({serialized});

status = bundle.session->Run({{"input_example_tensor", input.tensor()}}
    output_tensor_names, {}, &outputs);


问:
disable the list item for empty parent
I have 5 list item which has a tag with class Articles, Blogs, Brochures, Webinars, Whitepapers and have their child content in 'view-content' div.on load it shows blogs and hide the other child.when I chick 'whitepapers' child whitepaper shows and other child will hide(working fine).

I want to add the class 'disable' to the list item as

 for the list which doesn't has the child.In my example 'Brochures' and 'Webinars' have no child so need to add the class 'disable' for the respective list.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="perspective-list">
  <ul class="nav nav-justified">
    <li class="">Articles</li>
    <li class="">Blogs</li>
    <li class="">Brochures</li>
    <li class="">Webinars</li>
    <li class="active">Whitepapers</li>
  </ul>
</div>
<div class="view-content">
  <div class="wrapper">
    <div class=" Articles">
      article
    </div>
  </div>
  <div class="wrapper">
    <div class="Blogs">
      Blogs
    </div>
  </div>
  <div class="wrapper">
    <div class="Whitepapers">
      Whitepapers
    </div>
  </div>
</div></code>```

答:
I assume you just want to run this on the first load, rather than on every time the mouserover or click happens.

You will also probably want to stop your mouseover and click functions in the li has the class disable, but I'll leave that for you :)

(function($) {
  function perspective_type() {
    $(".perspective-list a").each(function(e){
      var target = $(this).attr('href');
      if($('div.'+target).text() == ''){
        $(this).parent().addClass('disable')
      }
    });
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="perspective-list">
  <ul class="nav nav-justified">
    <li class="">Articles</li>
    <li class="">Blogs</li>
    <li class="">Brochures</li>
    <li class="">Webinars</li>
    <li class="active">Whitepapers</li>
  </ul>
</div>
<div class="view-content">
  <div class="wrapper">
    <div class=" Articles">
      article
    </div>
  </div>
  <div class="wrapper">
    <div class="Blogs">
      Blogs
    </div>
  </div>
  <div class="wrapper">
    <div class="Whitepapers">
      Whitepapers
    </div>
  </div>
</div></code>```

Title: disable the list item for empty parent

Body:
I have 5 list item which has a tag with class Articles, Blogs, Brochures, Webinars, Whitepapers and have their child content in 'view-content' div.on load it shows blogs and hide the other child.when I chick 'whitepapers' child whitepaper shows and other child will hide(working fine).

I want to add the class 'disable' to the list item as

 for the list which doesn't has the child.In my example 'Brochures' and 'Webinars' have no child so need to add the class 'disable' for the respective list.

(function($) {
  function perspective_type() {
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)

Articles

Blogs

Brochures

Webinars

Whitepapers

      article

      Blogs

      Whitepapers

Body:
I assume you just want to run this on the first load, rather than on every time the mouserover or click happens.

You will also probably want to stop your mouseover and click functions in the li has the class disable, but I'll leave that for you :)

(function($) {
  function perspective_type() {
    $(".perspective-list a").each(function(e){
      var target = $(this).attr('href');
      if($('div.'+target).text() == ''){
        $(this).parent().addClass('disable')
      }
    });
    $(".perspective-list a").click(function(e) {
      e.preventDefault();
      $(".perspective-list a").parent().removeClass('active');
      $('.wrapper .page-perspective').show();
      var href = $(this).attr('href');
      $('.wrapper > :not(.' + href + ')').hide();
      $('.wrapper > .' + href + '').show();
      $(this).parent().addClass('active');
    });
    $(".perspective-list a").mouseover(
      function() {
        $(".perspective-list a").removeClass('hover');
        $(this).parent().addClass('hover');
      });
    $(".perspective-list a").mouseout(
      function() {
        $(".perspective-list a").each(function() {
          $(this).parent().removeClass('hover');
        });
      });
    $('#perspectives .perspectiveReadurl', '#page_perspectives .perspectiveReadurl').find('a').attr('target', '_blank');
  }
  jQuery(document).ready(function($) {
    var href = 'Blogs';
    jQuery('.perspective-list a.' + href + '').parent().addClass('active');
    jQuery('.wrapper > :not(.' + href + ')').hide();
    perspective_type();
  });

})(jQuery)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="perspective-list">
  <ul class="nav nav-justified">
    <li class=""><a href="Articles" class="Articles">Articles</a></li>
    <li class=""><a href="Blogs" class="Blogs">Blogs</a></li>
    <li class=""><a href="Brochures" class="Brochures">Brochures</a></li>
    <li class=""><a href="Webinars" class="Webinars">Webinars</a></li>
    <li class="active"><a href="Whitepapers" class="Whitepapers">Whitepapers</a></li>
  </ul>
</div>
<div class="view-content">
  <div class="wrapper">
    <div class=" Articles">
      article
    </div>
  </div>
  <div class="wrapper">
    <div class="Blogs">
      Blogs
    </div>
  </div>
  <div class="wrapper">
    <div class="Whitepapers">
      Whitepapers
    </div>
  </div>
</div>


问:
Android FFmpeg Unrecognized option
I am trying to compresses a video in android using ffmepg. Here is my code:

```<code>  String[] cmd = {"-y -i" ,myVideo.getAbsolutePath().replaceAll(" ", "%20"),"-vf","-s 640x480","-threads 5","-preset ultrafast","-strict -2", (local_paths.getLocal_images() + File.separator + "test.mp4")};
            FFmpeg ffmpeg = FFmpeg.getInstance(context);
            try {
                //Load the binary
                ffmpeg.loadBinary(new LoadBinaryResponseHandler() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure() {
                    }

                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onFinish() {
                    }
                });
            } catch (FFmpegNotSupportedException e) {
                // Handle if FFmpeg is not supported by device
            }
            try {
                // to execute "ffmpeg -version" command you just need to pass "-version"
                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {

                    @Override
                    public void onStart() {
                        Log.e("FFmpeg", "onStart");
                    }

                    @Override
                    public void onProgress(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onFailure(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onSuccess(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onFinish() {
                        Log.e("FFmpeg", "onFinish");
                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                e.printStackTrace();
                // Handle if FFmpeg is already running
            }
</code>```

The problem is that almost all commands that I use cause Unrecognized option error:

```<code>> 07-04 11:31:21.471 24610-25450/com.network.imyth.network E/FFmpeg:
> onStart 07-04 11:31:22.091 24610-25460/com.network.imyth.network
> D/FFmpeg: Running publishing updates method 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg: ffmpeg version n3.0.1
> Copyright (c) 2000-2016 the FFmpeg developers 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg:   built with gcc 4.8
> (GCC) 07-04 11:31:22.101 24610-24610/com.network.imyth.network
> E/FFmpeg:   configuration: --target-os=linux
> --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi-
> --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot
> --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include
> -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib
> -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags= 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavutil      55.
> 17.103 / 55. 17.103 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavcodec     57.
> 24.102 / 57. 24.102 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavformat    57.
> 25.100 / 57. 25.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavdevice    57.
> 0.101 / 57.  0.101 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavfilter     6.
> 31.100 /  6. 31.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libswscale      4.
> 0.100 /  4.  0.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libswresample   2.
> 0.101 /  2.  0.101 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libpostproc    54.
> 0.100 / 54.  0.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: Unrecognized option 'y
> -i'. 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: Error splitting the argument list: Option not found 07-04
> 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: ffmpeg
> version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
>                                                                      built with gcc 4.8 (GCC)
>                                                                      configuration: --target-os=linux
> --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi-
> --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot
> --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include
> -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib
> -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
>                                                                      libavutil      55. 17.103 / 55. 17.103
>                                                                      libavcodec     57. 24.102 / 57. 24.102
>                                                                      libavformat    57. 25.100 / 57. 25.100
>                                                                      libavdevice    57.  0.101 / 57.  0.101
>                                                                      libavfilter     6. 31.100 /  6. 31.100
>                                                                      libswscale      4.  0.100 /  4.  0.100
>                                                                      libswresample   2.  0.101 /  2.  0.101
>                                                                      libpostproc    54.  0.100 / 54.  0.100
>                                                                    Unrecognized option 'y -i'.
>                                                                    Error splitting the argument list: Option not found 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg: onFinish
</code>```

so what the problem i get this   Unrecognized option                                                                  Error splitting the argument list: Option not found

im using this LIB ffmpeg-android-java

答:
Try splitting your arguments. This should work:</p>

```<code>String[] command = {"-y", "-i", "/path/to/your/video.mp4", "-vf", "-s", "640x480", "-threads", "5", "-preset", "ultrafast", "-strict", "-2", "/path/to/your/video_out.mp4"};
</code>```

Title: Android FFmpeg Unrecognized option

Body:
I am trying to compresses a video in android using ffmepg. Here is my code:

  String[] cmd = {"-y -i" ,myVideo.getAbsolutePath().replaceAll(" ", "%20"),"-vf","-s 640x480","-threads 5","-preset ultrafast","-strict -2", (local_paths.getLocal_images() + File.separator + "test.mp4")};
            FFmpeg ffmpeg = FFmpeg.getInstance(context);
            try {
                //Load the binary
                ffmpeg.loadBinary(new LoadBinaryResponseHandler() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onFailure() {
                    }

                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onFinish() {
                    }
                });
            } catch (FFmpegNotSupportedException e) {
                // Handle if FFmpeg is not supported by device
            }
            try {
                // to execute "ffmpeg -version" command you just need to pass "-version"
                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {

                    @Override
                    public void onStart() {
                        Log.e("FFmpeg", "onStart");
                    }

                    @Override
                    public void onProgress(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onFailure(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onSuccess(String message) {
                        Log.e("FFmpeg", message);
                    }

                    @Override
                    public void onFinish() {
                        Log.e("FFmpeg", "onFinish");
                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                e.printStackTrace();
                // Handle if FFmpeg is already running
            }

The problem is that almost all commands that I use cause Unrecognized option error:

> 07-04 11:31:21.471 24610-25450/com.network.imyth.network E/FFmpeg:
> onStart 07-04 11:31:22.091 24610-25460/com.network.imyth.network
> D/FFmpeg: Running publishing updates method 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg: ffmpeg version n3.0.1
> Copyright (c) 2000-2016 the FFmpeg developers 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg:   built with gcc 4.8
> (GCC) 07-04 11:31:22.101 24610-24610/com.network.imyth.network
> E/FFmpeg:   configuration: --target-os=linux
> --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi-
> --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot
> --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include
> -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib
> -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags= 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavutil      55.
> 17.103 / 55. 17.103 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavcodec     57.
> 24.102 / 57. 24.102 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavformat    57.
> 25.100 / 57. 25.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavdevice    57.
> 0.101 / 57.  0.101 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libavfilter     6.
> 31.100 /  6. 31.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libswscale      4.
> 0.100 /  4.  0.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libswresample   2.
> 0.101 /  2.  0.101 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg:   libpostproc    54.
> 0.100 / 54.  0.100 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: Unrecognized option 'y
> -i'. 07-04 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: Error splitting the argument list: Option not found 07-04
> 11:31:22.101 24610-24610/com.network.imyth.network E/FFmpeg: ffmpeg
> version n3.0.1 Copyright (c) 2000-2016 the FFmpeg developers
>                                                                      built with gcc 4.8 (GCC)
>                                                                      configuration: --target-os=linux
> --cross-prefix=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/bin/arm-linux-androideabi-
> --arch=arm --cpu=cortex-a8 --enable-runtime-cpudetect --sysroot=/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/sysroot
> --enable-pic --enable-libx264 --enable-libass --enable-libfreetype --enable-libfribidi --enable-libmp3lame --enable-fontconfig --enable-pthreads --disable-debug --disable-ffserver --enable-version3 --enable-hardcoded-tables --disable-ffplay --disable-ffprobe --enable-gpl --enable-yasm --disable-doc --disable-shared --enable-static --pkg-config=/home/vagrant/SourceCode/ffmpeg-android/ffmpeg-pkg-config --prefix=/home/vagrant/SourceCode/ffmpeg-android/build/armeabi-v7a --extra-cflags='-I/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/include
> -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 -fno-strict-overflow -fstack-protector-all' --extra-ldflags='-L/home/vagrant/SourceCode/ffmpeg-android/toolchain-android/lib
> -Wl,-z,relro -Wl,-z,now -pie' --extra-libs='-lpng -lexpat -lm' --extra-cxxflags=
>                                                                      libavutil      55. 17.103 / 55. 17.103
>                                                                      libavcodec     57. 24.102 / 57. 24.102
>                                                                      libavformat    57. 25.100 / 57. 25.100
>                                                                      libavdevice    57.  0.101 / 57.  0.101
>                                                                      libavfilter     6. 31.100 /  6. 31.100
>                                                                      libswscale      4.  0.100 /  4.  0.100
>                                                                      libswresample   2.  0.101 /  2.  0.101
>                                                                      libpostproc    54.  0.100 / 54.  0.100
>                                                                    Unrecognized option 'y -i'.
>                                                                    Error splitting the argument list: Option not found 07-04 11:31:22.101
> 24610-24610/com.network.imyth.network E/FFmpeg: onFinish

so what the problem i get this   Unrecognized option                                                                  Error splitting the argument list: Option not found

im using this LIB ffmpeg-android-java

Body:
Try splitting your arguments. This should work:

String[] command = {"-y", "-i", "/path/to/your/video.mp4", "-vf", "-s", "640x480", "-threads", "5", "-preset", "ultrafast", "-strict", "-2", "/path/to/your/video_out.mp4"};


问:
Is that safe to share .xcarchive?
I`m somehow amateur in Xcode and this matter is so important for me.

My Friend use his developer id to publish my app and he ask me to give him .xcarchive instead *.ipa file

As I read in stackoverflow topics .xcarchive have the same content of ipa and there is no concern about lose and steal source code.

But when I check my xcarchive and use show content option I see most of project files like images and sources in application folder , also some of my code are in *.nib files

Is that normal ? and if I extract ipa if I get the same result ?

Is there any security or tips in Xcode that better to active before archive project ?

答:
It is normal. In order to publish your app, your friend really needs the xcarchive, because they need to export an IPA file with the appropriate provisioning profile and signed with their code signing identity. Although it's possible to replace the provisioning profile in an IPA file and re-sign it again, it's a daunting task you don't want any of your friends to do. If you trust your friend with publishing your app, you should trust them and share the xcarchive.

When you compare the contents of xcarchive and IPA files, you can see xcarchive contains a dSYMs folder with dSYM files used to desymbolicate your crash logs -- the developer needs that to know in what file and at what line number the application crashed.

Title: Is that safe to share .xcarchive?


问:
How do i upload an image to my mysql database with php?
I know that i should use LONGBLOB, and i've written this code so far that uploads text to my server. How do i upload images instead of text?.

```<code>//if(isset...)
$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = $_POST['tekst'];

$sqlScript = "INSERT INTO form (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);
</code>```

It should save the path to the mysql database. The image should be stored on the servers' computer.

答:
alternative: convert image in base64 and save like text. </p>

```<code>$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$image_string = base64_encode(file_get_contents($myimage));

$sqlScript = "INSERT INTO form (images) VALUES ('$image_string')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);
</code>```

Body:
I know that i should use LONGBLOB, and i've written this code so far that uploads text to my server. How do i upload images instead of text?.

//if(isset...)
$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$t = $_POST['tekst'];

$sqlScript = "INSERT INTO form (tekst) VALUES ('$t')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);

It should save the path to the mysql database. The image should be stored on the servers' computer.

Body:
alternative: convert image in base64 and save like text.

$connectionText = mysql_connect("localhost", "root");

if(!$connectionText){
die("Noget gik galt?". mysql_connect_error());
}
mysql_select_db("textbox", $connectionText);

$image_string = base64_encode(file_get_contents($myimage));

$sqlScript = "INSERT INTO form (images) VALUES ('$image_string')";

mysql_query($sqlScript, $connectionText);
mysql_close($connectionText);


问:
Python/Django - No module named
I try to work with a class from Django views.

sync.py

```<code>import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)
</code>```

views.py

```<code>import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")
</code>```

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?

答:
Direct reference to Sync() will not work with current import statement.

Change it to either:

```<code>from sync import Sync
</code>```

Or use:

```<code>s = sync.Sync()
</code>```

Title: Python/Django - No module named

Body:
I try to work with a class from Django views.

sync.py

import requests

class Sync:

    def do():
        r = requests.post('http://192.168.1.7/api/report_x')
        print(r.response)

views.py

import sync

def index(request):
    s = Sync()
    s.do()
    return HttpResponse("Hello, this is index")

When I access index from the browser I get:

global name 'Sync' is not defined

What am I doing wrong?

Body:
Direct reference to Sync() will not work with current import statement.

Change it to either:

from sync import Sync

Or use:

s = sync.Sync()


问:
Anti-aliasing issue in iPhones with OpenGL ES
I am Trying to draw curves/lines using OpenGL ES on iPhones. I have used glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER_OES, 4, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight) and  glResolveMultisampleFramebufferAPPLE() referring the link :

apple documentation link
https://developer.apple.com/library/ios/documentation/3ddrawing/conceptual/opengles_programmingguide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html

The output looks like this :

https://i.stack.imgur.com/gpPIK.png

The edges still looks pixelated.Any help is appreciated.

Thanks.

答:
I'm not sure what you are expecting - anti-alisaing can blur primitive edges, but it can't make the pixels disappear completely.

It looks to be working as expect to me ...


问:
Regular expression to validate time but exclude 0:00
I'm not an expert to regular expressions, but I tried to validate the user input for a time field with it.

My current regex: /^([0-9]|0[0-9]):[0-5][0-9]$/

It should validate anything positive between 0:01 and 9:59, but it also give positive return to 0:00.

Can you please help me to modify my regular expression to exclude 0:00?

Thanks a lot!

答:
Here is the regex you are looking for.

```<code>^((?!(0:00)|(00:00)$)0?[0-9]:[0-5][0-9])$
</code>```

Uses the concept of negative look ahead. Using negative lookahead, you can say match everything except 0:00 and 00:00.

Hope this helps!

Body:
Here is the regex you are looking for.

^((?!(0:00)|(00:00)$)0?[0-9]:[0-5][0-9])$

Uses the concept of negative look ahead. Using negative lookahead, you can say match everything except 0:00 and 00:00.

Hope this helps!


问:
HTML, CSS, Responsive: How to use a sprite containing images of different sizes?
In my website, I require images of different sizes. For example:

Images A, B, C : 320px x 320px

Image D, E : 400px x 200px

Image F : 20px x 16px

I want to make a single sprite for all the images. I want to make it responsive so I use percentages to define its height and width. All the methods I found online hard code heights and don't mention how to make it responsive.

The current method used:

I combined equal sized images into one sprite

Images A, B, C - sprite1.png

Images D, E - sprite2.png

Image F - not using any sprite

I also created transparent images (holders) for the sizes above.

The reason I'm doing it this way because I figured out the below way of making it work and still be responsive:

```<code><div class="type-1">
    <img src="transparent_img_320_320.png" class="image_a" />
    <img src="transparent_img_320_320.png" class="image_b" />
    <img src="transparent_img_320_320.png" class="image_c" />
</div>

<div class="type-2">
    <img src="transparent_img_400_200.png" class="image_d" />
    <img src="transparent_img_400_200.png" class="image_e" />
</div>

<div class="type-3">
    <img src="transparent_img_20_16.png" class="image_f" />
</div>
</code>```

And in CSS I put my images as background img as below (mentioning only one per one size but I'm repeating the same thing and changing position in my code):

```<code>.image_a {
    background: url(../images/sprite1.png);
    background-size: 300% 100%;
    background-position: 100% 0;
}

.image_d {
    background: url(../images/sprite2.png);
    background-size: 400% 200%;
    background-position: 300% 0;
}
</code>```

Problems:

Need to create a unique transparent image for each file.

Problematic to work with many sprites.

Have to put every image as background, as I haven't found a solution that doesn't use hardcoded height and width for .

making transparent images stretch for images of different sizes isn't working. Is there a way to avoid the transparent images?

Any other way to do this is appreciated.

Requirements:
multiple images of varying sizes,
responsive height and width

additional-question: Do large images(such as background of the entire page) be a part of the sprite, considering I've 8 background images.

答:
I think you have few options to manage with your problem.

My first idea:

Create one sprite file, with background-position and width, height with pixels. You can use transform:scale() to fill your responsive content.

But I never use sprite for big images for responsive print. In my opinion it's not good habit because you load big .png file instead of one on demand (like your few backgrounds).

Body:
In my website, I require images of different sizes. For example:

Images A, B, C : 320px x 320px

Image D, E : 400px x 200px

Image F : 20px x 16px

I want to make a single sprite for all the images. I want to make it responsive so I use percentages to define its height and width. All the methods I found online hard code heights and don't mention how to make it responsive.

The current method used:

I combined equal sized images into one sprite

Images A, B, C - sprite1.png

Images D, E - sprite2.png

Image F - not using any sprite

I also created transparent images (holders) for the sizes above.

The reason I'm doing it this way because I figured out the below way of making it work and still be responsive:

And in CSS I put my images as background img as below (mentioning only one per one size but I'm repeating the same thing and changing position in my code):

.image_a {
    background: url(../images/sprite1.png);
    background-size: 300% 100%;
    background-position: 100% 0;
}

.image_d {
    background: url(../images/sprite2.png);
    background-size: 400% 200%;
    background-position: 300% 0;
}

Problems:

Need to create a unique transparent image for each file.

Problematic to work with many sprites.

Have to put every image as background, as I haven't found a solution that doesn't use hardcoded height and width for .

making transparent images stretch for images of different sizes isn't working. Is there a way to avoid the transparent images?

Any other way to do this is appreciated.

Requirements:
multiple images of varying sizes,
responsive height and width

additional-question: Do large images(such as background of the entire page) be a part of the sprite, considering I've 8 background images.


问:
Cakephp 2.x and Csrf token
Im using cakephp 2.x with security component activated, the problem is i disabled csrf verification for my json requests like this :

```<code>$this->Security->unlockedActions = array('do_json');
</code>```

Is it possible to remove the unlockedActions code from the beforefilter and integrate csrf verification in json requests as well like other not json actions.

Thanks in advance.

答:
You'll most likely have to disable POST data validation, unless your requests would contain data from forms that have been built with the form helper:

```<code>$this->Security->validatePost = false;
</code>```

And then you have to include the CSRF token in your requests POST data. The generated token can be found in the request parameters as _Token.key:

```<code>$this->request->param('_Token.key')
// or
$this->request->params['_Token']['key']
</code>```

and needs to be submitted as _Token.key too, ie

```<code>{
    "_Token": {
        "key": "keyValue"
    }
}
</code>```

See also

Cookbook > Core Libraries > Controllers > Security > Form tampering prevention > SecurityComponent::$validatePost

Cookbook > Core Libraries > Controllers > Security > CSRF protection > Using CSRF protection

Title: Cakephp 2.x and Csrf token

Body:
Im using cakephp 2.x with security component activated, the problem is i disabled csrf verification for my json requests like this :

$this->Security->unlockedActions = array('do_json');

Is it possible to remove the unlockedActions code from the beforefilter and integrate csrf verification in json requests as well like other not json actions.

Thanks in advance.

Body:
You'll most likely have to disable POST data validation, unless your requests would contain data from forms that have been built with the form helper:

$this->Security->validatePost = false;

And then you have to include the CSRF token in your requests POST data. The generated token can be found in the request parameters as _Token.key:

$this->request->param('_Token.key')
// or
$this->request->params['_Token']['key']

and needs to be submitted as _Token.key too, ie

{
    "_Token": {
        "key": "keyValue"
    }
}

See also

Cookbook > Core Libraries > Controllers > Security > Form tampering prevention > SecurityComponent::$validatePost

Cookbook > Core Libraries > Controllers > Security > CSRF protection > Using CSRF protection


答:
Import the name before using it</p>

```<code>from sync import Sync
</code>```

Title: Python/Django - No module named

Body:
Import the name before using it

from sync import Sync


问:
Nhibernate: How to find responsible Field for SqlDateTime overflow exception
I know the reason for the exception (SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.) is a non nullable DateTime field in a Entity and so Nhibernate wants to save a smaller DateTime value than MSSQL accepts.

The Problem ist that there are far to many entities in the project to find the right DateTime field.

The exception occurs after an SaveOrUpdate() but is not triggered by the entity i want to save but any other entity which was loaded in the current session and now is affected by the flush().

How can i find out which field really is responsible for the exception?

答:
You can create a class that implements both IPreUpdateEventListener and IPreInsertEventListener as follows:

```<code>  public class InsertUpdateListener : IPreInsertEventListener, IPreUpdateEventListener {
     public bool OnPreInsert(PreInsertEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     public bool OnPreUpdate(PreUpdateEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     private static void CheckDateTimeWithinSqlRange(IEntityPersister persister, IReadOnlyList<object> state) {
        var rgnMin = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
        // There is a small but relevant difference between DateTime.MaxValue and SqlDateTime.MaxValue.
        // DateTime.MaxValue is bigger than SqlDateTime.MaxValue but still within the valid range of
        // values for SQL Server. Therefore we test against DateTime.MaxValue and not against
        // SqlDateTime.MaxValue. [Manfred, 04jul2017]
        //var rgnMax = System.Data.SqlTypes.SqlDateTime.MaxValue.Value;
        var rgnMax = DateTime.MaxValue;
        for (var i = 0; i < state.Count; i++) {
           if (state[i] != null
               && state[i] is DateTime) {
              var value = (DateTime)state[i];
              if (value < rgnMin /*|| value > rgnMax*/) { // we don't check max as SQL Server is happy with DateTime.MaxValue [Manfred, 04jul2017]
                 throw new ArgumentOutOfRangeException(persister.PropertyNames[i], value,
                    $"Property '{persister.PropertyNames[i]}' for class '{persister.EntityName}' must be between {rgnMin:s} and {rgnMax:s} but was {value:s}");
              }
           }
        }
     }
  }
</code>```

You also need to then register this event handler when you configure the session factory. Add an instance to Configuration.EventListeners.PreUpdateEventListeners and to Configuration.EventListeners.PreInsertEventListeners and then use the Configuration object when creating NHibernate's session factory.

What this does is this: Every time NHibernate inserts or updates an entity it will call OnPreInsert() or OnPreUpdate() respectively. Each of these methods in turn calls CheckDateTimeWithinSqlRange().

CheckDateTimeWithinSqlRange() iterates over all property values of the entity, ie the object, that is being saved. If the property value is not null it then checks if it is of type DateTime. If that is the case it checks that it is not less than SqlDateTime.MinValue.Value (note the additional .Value to avoid exceptions). There is no need to check against SqlDateTime.MaxValue.Value if you are using SQL Server 2012 or later. They will happily accept even DateTime.MaxValue which is a few time ticks greater than SqlDateTime.MaxValue.Value.

If the value is outside of the allowed range this code will then throw an ArgumentOutOfRangeException with an appropriate message that includes the names of the class (entity) and property causing the problem as well as the actual value that was passed in. The message is similar to the equivalent SqlServerException for the SqlDateTime overflow exception but will make it easier to pinpoint the problem.

A couple of things to consider. Obviously this does not come for free. You will incur a runtime overhead as this logic consumes CPU. Depending on your scenario this may not be a problem. If it is, you can also consider optimizing the code given in this example to make it faster. One option could perhaps be to use caching to avoid the loop for the same class. Another option could be to use it only in test and development environments. For production you could then rely that the rest of the system operates correctly and the values will always be within valid range.

Also, be aware that this code introduces a dependency on SQL Server. NHibernate is typically used to avoid dependencies like this. Other database servers that are supported by NHibernate may have a different range of allowed values for datetime. Again, there are options for resolving this as well, e.g. by using different boundaries depending on SQL dialect.

Happy coding!

ContentLicense: CC BY-SA 2.5

Body:
You can create a class that implements both IPreUpdateEventListener and IPreInsertEventListener as follows:

  public class InsertUpdateListener : IPreInsertEventListener, IPreUpdateEventListener {
     public bool OnPreInsert(PreInsertEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     public bool OnPreUpdate(PreUpdateEvent @event) {
        CheckDateTimeWithinSqlRange(@event.Persister, @event.State);
        return false;
     }

     private static void CheckDateTimeWithinSqlRange(IEntityPersister persister, IReadOnlyList<object> state) {
        var rgnMin = System.Data.SqlTypes.SqlDateTime.MinValue.Value;
        // There is a small but relevant difference between DateTime.MaxValue and SqlDateTime.MaxValue.
        // DateTime.MaxValue is bigger than SqlDateTime.MaxValue but still within the valid range of
        // values for SQL Server. Therefore we test against DateTime.MaxValue and not against
        // SqlDateTime.MaxValue. [Manfred, 04jul2017]
        //var rgnMax = System.Data.SqlTypes.SqlDateTime.MaxValue.Value;
        var rgnMax = DateTime.MaxValue;
        for (var i = 0; i < state.Count; i++) {
           if (state[i] != null
               && state[i] is DateTime) {
              var value = (DateTime)state[i];
              if (value < rgnMin /*|| value > rgnMax*/) { // we don't check max as SQL Server is happy with DateTime.MaxValue [Manfred, 04jul2017]
                 throw new ArgumentOutOfRangeException(persister.PropertyNames[i], value,
                    $"Property '{persister.PropertyNames[i]}' for class '{persister.EntityName}' must be between {rgnMin:s} and {rgnMax:s} but was {value:s}");
              }
           }
        }
     }
  }

You also need to then register this event handler when you configure the session factory. Add an instance to Configuration.EventListeners.PreUpdateEventListeners and to Configuration.EventListeners.PreInsertEventListeners and then use the Configuration object when creating NHibernate's session factory.

What this does is this: Every time NHibernate inserts or updates an entity it will call OnPreInsert() or OnPreUpdate() respectively. Each of these methods in turn calls CheckDateTimeWithinSqlRange().

CheckDateTimeWithinSqlRange() iterates over all property values of the entity, ie the object, that is being saved. If the property value is not null it then checks if it is of type DateTime. If that is the case it checks that it is not less than SqlDateTime.MinValue.Value (note the additional .Value to avoid exceptions). There is no need to check against SqlDateTime.MaxValue.Value if you are using SQL Server 2012 or later. They will happily accept even DateTime.MaxValue which is a few time ticks greater than SqlDateTime.MaxValue.Value.

If the value is outside of the allowed range this code will then throw an ArgumentOutOfRangeException with an appropriate message that includes the names of the class (entity) and property causing the problem as well as the actual value that was passed in. The message is similar to the equivalent SqlServerException for the SqlDateTime overflow exception but will make it easier to pinpoint the problem.

A couple of things to consider. Obviously this does not come for free. You will incur a runtime overhead as this logic consumes CPU. Depending on your scenario this may not be a problem. If it is, you can also consider optimizing the code given in this example to make it faster. One option could perhaps be to use caching to avoid the loop for the same class. Another option could be to use it only in test and development environments. For production you could then rely that the rest of the system operates correctly and the values will always be within valid range.

Also, be aware that this code introduces a dependency on SQL Server. NHibernate is typically used to avoid dependencies like this. Other database servers that are supported by NHibernate may have a different range of allowed values for datetime. Again, there are options for resolving this as well, e.g. by using different boundaries depending on SQL dialect.

Happy coding!


问:
How to order in pivot?
This question similiar from my previous question, but i have no idea to find the solution, because im not using union.

i have this query

```<code>CREATE TABLE #SampleData
(
    Name varchar(10),
    Location varchar(20),
    Item varchar(10),
    Date varchar(8)
)
INSERT INTO #SampleData
VALUES
('Ron', 'Loc A', 'Pencil', '20170610'),
('Ron', 'Loc A', 'Pencil', '20170611'),
('Ron', 'Loc B', 'Pen', '20170610'),
('Ron', 'Loc B', 'Laptop', '20170611'),
('Tom', 'Loc A', 'Pencil', '20170611'),
('Tom', 'Loc B', 'Pencil', '20170610'),
('Tom', 'Loc B', 'Pen', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610'),
('Tom', 'Loc A', 'Laptop', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610')

    DECLARE @Pivot_Columns  AS VARCHAR(MAX),
            @select_Columns VARCHAR(max)

    SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
    SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

    DECLARE @SQL AS VARCHAR(MAX)

    SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name
    when grouping(location) = 1 and grouping(name) = 1 then ''Total''
    else name end Name,
    case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location ))
    when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location ))
    else Location end Location,
    '+ @select_Columns + '
    FROM
    (
        SELECT name, location, item
        FROM #SampleData

    ) as PivotData
    PIVOT
    (
        count(item)
        for item  IN ('
               + @Pivot_Columns + ')
    ) AS PivotResult
    group by name,location with rollup
    '

    EXEC(@SQL)
</code>```

and the result like this:

how to order my query looks like this? if theres no count of my location my query work fine

i need the solution to fix this problem, thanks in advance!!

答:
Is this type of output acceptable ?

```<code>Name             Location             Laptop      Pen         Pencil
---------------- -------------------- ----------- ----------- -----------
Ron              Loc A                0           0           2
Ron              Loc B                1           1           0
Ron Total        2                    1           1           2
Tom              Loc B                0           1           1
Tom              Loc A                1           0           3
Tom Total        2                    1           1           4
Total            2                    2           2           6
</code>```

The query I have used :

```<code>DECLARE @Pivot_Columns  AS VARCHAR(MAX),
        @select_Columns VARCHAR(max)

SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

DECLARE @SQL AS VARCHAR(MAX)

SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then name + '' ''+ ''Total''
when grouping(location) = 1 and grouping(name) = 1 then ''Total''
else name end Name,
case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location ))
when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location ))
else Location end Location,
'+ @select_Columns + '
FROM
(
    SELECT name, location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ('
           + @Pivot_Columns + ')
) AS PivotResult
group by name,location with rollup
ORDER BY GROUPING (name), name'

EXEC(@SQL)
</code>```

Title: How to order in pivot?

Body:
This question similiar from my previous question, but i have no idea to find the solution, because im not using union.

i have this query

CREATE TABLE #SampleData
(
    Name varchar(10),
    Location varchar(20),
    Item varchar(10),
    Date varchar(8)
)
INSERT INTO #SampleData
VALUES
('Ron', 'Loc A', 'Pencil', '20170610'),
('Ron', 'Loc A', 'Pencil', '20170611'),
('Ron', 'Loc B', 'Pen', '20170610'),
('Ron', 'Loc B', 'Laptop', '20170611'),
('Tom', 'Loc A', 'Pencil', '20170611'),
('Tom', 'Loc B', 'Pencil', '20170610'),
('Tom', 'Loc B', 'Pen', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610'),
('Tom', 'Loc A', 'Laptop', '20170610'),
('Tom', 'Loc A', 'Pencil', '20170610')

    DECLARE @Pivot_Columns  AS VARCHAR(MAX),
            @select_Columns VARCHAR(max)

    SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
    SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

    DECLARE @SQL AS VARCHAR(MAX)

    SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then ''Total''+ '' '' + name
    when grouping(location) = 1 and grouping(name) = 1 then ''Total''
    else name end Name,
    case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location ))
    when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location ))
    else Location end Location,
    '+ @select_Columns + '
    FROM
    (
        SELECT name, location, item
        FROM #SampleData

    ) as PivotData
    PIVOT
    (
        count(item)
        for item  IN ('
               + @Pivot_Columns + ')
    ) AS PivotResult
    group by name,location with rollup
    '

    EXEC(@SQL)

and the result like this:

how to order my query looks like this? if theres no count of my location my query work fine

i need the solution to fix this problem, thanks in advance!!

Body:
Is this type of output acceptable ?

Name             Location             Laptop      Pen         Pencil
---------------- -------------------- ----------- ----------- -----------
Ron              Loc A                0           0           2
Ron              Loc B                1           1           0
Ron Total        2                    1           1           2
Tom              Loc B                0           1           1
Tom              Loc A                1           0           3
Tom Total        2                    1           1           4
Total            2                    2           2           6

The query I have used :

DECLARE @Pivot_Columns  AS VARCHAR(MAX),
        @select_Columns VARCHAR(max)

SELECT @Pivot_Columns = Stuff((SELECT DISTINCT ',' + Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')
SELECT @select_Columns = Stuff((SELECT DISTINCT ',Sum(' + Quotename(Item) + ') as '+Quotename(Item) FROM #SampleData FOR xml path('')), 1, 1, '')

DECLARE @SQL AS VARCHAR(MAX)

SET @SQL = 'SELECT case when grouping(location) = 1 and grouping(name) = 0 then name + '' ''+ ''Total''
when grouping(location) = 1 and grouping(name) = 1 then ''Total''
else name end Name,
case when grouping(location) = 1 and grouping(name) = 0 then CONVERT(varchar(10), COUNT(Distinct location ))
when grouping(location) = 1 and grouping(name) = 1 then CONVERT(varchar(10), COUNT(Distinct location ))
else Location end Location,
'+ @select_Columns + '
FROM
(
    SELECT name, location, item
    FROM #SampleData

) as PivotData
PIVOT
(
    count(item)
    for item  IN ('
           + @Pivot_Columns + ')
) AS PivotResult
group by name,location with rollup
ORDER BY GROUPING (name), name'

EXEC(@SQL)


问:
No trait information (runtime warning)
I wanted to test my app on my iPod 6th generation (iOS 9) but it gives me this warning (in Assets.xcassets)

```<code>No trait information for iPod "7,1"
</code>```

I have no idea what is going on. How can I fix this?

答: I had the same warning for a project after connecting the new 10.5" iPad: .../Assets.xcassets: No trait information for "iPad7,4". This seems to happen when your device is more recent than the installed Xcode version that is Xcode didn't know about any new iPads and their specs yet. After manually updating Xcode to the latest version the warning was gone.

Title: No trait information (runtime warning)

Body:
I wanted to test my app on my iPod 6th generation (iOS 9) but it gives me this warning (in Assets.xcassets)

No trait information for iPod "7,1"

I have no idea what is going on. How can I fix this?


问:
Admin login is not working
I have a admin login script which starts the session after successful login, but the problem is that it logs us in correctly and redirects us to index.php but at index.php it says your login session is not recorded on the database.

```<code>    <?php
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
session_start();
if (!isset($_SESSION["manager"])) {
    header("location: admin_login.php");
    exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($conn,"SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = @mysqli_num_rows($conn,$sql); // count the row nums
if ($existCount == 0) { // evaluate the count
     echo "Your login session data is not on record in the database.";
     exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Store Admin Area</title>
<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen" />
</head>

<body>
<div align="center" id="mainWrapper">
  <?php include_once("../template_header.php");?>
  <div id="pageContent"><br />
    <div align="left" style="margin-left:24px;">
      <h2>Hello store manager, what would you like to do today?</h2>
      <p><a href="inventory_list.php">Manage Inventory</a><br />
      <a href="#">Manage Blah Blah </a></p>
    </div>
    <br />
  <br />
  <br />
  </div>
  <?php include_once("../template_footer.php");?>
</div>
</body>
</html>
</code>```

My admin_login.php

```<code>    <?php
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
session_start();
if (isset($_SESSION["manager"])) {
    header("location: index.php");
    exit();
}
?>
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {

    $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
    $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
    // Connect to the MySQL database
    include "../storescripts/connect_to_mysql.php";
    $sql = mysqli_query($conn,"SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
    // ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
    $existCount = mysqli_num_rows($sql); // count the row nums
    if ($existCount == 1) { // evaluate the count
         while($row = mysql_fetch_array($sql)){
             $id = $row["id"];
         }
         $_SESSION["id"] = $id;
         $_SESSION["manager"] = $manager;
         $_SESSION["password"] = $password;
         header("location: index.php");
         exit();
    } else {
        echo 'That information is incorrect, try again <a href="index.php">Click Here</a>';
        exit();
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin Log In </title>

</head>

<body>
<div align="center" id="mainWrapper">

  <div id="pageContent"><br />
    <div align="left" style="margin-left:24px;">
      <h2>Please Log In To Manage the Store</h2>
      <form id="form1" name="form1" method="post" action="admin_login.php">
        User Name:<br />
          <input name="username" type="text" id="username" size="40" />
        <br /><br />
        Password:<br />
       <input name="password" type="password" id="password" size="40" />
       <br />
       <br />
       <br />

         <input type="submit" name="button" id="button" value="Log In" />

      </form>
      <p>  </p>
    </div>
    <br />
  <br />
  <br />
  </div>
  <?php include_once("../template_footer.php");?>
</div>
</body>
</html>
</code>```

答:
All database wrote in Session is by your code, not user input, I do not think you need regEx on it while password may contain special character, this will gone fail.

Just replace

$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters

with

$managerID = $_SESSION["id"]);
$manager =  $_SESSION["manager"]);
$password = $_SESSION["password"]);

Title: Admin login is not working

Body:
I have a admin login script which starts the session after successful login, but the problem is that it logs us in correctly and redirects us to index.php but at index.php it says your login session is not recorded on the database.

    <?php
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
session_start();
if (!isset($_SESSION["manager"])) {
    header("location: admin_login.php");
    exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysqli_query($conn,"SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = @mysqli_num_rows($conn,$sql); // count the row nums
if ($existCount == 0) { // evaluate the count
     echo "Your login session data is not on record in the database.";
     exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Store Admin Area</title>
<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen" />

  <?php include_once("../template_header.php");?>

Hello store manager, what would you like to do today?

Manage Inventory

      Manage Blah Blah

  <?php include_once("../template_footer.php");?>

My admin_login.php

    <?php
// This file is www.developphp.com curriculum material
// Written by Adam Khoury January 01, 2011
// http://www.youtube.com/view_play_list?p=442E340A42191003
session_start();
if (isset($_SESSION["manager"])) {
    header("location: index.php");
    exit();
}
?>
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {

    $manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
    $password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
    // Connect to the MySQL database
    include "../storescripts/connect_to_mysql.php";
    $sql = mysqli_query($conn,"SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
    // ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
    $existCount = mysqli_num_rows($sql); // count the row nums
    if ($existCount == 1) { // evaluate the count
         while($row = mysql_fetch_array($sql)){
             $id = $row["id"];
         }
         $_SESSION["id"] = $id;
         $_SESSION["manager"] = $manager;
         $_SESSION["password"] = $password;
         header("location: index.php");
         exit();
    } else {
        echo 'That information is incorrect, try again Click Here';
        exit();
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Admin Log In </title>

Please Log In To Manage the Store

      <form id="form1" name="form1" method="post" action="admin_login.php">
        User Name:

          <input name="username" type="text" id="username" size="40" />

        Password:

       <input name="password" type="password" id="password" size="40" />

         <input type="submit" name="button" id="button" value="Log In" />

      </form>

  <?php include_once("../template_footer.php");?>


问:
Git bash folder location under windows 7
I have installed git bash and create few folders using git bash. I wanted to search over Windows explorer but don't know exactly where these folders are actually created

Can please some one help me

答:
You can use the cygpath program to convert from POSIX names to Win32 names.

For example, to know the full name of the current directory:

```<code>$ cygpath -wa .
</code>```

Body:
You can use the cygpath program to convert from POSIX names to Win32 names.

For example, to know the full name of the current directory:

$ cygpath -wa .