问:
.NET IpcChannel doesn't reliably clean up properly?
For some reason, after using an IpcChannel and shutting it down, sometimes the namedpipe stays open, with a thread waiting on it.  I cannot make this happen on demand in a debug environment, but it happens 5 to 10 times per day in our production environment.  The bad effect this is having is that it is stopping me from unloading the appdomain as there is a thread waiting infinitely on the named pipe (in a native method)...no frame on the callstack is in my code - it's an internal .net thread.  If I fire up process explorer and find the named pipe handle that was left open and forcefully close it then it all becomes happy again, the appdomain unloads fine.  It's possible I'm doing something wrong as I haven't worked with IpcChannels a whole lot....my server-side code is here: http://pastebin.com/f6e2583b9 if anyone wants to take a peek....this is running on fully patched Server2003/.NET 2.0.

As an ugly-ass workaround, I'm thinking I'll track every channel I create and then periodically check to make sure they shut down properly, and then on appdomain unload I'll forcefully close any pipes which are left hanging....can anyone point me in the right direction as to how I could do this?  I know the name of the pipe....but I'm not sure how to check if it's still open, or how to close any existing handles...

答:
Yes, I've seen this before.

A similar thing can occur with IPC when the client still has the IPC channel open: The server will not be able to close and open it again because it's already in use by the client.

To get around these problems, the recommended way is to place all IPC server channel creation in a child AppDomain.

Then when you wish to shut it down, you merely perform the usual 'nice' shutdown procedures of Close() followed by an AppDomain Unload.

This will nuke any left overs.

It will remove any IPC related stuff as well as kick the client in the head for hogging the IPC channel ;)


来源: stackexchange

问:
Mechanisms to enumerate resources of Azure
I have a requirement where I need to periodically enumerate the resources of azure namely - VMs, Images, Instance types, Regions, Resource groups, storage, networks and so on.

The current approach I am thinking is to periodically make the Java SDK calls to list these resources and enumerate them into my local store. This can be done on a scheduled basis (say every 10 mins).

However, I was wondering if Azure provides any other mechanism to do this. For example, Is there a way to subscribe changes for say VMs and we get notified whenever there's a change in VM state (power off to power on, etc)?

答:
Just as @4c74356b41 said ,there is no any mechanism for monitoring changes in VMs.

You could use Time Trigger in Azure Function or Web Job to monitor your resources situation and send a reminder as a message.

ContentLicense: CC BY-SA 3.0


问:
Set tabView in the Application
I have Set the tabview in My Application But all tab shows very near to eachother. .  i want to Set the Little Space between then. . .
How it is Possible ?
Thanks in Advance.</p>

答:
You can add space in the tabview item by giving a margin inside that.
Use the code below.

```<code>for(int i=0; i < mTabLayout.getTabCount(); i++) {
     View tab = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i);
     ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams)
     tab.getLayoutParams(); > p.setMargins(0, 0, 50, 0); > tab.requestLayout();
}
</code>```

Title: Set tabView in the Application

Body:
You can add space in the tabview item by giving a margin inside that.
Use the code below.

for(int i=0; i < mTabLayout.getTabCount(); i++) {
     View tab = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(i);
     ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams)
     tab.getLayoutParams(); > p.setMargins(0, 0, 50, 0); > tab.requestLayout();
}


问:
ionic - Adding a button inside a input field
I'm trying to add a button inside an <ion-input> but wherever I add it inside the <ion-list> the button does not show on the screen.

What I'm trying to do is to show a button "Forgot" on top of the password field aligned to the right. Refer screen:

This is my HTML,

```<code><ion-content>
  <ion-list class="au-form" inset padding>
        <ion-item>
            <ion-input type="text" placeholder="Username"></ion-input>
        </ion-item>
        <ion-item>
            <ion-input type="password" placeholder="Password"></ion-input>
            <button clear>Forgot</button>
        </ion-item>
   </ion-list>
</ion-content>
</code>```

How do I achieve this layout in Ionic 2?

答:
I have something similar, a disabled input with an enabled icon button next to the input.
Here is my HTML:

```<code><ion-item>
    <ion-label floating>My Label</ion-label>
    <ion-input [disabled]="true" type="text" [(ngModel)]="MyModel"></ion-input>
    <button ion-button large clear (click)="doSomething()" item-end>
      <ion-icon name="search"></ion-icon>
    </button>
  </ion-item>
</code>```

So in you case, this will work:

```<code><ion-item>
    <ion-label>Your Label</ion-label>
    <ion-input type="text" [(ngModel)]="yourModel"></ion-input>
    <button ion-button large (click)="doSomething()" item-end></button>
  </ion-item>
</code>```

item-left and item-right directional properties are deprecated according to https://ionicframework.com/docs/theming/rtl-support/

Body:
I'm trying to add a button inside an <ion-input> but wherever I add it inside the <ion-list> the button does not show on the screen.

What I'm trying to do is to show a button "Forgot" on top of the password field aligned to the right. Refer screen:

This is my HTML,

<ion-content>
  <ion-list class="au-form" inset padding>
        <ion-item>
            <ion-input type="text" placeholder="Username"></ion-input>
        </ion-item>
        <ion-item>
            <ion-input type="password" placeholder="Password"></ion-input>
            <button clear>Forgot</button>
        </ion-item>
   </ion-list>
</ion-content>

How do I achieve this layout in Ionic 2?

Body:
I have something similar, a disabled input with an enabled icon button next to the input.
Here is my HTML:

<ion-item>
    <ion-label floating>My Label</ion-label>
    <ion-input [disabled]="true" type="text" [(ngModel)]="MyModel"></ion-input>
    <button ion-button large clear (click)="doSomething()" item-end>
      <ion-icon name="search"></ion-icon>
    </button>
  </ion-item>

So in you case, this will work:

<ion-item>
    <ion-label>Your Label</ion-label>
    <ion-input type="text" [(ngModel)]="yourModel"></ion-input>
    <button ion-button large (click)="doSomething()" item-end></button>
  </ion-item>

item-left and item-right directional properties are deprecated according to https://ionicframework.com/docs/theming/rtl-support/


问:
Traefik cluster mode on Kubernetes
The Traefik documentation is unclear when running Traefik on Kubernetes.

I want multiple instances of traefik running in my cluster, sharing one configuration and the acme file.

The configuration is initially provided with a ConfigMap.
Now the documentation states that one needs a separate KV-store to achieve traefik clustering.

But is that not covered by Traefik running Kubernetes mode?

答:
Briefly what  you have to do is the following:

deploy a key value store (either inside or outside kubernetes) by choosing one of the supported (consul, etcd, zookeeper, boltdb)

Run the traefik storeconfig command once by passing a configuration file in order to copy your configuration into the kv store

Run traefik with the proper flags to load configuration from the kv store.

Everything Is explained here https://docs.traefik.io/user-guide/kv-config/

This is not a kubernetes specific guide, but it is quite simple to adapt it.

Title: Traefik cluster mode on Kubernetes


问:
Promo Code Validation
I need to validate a Promo Code for one of my html Booking form field. If the entered promo code is correct, users can submit the Booking details. Only one unique promo code. Something like "15OFFNOW" How should I do it? Please help.

Thanks.

答:
i try your code

```<code><form method="post">
    <input class="form-control form-control-light bdr-2 rd-0" required
           data-label="Promo Code"
           data-msg="Please enter a valid promo code."
           type="text" name="promo-code"
           placeholder="Promo Code"
           pattern="15OFFNOW" required>
    <input type="submit" value="submit"/>
</form>
</code>```

validation is work .  show this message .

Title: Promo Code Validation

Body:
i try your code

<form method="post">
    <input class="form-control form-control-light bdr-2 rd-0" required
           data-label="Promo Code"
           data-msg="Please enter a valid promo code."
           type="text" name="promo-code"
           placeholder="Promo Code"
           pattern="15OFFNOW" required>
    <input type="submit" value="submit"/>
</form>

validation is work .  show this message .


问:
Is there any way to read from specific EventHub Partition using EventProcessorHost
I have a ServiceFabric Stateless service where I want to read from specific EventHub Partition using EventProcessorHost.
I would like to read from two event hub partition mapping each to one EventProcessorHost

First EventHub Partition => First EventProcessorHost

Second EventHub Partition => Second EventProcessorHost

