问:
TensorFlow 1.1 “bazel build tensorflow/tools/graph_transforms:transform_graph"
When I build quantization tool use the command
"bazel build tensorflow/tools/graph_transforms:transform_graph"

The complie result as below:

WARNING: Sandboxed execution is not supported on your system and thus hermeticity of actions cannot be guaranteed. See http://bazel.build/docs/bazel-user-manual.html#sandboxing for more information. You can turn off this warning via --ignore_unsupported_sandboxing.

INFO: Found 1 target...

ERROR: /root/tensorflow-master/tensorflow/core/BUILD:1287:1: C++ compilation of rule '//tensorflow/core:framework_internal' failed: gcc failed: error executing command /usr/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -B/usr/bin -B/usr/bin -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 '-D_FORTIFY_SOURCE=1' -DNDEBUG ... (remaining 106 argument(s) skipped): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.

tensorflow/core/framework/reader_op_kernel.cc:20:61: error: definition of implicitly-declared 'tensorflow::ReaderOpKernel::ReaderOpKernel(tensorflow::OpKernelConstruction*)'
 ReaderOpKernel::ReaderOpKernel(OpKernelConstruction* context)
                                                             ^
tensorflow/core/framework/reader_op_kernel.cc:27:33: error: definition of implicitly-declared 'virtual tensorflow::ReaderOpKernel::~ReaderOpKernel()'
 ReaderOpKernel::~ReaderOpKernel() {
                                 ^

tensorflow/core/framework/reader_op_kernel.cc:34:50: error: no 'void tensorflow::ReaderOpKernel::Compute(tensorflow::OpKernelContext*)' member function declared in class 'tensorflow::ReaderOpKernel'
 void ReaderOpKernel::Compute(OpKernelContext* ctx) {
                                                  ^
Target //tensorflow/tools/graph_transforms:transform_graph failed to build

Use --verbose_failures to see the command lines of failed build steps.

INFO: Elapsed time: 5.989s, Critical Path: 5.02s

What's the problem?

Thanks!

答:
Please try two things:
(1) configure the compile environment first and then compile, like

./configure

bazel build tensorflow/tools/graph_transforms:transform_graph

(2) You can also try:

sudo bazel build tensorflow/tools/graph_transforms:transform_graph

Point (2) worked for me sometimes to remove dependencies of including header files.

please download the latest tensorflow and bazel, if needed.


来源: stackexchange

问:
How to fetch device's mobile number programmatically in Android?
This code is not working...It giving null...</p>

```<code>TelephonyManager tMgr = (TelephonyManager)HomeActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

Log.e("Mobile No. :",""+mPhoneNumber);
Toast.makeText(getApplicationContext(),mPhoneNumber,Toast.LENGTH_SHORT).show();
</code>```

答: Check in Phone--> Settings --> About --> Phone identity If you are able to view the number  then you will get phone number otherwise won't able to get number</p>

ContentLicense: CC BY-SA 3.0

Body:
This code is not working...It giving null...

TelephonyManager tMgr = (TelephonyManager)HomeActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

Log.e("Mobile No. :",""+mPhoneNumber);
Toast.makeText(getApplicationContext(),mPhoneNumber,Toast.LENGTH_SHORT).show();


问:
how to control wild card using Regular expression javascript
I need java script regular expression to control on the client side.
I have a page with text field need following validation.

1) User allowed to enter two characters after %(ie) %ab or %abcde or %abcdef%

2) % -Not allowed

3) %%-Not allowed

4) %ab-Allowed

5)%ab% allowed

6) %%%-Not allowed

7) %a%- Not allowed.

I am new to write Regular expression. Please help on this.

Thanks in advance

答:
Here you go…

var re = /^%[A-Za-z]{2,}%?$/;

console.log(re.test('%')); // false expected
console.log(re.test('%%')); // false expected
console.log(re.test('%ab')); // true expected
console.log(re.test('%ab%')); // true expected
console.log(re.test('%abcde%')); // true expected
console.log(re.test('%abcdef%')); // true expected
console.log(re.test('%%%')); // false expected
console.log(re.test('%a%')); // false expected```

Explanation

^% - starts with %

[A-Za-z]{2,} - followed by at least 2 (uppercase or lowercase) letters

%?$ - with an optional % at the end

Body:
Here you go…

var re = /^%[A-Za-z]{2,}%?$/;

console.log(re.test('%')); // false expected
console.log(re.test('%%')); // false expected
console.log(re.test('%ab')); // true expected
console.log(re.test('%ab%')); // true expected
console.log(re.test('%abcde%')); // true expected
console.log(re.test('%abcdef%')); // true expected
console.log(re.test('%%%')); // false expected
console.log(re.test('%a%')); // false expected

Explanation

^% - starts with %

[A-Za-z]{2,} - followed by at least 2 (uppercase or lowercase) letters

%?$ - with an optional % at the end


问:
How to select latest date record and show other columns in mysql?
I'm using XAMPP MYSQL

I have table and the Date Column is String

```<code>  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

How to select query the latest date record of each customer with different locations?

Expect result:

```<code>Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000
</code>```

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.

答:
maybe you can try this</p>

```<code>select a.*
from yourtable a JOIN
( select Customer,Location,Max(Date) as Mdate
   from yourtable
   group by Customer,Location) b
on a.Customer=b.Customer and a.Location=b.Location and a.Date=b.Mdate
</code>```

Body:
I'm using XAMPP MYSQL

I have table and the Date Column is String

  Date    |  Customer   |   Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/20    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  South Beach   15000   1000
2015/6/22    LBalance      California    5000    4000
2015/6/22    LBalance      New York      6000    6000
2015/6/17    InHoss Dept.  North Beach   18000   1000

How to select query the latest date record of each customer with different locations?

Expect result:

Date      |  Customer   |    Location   | Cash | Balance |
2015/6/23    LBalance      California    5000    3000
2015/6/25    LBalance      New York      6000    4500
2015/6/25    InHoss Dept.  South Beach   15000   1000
2015/6/17    InHoss Dept.  North Beach   18000   1000

this is the closest i've been to: SELECT Customer, Location, Cash, Balance, max(Date) AS "As Of" FROM mytable WHERE Customer = 'LBalance' GROUP BY Customer, Location. Although It's showing the most recent date of a customer but the other column is just showing their first result.

Body:
maybe you can try this

select a.*
from yourtable a JOIN
( select Customer,Location,Max(Date) as Mdate
   from yourtable
   group by Customer,Location) b
on a.Customer=b.Customer and a.Location=b.Location and a.Date=b.Mdate


问:
How to change dataframe column names in PySpark?
I come from pandas background and am used to reading data from CSV files into a dataframe and then simply changing the column names to something useful using the simple command:

```<code>df.columns = new_column_name_list
</code>```

However, the same doesn't work in PySpark dataframes created using sqlContext.
The only solution I could figure out to do this easily is the following:

```<code>df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', inferschema='true', delimiter='\t').load("data.txt")
oldSchema = df.schema
for i,k in enumerate(oldSchema.fields):
  k.name = new_column_name_list[i]
df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', delimiter='\t').load("data.txt", schema=oldSchema)
</code>```

This is basically defining the variable twice and inferring the schema first then renaming the column names and then loading the dataframe again with the updated schema.

Is there a better and more efficient way to do this like we do in pandas?

My Spark version is 1.5.0

答: If you want to change all columns names, try df.toDF(*cols)

ContentLicense: CC BY-SA 4.0

Body:
I come from pandas background and am used to reading data from CSV files into a dataframe and then simply changing the column names to something useful using the simple command:

df.columns = new_column_name_list

However, the same doesn't work in PySpark dataframes created using sqlContext.
The only solution I could figure out to do this easily is the following:

df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', inferschema='true', delimiter='\t').load("data.txt")
oldSchema = df.schema
for i,k in enumerate(oldSchema.fields):
  k.name = new_column_name_list[i]
df = sqlContext.read.format("com.databricks.spark.csv").options(header='false', delimiter='\t').load("data.txt", schema=oldSchema)

This is basically defining the variable twice and inferring the schema first then renaming the column names and then loading the dataframe again with the updated schema.

Is there a better and more efficient way to do this like we do in pandas?

My Spark version is 1.5.0


问:
How to make div appear on button click using Javascript
I'm trying to make a div appear on button click which I've not succeeded from the below code.Please let me know if I've done any thing wrong in the code.

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Login

<div id="sign-in" class="login" style="display: none;">
  <form>
    <div class="row">
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="email" class="form-control" id="email" Placeholder="email">
        </div>
      </div>
      <div class="col-md-3">
        <div class="form-group inline-form">
          <input type="password" class="form-control" id="pwd">
        </div>
      </div>
      <div class="col-md-3">
        <div class="checkbox">
          <label><input type="checkbox"> Remember me</label>
        </div>
      </div>
      <div class="col-md-3">
        <button type="submit" class="btn btn-default ">Submit</button>
      </div>
    </div>
  </form>
</div></code>```

