问:
RxJava in a Service
In my app to make network calls I use the RxJava 1.1.6 and Retrofit 2.1.0. I need to implement offline mode - sync all data in my app with the data on the back-end. I tried to use Service + RxJava  but I faced with some problem - I wanted to send some notifications from the my RxJava chain but it looks like I can't do that. It seems that this chain executes in the different thread, not in that one that my Service works. But I didn't change the thread for RxJava chain.) Below I attached the code that I run.

```<code>protected void handleIntent(@Nullable Intent intent) {
    Log.d(TAG, "################ handleIntent ");
    if (isStarted) {
      return;
    }

    final ArrayList<Integer> languageKeys = intent.getIntegerArrayListExtra(LANGUAGES_KEY);
    final ArrayList<Integer> currencyKeys = intent.getIntegerArrayListExtra(CURRENCY_KEY);

    Log.d(TAG, "handleIntent: ");
    showStartLoadingNotifications(NOTIFICATION_ID, "Test: Data sync started"); //this one works fine
   Observable.just(null)
      .flatMap(o -> networkUtils.networkAvailable())
      .filter(isRequestAllowed -> isRequestAllowed)
      .flatMap(isRequestAllowed -> {
        if (isRequestAllowed) {
          showStartLoadingNotifications(NOTIFICATION_ID, "Data sync started"); //this one doesn't work
        } else {
          stopSelf();
          hideNotification(NOTIFICATION_ID);
        }
        return just(isRequestAllowed);
      })
      .doOnNext(o -> isStarted = true)
      .doOnNext(o -> {
        DaoMaster.dropAllTables(daoSession.getDatabase(), true);
        DaoMaster.createAllTables(daoSession.getDatabase(), true);
      })
      .concat(from(prepareRequests(languageKeys, currencyKeys)))
      .subscribe(loadAllResponse -> {
        },
        throwable -> {
          Log.d(TAG, throwable.getMessage());
          isStarted = false;
        }, () -> {
          isStarted = false;
          stopSelf();
        });
    Log.d(TAG, "##############  handleIntent: finished");
  }
</code>```

The prepareRequests(languageKeys, currencyKeys) method returns the List<Observable<LoadAllResponse>>.
All works fine service works as expected: data is downloading and storing in the DB but I cannot send the notification to the system.

Has someone faced with a similar issue? Also does someone know in what thread it is run and how to change the thread for this chain to get ability to send notifications?

答:
From the documentation:

Required notification contents
A Notification object must contain the following:

A small icon, set by setSmallIcon().

A title, set by setContentTitle().

Detail text, set by setContentText().

On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.

You are missing setContentTitle()

Title: RxJava in a Service

Body:
In my app to make network calls I use the RxJava 1.1.6 and Retrofit 2.1.0. I need to implement offline mode - sync all data in my app with the data on the back-end. I tried to use Service + RxJava  but I faced with some problem - I wanted to send some notifications from the my RxJava chain but it looks like I can't do that. It seems that this chain executes in the different thread, not in that one that my Service works. But I didn't change the thread for RxJava chain.) Below I attached the code that I run.

protected void handleIntent(@Nullable Intent intent) {
    Log.d(TAG, "################ handleIntent ");
    if (isStarted) {
      return;
    }

    final ArrayList<Integer> languageKeys = intent.getIntegerArrayListExtra(LANGUAGES_KEY);
    final ArrayList<Integer> currencyKeys = intent.getIntegerArrayListExtra(CURRENCY_KEY);

    Log.d(TAG, "handleIntent: ");
    showStartLoadingNotifications(NOTIFICATION_ID, "Test: Data sync started"); //this one works fine
   Observable.just(null)
      .flatMap(o -> networkUtils.networkAvailable())
      .filter(isRequestAllowed -> isRequestAllowed)
      .flatMap(isRequestAllowed -> {
        if (isRequestAllowed) {
          showStartLoadingNotifications(NOTIFICATION_ID, "Data sync started"); //this one doesn't work
        } else {
          stopSelf();
          hideNotification(NOTIFICATION_ID);
        }
        return just(isRequestAllowed);
      })
      .doOnNext(o -> isStarted = true)
      .doOnNext(o -> {
        DaoMaster.dropAllTables(daoSession.getDatabase(), true);
        DaoMaster.createAllTables(daoSession.getDatabase(), true);
      })
      .concat(from(prepareRequests(languageKeys, currencyKeys)))
      .subscribe(loadAllResponse -> {
        },
        throwable -> {
          Log.d(TAG, throwable.getMessage());
          isStarted = false;
        }, () -> {
          isStarted = false;
          stopSelf();
        });
    Log.d(TAG, "##############  handleIntent: finished");
  }

The prepareRequests(languageKeys, currencyKeys) method returns the List<Observable<LoadAllResponse>>.
All works fine service works as expected: data is downloading and storing in the DB but I cannot send the notification to the system.

Has someone faced with a similar issue? Also does someone know in what thread it is run and how to change the thread for this chain to get ability to send notifications?


来源: stackexchange

问:
Cannot convert lambda expression to type 'object' because it is not a delegate type
I have a base class that has a bool property which looks like this:

```<code>public abstract class MyBaseClass
{
     public bool InProgress { get; protected set; }
}
</code>```

I am inheriting it another class from it and trying to add InProgress as a delegate to the dictionary. But it throws me an error. This is how my Derived class looks like:

```<code>public abstract class MyClass
{
     Dictionary<string, object> dict = new Dictionary<string, object>();
     dict.Add("InProgress", InProgress => base.InProgress = InProgress);

}
</code>```

This is the error I am getting:

Cannot convert lambda expression to type 'object' because it is not a delegate type

What am I doing wrong here?

答:
I ran into this problem while writing unit tests. I was attempting to mock the behavior of a database to return a new object from a repository instead of actually connecting to a database.

Make sure your object has a usable constructor. You may not be able to successfully instantiate that object the way you want to. Ensure if you using a lambda to point to a constructor that the constructor can be called in the same way in a normal instantiation statement.

i.e.

```<code>return x => new FakeObject();
</code>```

say in the case of

```<code>var fake = new FakeObject();
</code>```

would not work then the lambda will also fail so be careful.

ContentLicense: CC BY-SA 3.0

Body:
I have a base class that has a bool property which looks like this:

public abstract class MyBaseClass
{
     public bool InProgress { get; protected set; }
}

I am inheriting it another class from it and trying to add InProgress as a delegate to the dictionary. But it throws me an error. This is how my Derived class looks like:

public abstract class MyClass
{
     Dictionary<string, object> dict = new Dictionary<string, object>();
     dict.Add("InProgress", InProgress => base.InProgress = InProgress);

}

This is the error I am getting:

Cannot convert lambda expression to type 'object' because it is not a delegate type

What am I doing wrong here?

Body:
I ran into this problem while writing unit tests. I was attempting to mock the behavior of a database to return a new object from a repository instead of actually connecting to a database.

Make sure your object has a usable constructor. You may not be able to successfully instantiate that object the way you want to. Ensure if you using a lambda to point to a constructor that the constructor can be called in the same way in a normal instantiation statement.

i.e.

return x => new FakeObject();

say in the case of

var fake = new FakeObject();

would not work then the lambda will also fail so be careful.


问:
How to Use HTTP Receive GET Message in Orchestration?
I have set up a HTTP Receive (req-response) adapter and the message appears to be getting to the message box. When I create an orchestration using a direct bound logical port, I am getting the message but everything I have tried to read the message body has failed (using passthrough pipeline, XML pipeline with allow unrecognized files = true) but I get exceptions any time I try to use the incoming message (message assignments, sending the message to a custom module to try to read the part(s)).

Rather than go into details on exceptions, can anyone point to instructions on what the proper way to access/use the body of the HTTP Get messages within an orchestration? To explain what I am trying to do, I want to take the query string (body) and send it verbatim to another orchestration for processing, so I simply want to extract the body (query string) from the message.

答: So the answer was to NOT use the HTTP adapter for GET requests. I did not realize the HTTP adapter has effectively been deprecated. For basic GET requests I had to switch to the WCF-WebHTTP adapter and make sure to include the property in the property schema and then make sure to set the schema in the variable mapping as the property schema, not the message type schema of the incoming message. I wish the Microsoft documentation was more clear that the HTTP adapter cannot be used for very basic GET requests in which a body is not provided in the request. </p>


问:
How Can I Sort A 'Version Number' Column Generically Using a SQL Server Query
I wonder if the SQL geniuses amongst us could lend me a helping hand.

I have a column VersionNo in a table Versions that contains 'version number' values like

```<code>VersionNo
---------
1.2.3.1
1.10.3.1
1.4.7.2
</code>```

etc.

I am looking to sort this, but unfortunately, when I do a standard order by, it is treated as a string, so the order comes out as

```<code>VersionNo
---------
1.10.3.1
1.2.3.1
1.4.7.2
</code>```

Intead of the following, which is what I am after:

```<code>VersionNo
---------
1.2.3.1
1.4.7.2
1.10.3.1
</code>```

So, what I need to do is to sort by the numbers in reverse order (e.g. in a.b.c.d, I need to sort by d,c,b,a to get the correct sort ourder).

But I am stuck as to how to achieve this in a GENERIC way. Sure, I can split the string up using the various sql functions (e.g. left, right, substring, len, charindex), but I can't guarantee that there will always be 4 parts to the version number. I may have a list like this:

```<code>VersionNo
---------
1.2.3.1
1.3
1.4.7.2
1.7.1
1.10.3.1
1.16.8.0.1
</code>```

Can, does anyone have any suggestions? Your help would be much appreciated.

答:
Another way to do it:

Assuming you only have a,b,c,d only you may as well separate the data out to columns and do an order by a,b,c,d(all desc) and get the top 1 row

If you need to scale to more than d to say e,f,g... just change 1,2,3,4, to 1,2,3,4,5,6,7 and so on in the query

Query :
see demo