```<code>  var eventHubClient = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, eventHubName);

            // Get the default Consumer Group
            eventProcessorHost = new EventProcessorHost(Guid.NewGuid().ToString(),
                                                        eventHubClient.Path.ToLower(),
                                                        consumerGroupName.ToLower(),
                                                        serviceBusConnectionString,
                                                        storageAccountConnectionString)
            {
                PartitionManagerOptions = new PartitionManagerOptions
                {
                    AcquireInterval = TimeSpan.FromSeconds(10), // Default is 10 seconds
                    RenewInterval = TimeSpan.FromSeconds(10), // Default is 10 seconds
                    LeaseInterval = TimeSpan.FromSeconds(30) // Default value is 30 seconds
                }
            };

            ServiceEventSource.Current.Message(RegisteringEventProcessor);
            var eventProcessorOptions = new EventProcessorOptions
            {
                InvokeProcessorAfterReceiveTimeout = true,
                MaxBatchSize = 100,
                PrefetchCount = 100,
                ReceiveTimeOut = TimeSpan.FromSeconds(30),
            };
            eventProcessorOptions.ExceptionReceived += EventProcessorOptions_ExceptionReceived;
            await eventProcessorHost.RegisterEventProcessorFactoryAsync(new EventProcessorFactory<EventProcessor>(deviceActorServiceUri),
                                                                        eventProcessorOptions);
</code>```

答:
There is a github repo that has an implementation you can build from here.
It hasn't been maintained for quite some time, but it seems to solve your problem.

4- Single: maps a single event hub partition to a single service fabric partition.
   Event Hub communication listener will expect a supplied valid event hub partition id

Body:
I have a ServiceFabric Stateless service where I want to read from specific EventHub Partition using EventProcessorHost.
I would like to read from two event hub partition mapping each to one EventProcessorHost

First EventHub Partition => First EventProcessorHost

Second EventHub Partition => Second EventProcessorHost

  var eventHubClient = EventHubClient.CreateFromConnectionString(serviceBusConnectionString, eventHubName);

            // Get the default Consumer Group
            eventProcessorHost = new EventProcessorHost(Guid.NewGuid().ToString(),
                                                        eventHubClient.Path.ToLower(),
                                                        consumerGroupName.ToLower(),
                                                        serviceBusConnectionString,
                                                        storageAccountConnectionString)
            {
                PartitionManagerOptions = new PartitionManagerOptions
                {
                    AcquireInterval = TimeSpan.FromSeconds(10), // Default is 10 seconds
                    RenewInterval = TimeSpan.FromSeconds(10), // Default is 10 seconds
                    LeaseInterval = TimeSpan.FromSeconds(30) // Default value is 30 seconds
                }
            };

            ServiceEventSource.Current.Message(RegisteringEventProcessor);
            var eventProcessorOptions = new EventProcessorOptions
            {
                InvokeProcessorAfterReceiveTimeout = true,
                MaxBatchSize = 100,
                PrefetchCount = 100,
                ReceiveTimeOut = TimeSpan.FromSeconds(30),
            };
            eventProcessorOptions.ExceptionReceived += EventProcessorOptions_ExceptionReceived;
            await eventProcessorHost.RegisterEventProcessorFactoryAsync(new EventProcessorFactory<EventProcessor>(deviceActorServiceUri),
                                                                        eventProcessorOptions);


问:
A table with a composite Primary key, one of the fields with autoincrement
Im using a table constraint to create a composite primary key,  I would like the id field to autoincrement, is this possible? or what are the alternatives?

```<code>   CREATE TABLE IF NOT EXISTS atable(
        id          INTEGER NOT NULL, --I want to autoincrement this one
        name     TEXT NOT NULL,
        anotherCol  TEXT,

    PRIMARY KEY(id, name));
</code>```

答:
Here's the link to the SQLite FAQ page where your question of how to autoincrement an integer primary key is #1.  http://www.sqlite.org/faq.html#q1

Here's your SQL reworked a little:

```<code> CREATE TABLE IF NOT EXISTS atable(
    id          INTEGER PRIMARY KEY, -- use NULL for this column on INSERT to autoinc
    name        TEXT NOT NULL,
    anotherCol  TEXT);
</code>```

then create a unique index on NAME as suggested by duffymo and Kaleb.

ContentLicense: CC BY-SA 2.5

Body:
Im using a table constraint to create a composite primary key,  I would like the id field to autoincrement, is this possible? or what are the alternatives?

   CREATE TABLE IF NOT EXISTS atable(
        id          INTEGER NOT NULL, --I want to autoincrement this one
        name     TEXT NOT NULL,
        anotherCol  TEXT,

    PRIMARY KEY(id, name));

Body:
Here's the link to the SQLite FAQ page where your question of how to autoincrement an integer primary key is #1.  http://www.sqlite.org/faq.html#q1

Here's your SQL reworked a little:

 CREATE TABLE IF NOT EXISTS atable(
    id          INTEGER PRIMARY KEY, -- use NULL for this column on INSERT to autoinc
    name        TEXT NOT NULL,
    anotherCol  TEXT);

then create a unique index on NAME as suggested by duffymo and Kaleb.


问:
Problem getting the AssemblyVersion into a web page using Razor /MVC3
I'm using the following code in a footer in my _Layout.cshtml file to put the AssemblyInfo version data into the footer of every page in my MVC3 site.  However:

```<code>@System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
</code>```

Just prints in the footer:

```<code>Revision 0.0.0.0
</code>```

When I modified the view to display all of the assembly info for the "Executing Assembly" using the following

```<code>@System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()
</code>```

Which prints the following:

```<code>Revision App_Web__layout.cshtml.639c3968.hlogy75x, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
</code>```

This shows that the "Executing Assembly" isn't my main app, it's the view itself.

How do I get the assembly information for the ACTUAL app, not just the individual views??

答:
GO to Home Controller and just copy this code :

Rename ActionResult to String

```<code>public string Index()

   return typeof(Controller).Assembly.GetName().Version.ToString() ;

run view
</code>```

Body:
I'm using the following code in a footer in my _Layout.cshtml file to put the AssemblyInfo version data into the footer of every page in my MVC3 site.  However:

@System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()

Just prints in the footer:

Revision 0.0.0.0

When I modified the view to display all of the assembly info for the "Executing Assembly" using the following

@System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()

Which prints the following:

Revision App_Web__layout.cshtml.639c3968.hlogy75x, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

This shows that the "Executing Assembly" isn't my main app, it's the view itself.

How do I get the assembly information for the ACTUAL app, not just the individual views??

Body:
GO to Home Controller and just copy this code :

Rename ActionResult to String

public string Index()

   return typeof(Controller).Assembly.GetName().Version.ToString() ;

run view


问:
How the example from Java Concurrency in practice is thread safe
Below is an example from book Java Concurrency in Practice(Listing 2.8) of a thread safe class.

My question is how the below class is thread safe?

For example if two threads Thread A and Thread B enter into service method of CachedFactorizer. Thread B followed by Thread A. Now if Thread A is executing first synchronized block and Thread B obviously waits for the intrinsic lock of the object. And if Thread B makes it to the first synchronized block before the Thread A makes it to the second synchronized block, it will be viewing a stale value and potentially this condition is known as Race Condition.

So, is my understanding right here? Or am I lacking some basic understanding of concurrency?

```<code>@ThreadSafe
public class CachedFactorizer implements Servlet {

    @GuardedBy("this") private BigInteger lastNumber;

    @GuardedBy("this") private BigInteger[] lastFactors;

    @GuardedBy("this") private long hits;

    @GuardedBy("this") private long cacheHits;

    public synchronized long getHits() { return hits; }

    public synchronized double getCacheHitRatio() {

        return (double) cacheHits / (double) hits;

    }

    public void service(ServletRequest req, ServletResponse resp) {

        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factor(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(resp, factors);
    }
}
</code>```

答:
This class is thread safe because all shared variables are accessed in sychronized blocks, and in such situation there is no data race:

"When a program contains two conflicting accesses (§17.4.1) that are not ordered by a happens-before relationship, it is said to contain a data race.https://docs.oracle.com/javase/specs/jls/se9/html/jls-17.html"

The question is if this behaviour is valid from business point of view, eg. if two threads meet after first synchronized blok, they can execute second block in different order.

ContentLicense: CC BY-SA 4.0

Body:
Below is an example from book Java Concurrency in Practice(Listing 2.8) of a thread safe class.

My question is how the below class is thread safe?

For example if two threads Thread A and Thread B enter into service method of CachedFactorizer. Thread B followed by Thread A. Now if Thread A is executing first synchronized block and Thread B obviously waits for the intrinsic lock of the object. And if Thread B makes it to the first synchronized block before the Thread A makes it to the second synchronized block, it will be viewing a stale value and potentially this condition is known as Race Condition.

So, is my understanding right here? Or am I lacking some basic understanding of concurrency?

@ThreadSafe
public class CachedFactorizer implements Servlet {

    @GuardedBy("this") private BigInteger lastNumber;

    @GuardedBy("this") private BigInteger[] lastFactors;

    @GuardedBy("this") private long hits;

    @GuardedBy("this") private long cacheHits;

    public synchronized long getHits() { return hits; }

    public synchronized double getCacheHitRatio() {

        return (double) cacheHits / (double) hits;

    }