答:
getElementById() is a function and its case sensitive . You need to write getElementByid() as getElementById().

Note:- i in getElementById() should be capital .

Body:
I'm trying to make a div appear on button click which I've not succeeded from the below code.Please let me know if I've done any thing wrong in the code.

function showDiv() {
  document.getElementById('sign-in').style.display = "block";
}

Login

  <form>

          <input type="email" class="form-control" id="email" Placeholder="email">

          <input type="password" class="form-control" id="pwd">

          <input type="checkbox"> Remember me

        <button type="submit" class="btn btn-default ">Submit</button>

  </form>


问:
Saving a Twitter Sample Stream to RavenDB results in the exception The maximum number of requests (30) allowed for this session has been reached
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

```<code>using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}
</code>```

DocumentStoreHolder.cs

```<code>using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}
</code>```

TwitterModels.cs

```<code>namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}
</code>```

答: Assuming that this is a very large set of data, you probably don't want to do it using the session, a bulk insert would work better here.</p>

Body:
I am attempting to save a Twitter sample stream to RavenDB but I am encountering the exception: "The maximum number of requests (30) allowed for this session has been reached."

This question has the same problem however I think by calling session.Store I am already doing what the accepted answer suggests.

I know I am doing something wrong but not sure what.

Here is my code:

using Tweetinvi;

namespace TwitterNoSql
{
    class Program
    {
        static void Main(string[] args)
        {
            Auth.SetUserCredentials() // redacted for SO

            var stream = Stream.CreateSampleStream();

            using (var session = DocumentStoreHolder.Store.OpenSession())
            {
                stream.TweetReceived += (sender, theTweet) =>
                {
                    var tm = new TwitterModels
                    {
                        Id = theTweet.Tweet.Id,
                        TheTextFromTwitter = theTweet.Tweet.FullText
                    };

                    session.Store(tm);
                    session.SaveChanges();

                };
                stream.StartStream();

            }
        }
    }
}

DocumentStoreHolder.cs

using System;
using Raven.Client;
using Raven.Client.Document;

namespace TwitterNoSql
{
    class DocumentStoreHolder
    {
        private static readonly Lazy<IDocumentStore> LazyStore =
            new Lazy<IDocumentStore>(() =>
            {
                var store = new DocumentStore
                {
                    Url = "http://localhost:8080",
                    DefaultDatabase = "TwitterNoSql"
                };
                return store.Initialize();
            });

        public static IDocumentStore Store =>
             LazyStore.Value;
    }
}

TwitterModels.cs

namespace TwitterNoSql
{
    public class TwitterModels
    {
        public long Id { get; set; }
        public string TheTextFromTwitter { get; set; }
    }
}


问:
SQL Server : select distinct until the value is changed
I have a table of tasks (each task can has a few rows) that looks something like this:

```<code>TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done
</code>```

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

```<code>TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done
</code>```

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

```<code>Started ==> InProgress ==> Break ==> InProgress ==> Done
</code>```

so will not help me to get for each task the unique status from each status type it passed

答:
Try Query (select distinct ):

```<code>SELECT DISTINCT TaskID, Status
FROM            (SELECT   TaskID, Status
                          FROM            task
                          ORDER BY TaskID) AS task_1
WHERE        (TaskID = 1)
ORDER BY Status DESC
</code>```

Or Simply :

```<code>SELECT DISTINCT TaskID, Status
FROM            task
WHERE        (TaskID = 1)
ORDER BY TaskID, Status DESC
</code>```

Result for your demo content:

Body:
I have a table of tasks (each task can has a few rows) that looks something like this:

TaskID | DateCreated | Status
-------+-------------+------------
  1    | 01-01-2017  | Started
  2    | 02-02-2017  | InProgress
  1    | 02-02-2017  | Started
  1    | 03-03-2017  | InProgress
  2    | 03-03-2017  | InProgress
  1    | 04-04-2017  | InProgress
  2    | 04-04-2017  | Done
  1    | 05-05-2017  | Done

I have more columns which are not relevant for this requirement.

What I need here is to select the actual status flow that a specific task has passed.

For example, for task with TaskID = 1, I want to get the following result:

TaskID | Status
-------+-------------
  1    | Started
  1    | InProgress
  1    | Done

Notes:

The rows may be not sorted

A status can repeat itself, e.g. there can be a task that its' status flow was:

Started ==> InProgress ==> Break ==> InProgress ==> Done

so will not help me to get for each task the unique status from each status type it passed

Body:
Try Query (select distinct ):

SELECT DISTINCT TaskID, Status
FROM            (SELECT   TaskID, Status
                          FROM            task
                          ORDER BY TaskID) AS task_1
WHERE        (TaskID = 1)
ORDER BY Status DESC

Or Simply :

SELECT DISTINCT TaskID, Status
FROM            task
WHERE        (TaskID = 1)
ORDER BY TaskID, Status DESC

Result for your demo content:


问:
Alias with variable in bash
I want to create an alias in bash like this:

```<code>alias tail_ls="ls -l $1 | tail"
</code>```

Thus, if somebody types:

```<code>tail_ls /etc/
</code>```

it will only show the last 10 files in the directory.

But $1 does not seem to work for me. Is there any way I can introduce variables in bash.

答:
I'd create a function for that, rather than alias, and then exported it, like this:

```<code>function tail_ls { ls -l "$1" | tail; }

export -f tail_ls
</code>```

Note -f switch to export: it tells it that you are exporting a function. Put this in your .bashrc and you are good to go.

Title: Alias with variable in bash

Body:
I want to create an alias in bash like this:

alias tail_ls="ls -l $1 | tail"

Thus, if somebody types:

tail_ls /etc/

it will only show the last 10 files in the directory.

But $1 does not seem to work for me. Is there any way I can introduce variables in bash.

Body:
I'd create a function for that, rather than alias, and then exported it, like this:

function tail_ls { ls -l "$1" | tail; }

export -f tail_ls

Note -f switch to export: it tells it that you are exporting a function. Put this in your .bashrc and you are good to go.


问:
.NET application deployment Error in IIS
When I am trying to deploy a .net application in the IIS Server I am getting an error as Configuration settings do not match. Please help me with this.

答:
Please try this in Web.Config </p>

```<code>    <configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
   </configuration>
</code>```

Body:
Please try this in Web.Config

    <configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
   </configuration>


问:
Safari Push Notifications
I would like to implement push notifications for my website (obviously only in compatible browser as Safari 7).
I have read the Apple documentation and I have successfully created my package containing my icon.iconset, my certificate.p12, manifest.json and a website.json.
Now I would like to ask the permission to the user when I first visit the website. If he allows it, I should send the package.
Everything is pretty clear but I don't know how to go on.

How do I create my push package out of my files? How do I precisely sign it? The package should be always the same so I could sign it on my mac and upload to my server only one package.

If you have experience with this technology, please let me know :)

答:
I have successfully create push package to ask permission on safari web push notifications using REST API in java. Also I have follow steps which provide by Apple officials on there sites.

Please follow below steps to create push package.

Create your web push notification P12 certificate from your apple account.

Create your REST API using https for pushPackage which contain icon.iconset, your certificate.p12, manifest.json and a website.json. p12 certificate must be web push notification certificate.

How to create push package:- Please refer below java code. I have create push package using java servlet. which provide 2 web service end points.

v1/pushpackage/webpushID

v1/log

Servlet which process your push package request which send by safari push notification method

SafariPushPakageAPI.java
/*
Push Package REST API handler
*/

```<code>import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.safari.Packager;

public class SafariPushPakageAPI extends HttpServlet{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static  String ServerPath = null;
    private static final String REQUEST_PERMISSION = "/v1/pushPackages/YOUR_WEB_PUSH_ID";
    private static final String REQUEST_ERRORLOG = "/v1/log";

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doRequest(request, response);
    }
//  /v1/pushPackages/webpushID
//  /v1/log
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doRequest(request, response);
    }

    private void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("===>> SAFARI PUSH NOTIFICATION REQUEST");
        String path = request.getPathInfo();
        System.out.println("PATH ===>> "+path);
        if(path == null){
            doRequestPermission(request, response);
        }else if (path.equalsIgnoreCase(REQUEST_PERMISSION)){
            doRequestPermission(request, response);
        }else if (path.equalsIgnoreCase(REQUEST_ERRORLOG)){
            doRequestShowErrorLog(request, response);
        }else{
            doRequestPermission(request, response);
        }
    }

    private void doRequestPermission(HttpServletRequest request,HttpServletResponse response) {
        try{
            System.out.println("INSIDE REQUEST PERMISSION ==>>>");
            System.out.println(IOUtils.toString(request.getReader()));
            String authToken = StringUtils.isBlank(request.getParameter("token")) ? "UserTokenRT124DFGH" : StringUtils.trimToEmpty(request.getParameter("token"));
            System.out.println("=>>>>>>>>>> USER TOKEN =>>>>>>>>>> "+authToken);
            @SuppressWarnings("deprecation")
            String packagePath =request.getRealPath("pushPackage.raw/icon.iconset/"); // LOCATION WHERE YOUR PUSH PACKAGE FOLDER CONTAIN LOGOS AND website.json file
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;filename=\"pushpackage.zip\"");
            OutputStream out = response.getOutputStream();
            out.write(Packager.createPackageFile(authToken,packagePath));
            response.flushBuffer();
        }catch(IOException ioe){
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doRequestShowErrorLog(HttpServletRequest request,HttpServletResponse response) {
        try{
            System.out.println("ERROR LOG STARTED");
            System.out.println(IOUtils.toString(request.getReader()));
            System.out.println("END");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}
</code>```