```<code>create table t (versionnumber varchar(255))
insert into t values
('1.0.0.505')
,('1.0.0.506')
,('1.0.0.507')
,('1.0.0.508')
,('1.0.0.509')
,('1.0.1.2')

; with cte as
(
    select
    column1=row_number() over (order by (select NULL)) ,
    column2=versionnumber
    from t
    )

select top 1
    CONCAT([1],'.',[2],'.',[3],'.',[4])
from
(
    select
        t.column1,
        split_values=SUBSTRING( t.column2, t1.N, ISNULL(NULLIF(CHARINDEX('.',t.column2,t1.N),0)-t1.N,8000)),
        r= row_number() over( partition by column1 order by t1.N)
    from cte t
        join
        (
            select
                t.column2,
                1 as N
            from cte t
                UNION ALL
            select
                t.column2,
                t1.N + 1 as N
            from cte t
                join
                (
                 select
                    top 8000
                        row_number() over(order by (select NULL)) as N
                 from
                    sys.objects s1
                        cross join
                   sys.objects s2
                ) t1
            on SUBSTRING(t.column2,t1.N,1) = '.'
         ) t1
          on t1.column2=t.column2
)a
pivot
(
    max(split_values) for r in ([1],[2],[3],[4])
   )p
  order by [1] desc,[2] desc,[3] desc,[4] desc
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I wonder if the SQL geniuses amongst us could lend me a helping hand.

I have a column VersionNo in a table Versions that contains 'version number' values like

VersionNo
---------
1.2.3.1
1.10.3.1
1.4.7.2

etc.

I am looking to sort this, but unfortunately, when I do a standard order by, it is treated as a string, so the order comes out as

VersionNo
---------
1.10.3.1
1.2.3.1
1.4.7.2

Intead of the following, which is what I am after:

VersionNo
---------
1.2.3.1
1.4.7.2
1.10.3.1

So, what I need to do is to sort by the numbers in reverse order (e.g. in a.b.c.d, I need to sort by d,c,b,a to get the correct sort ourder).

But I am stuck as to how to achieve this in a GENERIC way. Sure, I can split the string up using the various sql functions (e.g. left, right, substring, len, charindex), but I can't guarantee that there will always be 4 parts to the version number. I may have a list like this:

VersionNo
---------
1.2.3.1
1.3
1.4.7.2
1.7.1
1.10.3.1
1.16.8.0.1

Can, does anyone have any suggestions? Your help would be much appreciated.

Body:
Another way to do it:

Assuming you only have a,b,c,d only you may as well separate the data out to columns and do an order by a,b,c,d(all desc) and get the top 1 row

If you need to scale to more than d to say e,f,g... just change 1,2,3,4, to 1,2,3,4,5,6,7 and so on in the query

Query :
see demo

create table t (versionnumber varchar(255))
insert into t values
('1.0.0.505')
,('1.0.0.506')
,('1.0.0.507')
,('1.0.0.508')
,('1.0.0.509')
,('1.0.1.2')

; with cte as
(
    select
    column1=row_number() over (order by (select NULL)) ,
    column2=versionnumber
    from t
    )

select top 1
    CONCAT([1],'.',[2],'.',[3],'.',[4])
from
(
    select
        t.column1,
        split_values=SUBSTRING( t.column2, t1.N, ISNULL(NULLIF(CHARINDEX('.',t.column2,t1.N),0)-t1.N,8000)),
        r= row_number() over( partition by column1 order by t1.N)
    from cte t
        join
        (
            select
                t.column2,
                1 as N
            from cte t
                UNION ALL
            select
                t.column2,
                t1.N + 1 as N
            from cte t
                join
                (
                 select
                    top 8000
                        row_number() over(order by (select NULL)) as N
                 from
                    sys.objects s1
                        cross join
                   sys.objects s2
                ) t1
            on SUBSTRING(t.column2,t1.N,1) = '.'
         ) t1
          on t1.column2=t.column2
)a
pivot
(
    max(split_values) for r in ([1],[2],[3],[4])
   )p
  order by [1] desc,[2] desc,[3] desc,[4] desc


问:
Thread safety on Immutable object
I was reading about Immutable objects in java.

There is a statement which states - "Immutable objects are thread-safe".
I need more clarification for the above statement:

If I have a shared resource of type 'String' which is shared with multiple threads (say 3)
And if one of the thread make changes to the shared reference, it will create a new String object and that will available only with that Thread object and other threads will not get to know about the changes made by one of the thread.

Will it not lead to data inconsistency?

So could anyone please help me understand this?

Thanks in advance.

答:
Immutable types (in any language) are special reference types.
Their uniqueness lies in the fact that when they are changed they are replaced with an entirely new instance which reflects the previous state + the change

Lets say 2 threads running a function which receive an immutable reference type object as a parameter ( and of course i'll use string for this example)

// pseudo code !!

```<code>  main()
  {
      var str = "initialState";
      new Thread(Do,str,1).Start();
      new Thread(Do,str,2).Start();
  }

  void Do(string arg,int tid)
  {
      int i = 0;
      while(true)
      {
          arg += "running in thread " + tid + "for the " + i + "time";
          Console.WriteLine(arg);
      }
   }
</code>```

This program while print in parallel the number of occurrences running in each thread with out effecting what was printed in the other thread.

Why ?

If you think about it string is a reference type, it is passed by reference and not by value, meaning it is not copied only a copy of the reference occurs.
And yet though it was initially the same object. after the first change it is no longer and a different one is created.
If it was still the same object after changes it would be a shared resource between the 2 threads and will disrupt the state those threads men't to print.

Title: Thread safety on Immutable object

Body:
Immutable types (in any language) are special reference types.
Their uniqueness lies in the fact that when they are changed they are replaced with an entirely new instance which reflects the previous state + the change

Lets say 2 threads running a function which receive an immutable reference type object as a parameter ( and of course i'll use string for this example)

// pseudo code !!

  main()
  {
      var str = "initialState";
      new Thread(Do,str,1).Start();
      new Thread(Do,str,2).Start();
  }

  void Do(string arg,int tid)
  {
      int i = 0;
      while(true)
      {
          arg += "running in thread " + tid + "for the " + i + "time";
          Console.WriteLine(arg);
      }
   }

This program while print in parallel the number of occurrences running in each thread with out effecting what was printed in the other thread.

Why ?

If you think about it string is a reference type, it is passed by reference and not by value, meaning it is not copied only a copy of the reference occurs.
And yet though it was initially the same object. after the first change it is no longer and a different one is created.
If it was still the same object after changes it would be a shared resource between the 2 threads and will disrupt the state those threads men't to print.


问:
Automation of localized language web app
I do not have any question but I need suggestions for my approach .
I am testing a web app which can be converted to a local language from English language and vice versa by selecting language from dropdown. I am using Selenium with Java to automate it. Because this is a first time I am doing this kind of automation so I search a lot on google. From google I found mostly ppl used an approach where they have generated a properties files and stored the local language characters into ASCII values. I need suggestion from all the senior members. The scenario which I am trying to achieve is I want to use the same script to run on English language as well as in local language without making any code change. Right now I am doing is reading english ascii values and comparing with english ascii values and if I have to execute it in chinese I read chinese ascii values and compare with expected chinese ascii values.
Here is my approach.
For UI validation:1. First I have generated a properties files which stores the converted local language characters to ASCII value (expectedValue). Secondly,  manually I have generated another expectedValue properties files and using google translator and other online app manually found the ASCII values. Lastly I ma reading expected and actual properties files using java and using selenium assert condition I am comparing the expectedValue and  actualValue to check if they are same. The only disadvantage (may be) is the expected and actual ascii properties file is growing pretty big but I did not find any solution to control the size.
For functional Testing (the dropdown values are in local language) here is my approach.
1. Suppose I have to create a certain type of user (certain type eg admin but admin text is in local language in dropdown). I am reading the input data from my json file and start sending to webform (in usual way sendKeys) and the place where I have to select the dropdown entry I am reading the local language admin ascii value from properties files and finding the web element by Pass by reference and selecting the data in local language from dropdown. Because this is the start of automation (localization) so I want to make all the improvements/changes in the initial stage of automation not in later stage where the cost to make a small change is very high. Please give you suggestions for my approach.</p>

答:
The first project I ever worked on as an automator involved this kind of scenario.  What we did was to store the expected (tested) text values in separate XML files, one for each language, but all using the same key values for lookup.  Then each story (we use JBehave BDD) would pass the site code as a parameter, which would determine the language, except int he case of Canada where it could be either English or French, so one file was stored for each language for that particular site.  Eventually for simplicity we merged all the XML files into one large one and just used the site/language parameter as another lookup key, but the effect was the same.

I hope this helps answer your question.


问:
Radio button not posting value to MySQL database
I have a form that is being updated by PHP to a MySQL database.  I have two radio buttons:

```<code><input type="radio" name="show_on_website" value="Y" /> Yes
<input type="radio" name="show_on_website" value="N" /> No
</code>```

Upon clicking on the Yes or No radio button and submitting the form, the value Y or N, depending on which is selected does not get submitted into the MySQL database.  All other data within the form is updating fine, just not the radio buttons.  I am using $show_on_website = $POST['show_on_website']; upon submitting the form.

What am I missing or doing wrong?  Thanks for any help you may provided.

答: use $_POST instead of $POST

Body:
I have a form that is being updated by PHP to a MySQL database.  I have two radio buttons:

<input type="radio" name="show_on_website" value="Y" /> Yes
<input type="radio" name="show_on_website" value="N" /> No

Upon clicking on the Yes or No radio button and submitting the form, the value Y or N, depending on which is selected does not get submitted into the MySQL database.  All other data within the form is updating fine, just not the radio buttons.  I am using $show_on_website = $POST['show_on_website']; upon submitting the form.

What am I missing or doing wrong?  Thanks for any help you may provided.

Body: use $_POST instead of $POST


问:
Print string while adding newlines
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

```<code><%= comment.body %>
</code>```

I want to do something like this so that it automatically prints everything with new lines

```<code><%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>
</code>```

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

```<code><% for i in 0..comment.body.length do %>
<%= i %>
<% end %>
</code>```

Thanks

答:
i'm not sure but it can help you some how

```<code><%=simple_format(comment.body, html_options={ class: 'your_class'}, options={})%>
</code>```

for more details and modification follow this

Title: Print string while adding newlines

Body:
I'm trying to print out a string with embedded ruby to a webpage, if I use the following it ends up going off of the page.

<%= comment.body %>

I want to do something like this so that it automatically prints everything with new lines

<%= comment.body[0..136] %>
<%= "\n" %>
<%= comment.body[137..250] %>

I've done the following however it prints the characters with spaces between them and ignores spaces in the string.

<% for i in 0..comment.body.length do %>
<%= i %>
<% end %>

Thanks

Body:
i'm not sure but it can help you some how

<%=simple_format(comment.body, html_options={ class: 'your_class'}, options={})%>

for more details and modification follow this


问:
redirecting stdin to file
I want to write a program that takes whatever I type in terminal and writes it to file. Here is the code that I wrote.

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int fd[2];
void pri(){
   char a[10];
   int ad=open("t.txt",O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
   if(read(fd[0],a,10)>0){
       write(ad,a,10);
   }
}
int main()
{
   int a;
   char s[10];
   pipe(fd);
   while(read(0,s,10)>0){
      write(fd[1],s,10);
      pri();
   }
   return 0;
}
</code>```