    public void service(ServletRequest req, ServletResponse resp) {

        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = null;
        synchronized (this) {
            ++hits;
            if (i.equals(lastNumber)) {
                ++cacheHits;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factor(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }
        encodeIntoResponse(resp, factors);
    }
}


问:
Reverse Polish Notation Challenge - Boolean.getBoolean() vs. Boolean.parseBoolean()
I am trying to solve this question:
https://uchicago.kattis.com/problems/uchicago.rpn

I've posted the Java code below for reference.

EDIT: I've removed the original code as it was too long and not too helpful. I think this post can be useful for future readers, if it can serve as a practical example that is able to underscore the difference between getBoolean() and parseBoolean() functions in Java. Further clarification can be found here. The bug turned out to be related to getBoolean() vs. parseBoolean() as can be seen from the code below, in which val1 and val2 were of the boolean types, as opposed to string names.

```<code>boolean bool1 = Boolean.getBoolean(val1);// Should be using parseBoolean(val1)
boolean bool2 = Boolean.getBoolean(val2);// Should be using parseBoolean(val2)

String result = booleanHelper(bool1, bool2, next);
</code>```

答:
After further testing I think the only error you have is parsing the boolean values "true" and "false" with Boolean.getBoolean instead of Boolean.parseBoolean. that results in false answers with inputs like true true and (answer: false).

Boolean.getBoolean will read the system property with given name and try to parse that as boolean, not actually your strings "true" and "false".

Body:
I am trying to solve this question:
https://uchicago.kattis.com/problems/uchicago.rpn

I've posted the Java code below for reference.

EDIT: I've removed the original code as it was too long and not too helpful. I think this post can be useful for future readers, if it can serve as a practical example that is able to underscore the difference between getBoolean() and parseBoolean() functions in Java. Further clarification can be found here. The bug turned out to be related to getBoolean() vs. parseBoolean() as can be seen from the code below, in which val1 and val2 were of the boolean types, as opposed to string names.

boolean bool1 = Boolean.getBoolean(val1);// Should be using parseBoolean(val1)
boolean bool2 = Boolean.getBoolean(val2);// Should be using parseBoolean(val2)

String result = booleanHelper(bool1, bool2, next);


问:
Using boost asio to get web page
I'm trying to build a program that would take in a stock ticker, run a google search for it, and output data (current price, high, low, percent change, etc.). I am trying to use boost asio and it is not returning any data from the server.

```<code>#include "stdafx.h"
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

std::string getStockPage(std::string ticker) {
    boost::asio::ip::tcp::iostream stream;

    stream.connect("www.google.com", "http");
    std::cout << "connected\n";
    stream << "GET /search?q=" << ticker << " HTTP/1.1\r\n";
    stream << "Host: www.google.com\r\n";
    stream << "Cache-Control: no-cache\r\n";
    //stream << "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
    stream << "Connection: close\r\n\r\n";
    std::cout << "sent\n";

    std::ostringstream os;
    //os << stream.rdbuf();
    char buffer[100];
    os << stream.readsome(buffer, 100);
    return std::string(buffer, 100);
}

int main() {
    std::cout << getStockPage("$tsla");
    std::cout << "done\n";
    std::string temp;
    std::getline(std::cin, temp);
    return 0;

}
</code>```

I tried to read just the first 100 characters to see if it was having issues outputting the response, but it only outputs null characters. I want it to output the entirety of the google page "www.google.com/search?q=$tsla"

Any help would be greatly appreciated!

答:
std::istream::readsome is allowed to just always return 0 bytes. Then, it appears as if you received NUL bytes, because you did

```<code>return std::string(buffer, 100);
</code>```

instead of

```<code>return std::string(buffer, stream.gcount());
</code>```

Really, just use the other approach

```<code>std::ostringstream os;
os << stream.rdbuf();
return os.str();
</code>```

This works for me when testing. Note you could add a flush:

```<code>stream << "Connection: close\r\n\r\n" << std::flush;
</code>```

The resulting program

```<code>#include <boost/asio.hpp>
#include <iostream>
#include <string>

std::string getStockPage(std::string const& ticker) {
    boost::asio::ip::tcp::iostream stream;

    stream.connect("www.google.com", "http");
    stream    << "GET /search?q=" << ticker << " HTTP/1.1\r\n";
    stream    << "Host: www.google.com\r\n";
    stream    << "Cache-Control: no-cache\r\n";
    // stream << "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
    stream    << "Connection: close\r\n\r\n" << std::flush;

    std::ostringstream os;
    os << stream.rdbuf();
    return os.str();
}

int main() {
    std::cout << getStockPage("$tsla");
}
</code>```

Is printing

```<code>HTTP/1.1 302 Found
Location: http://www.google.nl/search?q=%24tsla&gws_rd=cr&dcr=0&ei=3EMqWrKxCILUwAKv9LqICg
Cache-Control: private
Content-Type: text/html; charset=UTF-8
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Date: Fri, 08 Dec 2017 07:48:44 GMT
Server: gws
Content-Length: 288
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: NID=118=MsVZZpoZFEz4mQDqDuuWFRViB8v8yEQju7FPdOw8Rr7ViQ1cJtF6ZeN9u-dSRhGMT4x8F8yDilk9FqsoTkO8IsoQX-YvHXRcCoHcOLk0p4VOTn8AZoldKeh84Ryl0bM0; expires=Sat, 09-Jun-2018 07:48:44 GMT; path=/; domain=.google.com; HttpOnly
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.nl/search?q=%24tsla&gws_rd=cr&dcr=0&ei=3EMqWrKxCILUwAKv9LqICg">here</A>.
</BODY></HTML>
</code>```

Title: Using boost asio to get web page

Body:
I'm trying to build a program that would take in a stock ticker, run a google search for it, and output data (current price, high, low, percent change, etc.). I am trying to use boost asio and it is not returning any data from the server.

#include "stdafx.h"
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>

std::string getStockPage(std::string ticker) {
    boost::asio::ip::tcp::iostream stream;

    stream.connect("www.google.com", "http");
    std::cout << "connected\n";
    stream << "GET /search?q=" << ticker << " HTTP/1.1\r\n";
    stream << "Host: www.google.com\r\n";
    stream << "Cache-Control: no-cache\r\n";
    //stream << "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
    stream << "Connection: close\r\n\r\n";
    std::cout << "sent\n";

    std::ostringstream os;
    //os << stream.rdbuf();
    char buffer[100];
    os << stream.readsome(buffer, 100);
    return std::string(buffer, 100);
}

int main() {
    std::cout << getStockPage("$tsla");
    std::cout << "done\n";
    std::string temp;
    std::getline(std::cin, temp);
    return 0;

}

I tried to read just the first 100 characters to see if it was having issues outputting the response, but it only outputs null characters. I want it to output the entirety of the google page "www.google.com/search?q=$tsla"

Any help would be greatly appreciated!

Body:
std::istream::readsome is allowed to just always return 0 bytes. Then, it appears as if you received NUL bytes, because you did

return std::string(buffer, 100);

instead of

return std::string(buffer, stream.gcount());

Really, just use the other approach

std::ostringstream os;
os << stream.rdbuf();
return os.str();

This works for me when testing. Note you could add a flush:

stream << "Connection: close\r\n\r\n" << std::flush;

The resulting program

#include <boost/asio.hpp>
#include <iostream>
#include <string>

std::string getStockPage(std::string const& ticker) {
    boost::asio::ip::tcp::iostream stream;

    stream.connect("www.google.com", "http");
    stream    << "GET /search?q=" << ticker << " HTTP/1.1\r\n";
    stream    << "Host: www.google.com\r\n";
    stream    << "Cache-Control: no-cache\r\n";
    // stream << "Content-Type: application/x-www-form-urlencoded\r\n\r\n";
    stream    << "Connection: close\r\n\r\n" << std::flush;

    std::ostringstream os;
    os << stream.rdbuf();
    return os.str();
}

int main() {
    std::cout << getStockPage("$tsla");
}

Is printing

HTTP/1.1 302 Found
Location: http://www.google.nl/search?q=%24tsla&gws_rd=cr&dcr=0&ei=3EMqWrKxCILUwAKv9LqICg
Cache-Control: private
Content-Type: text/html; charset=UTF-8
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Date: Fri, 08 Dec 2017 07:48:44 GMT
Server: gws
Content-Length: 288
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: NID=118=MsVZZpoZFEz4mQDqDuuWFRViB8v8yEQju7FPdOw8Rr7ViQ1cJtF6ZeN9u-dSRhGMT4x8F8yDilk9FqsoTkO8IsoQX-YvHXRcCoHcOLk0p4VOTn8AZoldKeh84Ryl0bM0; expires=Sat, 09-Jun-2018 07:48:44 GMT; path=/; domain=.google.com; HttpOnly
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.nl/search?q=%24tsla&amp;gws_rd=cr&amp;dcr=0&amp;ei=3EMqWrKxCILUwAKv9LqICg">here</A>.
</BODY></HTML>


问:
XML PATH output one by one using SQL Server
I'm trying to group column values by a specific column using FOR XML PATH('') in SQL Server.

For example when I pass the ModuleID value 1 then output RoleName : Admin Administrator Super Admin  which is present is same line.

```<code>ALTER PROCEDURE [dbo].[MEDEIL_SiteRoleModules_SelectOne]
    @ModuleID int
AS
    SELECT
        t1.ModuleID,
        RoleName = (SELECT s1.RoleName AS [data()]
                    FROM SiteRoleModules t2
                    INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                    WHERE t2.ModuleID = t1.ModuleID
                    GROUP BY s1.RoleName
                    FOR XML PATH(''))
    FROM
        SiteRoleModules t1
    WHERE
        ModuleId = @ModuleID
    GROUP BY
        ModuleID
</code>```

I need to display one by one

答:
You can just try to use CHAR(10) to break lines;

```<code>SELECT
    t1.ModuleID,
    RoleName = (SELECT CHAR(10) + s1.RoleName
                FROM SiteRoleModules t2
                INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                WHERE t2.ModuleID = t1.ModuleID
                GROUP BY s1.RoleName
                FOR XML PATH(''))
FROM
    SiteRoleModules t1
WHERE
    ModuleId = @ModuleID
GROUP BY
    ModuleID
</code>```

Body:
I'm trying to group column values by a specific column using FOR XML PATH('') in SQL Server.

For example when I pass the ModuleID value 1 then output RoleName : Admin Administrator Super Admin  which is present is same line.

ALTER PROCEDURE [dbo].[MEDEIL_SiteRoleModules_SelectOne]
    @ModuleID int
AS
    SELECT
        t1.ModuleID,
        RoleName = (SELECT s1.RoleName AS [data()]
                    FROM SiteRoleModules t2
                    INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                    WHERE t2.ModuleID = t1.ModuleID
                    GROUP BY s1.RoleName
                    FOR XML PATH(''))
    FROM
        SiteRoleModules t1
    WHERE
        ModuleId = @ModuleID
    GROUP BY
        ModuleID

I need to display one by one

Body:
You can just try to use CHAR(10) to break lines;

SELECT
    t1.ModuleID,
    RoleName = (SELECT CHAR(10) + s1.RoleName
                FROM SiteRoleModules t2
                INNER JOIN SiteRoles s1 ON t2.RoleID = s1.RoleID
                WHERE t2.ModuleID = t1.ModuleID
                GROUP BY s1.RoleName
                FOR XML PATH(''))
FROM
    SiteRoleModules t1
WHERE
    ModuleId = @ModuleID
GROUP BY
    ModuleID


问:
Laravel array validation via ajax : showing error message throws error
Trying to validate arrays in laravel via FormRequest validation

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class VendorStoreRoom extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'roomtype_id' => 'required',
            'price' => 'required|digits_between:1,8',
            'amenities' => 'required',

            //'max_children' => 'required',
            'max_adult' => 'required',
            //'capacity' => 'required',
            'floor.*' => 'required',
            'room_count' => 'min:1|max:50',
            'room_number.*' => 'required',
            //'room_number' => 'required|max:5',
            'image' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'roomtype_id.required'      => 'Please select a room type',

            'price.required'            => 'Price cannot be empty',
            'price.digits_between'      => 'Price cannot exceed 8 digits',

            'amenities.required'        => 'Atleast select one amenities',

            //'max_children.required'     => 'Vendor name cannot be empty',

            'max_adult.required'     => 'Maximum adult can not be empty',

            //'capacity.required'     => 'Vendor name cannot be empty',

            'floor.*.required'     => 'Please select a floor',

            'room_count.min'     => 'Room count cannot be empty',
            'room_count.max'     => 'Room count cannot exceed 50',

            'room_number.*.required'     => 'Room number cannot be empty',
            //'room_number.max'     => 'Room number cannot exceed 5 characters',

            'image.required'     => 'Atleast select one image',
            /*'image.*.mimes'     => 'Image Must be JPEG, JPG or PNG',
            'image.*.min'     => 'Image size must be more than 10 kb',
            'image.*.max'     => 'Image size cannot exceed 300 mb', */

        ];
    }
}
</code>```

This is the response i have got:

```<code>{"message":"The given data was invalid.","errors":{"roomtype_id":["Please select a room type"],"price":["Price cannot be empty"],"amenities":["Atleast select one amenities"],"image":["Atleast select one image"],"floor.0":["Please select a floor"],"room_number.0":["Room number cannot be empty"]}}
</code>```

I am catching these errors in jquery and do like below:

This works fine: $("#amenities_error").text(data.responseJSON.errors.amenities);

But not this: $("#floor_error").text(data.responseJSON.errors.floor.0);
How can i achieve this?

is there anything i can do like data.responseJSON.errors."floor.0" or data.responseJSON.errors.{floor.0}

答:
floor.0 is the string that is key for this error. However, javascript sees a . as a property separator. Because of this, javascript searches for an object floor with a property 0.

To fix this, you will have to use the array syntax for this key.

```<code>$("#floor_error").text(data.responseJSON.errors["floor.0"]);
</code>```

Body:
Trying to validate arrays in laravel via FormRequest validation

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class VendorStoreRoom extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'roomtype_id' => 'required',
            'price' => 'required|digits_between:1,8',
            'amenities' => 'required',

            //'max_children' => 'required',
            'max_adult' => 'required',
            //'capacity' => 'required',
            'floor.*' => 'required',
            'room_count' => 'min:1|max:50',
            'room_number.*' => 'required',
            //'room_number' => 'required|max:5',
            'image' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'roomtype_id.required'      => 'Please select a room type',

            'price.required'            => 'Price cannot be empty',
            'price.digits_between'      => 'Price cannot exceed 8 digits',

            'amenities.required'        => 'Atleast select one amenities',

            //'max_children.required'     => 'Vendor name cannot be empty',

            'max_adult.required'     => 'Maximum adult can not be empty',

            //'capacity.required'     => 'Vendor name cannot be empty',

            'floor.*.required'     => 'Please select a floor',

            'room_count.min'     => 'Room count cannot be empty',
            'room_count.max'     => 'Room count cannot exceed 50',

            'room_number.*.required'     => 'Room number cannot be empty',
            //'room_number.max'     => 'Room number cannot exceed 5 characters',

            'image.required'     => 'Atleast select one image',
            /*'image.*.mimes'     => 'Image Must be JPEG, JPG or PNG',
            'image.*.min'     => 'Image size must be more than 10 kb',
            'image.*.max'     => 'Image size cannot exceed 300 mb', */

        ];
    }
}

This is the response i have got:

{"message":"The given data was invalid.","errors":{"roomtype_id":["Please select a room type"],"price":["Price cannot be empty"],"amenities":["Atleast select one amenities"],"image":["Atleast select one image"],"floor.0":["Please select a floor"],"room_number.0":["Room number cannot be empty"]}}

I am catching these errors in jquery and do like below:

This works fine: $("#amenities_error").text(data.responseJSON.errors.amenities);

But not this: $("#floor_error").text(data.responseJSON.errors.floor.0);
How can i achieve this?

is there anything i can do like data.responseJSON.errors."floor.0" or data.responseJSON.errors.{floor.0}

Body:
floor.0 is the string that is key for this error. However, javascript sees a . as a property separator. Because of this, javascript searches for an object floor with a property 0.

To fix this, you will have to use the array syntax for this key.

$("#floor_error").text(data.responseJSON.errors["floor.0"]);


问:
kernel IRQ domain list
I'm developping a simple GPIO driver for a SoC running linux (newbie's level),
I am facing problem because IRQ numbers are different from those in datasheets.

I've learned that effective IRQ manager may create IRQ domains.
However  the

unsigned int irq_find_mapping(struct irq_domain *domain, irq_hw_number_t hwirq) needs a domain structure.
How can I list the available domain for my plateform.
Thank you.

here are some files' content

file: irq_domain_mapping

    name       mapped linear-max direct-max devtree_node
    gpio-dwapb 29     29         0          /soc/gpio@ff709000/gpio-controller
    ...
    99 0x00019 none

file : /proc/interrupts

    99 ... 25 edge gpiolib

however DTS file maps the interruption at 197 with dwapb manager

    interrupts = <0x00000000 0x000000a5 0x00000004>

答:
There are many things to consider:

/proc/interrupts will give IRQ number you can use that directly.

BSP documentation mentions IRQ assigned/used by drivers.

See kernel code /arch/arm/your-platform files, you will see IRQ Numbers assigned.

Device tree file is the best option for identifying the IRQ number.

Title: kernel IRQ domain list


问:
How to write a nice Low-Pass-Filter in Scala
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

```<code>def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