Packager.java

```<code>import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Ritesh
 */
public class Packager {

    final static String CERTIFICATE_PATH="PATH TO YOUR 12 CERTIFICATE";
    final static String CERTIFICATE_PASS="PASSWORD";

    static String getJSON(String authenticationToken) throws Exception {
        JSONObject obj = new JSONObject();
        obj.put("websiteName", "WEB SITE NAME");
        obj.put("websitePushID", "WEB PUSH ID");
        obj.put("allowedDomains", new JSONArray());

        obj.getJSONArray("allowedDomains").put("https://TEST.EXAMPLE.net");//LIST OF DOMAINS ALLOW

        obj.put("urlFormatString", "https://TEST.EXAMPLE.net/%@");
        obj.put("authenticationToken", authenticationToken);
        obj.put("webServiceURL", "https://API.EXAMPLE.COM");//callback URL WITHOUT WEB SERVICE ENDPOINT NAME

        return obj.toString();
    }

    public static byte[] createPackageFile(String authenticationToken, String path) throws Exception {

        System.out.println("packaging safari file with token: " + authenticationToken);
        ZipHandler zip = new ZipHandler();
        File dir = new File(path);

        for (File file : dir.listFiles()) {
             InputStream is = new FileInputStream(file);
             byte[] bytes = IOUtils.toByteArray(is);
             zip.addFile("icon.iconset", file.getName(),bytes );
        }

        zip.addFile("", "website.json", getJSON(authenticationToken).getBytes());

        byte[] manifest = zip.manifest();
        zip.addFile("", "manifest.json", manifest);

        zip.addFile("", "signature", sign(manifest));

        return zip.getBytes();

    }

    static byte[] sign(byte bytesToSign[]) throws Exception {
        return new PKCS7Signer().sign(CERTIFICATE_PATH,CERTIFICATE_PASS, bytesToSign);
    }

    /**
     * Servlet handler , should listen on the callback URL (as in webServiceURL)
     * @param requestPath
     * @param req
     * @param servletRequest
     * @param servletResponse
     * @throws Exception
     */

    public static void main(String[] args) throws Exception {
        Packager.createPackageFile("SafriNotifcation","");
    }

}
</code>```

PKCS7Signer.java which create your signature file.

```<code>import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;

public final class PKCS7Signer {

    static {
        try{
            Security.addProvider(new BouncyCastleProvider());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private KeyStore getKeystore(String storeLocation, String storePasswd) throws Exception {
        if (storeLocation == null) {
            System.out.println("Could not find store file (.p12)");
            return null;
        }
        // First load the keystore object by providing the p12 file path
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        // replace testPass with the p12 password/pin
        clientStore.load(new FileInputStream(storeLocation), storePasswd.toCharArray());
        return clientStore;
    }

    private X509CertificateHolder getCert(KeyStore keystore, String alias) throws Exception {
        java.security.cert.Certificate c = keystore.getCertificate(alias);
        return new X509CertificateHolder(c.getEncoded());
    }

    private PrivateKey getPrivateKey(KeyStore keystore, String alias, String storePasswd) throws Exception {
        return (PrivateKey) keystore.getKey(alias, storePasswd.toCharArray());
    }

    public byte[] sign(String storeLocation, String storePasswd, byte[] dataToSign) throws Exception {
        KeyStore clientStore = getKeystore(storeLocation, storePasswd);

        if (clientStore == null) {
            return null;
        }
        Enumeration aliases = clientStore.aliases();
        String alias = "";
        while (aliases.hasMoreElements()) {
            alias = (String) aliases.nextElement();
            if (clientStore.isKeyEntry(alias)) {
                break;
            }
        }

        CMSTypedData msg = new CMSProcessableByteArray(dataToSign); // Data to sign

        X509CertificateHolder x509Certificate = getCert(clientStore, alias);
        List certList = new ArrayList();
        certList.add(x509Certificate); // Adding the X509 Certificate

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        // Initializing the the BC's Signer
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(
                getPrivateKey(clientStore, alias, storePasswd));

        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build()).build(sha1Signer, x509Certificate));
        // adding the certificate
        gen.addCertificates(certs);
        // Getting the signed data
        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.getEncoded();
    }
}
</code>```

please note used latest bouncy castle jars for create signature file
bcprov-jdk15on-157.jar
bcpkix-jdk15on-157.jar

Write your javascript on your client side page.it contains simple java script to get permissions.

///

// For safari
var domain="YOUR WEB PUSH ID";

```<code>function safariIniti() {

    var pResult = window.safari.pushNotification.permission(domain);

    if(pResult.permission === 'default') {
        //request permission
        requestPermissions();
    } else if (pResult.permission === 'granted') {
        console.log("Permission for " + domain + " is " + pResult.permission);
        var token = pResult.deviceToken;
        // Show subscription for debug
        console.log('Subscription details:'+token);
    } else if(pResult.permission === 'denied') {
        console.log("Permission for " + domain + " is " + pResult.permission);
    }
}

function getToken(){

    // always start with a letter (for DOM friendlyness)
    var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
    do {
        // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
        var ascicode=Math.floor((Math.random()*42)+48);
        if (ascicode<58 || ascicode>64){
            // exclude all chars between : (58) and @ (64)
            idstr+=String.fromCharCode(ascicode);
        }
    } while (idstr.length<32);

    return (idstr);
}

function requestPermissions() {

    var tokenVal = getToken();
    window.safari.pushNotification.requestPermission('WEb service url without end points',domain,{token:tokenVal},
function(subscription) {

        console.log(subscription.permission);
        console.log("PERMISSION ====>> "+subscription.permission);
        if(subscription.permission === 'granted') {
            //TODO
        }
        else if(subscription.permission === 'denied') {
            // TODO:
        }
    });

}
</code>```

Title: Safari Push Notifications

Body:
I have successfully create push package to ask permission on safari web push notifications using REST API in java. Also I have follow steps which provide by Apple officials on there sites.

Please follow below steps to create push package.

Create your web push notification P12 certificate from your apple account.

Create your REST API using https for pushPackage which contain icon.iconset, your certificate.p12, manifest.json and a website.json. p12 certificate must be web push notification certificate.

How to create push package:- Please refer below java code. I have create push package using java servlet. which provide 2 web service end points.

v1/pushpackage/webpushID

v1/log

Servlet which process your push package request which send by safari push notification method

SafariPushPakageAPI.java
/*
Push Package REST API handler
*/

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import com.safari.Packager;

public class SafariPushPakageAPI extends HttpServlet{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    public static  String ServerPath = null;
    private static final String REQUEST_PERMISSION = "/v1/pushPackages/YOUR_WEB_PUSH_ID";
    private static final String REQUEST_ERRORLOG = "/v1/log";

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doRequest(request, response);
    }