Currently I am using arrays and a pipe for achieving this. Is there any way that I can achieve the same without using any arrays?

答:
I want to write a program that takes whatever I type in terminal and writes it to file. => yes it's possible, use dup() or dup2() and close() system call accordingly.

```<code>char c;
int main(int argc,char *argv[])
{

        close(1);//so that it should not print anything on console
        int ad=open(argv[1],O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
        // now ad is available file descriptor which is 1
        if(ad == -1){
                perror("open");
                return 0;
        }
        while(read(0,&c,1)>0){
                write(ad,&c,1);
        //when you don't want to take any input further press ctrl+d that will first save the data
        }
        return 0;
}
</code>```

What's the need of using pipe for input redirection task I mean you just want to redirect user input into file So  pipe() is unnecessary if this is only task because you are not doing any kind of communication b/w child or parent process.

Title: redirecting stdin to file

Body:
I want to write a program that takes whatever I type in terminal and writes it to file. Here is the code that I wrote.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int fd[2];
void pri(){
   char a[10];
   int ad=open("t.txt",O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
   if(read(fd[0],a,10)>0){
       write(ad,a,10);
   }
}
int main()
{
   int a;
   char s[10];
   pipe(fd);
   while(read(0,s,10)>0){
      write(fd[1],s,10);
      pri();
   }
   return 0;
}

Currently I am using arrays and a pipe for achieving this. Is there any way that I can achieve the same without using any arrays?

Body:
I want to write a program that takes whatever I type in terminal and writes it to file. => yes it's possible, use dup() or dup2() and close() system call accordingly.

char c;
int main(int argc,char *argv[])
{

        close(1);//so that it should not print anything on console
        int ad=open(argv[1],O_CREAT | O_APPEND | O_NONBLOCK |  O_RDWR, 0644);
        // now ad is available file descriptor which is 1
        if(ad == -1){
                perror("open");
                return 0;
        }
        while(read(0,&c,1)>0){
                write(ad,&c,1);
        //when you don't want to take any input further press ctrl+d that will first save the data
        }
        return 0;
}

What's the need of using pipe for input redirection task I mean you just want to redirect user input into file So  pipe() is unnecessary if this is only task because you are not doing any kind of communication b/w child or parent process.


问:
Passing a list<string> into Linq
The first query returns a list of string, and I am passing them into another table to find corresponding items, but nothing happens. no error message or nothing</p>

```<code>var classIds = _contextSpecRepo.Get(x => x.cId.Equals(cId)).Select(x => x.classNames).Distinct().ToList();
// issue happens in the following query
var classes= Repository.Get(x => x.Id.Equals(classIds)).ToList();
</code>```

答:
you can also skip .ToList()</p>

```<code>var classes= Repository.Get(x => classIds.Contains(x.Id));
</code>```

Title: Passing a list<string> into Linq

Body:
The first query returns a list of string, and I am passing them into another table to find corresponding items, but nothing happens. no error message or nothing

var classIds = _contextSpecRepo.Get(x => x.cId.Equals(cId)).Select(x => x.classNames).Distinct().ToList();
// issue happens in the following query
var classes= Repository.Get(x => x.Id.Equals(classIds)).ToList();

Body:
you can also skip .ToList()

var classes= Repository.Get(x => classIds.Contains(x.Id));


问:
RecyclerView goes out of Sync
I have created a firebase chat. It uses a RecyclerView with CardViews to show the messages. I'm changing the CardView Gravity inside the OnBindViewHolder method of RecyclerView.Adapter, so the senders messages will be on one side and others in other side(WhatsApp).
Here is my code,

```<code>public void onBindViewHolder(ViewHolder holder, int position) {

        final MessageItem messageItem = messageItems.get(position);
        holder.name.setText(messageItem.getSenderName());
        holder.message.setText(messageItem.getMessage());

        if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
            holder.linearLayout.setGravity(Gravity.RIGHT);
        }

    }
</code>```

This works fine when loading the messages for the first time

But goes out of sync as i scroll though or send a new message

What could be the reason for this? I have tried updating the gravity inside onViewAttachedToWindow and onViewRecycled methods too.

答:
Try to change this code

```<code>if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
    holder.linearLayout.setGravity(Gravity.RIGHT);
}else{
    holder.linearLayout.setGravity(Gravity.LEFT);
}
</code>```

You need a to set a left gravity in else because recyclerview recycled view when you scroll

Title: RecyclerView goes out of Sync

Body:
I have created a firebase chat. It uses a RecyclerView with CardViews to show the messages. I'm changing the CardView Gravity inside the OnBindViewHolder method of RecyclerView.Adapter, so the senders messages will be on one side and others in other side(WhatsApp).
Here is my code,

public void onBindViewHolder(ViewHolder holder, int position) {

        final MessageItem messageItem = messageItems.get(position);
        holder.name.setText(messageItem.getSenderName());
        holder.message.setText(messageItem.getMessage());

        if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
            holder.linearLayout.setGravity(Gravity.RIGHT);
        }

    }

This works fine when loading the messages for the first time

But goes out of sync as i scroll though or send a new message

What could be the reason for this? I have tried updating the gravity inside onViewAttachedToWindow and onViewRecycled methods too.

Body:
Try to change this code

if(messageItem.getFrom() == new UserLocalStore(context).getUserDetails().getId()){
    holder.linearLayout.setGravity(Gravity.RIGHT);
}else{
    holder.linearLayout.setGravity(Gravity.LEFT);
}

You need a to set a left gravity in else because recyclerview recycled view when you scroll


问:
How do I sort array of pairs based on the greater value in first or second
```<code>bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    if (p1.first > p1.second || p1.second > p1.first) return true;
    else return false;
}
int main()
{
    pair<int, int> arr[4];
    arr[0].first = 4, arr[0].second = 10;
    arr[1].first = 7, arr[1].second = 6;
    arr[2].first = 3, arr[2].second = 8;
    arr[3].first = 9, arr[3].second = 1;

    sort(arr, arr + 4 , custome_compare);
    //---------------------------------------
    return 0;
}
</code>```

My goal to sort the array of pairs based on the greater value.

I don't care the greater value is the first or the second element in the pair.

For example i have this pairs:

4,10

7,6

3,8

9,1

After sort them :

4,10

9,1

3,8

7,6

So i'm not sorting based on first or second i sorting based on both.

How can I edit this compare function to do this task ?

Thanks in advance.

答:
The custom compare function should compare the max value of the pair(s). So something like:

```<code>bool custom_compare(pair<int, int> i, pair<int, int> j) { return max(i.first,
i.second) > max(j.first, j.second); }
</code>```

Not tested, nor tried to compile, but I hope you can work things out from here.

Body:
bool custome_compare(const pair<int, int>& p1, const pair<int, int>& p2){
    if (p1.first > p1.second || p1.second > p1.first) return true;
    else return false;
}
int main()
{
    pair<int, int> arr[4];
    arr[0].first = 4, arr[0].second = 10;
    arr[1].first = 7, arr[1].second = 6;
    arr[2].first = 3, arr[2].second = 8;
    arr[3].first = 9, arr[3].second = 1;

    sort(arr, arr + 4 , custome_compare);
    //---------------------------------------
    return 0;
}

My goal to sort the array of pairs based on the greater value.

I don't care the greater value is the first or the second element in the pair.

For example i have this pairs:

4,10

7,6

3,8

9,1

After sort them :

4,10

9,1

3,8

7,6

So i'm not sorting based on first or second i sorting based on both.

How can I edit this compare function to do this task ?

Thanks in advance.

Body:
The custom compare function should compare the max value of the pair(s). So something like:

bool custom_compare(pair<int, int> i, pair<int, int> j) { return max(i.first,
i.second) > max(j.first, j.second); }

Not tested, nor tried to compile, but I hope you can work things out from here.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
They can.  I spent many, many hours as a college freshman doing program correctness proofs.

The reason it's not practical on a macro scale is that writing a proof of a program tends to be a lot harder than writing the program.  Also, programmers today tend to build systems, not write functions or programs.

On a micro scale, I sometimes do it mentally for individual functions, and tend to organize my code to make them easy to verify.

There's a famous article about the space shuttle software.  They do proofs, or something equivalent.  It's incredibly costly and time-consuming.  That level of verification may be necessary for them, but for any kind of consumer or commercial software company, with current techniques, you'll get your lunch eaten by a competitor who delivers a 99.9% solution at 1% of the cost.  Nobody's going to pay $5000 for an MS Office that's marginally more stable.

Title: Why can't programs be proven?

OwnerDisplayName: Ken


问:
Rails - Method that returns a boolean. Sometimes turns blank
I want to create a method that returns true or false.

```<code>Rails.logger.info is_a_valid_email?(params[:user][:email])

if is_a_valid_email(params[:user][:email]) != true
  @user.errors.add :email, 'address is not valid.'
end

protected
</code>```

def is_a_valid_email?(email)

```<code>email_regex = %r{
  ^ # Start of string
  [0-9a-z] # First character
  [0-9a-z.+]+ # Middle characters
  [0-9a-z] # Last character
  @ # Separating @ character
  [0-9a-z] # Domain name begin
  [0-9a-z.-]+ # Domain name middle
  [0-9a-z] # Domain name end
  $ # End of string
}xi # Case insensitive

!( email =~ email_regex )

end
</code>```