答:
If index lookups are a problem (O(n) with List), you could use a persistent vector.  This gives you O(1) indexing as well as O(1) update.  It's also purely functional (immutable), so life is still happy in that regard.

With a little bit of imagination, we can convert your code directly into a pure-functional version using Vector:

```<code>def filter(numbers: List[Double], size: Int) = {
  def walk(numbers: List[Double], buffer: Vector[Double], i: Int): List[Double] = {
    numbers match {
      case x :: tail => {
        val nextBuffer = buffer(i) = x
        val nextI = if (i == size) 0 else i + 1

        val avg = buffer.foldLeft(0.0) { _ + _ } / size
        avg :: walk(tail, nextBuffer, nextI)
      }

      case Nil => Nil
    }
  }

  walk(numbers, Vector.empty, 0)
}
</code>```

Note that this isn't tail-recursive, so it'll break down when numbers is too large.  It's pretty easy to fix this problem, but I'm being lazy right now.

OwnerDisplayName: Lemmy

Body:
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

Body:
If index lookups are a problem (O(n) with List), you could use a persistent vector.  This gives you O(1) indexing as well as O(1) update.  It's also purely functional (immutable), so life is still happy in that regard.

With a little bit of imagination, we can convert your code directly into a pure-functional version using Vector:

def filter(numbers: List[Double], size: Int) = {
  def walk(numbers: List[Double], buffer: Vector[Double], i: Int): List[Double] = {
    numbers match {
      case x :: tail => {
        val nextBuffer = buffer(i) = x
        val nextI = if (i == size) 0 else i + 1

        val avg = buffer.foldLeft(0.0) { _ + _ } / size
        avg :: walk(tail, nextBuffer, nextI)
      }

      case Nil => Nil
    }
  }

  walk(numbers, Vector.empty, 0)
}