//  /v1/pushPackages/webpushID
//  /v1/log
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doRequest(request, response);
    }

    private void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("===>> SAFARI PUSH NOTIFICATION REQUEST");
        String path = request.getPathInfo();
        System.out.println("PATH ===>> "+path);
        if(path == null){
            doRequestPermission(request, response);
        }else if (path.equalsIgnoreCase(REQUEST_PERMISSION)){
            doRequestPermission(request, response);
        }else if (path.equalsIgnoreCase(REQUEST_ERRORLOG)){
            doRequestShowErrorLog(request, response);
        }else{
            doRequestPermission(request, response);
        }
    }

    private void doRequestPermission(HttpServletRequest request,HttpServletResponse response) {
        try{
            System.out.println("INSIDE REQUEST PERMISSION ==>>>");
            System.out.println(IOUtils.toString(request.getReader()));
            String authToken = StringUtils.isBlank(request.getParameter("token")) ? "UserTokenRT124DFGH" : StringUtils.trimToEmpty(request.getParameter("token"));
            System.out.println("=>>>>>>>>>> USER TOKEN =>>>>>>>>>> "+authToken);
            @SuppressWarnings("deprecation")
            String packagePath =request.getRealPath("pushPackage.raw/icon.iconset/"); // LOCATION WHERE YOUR PUSH PACKAGE FOLDER CONTAIN LOGOS AND website.json file
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;filename=\"pushpackage.zip\"");
            OutputStream out = response.getOutputStream();
            out.write(Packager.createPackageFile(authToken,packagePath));
            response.flushBuffer();
        }catch(IOException ioe){
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doRequestShowErrorLog(HttpServletRequest request,HttpServletResponse response) {
        try{
            System.out.println("ERROR LOG STARTED");
            System.out.println(IOUtils.toString(request.getReader()));
            System.out.println("END");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

}

Packager.java

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Ritesh
 */
public class Packager {

    final static String CERTIFICATE_PATH="PATH TO YOUR 12 CERTIFICATE";
    final static String CERTIFICATE_PASS="PASSWORD";

    static String getJSON(String authenticationToken) throws Exception {
        JSONObject obj = new JSONObject();
        obj.put("websiteName", "WEB SITE NAME");
        obj.put("websitePushID", "WEB PUSH ID");
        obj.put("allowedDomains", new JSONArray());

        obj.getJSONArray("allowedDomains").put("https://TEST.EXAMPLE.net");//LIST OF DOMAINS ALLOW

        obj.put("urlFormatString", "https://TEST.EXAMPLE.net/%@");
        obj.put("authenticationToken", authenticationToken);
        obj.put("webServiceURL", "https://API.EXAMPLE.COM");//callback URL WITHOUT WEB SERVICE ENDPOINT NAME

        return obj.toString();
    }

    public static byte[] createPackageFile(String authenticationToken, String path) throws Exception {

        System.out.println("packaging safari file with token: " + authenticationToken);
        ZipHandler zip = new ZipHandler();
        File dir = new File(path);

        for (File file : dir.listFiles()) {
             InputStream is = new FileInputStream(file);
             byte[] bytes = IOUtils.toByteArray(is);
             zip.addFile("icon.iconset", file.getName(),bytes );
        }

        zip.addFile("", "website.json", getJSON(authenticationToken).getBytes());

        byte[] manifest = zip.manifest();
        zip.addFile("", "manifest.json", manifest);

        zip.addFile("", "signature", sign(manifest));

        return zip.getBytes();

    }

    static byte[] sign(byte bytesToSign[]) throws Exception {
        return new PKCS7Signer().sign(CERTIFICATE_PATH,CERTIFICATE_PASS, bytesToSign);
    }

    /**
     * Servlet handler , should listen on the callback URL (as in webServiceURL)
     * @param requestPath
     * @param req
     * @param servletRequest
     * @param servletResponse
     * @throws Exception
     */

    public static void main(String[] args) throws Exception {
        Packager.createPackageFile("SafriNotifcation","");
    }

}

PKCS7Signer.java which create your signature file.

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;

public final class PKCS7Signer {

    static {
        try{
            Security.addProvider(new BouncyCastleProvider());
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    private KeyStore getKeystore(String storeLocation, String storePasswd) throws Exception {
        if (storeLocation == null) {
            System.out.println("Could not find store file (.p12)");
            return null;
        }
        // First load the keystore object by providing the p12 file path
        KeyStore clientStore = KeyStore.getInstance("PKCS12");
        // replace testPass with the p12 password/pin
        clientStore.load(new FileInputStream(storeLocation), storePasswd.toCharArray());
        return clientStore;
    }

    private X509CertificateHolder getCert(KeyStore keystore, String alias) throws Exception {
        java.security.cert.Certificate c = keystore.getCertificate(alias);
        return new X509CertificateHolder(c.getEncoded());
    }

    private PrivateKey getPrivateKey(KeyStore keystore, String alias, String storePasswd) throws Exception {
        return (PrivateKey) keystore.getKey(alias, storePasswd.toCharArray());
    }

    public byte[] sign(String storeLocation, String storePasswd, byte[] dataToSign) throws Exception {
        KeyStore clientStore = getKeystore(storeLocation, storePasswd);

        if (clientStore == null) {
            return null;
        }
        Enumeration aliases = clientStore.aliases();
        String alias = "";
        while (aliases.hasMoreElements()) {
            alias = (String) aliases.nextElement();
            if (clientStore.isKeyEntry(alias)) {
                break;
            }
        }

        CMSTypedData msg = new CMSProcessableByteArray(dataToSign); // Data to sign

        X509CertificateHolder x509Certificate = getCert(clientStore, alias);
        List certList = new ArrayList();
        certList.add(x509Certificate); // Adding the X509 Certificate

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        // Initializing the the BC's Signer
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(
                getPrivateKey(clientStore, alias, storePasswd));

        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                .setProvider("BC").build()).build(sha1Signer, x509Certificate));
        // adding the certificate
        gen.addCertificates(certs);
        // Getting the signed data
        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.getEncoded();
    }
}

please note used latest bouncy castle jars for create signature file
bcprov-jdk15on-157.jar
bcpkix-jdk15on-157.jar

Write your javascript on your client side page.it contains simple java script to get permissions.

///

// For safari
var domain="YOUR WEB PUSH ID";

function safariIniti() {

    var pResult = window.safari.pushNotification.permission(domain);

    if(pResult.permission === 'default') {
        //request permission
        requestPermissions();
    } else if (pResult.permission === 'granted') {
        console.log("Permission for " + domain + " is " + pResult.permission);
        var token = pResult.deviceToken;
        // Show subscription for debug
        console.log('Subscription details:'+token);
    } else if(pResult.permission === 'denied') {
        console.log("Permission for " + domain + " is " + pResult.permission);
    }
}

function getToken(){

    // always start with a letter (for DOM friendlyness)
    var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
    do {
        // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
        var ascicode=Math.floor((Math.random()*42)+48);
        if (ascicode<58 || ascicode>64){
            // exclude all chars between : (58) and @ (64)
            idstr+=String.fromCharCode(ascicode);
        }
    } while (idstr.length<32);

    return (idstr);
}

function requestPermissions() {

    var tokenVal = getToken();
    window.safari.pushNotification.requestPermission('WEb service url without end points',domain,{token:tokenVal},
function(subscription) {

        console.log(subscription.permission);
        console.log("PERMISSION ====>> "+subscription.permission);
        if(subscription.permission === 'granted') {
            //TODO
        }
        else if(subscription.permission === 'denied') {
            // TODO:
        }
    });

}


问:
Using Like statement with DataView RowFIlter
I have a DataTable with some data and I want to filter with LIKE query so I have written a code like below and everything working fine, I'm generating the query and passing it to RowFilter object of DataView.

```<code>if (results.Count() == 2)
{
    if (results[0].ToString() == "" && results[1].ToString() != "")
    {
        searchString = String.Format("[" + searchBy + "] LIKE '%{0}'", results[1].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() == "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%'", results[0].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() != "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%{1}'", results[0].ToString(), results[1].ToString());
    }
}

if (searchString != "")
{
     DataView dv = new DataView(AccountList.Tables[0]);
     dv.RowFilter = searchString;
     var tab = dv.ToTable();
     DataSet data_set = new DataSet();
     data_set.Tables.Add(tab);
     ProcessDataSetAndLoadData(data_set);
}
</code>```

In above code segment is working fine except last else if condition, In that condition I'm getting the searchString like this,

[AccountCode] LIKE 'c%l'

When I passing this to RowFilter I'm getting the eror like below,

Error in Like operator: the string pattern 'c%l' is invalid.

From all other conditions I'm getting the searchString like below and those conditions are working fine.

```<code>[AccountCode] LIKE '%c%'
[AccountCode] LIKE 'c%'
[AccountCode] LIKE '%c
</code>```

My Question is why I'm getting the error only for the string like this
?.
    [AccountCode] LIKE 'c%l'

Please Advise me to complete my task.

答:
In DataView filter, wildcard characters are not allowed in middle of the string.

Please refer this MSDN article: https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression.aspx which says

Wildcard Characters

Both the * and % can be used interchangeably for wildcard characters in a LIKE comparison. If the string in a LIKE clause contains a * or %, those characters should be enclosed in brackets ([]). If a bracket is in the clause, each bracket character should be enclosed in brackets (for example [[] or []]). A wildcard is allowed at the start and end of a pattern, or at the end of a pattern, or at the start of a pattern. For example:

"ItemName LIKE 'product'"

"ItemName LIKE '*product'"

"ItemName LIKE 'product*'"

Wildcard characters are not allowed in the middle of a string. For example, 'te*xt' is not allowed.

Body:
I have a DataTable with some data and I want to filter with LIKE query so I have written a code like below and everything working fine, I'm generating the query and passing it to RowFilter object of DataView.

if (results.Count() == 2)
{
    if (results[0].ToString() == "" && results[1].ToString() != "")
    {
        searchString = String.Format("[" + searchBy + "] LIKE '%{0}'", results[1].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() == "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%'", results[0].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() != "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%{1}'", results[0].ToString(), results[1].ToString());
    }
}

if (searchString != "")
{
     DataView dv = new DataView(AccountList.Tables[0]);
     dv.RowFilter = searchString;
     var tab = dv.ToTable();
     DataSet data_set = new DataSet();
     data_set.Tables.Add(tab);
     ProcessDataSetAndLoadData(data_set);
}

In above code segment is working fine except last else if condition, In that condition I'm getting the searchString like this,

[AccountCode] LIKE 'c%l'

When I passing this to RowFilter I'm getting the eror like below,

Error in Like operator: the string pattern 'c%l' is invalid.

From all other conditions I'm getting the searchString like below and those conditions are working fine.

[AccountCode] LIKE '%c%'
[AccountCode] LIKE 'c%'
[AccountCode] LIKE '%c

My Question is why I'm getting the error only for the string like this
?.
    [AccountCode] LIKE 'c%l'

Please Advise me to complete my task.


问:
Property 'displayName' does not exist on type '() => any'
I am seeing the following error, on my angular2 component upon compiling/building

```<code>import { Component, OnInit } from '@angular/core';
import { Router, Params } from '@angular/router';
import {QueuedService} from '../queued.service';

@Component({
  selector: 'app-reservation',
  templateUrl: './reservation.component.html',
  styleUrls: ['./reservation.component.css']
})
export class ReservationComponent implements OnInit {
  username: string;
  useremail: string;
  route$: Router;
  queued$: QueuedService;
  constructor(route: Router, queued: QueuedService) {
    this.queued$ = queued;
    this.route$ = route;
    this.queued$.getUserInfo()
      .subscribe(
        result => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );
  }

  ngOnInit() {
  }

}
</code>```

The error is the following

```<code>Property 'displayName' does not exist on type '() => any'.
Property 'emails' does not exist on type '() => any'.
</code>```

I am unable to figure what the issue is?

EDIT
My getUserInfo function

```<code>  getUserInfo() {
    return this.http.get( this.host + '/auth/userdata')
    .map(response => response.json());
  }
</code>```

答: getUserInfo() doesn't declare a return type that has those properties. I suggest you do the sub action within getUserInfo() itself so that you don't cross any function boundaries with untyped objects.

Body:
I am seeing the following error, on my angular2 component upon compiling/building

import { Component, OnInit } from '@angular/core';
import { Router, Params } from '@angular/router';
import {QueuedService} from '../queued.service';

@Component({
  selector: 'app-reservation',
  templateUrl: './reservation.component.html',
  styleUrls: ['./reservation.component.css']
})
export class ReservationComponent implements OnInit {
  username: string;
  useremail: string;
  route$: Router;
  queued$: QueuedService;
  constructor(route: Router, queued: QueuedService) {
    this.queued$ = queued;
    this.route$ = route;
    this.queued$.getUserInfo()
      .subscribe(
        result => {
            this.username = result.displayName;
            this.useremail = result.emails[0].value;
        }
      );
  }

  ngOnInit() {
  }

}

The error is the following

Property 'displayName' does not exist on type '() => any'.
Property 'emails' does not exist on type '() => any'.

I am unable to figure what the issue is?

EDIT
My getUserInfo function

  getUserInfo() {
    return this.http.get( this.host + '/auth/userdata')
    .map(response => response.json());
  }


问:
How to change screen's in windows phone 7?
I am developing an app in which the user register to EULA then only he proceeds and is navigated to next page, but still after registration the app starts with EULA not the navigated page.</p>

答:
I recommend reviewing Peter Torr's advice with respect to navigation redirections and places.

Introducing the concept of “Places” - Peter Torr's Blog

Redirecting an initial navigation - Peter Torr's Blog

This recent release may also be worth consideration.

Solving Circular Navigation in Windows Phone Silverlight Applications

ContentLicense: CC BY-SA 2.5


问:
Sorting a vector in descending order
Should I use

```<code>std::sort(numbers.begin(), numbers.end(), std::greater<int>());
</code>```

or

```<code>std::sort(numbers.rbegin(), numbers.rend());   // note: reverse iterators
</code>```

to sort a vector in descending order? Are there any benefits or drawbacks with one approach or the other?

答:
First approach refers:

```<code>    std::sort(numbers.begin(), numbers.end(), std::greater<>());
</code>```

You may use the first approach because of getting more efficiency than second.

The first approach's time complexity less than second one.

Title: Sorting a vector in descending order

Body:
Should I use

std::sort(numbers.begin(), numbers.end(), std::greater<int>());

or

std::sort(numbers.rbegin(), numbers.rend());   // note: reverse iterators

to sort a vector in descending order? Are there any benefits or drawbacks with one approach or the other?

Body:
First approach refers:

    std::sort(numbers.begin(), numbers.end(), std::greater<>());

You may use the first approach because of getting more efficiency than second.

The first approach's time complexity less than second one.


问:
How do I replace a product image in Magento?
I need to replace a product image with a new one.

I need to replace image in position 2 with the new image.

This is my code.

```<code>$position = 2;//this is the image to delete
$file_location = "../WS-Access-000036-Black-2.jpg";
$sku = "WS-Access-000036-Black";

//delete image
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$product_id = $product->getId();
$items = $mediaApi->items($product_id);
foreach($items as $item){
    if($item['position']=="$position" or ($position==1 and $item['position']=="0")){

        $mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory

        $image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file'];
        unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk
        break;
    }
}
//end delete image
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND
//IN THE BACKEND OF THE PRODUCT

//save new image
$pathInfo = pathinfo($file_location);
switch($pathInfo['extension']){
    case 'png':
        $mimeType = 'image/png';
        break;
    case 'jpg':
        $mimeType = 'image/jpeg';
        break;
    case 'gif':
        $mimeType = 'image/gif';
        break;
}

$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array();

$newImage = array(
    'file' => array(
        'content' => base64_encode($file_location),
        'mime' => $mimeType,
        'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
    ),
    'label' => '',
    'position' => $position,
    'types' => $types,
    'exclude' => 0,
);

$media = Mage::getModel('catalog/product_attribute_media_api');
$media->create($sku, $newImage);
//end save new image
</code>```

My issue is that when I delete image WS-Access-000036-Black-2.jpg from disk and the products gallery then I add the new WS-Access-000036-Black-2.jpg to the products gallery it loads the old WS-Access-000036-Black-2.jpg.
 I'm thinking its a caching issue but i've cleared my cache and the old image keeps loading.
It's only when I change the name under this line

```<code>'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
</code>```

that everything works correctly.

I need to keep the original file name.

Why is this happening?

答:
It is understood that you are still seeing the old image but have you checked whether the new image inserted at the 2nd position in disk?

If the new image inserted then probably you need to go to admin, System -> Cache Management & refresh all cache + please flush catalog images cache.

Also please try checking this in another browser.

Thank you.

Body:
I need to replace a product image with a new one.

I need to replace image in position 2 with the new image.

This is my code.

$position = 2;//this is the image to delete
$file_location = "../WS-Access-000036-Black-2.jpg";
$sku = "WS-Access-000036-Black";

//delete image
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$product_id = $product->getId();
$items = $mediaApi->items($product_id);
foreach($items as $item){
    if($item['position']=="$position" or ($position==1 and $item['position']=="0")){

        $mediaApi->remove($product_id, $item['file']);//this doesnt remove file from directory

        $image_location = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $item['file'];
        unlink ($image_location);//have to use this to delete image from disk because $mediaApi->remove doesn't delete it from disk
        break;
    }
}
//end delete image
//EVERYTHING UP TO HERE WORKS, THE IMAGE IS DELETED FROM THE DISK AND
//IN THE BACKEND OF THE PRODUCT

//save new image
$pathInfo = pathinfo($file_location);
switch($pathInfo['extension']){
    case 'png':
        $mimeType = 'image/png';
        break;
    case 'jpg':
        $mimeType = 'image/jpeg';
        break;
    case 'gif':
        $mimeType = 'image/gif';
        break;
}

$types = ($position == 1) ? array('image', 'small_image', 'thumbnail') : array();

$newImage = array(
    'file' => array(
        'content' => base64_encode($file_location),
        'mime' => $mimeType,
        'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),
    ),
    'label' => '',
    'position' => $position,
    'types' => $types,
    'exclude' => 0,
);

$media = Mage::getModel('catalog/product_attribute_media_api');
$media->create($sku, $newImage);
//end save new image

My issue is that when I delete image WS-Access-000036-Black-2.jpg from disk and the products gallery then I add the new WS-Access-000036-Black-2.jpg to the products gallery it loads the old WS-Access-000036-Black-2.jpg.
 I'm thinking its a caching issue but i've cleared my cache and the old image keeps loading.
It's only when I change the name under this line

'name' => pathinfo($sku."-".$position, PATHINFO_FILENAME),

that everything works correctly.

I need to keep the original file name.

Why is this happening?


问:
how we crop image at front end from wordpress classiads theme
I purchase a classiads template of wordpress.
everything work is fine but i stuck at one point. i wish when i submit a post from front end as a user then image automatically crop 600 * 400 size. i apply different plugin but still image size not change.
Please guide what i am doing.

Below post i attach post page screenshot

答:
If you are looking for a plugin then try this one out. It will give you a custom button to crop and upload the image.

https://wordpress.org/plugins/image-regenerate-select-crop/


问:
how to use traceview in eclipse for android development?
I want to use traceview in android in eclipse. I have a few questions:
1. Does my emulator phone need to have a sd card for traceview to work?
2. Is there anyway to start traceview directly from eclipse ide?

I did try to put sd card memory in my avd device but still i cannot find the folder marked sdcard.

thanks in advance.

答:
You can use trace view directly from DDMS window on clicking profiling option and open trace view

Thanks


问:
Efficient way to turn a boolean matrix into a graph structure?
I am working on a maze-problem where the maze is represented in a two-dimensional array, so that if an element is false, the square is not possible to walt through, and the other way around. I have implemented a solving method that recursively tries to walk through all the neighbouring squares of the starting point in a depth first way, which works as it should.

I would however like to try to beat the DFS-algoritm, and I had the idea to simplify the maze into a graph, (and perhaps try to assign weights to the edges) and do a DFS on the graph and not every single square in the maze. The problem I run into is that the way I go about turning the maze into a grap seems very inefficient. Here is an outline of the method that turns the boolean matrix into a graph:

I begin at row 0, and go through each row from index 0, 0 to index n,0, then 0,1 .. n, 1 till n,n. Edit:to clarify: I let the x-values along the maze increase first. Then I link the nodes vertically in the next segment.

I'll call the true values in the matrix for open squares.
*If a white square is on the edge of the board, I make a new sub-class of my Node class called Opening. I will keep a reference to that node. Continuing to the right, if I hit either a crossroad or if the next square is black, I make a node and an endge between the two. If I step from a black square to a white square, and if the next square to the right is not black, I make a node, and I make an edge between that node and the next node along the row.

All the nodes get added to a list of nodes. Then, I loop through all the colomns from (0, 0), (0, 1), ..., (0, n), (1, 0), (1, 1).. (1, n).. and make edges between all the nodes that are not seperated by black squares.

This feels like a very costly way of going about things. I would love to hear any recommendations as to how this should be done properly.

```<code>F F F F F F F F F F F F F
T T F T T T T T T T T T F
F T F F F F F F F T F F F
F T T T F T T T F T F T F
F F F T F T F T F F F T F
F T F T F T F T T T T T F
F T F T F T F F F F F F F
F T T T F T T T T T T T F
F T F F F F F F F F F T F
F T F T T T T T T T T T F
F T F T F F F F F F F T F
F T T T F T T T T T T T T
F F F F F F F F F F F F F
</code>```

would make these nodes:

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

This does not show the edges, but maybe you get the idea.

答:
I have two solutions in mind and one of them already implemented. Before I start to explain the first algorithm, here some assumptions the algorithm relies on:

Assumtions

the maze is minimal in terms of: either the boarder tiles of the maze contain a walkable tile T or the whole maze is composed of unwalkable tiles F only.

the maze defines a rectangle or in other words: each row of the maze have the same amount of columns.

Algorithm

I will explain the algorithm by using a simpler example, still touching many important cases. Consider the following maze composed of 5 rows and 3 columns:

Walkable tiles T are green while wall tiles F are blue.

Phase one of the algorithm starts at (x, y) = (0, 0), in search of a walkable boarder tile, by visiting boarder tiles moving clockwise. It prefers walkable tiles having either less or more than 2 open edges. An open edge is an edge for which we know one node but not yet the other buddy node.

It starts at tile (x, y) = (0, 0) and finds a walkable node having 2 open edges (represented as white arrows). It memorizes the candidate node (represented by an orange circle) and continues, hoping to find a preferable node as stated above.

At step 5 it finds a preferable node represented by the tile (2, 2), having 3 open edges. It marks the node as unprocessed (represented as a circle with either a white or grey background) and terminates phase one.

Phase two will pick an arbitrary unprocessed node and process it, by determining the buddy nodes of open edges, until no more unprocessed nodes exists. Afterwards it will mark the node as processed. Determining buddy nodes may result in marking additional nodes as unprocessed.

The only unprocessed node available to pick is the boarder node at (2, 2) found in phase one. The algorithm picks it (represented by a circle having a grey background). The arbitrary selected open edge is represented as a gray arrow (in our case pointing south).

Now the algorithm searches for the buddy node by moving along walkable tiles until it finds a node (a tile having either less or more than 2 edges or being the tile the algorithm started at).

In our case the algorithm finds the buddy node in step 6 represented by the walkable tile (0, 2). Because this node is neither marked as processed nor as unprocessed it marks the node as unprocessed (represented by a circle having a white background). The open edge is now linked (represented by a black arrow) to its buddy node and vice versa.

The algorithm continues picking open edges of the selected node until all open edges are linked to their buddy nodes. In our example the next arbitrary picked open edge is pointing west.

The algorithm moves along walkable tiles and finds the buddy node represented by the tile (0, 2), which it already found before and which is already marked as unprocessed. Hence it links the open edge for both nodes and continues with the last open edge pointing north.

It finds the same node as before and links the last open edge. Now the selected node at (2, 2) has no more open edges and hence the algorithm marks it as processed (represented by circle having a green background).

The algorithm continues picking an arbitrary unprocessed node, finding the only one available represented by the tile at (0, 2). But because this node do not have any open edges it marks it immediately as processed and continues.

There are no more unprocessed nodes available and hence the algorithm terminates.

Applied to OP Example

If applied to the example provided by you the resulting graph would be much smaller without loosing any information about navigating the maze. Lets have a look at your graph (which I had to complete, because some nodes were missing):

The picture at the left shows the graph resulting from your example and suggested algorithm. The picture to the right shows the nodes the algorithm I described would not find because they may be optimized away without loosing any navigation information. They would either be replaced by an edge or completely eliminated. The result is shown below:

The picture at the left shows the replacements while the picture at the right is just a compressed version of it. The graph was reduced from 25 nodes to 8 nodes and from 23 to 7 edges. Overall a reduction of 2/3 nodes and edges.

Interesting Corner Cases

While I implemented the algorithm, I discovered some interesting corner cases I like to share with you. I will rush through the algorithm to keep the images small. I hope you already got how the algorithm works.

Single walkable tile and hence no edges at all:

Only boarder tiles are walkable:

All tiles are walkable:

Preferable boarder tile has single edge:

Body:
I am working on a maze-problem where the maze is represented in a two-dimensional array, so that if an element is false, the square is not possible to walt through, and the other way around. I have implemented a solving method that recursively tries to walk through all the neighbouring squares of the starting point in a depth first way, which works as it should.

I would however like to try to beat the DFS-algoritm, and I had the idea to simplify the maze into a graph, (and perhaps try to assign weights to the edges) and do a DFS on the graph and not every single square in the maze. The problem I run into is that the way I go about turning the maze into a grap seems very inefficient. Here is an outline of the method that turns the boolean matrix into a graph:

I begin at row 0, and go through each row from index 0, 0 to index n,0, then 0,1 .. n, 1 till n,n. Edit:to clarify: I let the x-values along the maze increase first. Then I link the nodes vertically in the next segment.

I'll call the true values in the matrix for open squares.
*If a white square is on the edge of the board, I make a new sub-class of my Node class called Opening. I will keep a reference to that node. Continuing to the right, if I hit either a crossroad or if the next square is black, I make a node and an endge between the two. If I step from a black square to a white square, and if the next square to the right is not black, I make a node, and I make an edge between that node and the next node along the row.

All the nodes get added to a list of nodes. Then, I loop through all the colomns from (0, 0), (0, 1), ..., (0, n), (1, 0), (1, 1).. (1, n).. and make edges between all the nodes that are not seperated by black squares.

This feels like a very costly way of going about things. I would love to hear any recommendations as to how this should be done properly.

F F F F F F F F F F F F F
T T F T T T T T T T T T F
F T F F F F F F F T F F F
F T T T F T T T F T F T F
F F F T F T F T F F F T F
F T F T F T F T T T T T F
F T F T F T F F F F F F F
F T T T F T T T T T T T F
F T F F F F F F F F F T F
F T F T T T T T T T T T F
F T F T F F F F F F F T F
F T T T F T T T T T T T T
F F F F F F F F F F F F F

would make these nodes:

. . . . . . . . . . . . .
O O . O . . . . . O . O .
. . . . . . . . . . . . .
. O . O . O . O . . . . .
. . . . . . . . . . . . .
. . . . . . . O . . . O .
. . . . . . . . . . . . .
. O . O . O . . . . . O .
. . . . . . . . . . . . .
. . . O . . . . . . . O .
. . . . . . . . . . . . .
. O . O . O . . . . . O O
. . . . . . . . . . . . .

This does not show the edges, but maybe you get the idea.


问:
How do you select a particular option in a SELECT element in jQuery?
If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

```<code><div class="selDiv">
  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>
</div>
</code>```

答:
For setting select value with triggering selected:

```<code>$('select.opts').val('SEL1').change();
</code>```

For setting option from a scope:

```<code>$('.selDiv option[value="SEL1"]')
    .attr('selected', 'selected')
    .change();
</code>```

This code use selector to find out the select object with condition, then change the selected attribute by attr().

Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.

Body:
If you know the Index, Value or Text. also if you don't have an ID for a direct reference.

This, this and this are all helpful answers.

Example markup

  <select class="opts">
    <option selected value="DEFAULT">Default</option>
    <option value="SEL1">Selection 1</option>
    <option value="SEL2">Selection 2</option>
  </select>

LastEditorDisplayName: Rich B

Body:
For setting select value with triggering selected:

$('select.opts').val('SEL1').change();

For setting option from a scope:

$('.selDiv option[value="SEL1"]')
    .attr('selected', 'selected')
    .change();

This code use selector to find out the select object with condition, then change the selected attribute by attr().

Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.


问:
Django postgres remove all data created after a point in time
How can I remove all the objects which were created after some timestamp t in django?

Plainly, I need to remove all the objects (all rows in all tables) which have created_at > t. Is there any better solution than writing this:

```<code>models = [Model1, Model2, ..., ModelN]
for model in models:
   model.objects.filter(created_at__gt=t).delete()
</code>```

答:
The Django app registry django.apps.apps allows you to get all models.

import datetime

import django.apps

red_letter_day = datetime.datetime(1949, 6, 8)

for model in django.apps.apps.get_models():
    model.objects.filter(created_at__gt=red_letter_day).delete()
```

Body:
How can I remove all the objects which were created after some timestamp t in django?

Plainly, I need to remove all the objects (all rows in all tables) which have created_at > t. Is there any better solution than writing this:

models = [Model1, Model2, ..., ModelN]
for model in models:
   model.objects.filter(created_at__gt=t).delete()


问:
Howto debug multiple web servers in intellij at once
Our application stack is composed of 1 grails app, 2 java web spring apps and 1 java app that does its own sockets.  I'm using Tomcat as the server for the two web spring apps.

I'd like to be able to launch all 4 apps at once inside of intellij so that I can debug some issues with data passing between the apps.

How do I do that?

Currently it doesn't work because I cannot get the two web spring apps to launch on different ports.  The grails app I set to port 80 and the java app does it's own custom port, but the other two use 8080.

Is there a way to launch them on different ports?  Is there a way to make them both debuggable while only launching one?  Can I hack anything into the tomcat server.xml?

Thanks

答:
If your Spring app can be packaged into a separate war, is there any reason you can't deploy them both on the same Tomcat instance?

If you can't, just install two separate Tomcat instances, each for different Spring app. Don't forget the HTTP port (8080 by default) is not the only port you need to change in server.xml, there's also Server port, which is set to 8005 by default and possibly others (e.g. AJP if not commented out). Have a look at your $tomcat_home/conf/server.xml to find out more.

Q> Is there a way to make them both debuggable while only launching one?

A> No, unless you want to mock one of them


问:
In Core Data, is it a good practice to have an one-to-one relationship
I'm having two entities: A and B in Core Data. A has an one-to-one relationship to B. Will I be better off to just save an entityB'Id in entity A, then do a fetch on entity B whenever I need?

My thoughts:

I still think having one-to-one relationship is better.

I agree that having a one-to-one relationship sometimes is not necessary.But I checked the sqlite file Core Data generated. To me, it looks like core data is saving that relationship as a column with an Id inside it. So I don't think saving an one-to-one relationship is more expensive than saving an entityB' Id.

After I fetch an object from entity A, having a one-to-one relationship allows me to access the related object in entity B without fetching again. And I think it's better to do one fetch to get an object with a relationship than do two fetch.

答: Either way is probably fine.  I agree that there is no real performance hit but storing the data in a relationship; faulting a relationship is very fast.  If the data in the relationship is relatively large it can be a good practice to store it in a separate entity as that allows it to not be faulted when not needed.  Storing it in one entity can make some interactions with a fetchedResultsController easier.  For example if are fetching entity A but have a predicate that is based party on entity B, if entity B changes the fetchedResultsController will miss it.  </p>


问:
SQL Server query update child node based on parent records
I am trying to query data with the following structure in a SQL Server table
'tableA' with column 'node' (varchar) and 'destination' (bit). The data in the node column is based on parent/child relationship. Row child: 1001111001 has all these rows/nodes as parents (100111100, 10011110, 1001111, 100111, 10011, 1001, 100, 10, 1). I would like to accomplish the following in a store procedure on sql server

1- Retrieve all parents of a child node.

2- Update destination of child row if all parent destination are equal to 0

答:
```<code>SELECT ones.n + 10*tens.n + 100*hundreds.n + 1 AS Num,
    Left(@S, ones.n + 10*tens.n + 100*hundreds.n + 1) as ParentNode,
    t.Destination as ParentDestination
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
         (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
         (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
         tableA t
WHERE ones.n + 10*tens.n + 100*hundreds.n BETWEEN 0 AND Len(@s)-2 AND t.Node = Left(@S, ones.n + 10*tens.n + 100*hundreds.n + 1)
ORDER BY ones.n + 10*tens.n + 100*hundreds.n
</code>```

as for update, you can now check if SUM of all parent destinations = 0

Body:
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1 AS Num,
    Left(@S, ones.n + 10*tens.n + 100*hundreds.n + 1) as ParentNode,
    t.Destination as ParentDestination
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
         (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
         (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
         tableA t
WHERE ones.n + 10*tens.n + 100*hundreds.n BETWEEN 0 AND Len(@s)-2 AND t.Node = Left(@S, ones.n + 10*tens.n + 100*hundreds.n + 1)
ORDER BY ones.n + 10*tens.n + 100*hundreds.n

as for update, you can now check if SUM of all parent destinations = 0


问:
Webgl strange float math
One gets strange results when modifying values of float variables inside a conditional statement when a uniform or texture coordinates are used in the condition. This happens inside a fragment shader on numerous mobile devices like iPhone 4S, iPhone 5, iPhone 5S, iPhone 6 (Safari, Chrome and Firefox), Samsung J3 (Android browser, Chrome) and quite possibly others.
It seems the value can be compared to another float, but when is divided one gets zero if the divisor is more than half bigger than the value.
Here is a simple test case. All values of R, G and B colors are expected to be the same 128 and the output should be thus grey, however on these mobile devices one gets R equal to zero and so the output is of sea color.
The jsfiddle is here

The html is:

```<code><html>
<head>
    <title>Hello</title>
</head>
<body>
    <script src="js/shadertest.js"></script>
</body>
</code>```

The js code is:

```<code>    function test(){
    var create3DContext = function(canvas, opt_attribs) {
      var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
      var context = null;
      for (var ii = 0; ii < names.length; ++ii) {
        try {
          context = canvas.getContext(names[ii], opt_attribs);
        } catch(e) {}
        if (context) {
          break;
        }
      }
      return context;
    }

    var compileShader = function(type, source) {
        var shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);

        if( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) {
            throw new Error(gl.getShaderInfoLog(shader));
        }

        return shader;
    };

    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    document.body.appendChild(canvas);

    var gl = create3DContext(canvas, {});

    // init buffers
    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]), gl.STATIC_DRAW);

    // The main IDWT Shader
    var webglProgram = gl.createProgram();
    gl.attachShader(webglProgram, compileShader(gl.VERTEX_SHADER, SHADER_VERTEX_IDENTITY));
    gl.attachShader(webglProgram, compileShader(gl.FRAGMENT_SHADER, SHADER_FRAGMENT));

    gl.linkProgram(webglProgram);

    if( !gl.getProgramParameter(webglProgram, gl.LINK_STATUS) ) {
        throw new Error(gl.getProgramInfoLog(webglProgram));
    }

    gl.useProgram(webglProgram);

    var vertexAttr = gl.getAttribLocation(webglProgram, 'vertex');
    gl.enableVertexAttribArray(vertexAttr);
    gl.vertexAttribPointer(vertexAttr, 2, gl.FLOAT, false, 0, 0);

    gl.uniform1i(gl.getUniformLocation(webglProgram, 'vertical'), 0);

    gl.viewport(0, 0, 1, 1);

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

    var pixels = new Uint8Array(4);
    var imgData = gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE, pixels);
    console.log('R = '+pixels[0]);
    console.log('G = '+pixels[1]);
    console.log('B = '+pixels[2]);
    console.log('A = '+pixels[3]);
}
var SHADER_FRAGMENT = [

        'precision mediump float;',

        'uniform int vertical;',

        'void main() {',
            'float valueLow  = 60.0;',
            'float valueHigh = 60.0;',
            'if ( vertical == 1)',
            '{',
                'valueLow = 60.0;',
            '}',
            'gl_FragColor.rgba = vec4((valueLow+10000.0)/20000.0, (valueHigh+10000.0)/20000.0, (60.0+10000.0)/20000.0, 1.0);',
        '}'
    ].join('\n'),