For app related reasons I need to be able to validate in the controller and no the model. The above isn't working reliably. I want 'is_a_valid_email' to either return true or false, allowing me to then apply an error msg if false.

Suggestions? thxs

答:
You probably got a typo in your method call here:

```<code>if is_a_valid_email(params[:user][:email])
</code>```

You should add a question mark there:

```<code>if is_a_valid_email?(params[:user][:email])
</code>```

Also if you have to do validation in controller, you're probably doing something wrong.

Body:
I want to create a method that returns true or false.

Rails.logger.info is_a_valid_email?(params[:user][:email])

if is_a_valid_email(params[:user][:email]) != true
  @user.errors.add :email, 'address is not valid.'
end

protected

def is_a_valid_email?(email)

email_regex = %r{
  ^ # Start of string
  [0-9a-z] # First character
  [0-9a-z.+]+ # Middle characters
  [0-9a-z] # Last character
  @ # Separating @ character
  [0-9a-z] # Domain name begin
  [0-9a-z.-]+ # Domain name middle
  [0-9a-z] # Domain name end
  $ # End of string
}xi # Case insensitive

!( email =~ email_regex )

end

For app related reasons I need to be able to validate in the controller and no the model. The above isn't working reliably. I want 'is_a_valid_email' to either return true or false, allowing me to then apply an error msg if false.

Suggestions? thxs

Body:
You probably got a typo in your method call here:

if is_a_valid_email(params[:user][:email])

You should add a question mark there:

if is_a_valid_email?(params[:user][:email])

Also if you have to do validation in controller, you're probably doing something wrong.


问:
show wordpress post outside non wordpress php page
I need to display the wordpress blog posts in a non wordpress php page. I have tried the following code.

```<code><?php
// Include WordPress
define('WP_USE_THEMES', false);
//exact path for wp-load.php.
// This file is kept in the root of wordpress install
require('http://test.com/wordpress/blog/wp-load.php');
//Query wordpress for latest 4 posts
query_posts('showposts=5');
?>
<?php while (have_posts ()): the_post(); ?>
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>

<?php endwhile; ?>
</code>```

But it showed me the following error

```<code>Fatal error: Call to undefined function query_posts()
</code>```

How to fix this?

答:
After you include the wp-load.php you have to instantiate  the query like this:

```<code>$wp_query = new \WP_Query();
$wp_query->query('showposts=5');
</code>```

After that your loop should look like this:

```<code><?php while ($wp_query->have_posts()) :
    $wp_query->the_post();
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>

<?php endwhile; ?>
</code>```

Body:
I need to display the wordpress blog posts in a non wordpress php page. I have tried the following code.

<?php
// Include WordPress
define('WP_USE_THEMES', false);
//exact path for wp-load.php.
// This file is kept in the root of wordpress install
require('http://test.com/wordpress/blog/wp-load.php');
//Query wordpress for latest 4 posts
query_posts('showposts=5');
?>
<?php while (have_posts ()): the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_excerpt(); ?>

<?php endwhile; ?>

But it showed me the following error

Fatal error: Call to undefined function query_posts()

How to fix this?

Body:
After you include the wp-load.php you have to instantiate  the query like this:

$wp_query = new \WP_Query();
$wp_query->query('showposts=5');

After that your loop should look like this:

<?php while ($wp_query->have_posts()) :
    $wp_query->the_post();
    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>

<?php endwhile; ?>


问:
How to efficiently calculate multiple quantiles of column z when grouping by columns (x, y)
For example,

```<code>set.seed(2017)
dt <- data.table(
  x = sample(LETTERS, size = 10^7, replace = T),
  y = sample(LETTERS, size = 10^7, replace = T),
  z = sample(10^7, size = 10^7, replace = T)
)

          x y       z
       1: Y U 6830565
       2: N V 5063188
       3: M L 7551719
      ---
 9999998: C J 8951173
 9999999: C T 2265750
10000000: L B 1303897
</code>```

I would like to group by (x, y) and calculate multiple things regarding z.  This works,

```<code>system.time(
  result1 <- dt[, list(
    firstval = first(z),
    q1 = quantile(z, 0.5),
    q2 = quantile(z, 0.75),
    q3 = quantile(z, 0.9)
    ), keyby=list(x, y)]
)

     x y firstval      q1      q2      q3
  1: A A  4600349 4982000 7469398 8981072
  2: A B  9731616 4984859 7493566 9028473
  3: A C  3672771 5071190 7496436 8972589
 ---
674: Z X  1908196 5048164 7521350 9014482
675: Z Y  2933076 4985024 7500346 8977680
676: Z Z  6215175 5018085 7524220 9031993
</code>```

but is unnecessarily slow because each call to quantile is presumably re-ordering the same data.  I can vectorize this as follows

```<code>system.time(
  result2 <- dt[, list(
    firstval = first(z),
    quant = c(0.5, 0.75, 0.9),
    val = quantile(z, c(0.5, 0.75, 0.9))
  ), keyby=list(x, y)]
)

      x y firstval quant     val
   1: A A  4600349  0.50 4982000
   2: A A  4600349  0.75 7469398
   3: A A  4600349  0.90 8981072
  ---
2026: Z Z  6215175  0.50 5018085
2027: Z Z  6215175  0.75 7524220
2028: Z Z  6215175  0.90 9031993
</code>```

^^ this is faster but now my data is the wrong shape (and could be significantly, unnecessarily larger in size).  I can dcast the result to get what I want, but this is still memory inefficient.

How can I calculate the quantiles efficiently without transforming the shape of my data?  Ideally, I'm looking for something like

```<code>result3 <- dt[, c(
  list(firstval = first(z)),
  c("q1", "q2", "q3") = t(quantile(z, c(0.5, 0.75, 0.9)))
), keyby=list(x, y)]
</code>```

答:
@akrun already got a good solution, but you could also use code-block inside the data.table call:

```<code>system.time(
  result2b <- dt[, {
      the_quantiles = quantile(z, c(0.5, 0.75, 0.9))
      list(
        firstval = first(z),
        q1 = the_quantiles[1],
        q2 = the_quantiles[2],
        q3 = the_quantiles[3]
      )
    }, keyby=list(x, y)]
)
</code>```

Notice how the_quantiles are first computed in one call, and then a code very similar to your first solution is used.

Body:
For example,

set.seed(2017)
dt <- data.table(
  x = sample(LETTERS, size = 10^7, replace = T),
  y = sample(LETTERS, size = 10^7, replace = T),
  z = sample(10^7, size = 10^7, replace = T)
)

          x y       z
       1: Y U 6830565
       2: N V 5063188
       3: M L 7551719
      ---
 9999998: C J 8951173
 9999999: C T 2265750
10000000: L B 1303897

I would like to group by (x, y) and calculate multiple things regarding z.  This works,

system.time(
  result1 <- dt[, list(
    firstval = first(z),
    q1 = quantile(z, 0.5),
    q2 = quantile(z, 0.75),
    q3 = quantile(z, 0.9)
    ), keyby=list(x, y)]
)

     x y firstval      q1      q2      q3
  1: A A  4600349 4982000 7469398 8981072
  2: A B  9731616 4984859 7493566 9028473
  3: A C  3672771 5071190 7496436 8972589
 ---
674: Z X  1908196 5048164 7521350 9014482
675: Z Y  2933076 4985024 7500346 8977680
676: Z Z  6215175 5018085 7524220 9031993

but is unnecessarily slow because each call to quantile is presumably re-ordering the same data.  I can vectorize this as follows

system.time(
  result2 <- dt[, list(
    firstval = first(z),
    quant = c(0.5, 0.75, 0.9),
    val = quantile(z, c(0.5, 0.75, 0.9))
  ), keyby=list(x, y)]
)

      x y firstval quant     val
   1: A A  4600349  0.50 4982000
   2: A A  4600349  0.75 7469398
   3: A A  4600349  0.90 8981072
  ---
2026: Z Z  6215175  0.50 5018085
2027: Z Z  6215175  0.75 7524220
2028: Z Z  6215175  0.90 9031993

^^ this is faster but now my data is the wrong shape (and could be significantly, unnecessarily larger in size).  I can dcast the result to get what I want, but this is still memory inefficient.

How can I calculate the quantiles efficiently without transforming the shape of my data?  Ideally, I'm looking for something like

result3 <- dt[, c(
  list(firstval = first(z)),
  c("q1", "q2", "q3") = t(quantile(z, c(0.5, 0.75, 0.9)))
), keyby=list(x, y)]

Body:
@akrun already got a good solution, but you could also use code-block inside the data.table call:

system.time(
  result2b <- dt[, {
      the_quantiles = quantile(z, c(0.5, 0.75, 0.9))
      list(
        firstval = first(z),
        q1 = the_quantiles[1],
        q2 = the_quantiles[2],
        q3 = the_quantiles[3]
      )
    }, keyby=list(x, y)]
)

Notice how the_quantiles are first computed in one call, and then a code very similar to your first solution is used.


问:
Bot Framework - imBack or postBack message without buttons? Is it possible?
I am trying to display a card (or list of links ) to my Skype, Slack or Messenger users with some postBack actions.

Herocard works fine, they display the buttons with the text like in this example:

```<code>    IMessageActivity replyMessage = context.MakeMessage();
    replyMessage.Attachments.Add(
    new HeroCard
    {
        Subtitle = "Settings",
        Buttons = new List<CardAction> {
            new CardAction(ActionTypes.ImBack, $"Spell-check {spellcheckst}", value: $"Set Spell-check setting {spellcheckst}", text: $"Spell-check {spellcheckst}", displayText: $"Spell-check {spellcheckst}"),
            new CardAction(ActionTypes.ImBack, $"Small-talk {smalltalkst}", value: $"Set Small-talk setting {smalltalkst}", text: $"Small-talk {smalltalkst}", displayText: $"Small-talk {smalltalkst}")

        }
    }.ToAttachment()
    );
    await context.PostAsync(replyMessage);
</code>```