Note that this isn't tail-recursive, so it'll break down when numbers is too large.  It's pretty easy to fix this problem, but I'm being lazy right now.

OwnerDisplayName: Daniel Spiewak

LastEditorDisplayName: Daniel Spiewak


问:
Pycharm/Django indentation error
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording.  I didn't know what the option meant but since I pressed that button I'm getting an ident error.  But I do not get an ident error in other locations.  Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial.

```<code>from django.contrib import admin
from .models import Post

class PostModelAdmin(admin.ModelAdmin):
    list_display = ["title", "updated", "timestamp"]
    list_display_links = ['updated']
    class Meta:
        model = Post
</code>```

tutorial image

答:
PyCharm follows PEP 8 -- Style Guide for Python Code so it will notify you about code not indented properly (read about pep 8 indentation)

When you use pycharm feature of reformat code it will modify your code with pep 8 guideline such as indentation with 4 spaces, import statements, line spacing after class/function single space after comma space before and after = at variable assignment, it will also wrap code with Maximum line length of 79 characters and many more

Title: Pycharm/Django indentation error

Body:
I was asked in Pycharm some question along the lines of 'your code was was written with 4 spaces rather than tabs, press ok' but I cannot remember the exact wording.  I didn't know what the option meant but since I pressed that button I'm getting an ident error.  But I do not get an ident error in other locations.  Now I'm getting an indentation error at 'list_display_links' and the code looks just the same as it does on this tutorial.

from django.contrib import admin
from .models import Post

class PostModelAdmin(admin.ModelAdmin):
    list_display = ["title", "updated", "timestamp"]
    list_display_links = ['updated']
    class Meta:
        model = Post

tutorial image


问:
Actuator - status only information if security is disabled
I want configure actuator in a way that:

Security configuration is disabled:

```<code>management.security.enabled=false
</code>```

And only available information is status:

```<code>"status" : "UP",
</code>```

But after disabling security I get full complet of reduntant for me information.
I tried to disable health properties but after disabling all I ended with:

```<code>"status" : "UP", "application", "UP"
</code>```

答:
Ok I managed to do it.
First I create own HealthEndpoint where I cut down information other than status:

```<code>public class StatusOnlyHealthEndpoint extends HealthEndpoint {

public StatusOnlyHealthEndpoint(final Map<String, HealthIndicator> healthIndicators) {
    super(new OrderedHealthAggregator(), healthIndicators);
}

@Override
public Health invoke() {
    Health health = super.invoke();
    return Health.status(health.getStatus())
                 .build();
}}
</code>```

Then I just override HealthEndpoint Bean with use of recent created Bean - thanks to that I can configure which indicators influence status from properties:

```<code>@Configuration
public class ApplicationHealth extends EndpointAutoConfiguration {

public ApplicationHealth(final ObjectProvider<HealthAggregator> healthAggregator,
                         final ObjectProvider<Map<String, HealthIndicator>> healthIndicators,
                         final ObjectProvider<List<InfoContributor>> infoContributors,
                         final ObjectProvider<Collection<PublicMetrics>> publicMetrics,
                         final ObjectProvider<TraceRepository> traceRepository) {
    super(healthAggregator, healthIndicators, infoContributors, publicMetrics, traceRepository);
}

@Bean
@ConditionalOnMissingBean
public HealthEndpoint healthEndpoint() {
    return new StatusOnlyHealthEndpoint(super.healthEndpoint());
}}
</code>```

Body:
I want configure actuator in a way that:

Security configuration is disabled:

management.security.enabled=false

And only available information is status:

"status" : "UP",

But after disabling security I get full complet of reduntant for me information.
I tried to disable health properties but after disabling all I ended with:

"status" : "UP", "application", "UP"

Body:
Ok I managed to do it.
First I create own HealthEndpoint where I cut down information other than status:

public class StatusOnlyHealthEndpoint extends HealthEndpoint {

public StatusOnlyHealthEndpoint(final Map<String, HealthIndicator> healthIndicators) {
    super(new OrderedHealthAggregator(), healthIndicators);
}

@Override
public Health invoke() {
    Health health = super.invoke();
    return Health.status(health.getStatus())
                 .build();
}}

Then I just override HealthEndpoint Bean with use of recent created Bean - thanks to that I can configure which indicators influence status from properties:

@Configuration
public class ApplicationHealth extends EndpointAutoConfiguration {

public ApplicationHealth(final ObjectProvider<HealthAggregator> healthAggregator,
                         final ObjectProvider<Map<String, HealthIndicator>> healthIndicators,
                         final ObjectProvider<List<InfoContributor>> infoContributors,
                         final ObjectProvider<Collection<PublicMetrics>> publicMetrics,
                         final ObjectProvider<TraceRepository> traceRepository) {
    super(healthAggregator, healthIndicators, infoContributors, publicMetrics, traceRepository);
}

@Bean
@ConditionalOnMissingBean
public HealthEndpoint healthEndpoint() {
    return new StatusOnlyHealthEndpoint(super.healthEndpoint());
}}


问:
when i try to upload new build on app store getting itunes error 90046 for applink
I am using firebase dynamic link when trying archive and upload to app store with new build getting error.

Associated domain is well set and enabled from capabilities in xcode.

Need help.

The error description is as follow:

iTunes Store Operation Failed

description length:15189238

iTunes store Operation Failed

ERROR ITMS-90046: "Invalid Code Signing Entitlement.Your application signature contains code signing entitlement that are not supported on iOS. Specifically, value 'applinks://abcd.app.goog.gl/' for key 'com.apple.developer.associated-domains' in 'Payload/Myapp.app/Myapp' is not supported"

答:
I guess applinks://abcd.app.goog.gl is wrong.
Might you try to change your configuration with applinks:abcd.app.goog.gl ?


问:
Disabling android's chrome pull-down-to-refresh feature
I've created a small HTML5 web application for my company.

This application displays a list of items and everything works fine.

The application is mainly used on android phones and Chrome as browser. Also, the site is saved on the home screen so Android manage the whole thing as an app (using a WebView I guess).

Chrome Beta (and I think also the Android System WebView) has introduced a "pull down to refresh" feature (See this link for example).

This is an handy feature but I was wondering if it can be disabled with some meta tag (or javascript stuff) because the refresh can be easily triggered by the user while navigating the list and the whole app is reloaded.

Also this is a feature not needed by the application.

I know that this feature is still available only in Chrome beta, but I have the sensation that this is landing on the stable app, too.

Thank you!

Edit: I've uninstalled Chrome Beta and the link pinned to the home screen now opens with the stable Chrome. So the pinned links starts with Chrome and not with a webview.

Edit: today (2015-03-19) the pull-down-to-refresh has come to the stable chrome.

Edit: from @Evyn answer I follow this link and got this javascript/jquery code that work.

var lastTouchY = 0;
var preventPullToRefresh = false;

$('body').on('touchstart', function (e) {
    if (e.originalEvent.touches.length != 1) { return; }
    lastTouchY = e.originalEvent.touches[0].clientY;
    preventPullToRefresh = window.pageYOffset == 0;
});