SHADER_VERTEX_IDENTITY = [
    'attribute vec2 vertex;',
    'varying vec2 texCoord;',

    'void main() {',
        'texCoord = vertex;',
        'gl_Position = vec4((vertex * 2.0 - 1.0) * vec2(1, -1), 0.0, 1.0);',
    '}'
].join('\n');
test();
</code>```

EDIT
I found one workaround which is to move the math with the variable in question inside the same conditional statement like in this jsfiddle, but I hope there is a more elegant way.

答:
I don't know how to work around low percision issues except to change your math not to run into the but you can conditionally ask for high percision

```<code>#if GL_FRAGMENT_PRECISION_HIGH
  precision highp float;
#else
  precision mediump float;
#else
</code>```

Most modern phones support highp at the expense of speed but some older ones like an iPhone3GS don't.

You can also set the precision of specific variables

```<code>#if GL_FRAGMENT_PRECISION_HIGH
  highp vec3 someVar;
#else
  mediump vec3 someVar;
#else
</code>```

On desktop you just always get highp regardless of what you ask for which is fine as far as the spec in concerned.

Title: Webgl strange float math

Body:
One gets strange results when modifying values of float variables inside a conditional statement when a uniform or texture coordinates are used in the condition. This happens inside a fragment shader on numerous mobile devices like iPhone 4S, iPhone 5, iPhone 5S, iPhone 6 (Safari, Chrome and Firefox), Samsung J3 (Android browser, Chrome) and quite possibly others.
It seems the value can be compared to another float, but when is divided one gets zero if the divisor is more than half bigger than the value.
Here is a simple test case. All values of R, G and B colors are expected to be the same 128 and the output should be thus grey, however on these mobile devices one gets R equal to zero and so the output is of sea color.
The jsfiddle is here

The html is:

    <title>Hello</title>

The js code is:

    function test(){
    var create3DContext = function(canvas, opt_attribs) {
      var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
      var context = null;
      for (var ii = 0; ii < names.length; ++ii) {
        try {
          context = canvas.getContext(names[ii], opt_attribs);
        } catch(e) {}
        if (context) {
          break;
        }
      }
      return context;
    }

    var compileShader = function(type, source) {
        var shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);

        if( !gl.getShaderParameter(shader, gl.COMPILE_STATUS) ) {
            throw new Error(gl.getShaderInfoLog(shader));
        }

        return shader;
    };

    var canvas = document.createElement('canvas');
    canvas.width = 1;
    canvas.height = 1;
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    document.body.appendChild(canvas);

    var gl = create3DContext(canvas, {});

    // init buffers
    var buffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]), gl.STATIC_DRAW);

    // The main IDWT Shader
    var webglProgram = gl.createProgram();
    gl.attachShader(webglProgram, compileShader(gl.VERTEX_SHADER, SHADER_VERTEX_IDENTITY));
    gl.attachShader(webglProgram, compileShader(gl.FRAGMENT_SHADER, SHADER_FRAGMENT));

    gl.linkProgram(webglProgram);

    if( !gl.getProgramParameter(webglProgram, gl.LINK_STATUS) ) {
        throw new Error(gl.getProgramInfoLog(webglProgram));
    }

    gl.useProgram(webglProgram);

    var vertexAttr = gl.getAttribLocation(webglProgram, 'vertex');
    gl.enableVertexAttribArray(vertexAttr);
    gl.vertexAttribPointer(vertexAttr, 2, gl.FLOAT, false, 0, 0);

    gl.uniform1i(gl.getUniformLocation(webglProgram, 'vertical'), 0);

    gl.viewport(0, 0, 1, 1);

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

    var pixels = new Uint8Array(4);
    var imgData = gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE, pixels);
    console.log('R = '+pixels[0]);
    console.log('G = '+pixels[1]);
    console.log('B = '+pixels[2]);
    console.log('A = '+pixels[3]);
}
var SHADER_FRAGMENT = [

        'precision mediump float;',

        'uniform int vertical;',

        'void main() {',
            'float valueLow  = 60.0;',
            'float valueHigh = 60.0;',
            'if ( vertical == 1)',
            '{',
                'valueLow = 60.0;',
            '}',
            'gl_FragColor.rgba = vec4((valueLow+10000.0)/20000.0, (valueHigh+10000.0)/20000.0, (60.0+10000.0)/20000.0, 1.0);',
        '}'
    ].join('\n'),
SHADER_VERTEX_IDENTITY = [
    'attribute vec2 vertex;',
    'varying vec2 texCoord;',

    'void main() {',
        'texCoord = vertex;',
        'gl_Position = vec4((vertex * 2.0 - 1.0) * vec2(1, -1), 0.0, 1.0);',
    '}'
].join('\n');
test();

EDIT
I found one workaround which is to move the math with the variable in question inside the same conditional statement like in this jsfiddle, but I hope there is a more elegant way.

Body:
I don't know how to work around low percision issues except to change your math not to run into the but you can conditionally ask for high percision

#if GL_FRAGMENT_PRECISION_HIGH
  precision highp float;
#else
  precision mediump float;
#else

Most modern phones support highp at the expense of speed but some older ones like an iPhone3GS don't.

You can also set the precision of specific variables

#if GL_FRAGMENT_PRECISION_HIGH
  highp vec3 someVar;
#else
  mediump vec3 someVar;
#else

On desktop you just always get highp regardless of what you ask for which is fine as far as the spec in concerned.


问:
How to set up validation in PowerShell that will check status of service and then activate rest of script
I want to set-up procedure for cleaning tomcat cache folder (when I need it) and I have read about this cmdlets:

```<code>Stop-Service Tomcat8
Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\*"
-Confirm:$false
Start-Service Tomcat8
</code>```

I don't have control over this so I am interested if there is some kind of validation so I can write in console like this:

```<code>Stop-Service Tomcat8
</code>```

Check if service is stopped.

Write in console "Service is stopped"

```<code>Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\`*"
-Confirm:$false
</code>```