But buttons take a lot of screen real estate and many times their captions are truncated.

Is there a way to trigger a postBack or imBack card action without displaying buttons. Here is an example scenario, when the User asks for Help, the Bot displays list of commands:

Add a webpage Try Me

delete a webpage Try Me

Display help Try Me

etc.

The "Try Me" links would postBack to the bot exactly as the buttons above do.

Is this possible to do?

Thanks

答:
Using the buttons, you can set the title to the display text, and set the value to what you need to post back. Then you could have a little piece of text above the buttons that says something along the lines, "click any of the buttons to try".

I use this approach within messenger, to make my button text short, but the "payload" (or value) of the button set to a richer description. Next thing is, the value is not displayed to the user, but it is received by the framework within the channel data portion of the message activity.

Body:
I am trying to display a card (or list of links ) to my Skype, Slack or Messenger users with some postBack actions.

Herocard works fine, they display the buttons with the text like in this example:

    IMessageActivity replyMessage = context.MakeMessage();
    replyMessage.Attachments.Add(
    new HeroCard
    {
        Subtitle = "Settings",
        Buttons = new List<CardAction> {
            new CardAction(ActionTypes.ImBack, $"Spell-check {spellcheckst}", value: $"Set Spell-check setting {spellcheckst}", text: $"Spell-check {spellcheckst}", displayText: $"Spell-check {spellcheckst}"),
            new CardAction(ActionTypes.ImBack, $"Small-talk {smalltalkst}", value: $"Set Small-talk setting {smalltalkst}", text: $"Small-talk {smalltalkst}", displayText: $"Small-talk {smalltalkst}")

        }
    }.ToAttachment()
    );
    await context.PostAsync(replyMessage);

But buttons take a lot of screen real estate and many times their captions are truncated.

Is there a way to trigger a postBack or imBack card action without displaying buttons. Here is an example scenario, when the User asks for Help, the Bot displays list of commands:

Add a webpage Try Me

delete a webpage Try Me

Display help Try Me

etc.

The "Try Me" links would postBack to the bot exactly as the buttons above do.

Is this possible to do?

Thanks


问:
While writing records in a flat file using Informatica ETL job, greek characters are coming as boxes
While writing records in a flat file using Informatica ETL job, greek characters are coming as boxes.We can see original characters in the database.In session level, we are using UTF-8 encoding.We have a multi language application and need to process Chinese, Russian, Greek,Polish,Japanese etc. characters.Please suggest.</p>

答: try to change your page encoding. I also faced this kind of issue. We are using ANSII encoding, hence we created separate integration service with different encoding and file ran successfully.</p>


问:
Canonical way to parse the command line into arguments in plain C Windows API
In a Windows program, what is the canonical way to parse the command line obtained from GetCommandLine into multiple arguments, similar to the argv array in Unix?  It seems that CommandLineToArgvW does this for a Unicode command line, but I can't find a non-Unicode equivalent.  Should I be using Unicode or not?  If not, how do I parse the command line?</p>

答:
I followed the source for parse_cmd (see "argv_parsing.cpp" in the latest SDK) and modified it to match the paradigm and operation for CommandLineToArgW and developed the following. Note: instead of using LocalAlloc, per Microsoft recommendations  (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa366723(v=vs.85).aspx) I've substituted HeapAlloc. Additionally one change in the SAL notation. I deviate slightly be stating _In_opt_ for lpCmdLine - as CommandLineToArgvW does allow this to be NULL, in which case it returns an argument list containing just the program name.

A final caveat, parse_cmd will parse the command line slightly different from CommandLineToArgvW in one aspect only: two double quote characters in a row while the state is 'in quote' mode are interpreted as an escaped double quote character. Both functions consume the first one and output the second one. The difference is that for CommandLineToArgvW, there is a transition out of 'in quote' mode, while parse_cmdline remains in 'in quote' mode. This is properly reflected in the function below.

You would use the below function as follows:

int    argc  = 0;
 LPSTR *argv  = CommandLineToArgvA(GetCommandLineA(), &argc);
 HeapFree(GetProcessHeap(), NULL, argv);

```<code>LPSTR* CommandLineToArgvA(_In_opt_ LPCSTR lpCmdLine, _Out_ int *pNumArgs)
{
    if (!pNumArgs)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }
    *pNumArgs = 0;
    /*follow CommandLinetoArgvW and if lpCmdLine is NULL return the path to the executable.
    Use 'programname' so that we don't have to allocate MAX_PATH * sizeof(CHAR) for argv
    every time. Since this is ANSI the return can't be greater than MAX_PATH (260
    characters)*/
    CHAR programname[MAX_PATH] = {};
    /*pnlength = the length of the string that is copied to the buffer, in characters, not
    including the terminating null character*/
    DWORD pnlength = GetModuleFileNameA(NULL, programname, MAX_PATH);
    if (pnlength == 0) //error getting program name
    {
        //GetModuleFileNameA will SetLastError
        return NULL;
    }
    if (*lpCmdLine == NULL)
    {

        /*In keeping with CommandLineToArgvW the caller should make a single call to HeapFree
        to release the memory of argv. Allocate a single block of memory with space for two
        pointers (representing argv[0] and argv[1]). argv[0] will contain a pointer to argv+2
        where the actual program name will be stored. argv[1] will be nullptr per the C++
        specifications for argv. Hence space required is the size of a LPSTR (char*) multiplied
        by 2 [pointers] + the length of the program name (+1 for null terminating character)
        multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS flag,
        so if there is a failure on allocating memory an exception will be generated.*/
        LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),
            HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
            (sizeof(LPSTR) * 2) + ((pnlength + 1) * sizeof(CHAR))));
        memcpy(argv + 2, programname, pnlength+1); //add 1 for the terminating null character
        argv[0] = reinterpret_cast<LPSTR>(argv + 2);
        argv[1] = nullptr;
        *pNumArgs = 1;
        return argv;
    }
    /*We need to determine the number of arguments and the number of characters so that the
    proper amount of memory can be allocated for argv. Our argument count starts at 1 as the
    first "argument" is the program name even if there are no other arguments per specs.*/
    int argc        = 1;
    int numchars    = 0;
    LPCSTR templpcl = lpCmdLine;
    bool in_quotes  = false;  //'in quotes' mode is off (false) or on (true)
    /*first scan the program name and copy it. The handling is much simpler than for other
    arguments. Basically, whatever lies between the leading double-quote and next one, or a
    terminal null character is simply accepted. Fancier handling is not required because the
    program name must be a legal NTFS/HPFS file name. Note that the double-quote characters are
    not copied.*/
    do {
        if (*templpcl == '"')
        {
            //don't add " to character count
            in_quotes = !in_quotes;
            templpcl++; //move to next character
            continue;
        }
        ++numchars; //count character
        templpcl++; //move to next character
        if (_ismbblead(*templpcl) != 0) //handle MBCS
        {
            ++numchars;
            templpcl++; //skip over trail byte
        }
    } while (*templpcl != '\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\t')));
    //parsed first argument
    if (*templpcl == '\0')
    {
        /*no more arguments, rewind and the next for statement will handle*/
        templpcl--;
    }
    //loop through the remaining arguments
    int slashcount       = 0; //count of backslashes
    bool countorcopychar = true; //count the character or not
    for (;;)
    {
        if (*templpcl)
        {
            //next argument begins with next non-whitespace character
            while (*templpcl == ' ' || *templpcl == '\t')
                ++templpcl;
        }
        if (*templpcl == '\0')
            break; //end of arguments

        ++argc; //next argument - increment argument count
        //loop through this argument
        for (;;)
        {
            /*Rules:
              2N     backslashes   + " ==> N backslashes and begin/end quote
              2N + 1 backslashes   + " ==> N backslashes + literal "
              N      backslashes       ==> N backslashes*/
            slashcount     = 0;
            countorcopychar = true;
            while (*templpcl == '\\')
            {
                //count the number of backslashes for use below
                ++templpcl;
                ++slashcount;
            }
            if (*templpcl == '"')
            {
                //if 2N backslashes before, start/end quote, otherwise count.
                if (slashcount % 2 == 0) //even number of backslashes
                {
                    if (in_quotes && *(templpcl +1) == '"')
                    {
                        in_quotes = !in_quotes; //NB: parse_cmdline omits this line
                        templpcl++; //double quote inside quoted string
                    }
                    else
                    {
                        //skip first quote character and count second
                        countorcopychar = false;
                        in_quotes = !in_quotes;
                    }
                }
                slashcount /= 2;
            }
            //count slashes
            while (slashcount--)
            {
                ++numchars;
            }
            if (*templpcl == '\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\t')))
            {
                //at the end of the argument - break
                break;
            }
            if (countorcopychar)
            {
                if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
                {
                    ++templpcl; //skip over trail byte
                    ++numchars;
                }
                ++numchars;
            }
            ++templpcl;
        }
        //add a count for the null-terminating character
        ++numchars;
    }
    /*allocate memory for argv. Allocate a single block of memory with space for argc number of
    pointers. argv[0] will contain a pointer to argv+argc where the actual program name will be
    stored. argv[argc] will be nullptr per the C++ specifications. Hence space required is the
    size of a LPSTR (char*) multiplied by argc + 1 pointers + the number of characters counted
    above multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS
    flag, so if there is a failure on allocating memory an exception will be generated.*/
    LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),
        HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
        (sizeof(LPSTR) * (argc+1)) + (numchars * sizeof(CHAR))));
    //now loop through the commandline again and split out arguments
    in_quotes      = false;
    templpcl       = lpCmdLine;
    argv[0]        = reinterpret_cast<LPSTR>(argv + argc+1);
    LPSTR tempargv = reinterpret_cast<LPSTR>(argv + argc+1);
    do {
        if (*templpcl == '"')
        {
            in_quotes = !in_quotes;
            templpcl++; //move to next character
            continue;
        }
        *tempargv++ = *templpcl;
        templpcl++; //move to next character
        if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
        {
            *tempargv++ = *templpcl; //copy second byte
            templpcl++; //skip over trail byte
        }
    } while (*templpcl != '\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\t')));
    //parsed first argument
    if (*templpcl == '\0')
    {
        //no more arguments, rewind and the next for statement will handle
        templpcl--;
    }
    else
    {
        //end of program name - add null terminator
        *tempargv = '\0';
    }
    int currentarg   = 1;
    argv[currentarg] = ++tempargv;
    //loop through the remaining arguments
    slashcount      = 0; //count of backslashes
    countorcopychar = true; //count the character or not
    for (;;)
    {
        if (*templpcl)
        {
            //next argument begins with next non-whitespace character
            while (*templpcl == ' ' || *templpcl == '\t')
                ++templpcl;
        }
        if (*templpcl == '\0')
            break; //end of arguments
        argv[currentarg] = ++tempargv; //copy address of this argument string
        //next argument - loop through it's characters
        for (;;)
        {
            /*Rules:
              2N     backslashes   + " ==> N backslashes and begin/end quote
              2N + 1 backslashes   + " ==> N backslashes + literal "
              N      backslashes       ==> N backslashes*/
            slashcount      = 0;
            countorcopychar = true;
            while (*templpcl == '\\')
            {
                //count the number of backslashes for use below
                ++templpcl;
                ++slashcount;
            }
            if (*templpcl == '"')
            {
                //if 2N backslashes before, start/end quote, otherwise copy literally.
                if (slashcount % 2 == 0) //even number of backslashes
                {
                    if (in_quotes && *(templpcl+1) == '"')
                    {
                        in_quotes = !in_quotes; //NB: parse_cmdline omits this line
                        templpcl++; //double quote inside quoted string
                    }
                    else
                    {
                        //skip first quote character and count second
                        countorcopychar = false;
                        in_quotes       = !in_quotes;
                    }
                }
                slashcount /= 2;
            }
            //copy slashes
            while (slashcount--)
            {
                *tempargv++ = '\\';
            }
            if (*templpcl == '\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\t')))
            {
                //at the end of the argument - break
                break;
            }
            if (countorcopychar)
            {
                *tempargv++ = *templpcl;
                if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
                {
                    ++templpcl; //skip over trail byte
                    *tempargv++ = *templpcl;
                }
            }
            ++templpcl;
        }
        //null-terminate the argument
        *tempargv = '\0';
        ++currentarg;
    }
    argv[argc] = nullptr;
    *pNumArgs = argc;
    return argv;
}
</code>```