$('body').on('touchmove', function (e) {
    var touchY = e.originalEvent.touches[0].clientY;
    var touchYDelta = touchY - lastTouchY;
    lastTouchY = touchY;
    if (preventPullToRefresh) {
        // To suppress pull-to-refresh it is sufficient to preventDefault the first overscrolling touchmove.
        preventPullToRefresh = false;
        if (touchYDelta > 0) {
            e.preventDefault();
            return;
        }
    }
});```

As @bcintegrity pointed out, I hope for a site manifest solution (and/or a meta-tag) in the future.

Moreover suggestions for the code above are welcome.

答:
Simple solution for 2019+

Chrome 63 has added a css property to help out with exactly this. Have a read through this guide by Google to get a good idea of how you can handle it.

Here is their TL:DR

The CSS overscroll-behavior property allows developers to override the
  browser's default overflow scroll behavior when reaching the
  top/bottom of content. Use cases include disabling the pull-to-refresh
  feature on mobile, removing overscroll glow and rubberbanding effects,
  and preventing page content from scrolling when it's beneath a
  modal/overlay.

To get it working, all you have to add is this in your CSS:

```<code>body {
  overscroll-behavior: contain;
}
</code>```

It is also only supported by Chrome, Edge and Firefox for now but I'm sure Safari will add it soon as they seem to be fully onboard with service workers and the future of PWA's.

Body:
I've created a small HTML5 web application for my company.

This application displays a list of items and everything works fine.

The application is mainly used on android phones and Chrome as browser. Also, the site is saved on the home screen so Android manage the whole thing as an app (using a WebView I guess).

Chrome Beta (and I think also the Android System WebView) has introduced a "pull down to refresh" feature (See this link for example).

This is an handy feature but I was wondering if it can be disabled with some meta tag (or javascript stuff) because the refresh can be easily triggered by the user while navigating the list and the whole app is reloaded.

Also this is a feature not needed by the application.

I know that this feature is still available only in Chrome beta, but I have the sensation that this is landing on the stable app, too.

Thank you!

Edit: I've uninstalled Chrome Beta and the link pinned to the home screen now opens with the stable Chrome. So the pinned links starts with Chrome and not with a webview.

Edit: today (2015-03-19) the pull-down-to-refresh has come to the stable chrome.

Edit: from @Evyn answer I follow this link and got this javascript/jquery code that work.

var lastTouchY = 0;
var preventPullToRefresh = false;

$('body').on('touchstart', function (e) {
    if (e.originalEvent.touches.length != 1) { return; }
    lastTouchY = e.originalEvent.touches[0].clientY;
    preventPullToRefresh = window.pageYOffset == 0;
});

$('body').on('touchmove', function (e) {
    var touchY = e.originalEvent.touches[0].clientY;
    var touchYDelta = touchY - lastTouchY;
    lastTouchY = touchY;
    if (preventPullToRefresh) {
        // To suppress pull-to-refresh it is sufficient to preventDefault the first overscrolling touchmove.
        preventPullToRefresh = false;
        if (touchYDelta > 0) {
            e.preventDefault();
            return;
        }
    }
});

As @bcintegrity pointed out, I hope for a site manifest solution (and/or a meta-tag) in the future.

Moreover suggestions for the code above are welcome.

Body:
Simple solution for 2019+

Chrome 63 has added a css property to help out with exactly this. Have a read through this guide by Google to get a good idea of how you can handle it.

Here is their TL:DR

The CSS overscroll-behavior property allows developers to override the
  browser's default overflow scroll behavior when reaching the
  top/bottom of content. Use cases include disabling the pull-to-refresh
  feature on mobile, removing overscroll glow and rubberbanding effects,
  and preventing page content from scrolling when it's beneath a
  modal/overlay.

To get it working, all you have to add is this in your CSS:

body {
  overscroll-behavior: contain;
}

It is also only supported by Chrome, Edge and Firefox for now but I'm sure Safari will add it soon as they seem to be fully onboard with service workers and the future of PWA's.


问:
How to call a Query other than by name in Access VBA
I know it is possible to call query by name as follow:

```<code>DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit
</code>```

OR

```<code>CurrentDb.OpenRecordset("yourQueryName")
</code>```

But is it possible to call them with numbers like Sheets in Excel?
Something like:

```<code>CurrentDb.OpenRecordset Queries(1)
</code>```

or any other way possible?

Note: I want to do that because my queries are in Japanese and I would like to avoid the hard way to read them in VBA.

答:
You can certainly execute queries using the QueryDefs collection. However, referring to them by position is a dangerous thing to do, since the position may change and you might be opening the wrong query.

To do so, you can use CurrentDb.QueryDefs(1).OpenRecordset

Note that Access also makes temporary/internal queries available to the QueryDefs collection. Their name starts with ~, and there are often many on a large database.

 (in my general development database, the first real query is currently QueryDefs(20))

Body:
I know it is possible to call query by name as follow:

DoCmd.OpenQuery "yourQueryName", acViewNormal, acEdit

OR

CurrentDb.OpenRecordset("yourQueryName")

But is it possible to call them with numbers like Sheets in Excel?
Something like:

CurrentDb.OpenRecordset Queries(1)

or any other way possible?

Note: I want to do that because my queries are in Japanese and I would like to avoid the hard way to read them in VBA.


问:
not getting proper string in assign function in c++ when trying to get data from file
```<code>data.assign( content,
             (content.find_first_of("= ")) + 3,
             content.find_first_of('\n')-content.find_first_of("= ") + 3);
</code>```

I am getting invalid length of string when reading from file and comparing it with local string in my code what checking I have missed in this it can be '\0' or '\n' at the end of the file means I am trying to get the data from file from '=' character I find to end of that line file could be of one line or multiple line I just need data upto '\n' or '\0'

content : Scenario = sampl_verification

data : sampl_verification

data size : 19

data length : 19

cdata : sampl_verification

cdata size : 18

cdata length : 18

答:
Use std::getline instead of std::assign. std::getline reads data upto '\n' or '\0'.

For more info, you can read these -

std::getline

std::assign

Body:
data.assign( content,
             (content.find_first_of("= ")) + 3,
             content.find_first_of('\n')-content.find_first_of("= ") + 3);

I am getting invalid length of string when reading from file and comparing it with local string in my code what checking I have missed in this it can be '\0' or '\n' at the end of the file means I am trying to get the data from file from '=' character I find to end of that line file could be of one line or multiple line I just need data upto '\n' or '\0'

content : Scenario = sampl_verification

data : sampl_verification

data size : 19

data length : 19

cdata : sampl_verification

cdata size : 18

cdata length : 18


问:
Error Installing Dynet w/ Python on Windows
I am following the tutorial here: http://dynet.readthedocs.io/en/latest/python.html#windows-python-install
 for installing Dynet w/ GPU and Python.

I can get to the step where I run cmake, and everything seems fine. The issue seems to be building the Python project.

I run:

```<code>cmake .. -DEIGEN3_INCLUDE_DIR=$PWD/../../eigen -DPYTHON=`which python` -DBACKEND=cuda -DCUDA_TOOLKIT_ROOT_DIR="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0" -G"Visual Studio 14 2015 Win64"
</code>```

which produces

```<code>$ cmake .. -DEIGEN3_INCLUDE_DIR=$PWD/../../eigen -DPYTHON=`which python` -DBACKEND=cuda -DCUDA_TOOLKIT_ROOT_DIR="C:/P
rogram Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0" -G"Visual Studio 14 2015 Win64"
-- Selecting Windows SDK version  to target Windows 10.0.16299.
-- The C compiler identification is MSVC 19.0.24210.0
-- The CXX compiler identification is MSVC 19.0.24210.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works

-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- BACKEND: cuda
-- Found CUDA: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0 (found version "9.0")
CUDA_LIBRARIES: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib
-- Failed to find CUDNN in path:  (Did you set CUDNN_ROOT properly?)
-- CUDNN not found, some dependent functionalities will be disabled
-- Eigen dir is C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/eigen
-- Looking for pthread.h
-- Looking for pthread.h - not found
-- Found Threads: TRUE
-- Found Cython version 0.27.3

--- CUDA: CUBLAS: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cublas.lib;C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cublas_device.lib RT: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib
CMAKE_INSTALL_PREFIX="C:/Program Files/dynet"
PROJECT_SOURCE_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet"
PROJECT_BINARY_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet/build"
LIBS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib"
EIGEN3_INCLUDE_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/eigen"
MKL_LINK_DIRS=""
WITH_CUDA_BACKEND="1"
CUDA_RT_FILES="cudart_static.lib"
CUDA_RT_DIRS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64"
CUDA_CUBLAS_FILES="cublas.lib\;cublas_device.lib"
CUDA_CUBLAS_DIRS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64"
MSVC="1"
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet/build
</code>```

All seems good. But, when I try to build on Visual Studio, I encounter 37 errors in  the pydynet project, including:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error       command 'C:\\Users\\pie_a\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2   pydynet C:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\build\python\CUSTOMBUILD    1
</code>```

I assume it hasn't work at this point, and proceeding the next step fails, since running the following command gives an error:

```<code>$ python setup.py build --skip-build install
running build
INFO:root:CMAKE_PATH='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Scripts\\cmake.exe'
INFO:root:MAKE_PATH='C:\\MinGW\\msys\\1.0\\bin\\make.exe'
INFO:root:MAKE_FLAGS='-j 8'
INFO:root:EIGEN3_INCLUDE_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit\\eigen'
INFO:root:EIGEN3_DOWNLOAD_URL='https://bitbucket.org/eigen/eigen/get/699b6595fc47.zip'
INFO:root:CC_PATH='C:\\MinGW\\bin\\gcc.exe'
INFO:root:CXX_PATH='C:\\MinGW\\bin\\g++.exe'
INFO:root:SCRIPT_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet'
INFO:root:BUILD_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit'
INFO:root:INSTALL_PREFIX='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Lib\\site-packages\\..\\..\\..'
INFO:root:PYTHON='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\python.exe'
cmake version 3.10.0

CMake suite maintained and supported by Kitware (kitware.com/cmake).
g++.exe (GCC) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

running build_py
INFO:root:Building Python files...
file dynet_viz.py (for module dynet_viz) not found
file dynet_config.py (for module dynet_config) not found
creating build
creating build\lib.win-amd64-2.7
copying dynet.py -> build\lib.win-amd64-2.7
file dynet_viz.py (for module dynet_viz) not found
file dynet_config.py (for module dynet_config) not found
running build_ext
INFO:root:Building Cython extensions...
INFO:root:INCLUDE_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit\\eigen'
INFO:root:LIBRARIES='dynet'
INFO:root:LIBRARY_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet/dynet/ . C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit/dynet/'
INFO:root:COMPILER_ARGS='-std=c++11 -Wno-unused-function'
INFO:root:EXTRA_LINK_ARGS="-Wl,-rpath='C:\\\\Users\\\\pie_a\\\\Anaconda3\\\\envs\\\\nlphw\\\\Lib\\\\site-packages\\\\..\\\\..\\\\../lib/',--no-as-needed"
INFO:root:RUNTIME_LIB_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet/dynet/ C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Lib\\site-packages\\..\\..\\../lib/'
skipping 'C:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.cpp' Cython extension (up-to-date)
building '_dynet' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
creating build\temp.win-amd64-2.7\Release\Users
creating build\temp.win-amd64-2.7\Release\Users\pie_a
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\python
C:\Users\pie_a\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet -IC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\build\py2.7-64bit\eigen -IC:\Users\pie_a\Anaconda3\envs\nlphw\include -IC:\Users\pie_a\Anaconda3\envs\nlphw\PC /TpC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.cpp /Fobuild\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.obj -std=c++11 -Wno-unused-function
cl : Command line error D8021 : invalid numeric argument '/Wno-unused-function'
error: command 'C:\\Users\\pie_a\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
</code>```

I'm happy to provide more information! A few possible sources of the problem: I installed Boost with pip. I saw a note that the c++ compiler needed to be the same version as the compiler that you install Boost is, but a message on Visual Studio had me install a different c++ driver when building for the first time.

Also, the value of this variable is in Windowese rather than Unix format is this a problem? I set it as a System Environment Variable.

```<code>$ echo $VS90COMNTOOLS
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\
</code>```

答: Try setting the environment variable MSVC to 1 and building again. This variable tells the setup code to use settings appropriate for Windows.

Body:
I am following the tutorial here: http://dynet.readthedocs.io/en/latest/python.html#windows-python-install
 for installing Dynet w/ GPU and Python.

I can get to the step where I run cmake, and everything seems fine. The issue seems to be building the Python project.

I run:

cmake .. -DEIGEN3_INCLUDE_DIR=$PWD/../../eigen -DPYTHON=`which python` -DBACKEND=cuda -DCUDA_TOOLKIT_ROOT_DIR="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0" -G"Visual Studio 14 2015 Win64"

which produces

$ cmake .. -DEIGEN3_INCLUDE_DIR=$PWD/../../eigen -DPYTHON=`which python` -DBACKEND=cuda -DCUDA_TOOLKIT_ROOT_DIR="C:/P
rogram Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0" -G"Visual Studio 14 2015 Win64"
-- Selecting Windows SDK version  to target Windows 10.0.16299.
-- The C compiler identification is MSVC 19.0.24210.0
-- The CXX compiler identification is MSVC 19.0.24210.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/x86_amd64/cl.exe -- works

-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- BACKEND: cuda
-- Found CUDA: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0 (found version "9.0")
CUDA_LIBRARIES: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib
-- Failed to find CUDNN in path:  (Did you set CUDNN_ROOT properly?)
-- CUDNN not found, some dependent functionalities will be disabled
-- Eigen dir is C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/eigen
-- Looking for pthread.h
-- Looking for pthread.h - not found
-- Found Threads: TRUE
-- Found Cython version 0.27.3

--- CUDA: CUBLAS: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cublas.lib;C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cublas_device.lib RT: C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib
CMAKE_INSTALL_PREFIX="C:/Program Files/dynet"
PROJECT_SOURCE_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet"
PROJECT_BINARY_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet/build"
LIBS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64/cudart_static.lib"
EIGEN3_INCLUDE_DIR="C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/eigen"
MKL_LINK_DIRS=""
WITH_CUDA_BACKEND="1"
CUDA_RT_FILES="cudart_static.lib"
CUDA_RT_DIRS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64"
CUDA_CUBLAS_FILES="cublas.lib\;cublas_device.lib"
CUDA_CUBLAS_DIRS="C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v9.0/lib/x64"
MSVC="1"
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/pie_a/Documents/coding/nlp/adc2181_h4/dynet-base/dynet/build

All seems good. But, when I try to build on Visual Studio, I encounter 37 errors in  the pydynet project, including:

Severity    Code    Description Project File    Line    Suppression State
Error       command 'C:\\Users\\pie_a\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2   pydynet C:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\build\python\CUSTOMBUILD    1

I assume it hasn't work at this point, and proceeding the next step fails, since running the following command gives an error:

$ python setup.py build --skip-build install
running build
INFO:root:CMAKE_PATH='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Scripts\\cmake.exe'
INFO:root:MAKE_PATH='C:\\MinGW\\msys\\1.0\\bin\\make.exe'
INFO:root:MAKE_FLAGS='-j 8'
INFO:root:EIGEN3_INCLUDE_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit\\eigen'
INFO:root:EIGEN3_DOWNLOAD_URL='https://bitbucket.org/eigen/eigen/get/699b6595fc47.zip'
INFO:root:CC_PATH='C:\\MinGW\\bin\\gcc.exe'
INFO:root:CXX_PATH='C:\\MinGW\\bin\\g++.exe'
INFO:root:SCRIPT_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet'
INFO:root:BUILD_DIR='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit'
INFO:root:INSTALL_PREFIX='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Lib\\site-packages\\..\\..\\..'
INFO:root:PYTHON='C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\python.exe'
cmake version 3.10.0

CMake suite maintained and supported by Kitware (kitware.com/cmake).
g++.exe (GCC) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

running build_py
INFO:root:Building Python files...
file dynet_viz.py (for module dynet_viz) not found
file dynet_config.py (for module dynet_config) not found
creating build
creating build\lib.win-amd64-2.7
copying dynet.py -> build\lib.win-amd64-2.7
file dynet_viz.py (for module dynet_viz) not found
file dynet_config.py (for module dynet_config) not found
running build_ext
INFO:root:Building Cython extensions...
INFO:root:INCLUDE_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit\\eigen'
INFO:root:LIBRARIES='dynet'
INFO:root:LIBRARY_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet/dynet/ . C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet\\build\\py2.7-64bit/dynet/'
INFO:root:COMPILER_ARGS='-std=c++11 -Wno-unused-function'
INFO:root:EXTRA_LINK_ARGS="-Wl,-rpath='C:\\\\Users\\\\pie_a\\\\Anaconda3\\\\envs\\\\nlphw\\\\Lib\\\\site-packages\\\\..\\\\..\\\\../lib/',--no-as-needed"
INFO:root:RUNTIME_LIB_DIRS='C:\\Users\\pie_a\\Documents\\coding\\nlp\\adc2181_h4\\dynet-base\\dynet/dynet/ C:\\Users\\pie_a\\Anaconda3\\envs\\nlphw\\Lib\\site-packages\\..\\..\\../lib/'
skipping 'C:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.cpp' Cython extension (up-to-date)
building '_dynet' extension
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
creating build\temp.win-amd64-2.7\Release\Users
creating build\temp.win-amd64-2.7\Release\Users\pie_a
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet
creating build\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\python
C:\Users\pie_a\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet -IC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet\build\py2.7-64bit\eigen -IC:\Users\pie_a\Anaconda3\envs\nlphw\include -IC:\Users\pie_a\Anaconda3\envs\nlphw\PC /TpC:\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.cpp /Fobuild\temp.win-amd64-2.7\Release\Users\pie_a\Documents\coding\nlp\adc2181_h4\dynet-base\dynet/python\_dynet.obj -std=c++11 -Wno-unused-function
cl : Command line error D8021 : invalid numeric argument '/Wno-unused-function'
error: command 'C:\\Users\\pie_a\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2