Check if job has been done?

Start service

```<code>Start-Service Tomcat8
</code>```

答:
I believe Stop-Service will wait for a service to stop by default, but I think it is still possible for it to fail to stop the service and timeout. To add a check you could do this:

```<code>$TomcatStartup = (Get-Service Tomcat8).StartType

Set-Service Tomcat8 -StartupType Disabled
Stop-Service Tomcat8

If ((Get-Service Tomcat8).Status -eq 'Stopped'){
    Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\*" -Confirm:$false
    Set-Service Tomcat8 -StartupType $TomcatStartup
    Start-Service Tomcat8
} Else {
    Throw 'Tomcat was not stopped'
}
</code>```

I added setting the service to disabled temporarily so that it doesn't get automatically restarted when you didn't want it to.

Body:
I want to set-up procedure for cleaning tomcat cache folder (when I need it) and I have read about this cmdlets:

Stop-Service Tomcat8
Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\*"
-Confirm:$false
Start-Service Tomcat8

I don't have control over this so I am interested if there is some kind of validation so I can write in console like this:

Stop-Service Tomcat8

Check if service is stopped.

Write in console "Service is stopped"

Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\`*"
-Confirm:$false

Check if job has been done?

Start service

Start-Service Tomcat8

Body:
I believe Stop-Service will wait for a service to stop by default, but I think it is still possible for it to fail to stop the service and timeout. To add a check you could do this:

$TomcatStartup = (Get-Service Tomcat8).StartType

Set-Service Tomcat8 -StartupType Disabled
Stop-Service Tomcat8

If ((Get-Service Tomcat8).Status -eq 'Stopped'){
    Remove-Item "C:\Program Files\Apache Software Foundation\Tomcat 8.0\work\Catalina\localhost\*" -Confirm:$false
    Set-Service Tomcat8 -StartupType $TomcatStartup
    Start-Service Tomcat8
} Else {
    Throw 'Tomcat was not stopped'
}

I added setting the service to disabled temporarily so that it doesn't get automatically restarted when you didn't want it to.