OwnerDisplayName: debeige

Body:
I followed the source for parse_cmd (see "argv_parsing.cpp" in the latest SDK) and modified it to match the paradigm and operation for CommandLineToArgW and developed the following. Note: instead of using LocalAlloc, per Microsoft recommendations  (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa366723(v=vs.85).aspx) I've substituted HeapAlloc. Additionally one change in the SAL notation. I deviate slightly be stating _In_opt_ for lpCmdLine - as CommandLineToArgvW does allow this to be NULL, in which case it returns an argument list containing just the program name.

A final caveat, parse_cmd will parse the command line slightly different from CommandLineToArgvW in one aspect only: two double quote characters in a row while the state is 'in quote' mode are interpreted as an escaped double quote character. Both functions consume the first one and output the second one. The difference is that for CommandLineToArgvW, there is a transition out of 'in quote' mode, while parse_cmdline remains in 'in quote' mode. This is properly reflected in the function below.

You would use the below function as follows:

int    argc  = 0;
 LPSTR *argv  = CommandLineToArgvA(GetCommandLineA(), &argc);
 HeapFree(GetProcessHeap(), NULL, argv);

LPSTR* CommandLineToArgvA(_In_opt_ LPCSTR lpCmdLine, _Out_ int *pNumArgs)
{
    if (!pNumArgs)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return NULL;
    }
    *pNumArgs = 0;
    /*follow CommandLinetoArgvW and if lpCmdLine is NULL return the path to the executable.
    Use 'programname' so that we don't have to allocate MAX_PATH * sizeof(CHAR) for argv
    every time. Since this is ANSI the return can't be greater than MAX_PATH (260
    characters)*/
    CHAR programname[MAX_PATH] = {};
    /*pnlength = the length of the string that is copied to the buffer, in characters, not
    including the terminating null character*/
    DWORD pnlength = GetModuleFileNameA(NULL, programname, MAX_PATH);
    if (pnlength == 0) //error getting program name
    {
        //GetModuleFileNameA will SetLastError
        return NULL;
    }
    if (*lpCmdLine == NULL)
    {

        /*In keeping with CommandLineToArgvW the caller should make a single call to HeapFree
        to release the memory of argv. Allocate a single block of memory with space for two
        pointers (representing argv[0] and argv[1]). argv[0] will contain a pointer to argv+2
        where the actual program name will be stored. argv[1] will be nullptr per the C++
        specifications for argv. Hence space required is the size of a LPSTR (char*) multiplied
        by 2 [pointers] + the length of the program name (+1 for null terminating character)
        multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS flag,
        so if there is a failure on allocating memory an exception will be generated.*/
        LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),
            HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
            (sizeof(LPSTR) * 2) + ((pnlength + 1) * sizeof(CHAR))));
        memcpy(argv + 2, programname, pnlength+1); //add 1 for the terminating null character
        argv[0] = reinterpret_cast<LPSTR>(argv + 2);
        argv[1] = nullptr;
        *pNumArgs = 1;
        return argv;
    }
    /*We need to determine the number of arguments and the number of characters so that the
    proper amount of memory can be allocated for argv. Our argument count starts at 1 as the
    first "argument" is the program name even if there are no other arguments per specs.*/
    int argc        = 1;
    int numchars    = 0;
    LPCSTR templpcl = lpCmdLine;
    bool in_quotes  = false;  //'in quotes' mode is off (false) or on (true)
    /*first scan the program name and copy it. The handling is much simpler than for other
    arguments. Basically, whatever lies between the leading double-quote and next one, or a
    terminal null character is simply accepted. Fancier handling is not required because the
    program name must be a legal NTFS/HPFS file name. Note that the double-quote characters are
    not copied.*/
    do {
        if (*templpcl == '"')
        {
            //don't add " to character count
            in_quotes = !in_quotes;
            templpcl++; //move to next character
            continue;
        }
        ++numchars; //count character
        templpcl++; //move to next character
        if (_ismbblead(*templpcl) != 0) //handle MBCS
        {
            ++numchars;
            templpcl++; //skip over trail byte
        }
    } while (*templpcl != '\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\t')));
    //parsed first argument
    if (*templpcl == '\0')
    {
        /*no more arguments, rewind and the next for statement will handle*/
        templpcl--;
    }
    //loop through the remaining arguments
    int slashcount       = 0; //count of backslashes
    bool countorcopychar = true; //count the character or not
    for (;;)
    {
        if (*templpcl)
        {
            //next argument begins with next non-whitespace character
            while (*templpcl == ' ' || *templpcl == '\t')
                ++templpcl;
        }
        if (*templpcl == '\0')
            break; //end of arguments

        ++argc; //next argument - increment argument count
        //loop through this argument
        for (;;)
        {
            /*Rules:
              2N     backslashes   + " ==> N backslashes and begin/end quote
              2N + 1 backslashes   + " ==> N backslashes + literal "
              N      backslashes       ==> N backslashes*/
            slashcount     = 0;
            countorcopychar = true;
            while (*templpcl == '\\')
            {
                //count the number of backslashes for use below
                ++templpcl;
                ++slashcount;
            }
            if (*templpcl == '"')
            {
                //if 2N backslashes before, start/end quote, otherwise count.
                if (slashcount % 2 == 0) //even number of backslashes
                {
                    if (in_quotes && *(templpcl +1) == '"')
                    {
                        in_quotes = !in_quotes; //NB: parse_cmdline omits this line
                        templpcl++; //double quote inside quoted string
                    }
                    else
                    {
                        //skip first quote character and count second
                        countorcopychar = false;
                        in_quotes = !in_quotes;
                    }
                }
                slashcount /= 2;
            }
            //count slashes
            while (slashcount--)
            {
                ++numchars;
            }
            if (*templpcl == '\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\t')))
            {
                //at the end of the argument - break
                break;
            }
            if (countorcopychar)
            {
                if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
                {
                    ++templpcl; //skip over trail byte
                    ++numchars;
                }
                ++numchars;
            }
            ++templpcl;
        }
        //add a count for the null-terminating character
        ++numchars;
    }
    /*allocate memory for argv. Allocate a single block of memory with space for argc number of
    pointers. argv[0] will contain a pointer to argv+argc where the actual program name will be
    stored. argv[argc] will be nullptr per the C++ specifications. Hence space required is the
    size of a LPSTR (char*) multiplied by argc + 1 pointers + the number of characters counted
    above multiplied by the sizeof CHAR. HeapAlloc is called with HEAP_GENERATE_EXCEPTIONS
    flag, so if there is a failure on allocating memory an exception will be generated.*/
    LPSTR *argv = static_cast<LPSTR*>(HeapAlloc(GetProcessHeap(),
        HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
        (sizeof(LPSTR) * (argc+1)) + (numchars * sizeof(CHAR))));
    //now loop through the commandline again and split out arguments
    in_quotes      = false;
    templpcl       = lpCmdLine;
    argv[0]        = reinterpret_cast<LPSTR>(argv + argc+1);
    LPSTR tempargv = reinterpret_cast<LPSTR>(argv + argc+1);
    do {
        if (*templpcl == '"')
        {
            in_quotes = !in_quotes;
            templpcl++; //move to next character
            continue;
        }
        *tempargv++ = *templpcl;
        templpcl++; //move to next character
        if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
        {
            *tempargv++ = *templpcl; //copy second byte
            templpcl++; //skip over trail byte
        }
    } while (*templpcl != '\0' && (in_quotes || (*templpcl != ' ' && *templpcl != '\t')));
    //parsed first argument
    if (*templpcl == '\0')
    {
        //no more arguments, rewind and the next for statement will handle
        templpcl--;
    }
    else
    {
        //end of program name - add null terminator
        *tempargv = '\0';
    }
    int currentarg   = 1;
    argv[currentarg] = ++tempargv;
    //loop through the remaining arguments
    slashcount      = 0; //count of backslashes
    countorcopychar = true; //count the character or not
    for (;;)
    {
        if (*templpcl)
        {
            //next argument begins with next non-whitespace character
            while (*templpcl == ' ' || *templpcl == '\t')
                ++templpcl;
        }
        if (*templpcl == '\0')
            break; //end of arguments
        argv[currentarg] = ++tempargv; //copy address of this argument string
        //next argument - loop through it's characters
        for (;;)
        {
            /*Rules:
              2N     backslashes   + " ==> N backslashes and begin/end quote
              2N + 1 backslashes   + " ==> N backslashes + literal "
              N      backslashes       ==> N backslashes*/
            slashcount      = 0;
            countorcopychar = true;
            while (*templpcl == '\\')
            {
                //count the number of backslashes for use below
                ++templpcl;
                ++slashcount;
            }
            if (*templpcl == '"')
            {
                //if 2N backslashes before, start/end quote, otherwise copy literally.
                if (slashcount % 2 == 0) //even number of backslashes
                {
                    if (in_quotes && *(templpcl+1) == '"')
                    {
                        in_quotes = !in_quotes; //NB: parse_cmdline omits this line
                        templpcl++; //double quote inside quoted string
                    }
                    else
                    {
                        //skip first quote character and count second
                        countorcopychar = false;
                        in_quotes       = !in_quotes;
                    }
                }
                slashcount /= 2;
            }
            //copy slashes
            while (slashcount--)
            {
                *tempargv++ = '\\';
            }
            if (*templpcl == '\0' || (!in_quotes && (*templpcl == ' ' || *templpcl == '\t')))
            {
                //at the end of the argument - break
                break;
            }
            if (countorcopychar)
            {
                *tempargv++ = *templpcl;
                if (_ismbblead(*templpcl) != 0) //should copy another character for MBCS
                {
                    ++templpcl; //skip over trail byte
                    *tempargv++ = *templpcl;
                }
            }
            ++templpcl;
        }
        //null-terminate the argument
        *tempargv = '\0';
        ++currentarg;
    }
    argv[argc] = nullptr;
    *pNumArgs = argc;
    return argv;
}