I'm happy to provide more information! A few possible sources of the problem: I installed Boost with pip. I saw a note that the c++ compiler needed to be the same version as the compiler that you install Boost is, but a message on Visual Studio had me install a different c++ driver when building for the first time.

Also, the value of this variable is in Windowese rather than Unix format is this a problem? I set it as a System Environment Variable.

$ echo $VS90COMNTOOLS
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\


问:
How to check if a string starts with another string in C?
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

```<code>"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true
</code>```

答:
There's no standard function for this, but you can define

```<code>bool prefix(const char *pre, const char *str)
{
    return strncmp(pre, str, strlen(pre)) == 0;
}
</code>```

We don't have to worry about str being shorter than pre because according to the C standard (7.21.4.4/2):

The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2."

Body:
Is there something like startsWith(str_a, str_b) in the standard C library?

It should take pointers to two strings that end with nullbytes, and tell me whether the first one also appears completely at the beginning of the second one.

Examples:

"abc", "abcdef" -> true
"abcdef", "abc" -> false
"abd", "abdcef" -> true
"abc", "abc"    -> true

Body:
There's no standard function for this, but you can define

bool prefix(const char *pre, const char *str)
{
    return strncmp(pre, str, strlen(pre)) == 0;
}

We don't have to worry about str being shorter than pre because according to the C standard (7.21.4.4/2):

The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2."


问:
Mongodb: get only array of post comments from this object
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}
</code>```

My Query is:

```<code>db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})
</code>```

and the result is:

```<code>{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}
</code>```

What I want is:

```<code> [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
</code>```

Also I am using MongoRepository in Spring Boot and the query there is:

```<code>@Query(value = "{'_id' : ?0}, {'postComments':1}")
</code>```

and it gave me the same result.

答:
You can try out this

db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1}).then(function(u){return u.postComments;})

Body:
So far I achieved is I got the array inside the object and I want the array directly.

Here is my object:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "description" : "My Post",
    "postLikes" : [
        {
            "likesCount" : 0,
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512631701702),
            "updatedOn" : NumberLong(0)
        }
    ],
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ],
    "createdOn" : NumberLong(0),
    "updatedOn" : NumberLong(0)
}

My Query is:

db.user_posts.find({_id: ObjectId("5a28e2a1bf22d2a9ddb8f5d5")}, {postComments:1})

and the result is:

{
    "_id" : ObjectId("5a28e2a1bf22d2a9ddb8f5d5"),
    "postComments" : [
        {
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]
}

What I want is:

 [
        {
            "_id" : null,
            "comment" : "This is first comment",
            "likeByEmail" : "a@a.com",
            "createdOn" : NumberLong(1512643824764),
            "updatedOn" : NumberLong(1512643824764)
        }
    ]

Also I am using MongoRepository in Spring Boot and the query there is:

@Query(value = "{'_id' : ?0}, {'postComments':1}")

and it gave me the same result.


问:
How to Data model for an educational application in FirebaseFirestore
I need to implement a student-Teacher Interaction application where students can learn any number of courses  from teachers in that particular field. I have a data model that stores all the short objects of students who are enrolled to a  course under a teacher which will be stored under Teacher main object and  all the the short objects of teachers who teach that student under Students main object. My question is how do I update changes to all the short objects of this Teacher,if he updates his profile.

答: I think your question is related to where your background is for example if you are coming from relational database there then you need to reference ids etc.. then think the same way too does not hurt something to know is that you can use the same thinking in firestore too.</p>


答: You say that your associated domains are well set in Project Settings -> Capabilities. Are you sure then, that you have used correct certificate? I would check it again if it's a production environment cert.

Title: when i try to upload new build on app store getting itunes error 90046 for applink

Body:
I am using firebase dynamic link when trying archive and upload to app store with new build getting error.

Associated domain is well set and enabled from capabilities in xcode.

Need help.

The error description is as follow:

iTunes Store Operation Failed

description length:15189238

iTunes store Operation Failed

ERROR ITMS-90046: "Invalid Code Signing Entitlement.Your application signature contains code signing entitlement that are not supported on iOS. Specifically, value 'applinks://abcd.app.goog.gl/' for key 'com.apple.developer.associated-domains' in 'Payload/Myapp.app/Myapp' is not supported"


问:
How to remove cordova-plugin-compat?
In the release notes of cordova-android 6.3.0 (https://cordova.apache.org/announcements/2017/09/27/android-release.html) it's written down that cordova-plugin-compat has to be removed

If I try

```<code>cordova plugin rm cordova-plugin-compat
</code>```

I get following error

[ERROR] An error occurred while running cordova plugin remove
  cordova-plugin-compat --save (exit code 1):

Error: The plugin ‘cordova-plugin-compat’ is required by
  (cordova-plugin-calendar, cordova-plugin-camera, cordova-plugin-file,
  cordova-plugin-geolocation), skipping uninstallation. (try --force if
  trying to update)

If I then try to --force the remove, it works, the plugin is removed and I'm able to build my android app.

BUT, I just removed my iOS platform to add it again and I face now the error

cordova prepare ios Error: Cannot find plugin.xml for plugin "cordova-plugin-compat". Please try adding it again.

[ERROR] An error occurred while running cordova prepare ios (exit code
  1).

Any idea what am I doing wrong? Should really cordova-plugin-compat be removed? Why my iOS platform is referencing it, I thought it was only for android?

I use cordova-android@6.3.0 and cordova-ios@4.5.1

P.S.: If I remove and add the iOS platform, the compat plugin is automatically added as reference in package.json and package-lock.json

UPDATE

The last plugin release (https://cordova.apache.org/news/2017/11/10/plugins-release.html) most probably solve this issue respectively it looks like that the problem was the reference to the cordova-plugin-compat plugin from other plugin. But,

I'm not yet able to totally test it and solve it because I'm using another plugin where compat is also referenced (https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/issues/426).

I will keep this thread open till I could 100% confirm that this solve the referencing of compat.

FINAL UPDATE

The PR to remove the dependency from Calendar-PhoneGap-Plugin to ‘cordova-plugin-compat’ went thru, I was able to remove this last plugin without "force"

答:
The source of the problem was that plugins were directly referencing cordova-plugin-compat.

Therefore, even if the use of the plugin was deprecated, it was still needed. Forcing a deletion (using --force) wasn't a solution, because if I removed and added a platform again, then, because of these references, the plugin ‘cordova-plugin-compat’ was automatically added again during that process.

The solution of the problem was then to wait for new releases or to submit PR to remove the dependency.

In my case there were the plugins which were referencing cordova-plugin-compat:

Error: The plugin ‘cordova-plugin-compat’ is required by
  (cordova-plugin-calendar, cordova-plugin-camera, cordova-plugin-file,
  cordova-plugin-geolocation), skipping uninstallation. (try --force if
  trying to update)

Updating following plugins solved my issue:

cordova-plugin-camera@3.0.0, cordova-plugin-file@5.0.0 and cordova-plugin-geolocation@3.0.0 removed the dependency (see https://cordova.apache.org/news/2017/11/10/plugins-release.html)

cordova-plugin-calendar@5.0.0 removed the dependency thru this PR
https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/pull/430

Title: How to remove cordova-plugin-compat?

Body:
In the release notes of cordova-android 6.3.0 (https://cordova.apache.org/announcements/2017/09/27/android-release.html) it's written down that cordova-plugin-compat has to be removed

If I try

cordova plugin rm cordova-plugin-compat

I get following error

[ERROR] An error occurred while running cordova plugin remove
  cordova-plugin-compat --save (exit code 1):

Error: The plugin ‘cordova-plugin-compat’ is required by
  (cordova-plugin-calendar, cordova-plugin-camera, cordova-plugin-file,
  cordova-plugin-geolocation), skipping uninstallation. (try --force if
  trying to update)

If I then try to --force the remove, it works, the plugin is removed and I'm able to build my android app.

BUT, I just removed my iOS platform to add it again and I face now the error

cordova prepare ios Error: Cannot find plugin.xml for plugin "cordova-plugin-compat". Please try adding it again.

[ERROR] An error occurred while running cordova prepare ios (exit code
  1).

Any idea what am I doing wrong? Should really cordova-plugin-compat be removed? Why my iOS platform is referencing it, I thought it was only for android?

I use cordova-android@6.3.0 and cordova-ios@4.5.1

P.S.: If I remove and add the iOS platform, the compat plugin is automatically added as reference in package.json and package-lock.json

UPDATE

The last plugin release (https://cordova.apache.org/news/2017/11/10/plugins-release.html) most probably solve this issue respectively it looks like that the problem was the reference to the cordova-plugin-compat plugin from other plugin. But,

I'm not yet able to totally test it and solve it because I'm using another plugin where compat is also referenced (https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/issues/426).

I will keep this thread open till I could 100% confirm that this solve the referencing of compat.

FINAL UPDATE

The PR to remove the dependency from Calendar-PhoneGap-Plugin to ‘cordova-plugin-compat’ went thru, I was able to remove this last plugin without "force"