问:
Class inside dict - Django template
Probably a simple question but I've searched for a while and haven't been able to find an answer for how to cycle through all of the items in my dictionary and call the class items inside of the template

I've tried using custom template tags, but the syntax doesn't seem to line up with what I'd like.

Here is my code:

```<code>data = [[OrderedDict([('token', 'XXXXXXXXXXXXXXX'), ('devices', [['Christmas Lights', 'XXXXXXXXXX'], ['Gold Beedrom Lamp', 'XXXXXXXX']])])], [[['5', 'off', 124], ['6', 'off', 124], ['7', 'off', 100], ['8', 'off', 124]]]]

#Dictionary and Class assignment

class LightStatus:
      def __init__(self,id):
          self.id = id
          self.state = None
          self.bri = None
      def add_data(self,id,state,bri):
          self.id = id
          self.state = state
          self.bri = bri

AllLights = dict()
for i in data[1]:
    for light in i:
        id = light[0]
        state = light[1]
        bri = light[2]
        AllLights[id] = LightStatus(id)
        AllLights[id].add_data(id,state,bri)
</code>```

What I'd like to have in template:

```<code>#What I want to do in the template
for i in AllLights:
    print(AllLights[i].id)
    print(AllLights[i].state)
    print(AllLights[i].bri)
return render(request, 'file.html', 'lights': AllLights)

#What I've tried
{% for light in lights %}
    {% for i in light %}
       {{lights.light.id}} #light being the variable from above.
    {% endfor %}
{% endfor %}
</code>```

I've also tried using a custom template tag:

```<code>from django import template
register = template.Library()

@register.filter
def lights(LightDict, i):
    return LightDict[int(i)]
#template
{{ AllLights|lights.forloop.counter0 }}
</code>```

To summarize what I'd like to do. I'd like to pass the AllLights dict to my template and then cycle through all of the keys and call id,state, and bri for each key.

Update:

Someone asks what happens when I print(AllLights) before render:

```<code>{'5': <dashboard.views.LightStatus object at 0x106f016a0>, '6': <dashboard.views.LightStatus object at 0x106f01320>, '7': <dashboard.views.LightStatus object at 0x106f01ac8>, '8': <dashboard.views.LightStatus object at 0x106f014e0>}
</code>```

答:
You're (correctly) using an ordered dict to maintain order, so assuming the order in that dict is the desired order you should be able to just iterate over your ordered dict's values in your template:

```<code>{% for light in all_lights.values %}
  {{ light.id }}
  {{ light.state }}
  {{ light.bri }}
{% endfor %}
</code>```

Title: Class inside dict - Django template

Body:
Probably a simple question but I've searched for a while and haven't been able to find an answer for how to cycle through all of the items in my dictionary and call the class items inside of the template

I've tried using custom template tags, but the syntax doesn't seem to line up with what I'd like.

Here is my code:

data = [[OrderedDict([('token', 'XXXXXXXXXXXXXXX'), ('devices', [['Christmas Lights', 'XXXXXXXXXX'], ['Gold Beedrom Lamp', 'XXXXXXXX']])])], [[['5', 'off', 124], ['6', 'off', 124], ['7', 'off', 100], ['8', 'off', 124]]]]

#Dictionary and Class assignment

class LightStatus:
      def __init__(self,id):
          self.id = id
          self.state = None
          self.bri = None
      def add_data(self,id,state,bri):
          self.id = id
          self.state = state
          self.bri = bri

AllLights = dict()
for i in data[1]:
    for light in i:
        id = light[0]
        state = light[1]
        bri = light[2]
        AllLights[id] = LightStatus(id)
        AllLights[id].add_data(id,state,bri)

What I'd like to have in template:

#What I want to do in the template
for i in AllLights:
    print(AllLights[i].id)
    print(AllLights[i].state)
    print(AllLights[i].bri)
return render(request, 'file.html', 'lights': AllLights)

#What I've tried
{% for light in lights %}
    {% for i in light %}
       {{lights.light.id}} #light being the variable from above.
    {% endfor %}
{% endfor %}

I've also tried using a custom template tag:

from django import template
register = template.Library()

@register.filter
def lights(LightDict, i):
    return LightDict[int(i)]
#template
{{ AllLights|lights.forloop.counter0 }}

To summarize what I'd like to do. I'd like to pass the AllLights dict to my template and then cycle through all of the keys and call id,state, and bri for each key.

Update:

Someone asks what happens when I print(AllLights) before render:

{'5': <dashboard.views.LightStatus object at 0x106f016a0>, '6': <dashboard.views.LightStatus object at 0x106f01320>, '7': <dashboard.views.LightStatus object at 0x106f01ac8>, '8': <dashboard.views.LightStatus object at 0x106f014e0>}

Body:
You're (correctly) using an ordered dict to maintain order, so assuming the order in that dict is the desired order you should be able to just iterate over your ordered dict's values in your template:

{% for light in all_lights.values %}
  {{ light.id }}
  {{ light.state }}
  {{ light.bri }}
{% endfor %}


问:
hide() show() jquery
I'm using the following:

$('#info').click(function (){
$('#message').fadeIn(200).show();
return false;
});

How could I change my script so that it would dissapear once clicked apon again?

Tried .fadeout().hide()

But it only show/hide so fast it looks as though nothing is happening.

答:
You could try:

```<code>$('#info').click(
    function(){
       $('#message').toggle();
       return false;
    });
</code>```

Using jQuery's toggle().

Edited to change from plain ol' toggle() to the slightly more in-keeping with the question fadeToggle():

```<code>$('#info').click(
    function(){
        $('#message').fadeToggle(400);
        return false;
    });
</code>```

JS Fiddle demo, featuring fadeToggle().

There is, of course, also slideToggle(), which may be used similarly.

Title: hide() show() jquery

Body:
You could try:

$('#info').click(
    function(){
       $('#message').toggle();
       return false;
    });

Using jQuery's toggle().

Edited to change from plain ol' toggle() to the slightly more in-keeping with the question fadeToggle():

$('#info').click(
    function(){
        $('#message').fadeToggle(400);
        return false;
    });

JS Fiddle demo, featuring fadeToggle().

There is, of course, also slideToggle(), which may be used similarly.


问:
Static Content in NancyFX with ASP.Net Core
I'm using Nancy 2.0.0 with ASP.Net Core 2.0.0 and I can't get my application to return static content (in this case, a zip file) from a route defined in a Nancy module.

The Nancy convention is to store static content in /Content and the ASP.Net Core convention is to store it in /wwwroot, but I can't get my app to recognize either.

My Startup.Configure method looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
    app.UseOwin(b => b.UseNancy());
}
```

<p>And my module route looks like this:</p>

<pre class="lang-cs prettyprint-override"><code>Get("/big_file", _ => {
    return Response.AsFile("wwwroot/test.zip");
});
</code>```

But Nancy always returns a 404 when I hit this route. I've also tried directing ASP.Net Core to the static directory expected by Nancy, like this:

```<code>app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Content")),
    RequestPath = new PathString("/Content")
});
</code>```

But this didn't work either. I've tried putting the file in /Content and in /wwwroot with the same result. And I've tried different casing of Content, but nothing seems to work. What am I missing?

答:
I figured it out. The issue was that I needed to let Nancy know what I wanted to use as the root path for the application. I did this by creating a class that inherits from IRootPathProvider. Nancy will discover any class that inherits from this on Startup, so you can put it wherever you want.

```<code>public class DemoRootPathProvider : IRootPathProvider
{
  public string GetRootPath()
  {
    return Directory.GetCurrentDirectory();
  }
}
</code>```

Once this was in place I was able to access static content in /Content. Additionally, I was able to add additional static directories (for example, if I wanted to stick with /wwwroot) by adding a class that inherits from DefaultNancyBootstrapper. Again, Nancy will find this on Startup, so you can put it anywhere.

```<code>public class DemoBootstrapper : DefaultNancyBootstrapper
{
  protected override void ConfigureConventions(NancyConventions conventions)
  {
    base.ConfigureConventions(conventions);

    conventions.StaticContentsConventions.Add(
        StaticContentConventionBuilder.AddDirectory("wwwroot")
    );
  }
}
</code>```

Body:
I'm using Nancy 2.0.0 with ASP.Net Core 2.0.0 and I can't get my application to return static content (in this case, a zip file) from a route defined in a Nancy module.

The Nancy convention is to store static content in /Content and the ASP.Net Core convention is to store it in /wwwroot, but I can't get my app to recognize either.

My Startup.Configure method looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
    app.UseOwin(b => b.UseNancy());
}

And my module route looks like this:

Get("/big_file", _ => {
    return Response.AsFile("wwwroot/test.zip");
});

But Nancy always returns a 404 when I hit this route. I've also tried directing ASP.Net Core to the static directory expected by Nancy, like this:

app.UseStaticFiles(new StaticFileOptions()
{
    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Content")),
    RequestPath = new PathString("/Content")
});

But this didn't work either. I've tried putting the file in /Content and in /wwwroot with the same result. And I've tried different casing of Content, but nothing seems to work. What am I missing?

Body:
I figured it out. The issue was that I needed to let Nancy know what I wanted to use as the root path for the application. I did this by creating a class that inherits from IRootPathProvider. Nancy will discover any class that inherits from this on Startup, so you can put it wherever you want.

public class DemoRootPathProvider : IRootPathProvider
{
  public string GetRootPath()
  {
    return Directory.GetCurrentDirectory();
  }
}

Once this was in place I was able to access static content in /Content. Additionally, I was able to add additional static directories (for example, if I wanted to stick with /wwwroot) by adding a class that inherits from DefaultNancyBootstrapper. Again, Nancy will find this on Startup, so you can put it anywhere.

public class DemoBootstrapper : DefaultNancyBootstrapper
{
  protected override void ConfigureConventions(NancyConventions conventions)
  {
    base.ConfigureConventions(conventions);

    conventions.StaticContentsConventions.Add(
        StaticContentConventionBuilder.AddDirectory("wwwroot")
    );
  }
}


问:
Does dropout layer go before or after dense layer in TensorFlow?
According to A Guide to TF Layers the dropout layer goes after the last dense layer:

dense = tf.layers.dense(input, units=1024, activation=tf.nn.relu)
dropout = tf.layers.dropout(dense, rate=params['dropout_rate'],
                            training=mode == tf.estimator.ModeKeys.TRAIN)
logits = tf.layers.dense(dropout, units=params['output_classes'])
```

<p>Doesn't it make more sense to have it <em>before</em> that dense layer, so it learns the mapping from input to output with the dropout effect?</p>

<pre class="lang-python prettyprint-override"><code>dropout = tf.layers.dropout(prev_layer, rate=params['dropout_rate'],
                            training=mode ==
dense = tf.layers.dense(dropout, units=1024, activation=tf.nn.relu)
logits = tf.layers.dense(dense, units=params['output_classes'])
</code>```

答:
It is not an either/or situation. Informally speaking, common wisdom says to apply dropout after dense layers, and not so much after convolutional or pooling ones, so at first glance that would depend on what exactly the prev_layer is in your second code snippet.

Nevertheless, this "design principle" is routinely violated nowadays (see some interesting relevant discussions in Reddit & CrossValidated); even in the MNIST CNN example included in Keras, we can see that dropout is applied both after the max pooling layer and after the dense one:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25)) # <-- dropout here
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))  # <-- and here
model.add(Dense(num_classes, activation='softmax'))
```
<p>So, both your code snippets are valid, and we can easily imagine a third valid option as well:</p>
<pre class="lang-python prettyprint-override"><code>dropout = tf.layers.dropout(prev_layer, [...])
dense = tf.layers.dense(dropout, units=1024, activation=tf.nn.relu)
dropout2 = tf.layers.dropout(dense, [...])
logits = tf.layers.dense(dropout2, units=params['output_classes'])
</code>```

As a general advice: tutorials such the one you link to are only trying to get you familiar with the tools and the (very) general principles, so "overinterpreting" the solutions shown is not recommended...

Body:
According to A Guide to TF Layers the dropout layer goes after the last dense layer:

dense = tf.layers.dense(input, units=1024, activation=tf.nn.relu)
dropout = tf.layers.dropout(dense, rate=params['dropout_rate'],
                            training=mode == tf.estimator.ModeKeys.TRAIN)
logits = tf.layers.dense(dropout, units=params['output_classes'])

Doesn't it make more sense to have it before that dense layer, so it learns the mapping from input to output with the dropout effect?

dropout = tf.layers.dropout(prev_layer, rate=params['dropout_rate'],
                            training=mode ==
dense = tf.layers.dense(dropout, units=1024, activation=tf.nn.relu)
logits = tf.layers.dense(dense, units=params['output_classes'])

Body:
It is not an either/or situation. Informally speaking, common wisdom says to apply dropout after dense layers, and not so much after convolutional or pooling ones, so at first glance that would depend on what exactly the prev_layer is in your second code snippet.

Nevertheless, this "design principle" is routinely violated nowadays (see some interesting relevant discussions in Reddit & CrossValidated); even in the MNIST CNN example included in Keras, we can see that dropout is applied both after the max pooling layer and after the dense one:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25)) # <-- dropout here
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))  # <-- and here
model.add(Dense(num_classes, activation='softmax'))

So, both your code snippets are valid, and we can easily imagine a third valid option as well:

dropout = tf.layers.dropout(prev_layer, [...])
dense = tf.layers.dense(dropout, units=1024, activation=tf.nn.relu)
dropout2 = tf.layers.dropout(dense, [...])
logits = tf.layers.dense(dropout2, units=params['output_classes'])

As a general advice: tutorials such the one you link to are only trying to get you familiar with the tools and the (very) general principles, so "overinterpreting" the solutions shown is not recommended...

ContentLicense: CC BY-SA 4.0


问:
What is the exact chain of events when GNU make updates the .d files?
Consider the following simple makefile:

```<code>#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)
</code>```

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

```<code>main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o
</code>```

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

```<code>#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)
</code>```

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)

答:
I'll answer both questions together as it makes more sense.

Make has no built-in rule for .d - it doesn't need one. -MMD -MP instructs the compiler to output dependencies as part of compilation proper.

If you think about it this is exactly what you want, as the only time you need to update a dependency file is if the relative source file has changed itself, if dependencies are generated during compilation you only need to run the compiler once to generate both the .d and .o files.

The last piece of the puzzle is -include which tells make to include dependencies if it can find them but not to worry if they aren't present, they'll be generated anyway by the compiler.

Body:
Consider the following simple makefile:

#------------------------------#
#    List all object files     #
#------------------------------#
objects := main.o foo.o bar.o baz.o

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

If you give the command make all, GNU make will start at the target myApp.elf. It looks at all the prerequisites main.o, foo.o, bar.o and baz.o and attempts to update them.

To do that, make uses the pattern rule defined in the middle of the makefile. This pattern rule expands like this:

main.o: main.c
    $(CC) -c $(CFLAGS) main.c -o main.o

foo.o: foo.c
    $(CC) -c $(CFLAGS) foo.c -o foo.o

bar.o: bar.c
    $(CC) -c $(CFLAGS) bar.c -o bar.o

baz.o: baz.c
    $(CC) -c $(CFLAGS) baz.c -o baz.o

So far, so good. But you can clearly see that dependencies (included h-files) are missing.

I found some sources that recommend the following approach:

#------------------------------#
#    List all object files     #
#    and all dependency files  #
#------------------------------#
objects := main.o foo.o bar.o baz.o
deps := $(objects:.o=.d)

#------------------------------#
#    Define pattern rule       #
#    for   *.c -> *.o          #
#------------------------------#
%.o: %.c
    $(CC) -c $(CFLAGS) -MMD -MP $< -o $@

#------------------------------#
#    Define the rule to make   #
#    the end result            #
#------------------------------#
.PHONY all
all: myApp.elf

myApp.elf: $(objects)
    $(CC) $(objects) -o myApp.elf $(LFLAGS) $(LIBS)

-include $(deps)

I'm trying to wrap my head around this approach. First GNU make reads the makefile and looks for other included makefiles (see GNU make manual paragraph 3.5 "How Makefiles Are Remade"). Make attempts to update each included makefile it can find (in this case the dependency files main.d, foo.d, bar.d and baz.d) before starting execution of the makefiles. I've summarized this in the following figure:

Exactly. I don't see any rule where the dependency files are specified as targets.

Please help me to understand what actually happens next. Please, write your answer as a step-by-step chain of events. That would be great to gain insight in the matter.

Note:

Of course, the -MMD and -MP arguments in the compilation command (see pattern rule in the middle) lead to dependency files getting created. But the targets of this pattern rule are the object-files, not the dependency-files.

Note:

I had wrongly assumed that GNU make has an implicit rule getting activated here. But thanks to your comments and answers, I now know this was wrong :-)


问:
PanGesture and some basic math
I'd like to calculate a percentage from 0-100 based on where the user "pans" the screen. If it's at the most bottom, 0%. If it's at the most top, 100%. I need this for an opacity sliding feature. A user can change the opacity of the screen by sliding, where the bottom most sets the screen to invisible while the top most sets it to brightest, 100%.

```<code>- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer{
    CGPoint translation = [recognizer translationInView:self.view];
    NSLog(@"Translation: %f", translation.x);
}
</code>```

I'm pretty sure I'm looking at converting translation.x to a percetange but it's confusing.

答: translation:in: give you the cumulative movement since the beginning location of the touch.  It sounds like what you are after is the touch location relative to the view's bounds and for that you should use location:in: instead.  this value .y divied by view.bounds.size.height will give you the relative distance down the screen with 0 at the top and 1 at the bottom,</p>

Title: PanGesture and some basic math

Body:
I'd like to calculate a percentage from 0-100 based on where the user "pans" the screen. If it's at the most bottom, 0%. If it's at the most top, 100%. I need this for an opacity sliding feature. A user can change the opacity of the screen by sliding, where the bottom most sets the screen to invisible while the top most sets it to brightest, 100%.

- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer{
    CGPoint translation = [recognizer translationInView:self.view];
    NSLog(@"Translation: %f", translation.x);
}

I'm pretty sure I'm looking at converting translation.x to a percetange but it's confusing.