问:
Full documentation on Scala's XML support?
I'm reading the preprint of the 2nd Ed of Programming in Scala, but as it says it "only scratched the surface of what you can do with XML".  Are there any resources for understanding the entire XML support in Scala 2.8? (right now, I want to know about namespace handling, but I'd like to have something complete to refer to).

Scaladoc doesn't count.

答:
This is a book by the author of the Scala XML supoort. Scala XML support did not change much over the versions so it is still up to date: http://burak.emir.googlepages.com/scalaxbook.docbk.html

This is a very good article: http://www.codecommit.com/blog/scala/working-with-scalas-xml-support

There's also a nice article here: http://www.ibm.com/developerworks/library/x-scalaxml/


来源: stackexchange

问:
From where should I install git: xcode-select --install or brew install git?
From where should I install git:
xcode-select --install or brew install git?

答:
You need to do xcode-select --install anyway if you want to do any development.

You can then do

```<code>brew install git
</code>```

and it will install git into /usr/local/bin/git without affecting the Apple Xcode git. There will not be two git versions running, but there will be two installed. Which one runs when you type git will depend on your PATH. In general, you would want /usr/local/bin first on your PATH so you benefit from the newer packages provided by homebrew rather than the outdated versions Apple supplies.

ContentLicense: CC BY-SA 3.0

Body:
You need to do xcode-select --install anyway if you want to do any development.

You can then do

brew install git

and it will install git into /usr/local/bin/git without affecting the Apple Xcode git. There will not be two git versions running, but there will be two installed. Which one runs when you type git will depend on your PATH. In general, you would want /usr/local/bin first on your PATH so you benefit from the newer packages provided by homebrew rather than the outdated versions Apple supplies.


问:
Google DFP - Refresh AD slot without New Impression Count
I need to refresh all ad slots after 15 sec and load new ads to the slots without counting new impression.
** This works :

```<code>googletag.pubads().refresh([slot1], {changeCorrelator: false});
</code>```

**but when I add the set interval 30 sec.. it is not refreshing-

```<code>setInterval(function(){googletag.pubads().refresh(null, {changeCorrelator: false}, 30000)});
</code>```

Pls help..Tnx

答:
The problem you have is due to the fact that the refresh() call should be pushed to googletag commands. So this should solve your issue:

```<code>setInterval(function(){
    googletag.cmd.push(function() {
         // refresh fetches a new ad for each slot, without changing the correlator.
        googletag.pubads().refresh(null, {changeCorrelator: false});
    });
}, 30000);
</code>```

Please note this line in th example above:
googletag.cmd.push(function() {...});

Body:
I need to refresh all ad slots after 15 sec and load new ads to the slots without counting new impression.
** This works :

googletag.pubads().refresh([slot1], {changeCorrelator: false});

**but when I add the set interval 30 sec.. it is not refreshing-

setInterval(function(){googletag.pubads().refresh(null, {changeCorrelator: false}, 30000)});

Pls help..Tnx

Body:
The problem you have is due to the fact that the refresh() call should be pushed to googletag commands. So this should solve your issue:

setInterval(function(){
    googletag.cmd.push(function() {
         // refresh fetches a new ad for each slot, without changing the correlator.
        googletag.pubads().refresh(null, {changeCorrelator: false});
    });
}, 30000);

Please note this line in th example above:
googletag.cmd.push(function() {...});


问:
ListView with CursorAdapter slow refresh
I am using a ListActivity which displays a ListView with the help of a CursorAdapter and a ContentProvider.

The list contains more than 1.000 items, so the initial load takes a while.
If the user selects an item, another activity is called via startActivityForResult().
The user can edit the item, changes are stored in database.

Back in ListActivity with onActivityResult(): The cursor is reloaded with getAdapter().changeCursor() and the view is refreshed with getAdapter().notifyDataSetChanged()

Is this the right way? Because the refresh takes 1-2 seconds and is very slow!

答: Using AsynTask and run a backgroundTask and you can use RecyclerView instead if ListView</p>


问:
beepbeepboopbeep
```<code>import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}
</code>```

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

答:
Use the tools that are best for the job, don't try to make existing tools do something they're not designed for.

In this case, you have a Collection of the following properties:

variable length;

sorted output;

no duplicates.

In this case, it's better to use a SortedSet<int>because it has all those things. If you also need to keep the count of each item you have, use a SortedMap where the first int is the number and the second int is the count of that number. Both of these will immediately sort new items as they come in and only have 1 item with a certain value.

Title: beepbeepboopbeep

Body:
import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.


问:
Directory does not exist. Parameter name: directoryVirtualPath
i just published my project to my host on Arvixe and get this error (Works fine local):

```<code>Server Error in '/' Application.

Directory does not exist.
Parameter name: directoryVirtualPath

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Directory does not exist.
Parameter name: directoryVirtualPath

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.Optimization.Bundle.IncludeDirectory(String directoryVirtualPath, String searchPattern, Boolean searchSubdirectories) +357
   System.Web.Optimization.Bundle.Include(String[] virtualPaths) +287
   IconBench.BundleConfig.RegisterBundles(BundleCollection bundles) +75
   IconBench.MvcApplication.Application_Start() +128

[HttpException (0x80004005): Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9160125
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +131
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253

[HttpException (0x80004005): Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9079228
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237
</code>```

What does it mean ?

答:
I also had this error when I combined all my separated bundles into one bundle.

```<code>bundles.Add(new ScriptBundle("~/bundles/one").Include(
            "~/Scripts/one.js"));
bundles.Add(new ScriptBundle("~/bundles/two").Include(
            "~/Scripts/two.js"));
</code>```

Changed to

```<code>bundles.Add(new ScriptBundle("~/bundles/js").Include(
            "~/Scripts/one.js",
            "~/Scripts/two.js"));
</code>```

I had to refresh application pool on my shared hosting's control panel to fix this issue.

Body:
i just published my project to my host on Arvixe and get this error (Works fine local):

Server Error in '/' Application.

Directory does not exist.
Parameter name: directoryVirtualPath

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Directory does not exist.
Parameter name: directoryVirtualPath

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.Optimization.Bundle.IncludeDirectory(String directoryVirtualPath, String searchPattern, Boolean searchSubdirectories) +357
   System.Web.Optimization.Bundle.Include(String[] virtualPaths) +287
   IconBench.BundleConfig.RegisterBundles(BundleCollection bundles) +75
   IconBench.MvcApplication.Application_Start() +128

[HttpException (0x80004005): Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9160125
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +131
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253

[HttpException (0x80004005): Directory does not exist.
Parameter name: directoryVirtualPath]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9079228
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237

What does it mean ?

Body:
I also had this error when I combined all my separated bundles into one bundle.

bundles.Add(new ScriptBundle("~/bundles/one").Include(
            "~/Scripts/one.js"));
bundles.Add(new ScriptBundle("~/bundles/two").Include(
            "~/Scripts/two.js"));

Changed to

bundles.Add(new ScriptBundle("~/bundles/js").Include(
            "~/Scripts/one.js",
            "~/Scripts/two.js"));

I had to refresh application pool on my shared hosting's control panel to fix this issue.


问:
ASP.NET BoilerPlate: How do I inject object of DbContext in application service?
How do I inject object of DbContext in application service?

Need to access it to create clone of a entity record.

答: You can use IDbContextProvider<TDbContext> _sampleDbContextProvider as constructor injection, using with _sampleDbContextProvider.GetDbContext();


问:
Console log on click event with textbox
I know this is probably a duplicate question. I am trying to use the value of a textbox and just show it in my console.log. It appears for a second and disappears.

Here is my HTML form

```<code><form>
    <input type ="text" id="search" name="search" placeholder="Search..." size="45" required>
    <input type ="submit" value="GO" id="submit">
</form>
</code>```

Here is my JavaScript

```<code>$(function(){

$("#submit").on("click", function(){

    var t = document.getElementById("search").value;
    console.log(t);

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

For future context, I am trying to use that information to plug it into the wikipedia API.

```<code>        var wikipediaURL = "https://en.wikipedia.org//w/api.php?action=opensearch&search="+ t +"&format=json&callback=?";

    $.ajax({
        url: wikipediaURL,
        type:'GET',
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function(data, status, jqXR){
            console.log(data);
        },
    })
    .done(function() {
        console.log("success");
    })
    .fail(function() {
        console.log("fail");
    })
    .always(function() {
        console.log("complete");
    });
</code>```

答:
Reason you see it for a moment in your console and then it's disappear is you are using submit button inside your form and whenever you click submit button it will by default submit the form and refresh the page if target is same page unless you stop form submission.

In order to avoid form submission try this.

```<code>$(function(){

$("#submit").on("click", function(){

    var t = document.getElementById("search").value;
    console.log(t);
    e.preventDefault(); // this will also do the trick and avoid form submission.
    return false; // return statement is included just as safety measure as this will make sure form is not submitted.

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

Title: Console log on click event with textbox

Body:
I know this is probably a duplicate question. I am trying to use the value of a textbox and just show it in my console.log. It appears for a second and disappears.

Here is my HTML form

<form>
    <input type ="text" id="search" name="search" placeholder="Search..." size="45" required>
    <input type ="submit" value="GO" id="submit">
</form>

Here is my JavaScript

$(function(){

$("#submit").on("click", function(){

    var t = document.getElementById("search").value;
    console.log(t);

    });
});

For future context, I am trying to use that information to plug it into the wikipedia API.

        var wikipediaURL = "https://en.wikipedia.org//w/api.php?action=opensearch&search="+ t +"&format=json&callback=?";

    $.ajax({
        url: wikipediaURL,
        type:'GET',
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function(data, status, jqXR){
            console.log(data);
        },
    })
    .done(function() {
        console.log("success");
    })
    .fail(function() {
        console.log("fail");
    })
    .always(function() {
        console.log("complete");
    });

Body:
Reason you see it for a moment in your console and then it's disappear is you are using submit button inside your form and whenever you click submit button it will by default submit the form and refresh the page if target is same page unless you stop form submission.

In order to avoid form submission try this.

$(function(){

$("#submit").on("click", function(){

    var t = document.getElementById("search").value;
    console.log(t);
    e.preventDefault(); // this will also do the trick and avoid form submission.
    return false; // return statement is included just as safety measure as this will make sure form is not submitted.

    });
});


问:
Getting messages sent from python KafkaProducer
My goal is to get data from non-file sources (i.e. generated within a program or sent though an API) and have it sent to a spark stream. To accomplish this, I'm sending the data through a python-based KafkaProducer:

```<code>$ bin/zookeeper-server-start.sh config/zookeeper.properties &
$ bin/kafka-server-start.sh config/server.properties &
$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic my-topic
$ python
Python 3.6.1| Anaconda custom (64-bit)
> from kafka import KafkaProducer
> import time
> producer = KafkaProducer(bootstrap_servers='localhost:9092', value_serializer=lambda v: json.dumps(v).encode('utf-8'))
> producer.send(topic = 'my-topic', value = 'MESSAGE ACKNOWLEDGED', timestamp_ms = time.time())
> producer.close()
> exit()
</code>```

My issue is that nothing appears when checking the topic from the consumer shell script:

```<code>$ bin/kafka-console-consumer.sh --bootstrap-server localhost:2181 --topic my-topic
^C$
</code>```

Is something missing or wrong here? I'm new to spark/kafka/messaging systems, so anything will help. The Kafka version is 0.11.0.0 (Scala 2.11) and no changes are made to the config files.

答:
If you start a consumer after sending messages to a topic, it is possible that the consumer will skip that messages because it will set a topic offset (which could be considered as a "starting point" to read from) to the topic's end. To change that behavior try to add --from-beginning option:

```<code>$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my-topic --from-beginning
</code>```

Also you can try kafkacat, which is more convenient than Kafka's console consumer and producer (imho). Reading messages from Kafka with kafkacat can be performed with the following command:

```<code>kafkacat -C -b 'localhost:9092' -o beginning -e -D '\n' -t 'my-topic'
</code>```

Hope it will help.

Body:
My goal is to get data from non-file sources (i.e. generated within a program or sent though an API) and have it sent to a spark stream. To accomplish this, I'm sending the data through a python-based KafkaProducer:

$ bin/zookeeper-server-start.sh config/zookeeper.properties &
$ bin/kafka-server-start.sh config/server.properties &
$ bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic my-topic
$ python
Python 3.6.1| Anaconda custom (64-bit)
> from kafka import KafkaProducer
> import time
> producer = KafkaProducer(bootstrap_servers='localhost:9092', value_serializer=lambda v: json.dumps(v).encode('utf-8'))
> producer.send(topic = 'my-topic', value = 'MESSAGE ACKNOWLEDGED', timestamp_ms = time.time())
> producer.close()
> exit()

My issue is that nothing appears when checking the topic from the consumer shell script:

$ bin/kafka-console-consumer.sh --bootstrap-server localhost:2181 --topic my-topic
^C$

Is something missing or wrong here? I'm new to spark/kafka/messaging systems, so anything will help. The Kafka version is 0.11.0.0 (Scala 2.11) and no changes are made to the config files.

Body:
If you start a consumer after sending messages to a topic, it is possible that the consumer will skip that messages because it will set a topic offset (which could be considered as a "starting point" to read from) to the topic's end. To change that behavior try to add --from-beginning option:

$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my-topic --from-beginning

Also you can try kafkacat, which is more convenient than Kafka's console consumer and producer (imho). Reading messages from Kafka with kafkacat can be performed with the following command:

kafkacat -C -b 'localhost:9092' -o beginning -e -D '\n' -t 'my-topic'

Hope it will help.


问:
Error when If statement to definition. (Python)
so I'm very basic with coding and Python. I used to be much better but haven't used it in some time and I'm trying to get back into the swing of things. I'm trying to execute an If statement, where input is asked for a username and password, if correct it then goes to a "definition" I think it's called, where it then executes the code in def access()

Code:

```<code>def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access()

    else:
        print("Access denied")
        return main()

    def access():

        print("Welcome, " + userName)

    access()

main()
</code>```

However, I get this error when the correct inputs are executed:

```<code>Username: u123
Password: p123
Access granted
Traceback (most recent call last):
  File "C:/Users/Tom/Desktop/test.py", line 23, in <module>
    main()
  File "C:/Users/Tom/Desktop/test.py", line 11, in main
    access()
UnboundLocalError: local variable 'access' referenced before assignment
>>>
</code>```

Any help will be appreciated, thank you.

答:
You have wrong the scopes, also you need to add a parameter to the function access:</p>

```<code>def main():

  userName = ("u123")
  userPass = ("p123")

  userNameInput = input("Username: ")
  userPassInput = input("Password: ")

  if userPassInput == userPass and userNameInput == userName:
    print("Access granted")
    #now you are able to use the function "access"
    access(userName)

  else:
    print("Access denied")
    return main()

#here, define the function in the same identation of the main function, not inside it
def access(userName):
  print("Welcome, " + userName)

main()
</code>```

Body:
so I'm very basic with coding and Python. I used to be much better but haven't used it in some time and I'm trying to get back into the swing of things. I'm trying to execute an If statement, where input is asked for a username and password, if correct it then goes to a "definition" I think it's called, where it then executes the code in def access()

Code:

def main():

    userName = ("u123")
    userPass = ("p123")

    userNameInput = input("Username: ")
    userPassInput = input("Password: ")

    if userPassInput == userPass and userNameInput == userName:
        print("Access granted")
        access()

    else:
        print("Access denied")
        return main()

    def access():

        print("Welcome, " + userName)

    access()

main()

However, I get this error when the correct inputs are executed:

Username: u123
Password: p123
Access granted
Traceback (most recent call last):
  File "C:/Users/Tom/Desktop/test.py", line 23, in <module>
    main()
  File "C:/Users/Tom/Desktop/test.py", line 11, in main
    access()
UnboundLocalError: local variable 'access' referenced before assignment
>>>

Any help will be appreciated, thank you.

Body:
You have wrong the scopes, also you need to add a parameter to the function access:

def main():

  userName = ("u123")
  userPass = ("p123")

  userNameInput = input("Username: ")
  userPassInput = input("Password: ")

  if userPassInput == userPass and userNameInput == userName:
    print("Access granted")
    #now you are able to use the function "access"
    access(userName)

  else:
    print("Access denied")
    return main()

#here, define the function in the same identation of the main function, not inside it
def access(userName):
  print("Welcome, " + userName)

main()


问:
How can i smoothly playback a FLV at different speeds?
I will need to display the frames of an FLV at different rates.

Here are some examples:

the user will 'scrub' through the flv frames(front/back)

the flv will need to play at half the speed on a user interaction.

Currently I'm using LoaderMax and it's VideoLoader object to load and play FLV files.
I've tried using the playProgress property, but only the keyframes of the FLV are displayed. I got the same result with the basic setup(using the NetStream class)

As a workaround, I playback the FLV once, and cache BitmapData instances in which I draw/cache each frame of the video. After this is done, I use the BitmapData Vector to update a Bitmap on stage. Scrubbing/changing speed works fine with this method, but still the user needs to see(wait for) the sequence once, while it gets cached, which I don't like.

Any better ideas on how to do this ?

Any tips are useful,
Thanks!

答: I've seen this done before but the video was imported into the flash ide and we manipulated the time line for the scrubbing. I believe we had a second version of the video for the slow motion play back version and switched between the two movieclips. Fairly low-tech method and wasn't without it's issues but we got round them. I have a feeling you're going to struggle to do this with a plain old flv using progressive download.</p>

ContentLicense: CC BY-SA 2.5


问:
tcp server using epoll gives non-socket error
i am creating a simple tcp echo server in c using epoll. while compiling it gives error:
Socket operation on non-socket

why does it gives non-socket? i tried but couldn't get my head around it.
below is my code and here is the article that i am following

my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <errno.h>
#include <unistd.h>
#define MAX_LISTEN_BACKLOG 1
#define BUFFER_SIZE 4096

int bind_and_create(char *port){
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int s, sfd;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    s = getaddrinfo(NULL, port , &hints, &result);
    if( s != 0 ){
        fprintf(stderr,"getaddrinfo :%s\n",gai_strerror(s));
        return -1;
    }

    for( rp = result; rp!= NULL; rp->ai_next){
          int sfd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
      if ( sfd == -1)
          continue;
      s = bind(sfd, rp->ai_addr,rp->ai_addrlen);
      if ( s == 0){
          //succefull managed to bind socket
        break;
      }

          close(sfd);
        }

    if ( rp == NULL){
        fprintf(stderr,"could not bind");
    }
    freeaddrinfo(result);
    return sfd;
    }

int make_socket_non_blocking( int sfd ){

    int flags , s;
    flags = fcntl(sfd, F_GETFL, 0);
    if (flags == -1){
        perror("fnctl error");
        return -1;
    }

    flags |= O_NONBLOCK;
    s = fcntl(sfd,F_SETFL,flags);
    if (s == -1){
        perror("fnctl error");
        return -1;
    }
    return 0;
}

#define MAXEVENTS 64

int main (int argc, char *argv[])
{
  int sfd, s;
  int efd;
  struct epoll_event event;
  struct epoll_event *events;

  if (argc != 2)
    {
      fprintf (stderr, "Usage: %s [port]\n", argv[0]);
      exit (EXIT_FAILURE);
    }

  sfd = bind_and_create (argv[1]);
  if (sfd == -1)
    abort ();

  s = make_socket_non_blocking (sfd);
  if (s == -1)
    abort ();

  s = listen (sfd, SOMAXCONN); // error is here but why????
  if (s == -1)
    {
      perror ("listen");
      abort ();
    }

  efd = epoll_create1 (0);
  if (efd == -1)
    {
      perror ("epoll_create");
      abort ();
    }

  event.data.fd = sfd;
  event.events = EPOLLIN | EPOLLET;
  s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);
  if (s == -1)
    {
      perror ("epoll_ctl");
      abort ();
    }

  /* Buffer where events are returned */
  events = calloc (MAXEVENTS, sizeof event);

  /* The event loop */
  while (1)
    {
      int n, i;

      n = epoll_wait (efd, events, MAXEVENTS, -1);
      for (i = 0; i < n; i++)
    {
      if ((events[i].events & EPOLLERR) ||
              (events[i].events & EPOLLHUP) ||
              (!(events[i].events & EPOLLIN)))
        {
              /* An error has occured on this fd, or the socket is not
                 ready for reading (why were we notified then?) */
          fprintf (stderr, "epoll error\n");
          close (events[i].data.fd);
          continue;
        }

      else if (sfd == events[i].data.fd)
        {
              /* We have a notification on the listening socket, which
                 means one or more incoming connections. */
              while (1)
                {
                  struct sockaddr in_addr;
                  socklen_t in_len;
                  int infd;
                  char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

                  in_len = sizeof in_addr;
                  infd = accept (sfd, &in_addr, &in_len);
                  if (infd == -1)
                    {
                      if ((errno == EAGAIN) ||
                          (errno == EWOULDBLOCK))
                        {
                          /* We have processed all incoming
                             connections. */
                          break;
                        }
                      else
                        {
                          perror ("accept");
                          break;
                        }
                    }

                  s = getnameinfo (&in_addr, in_len,
                                   hbuf, sizeof hbuf,
                                   sbuf, sizeof sbuf,
                                   NI_NUMERICHOST | NI_NUMERICSERV);
                  if (s == 0)
                    {
                      printf("Accepted connection on descriptor %d "
                             "(host=%s, port=%s)\n", infd, hbuf, sbuf);
                    }

                  /* Make the incoming socket non-blocking and add it to the
                     list of fds to monitor. */
                  s = make_socket_non_blocking (infd);
                  if (s == -1)
                    abort ();

                  event.data.fd = infd;
                  event.events = EPOLLIN | EPOLLET;
                  s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);
                  if (s == -1)
                    {
                      perror ("epoll_ctl");
                      abort ();
                    }
                }
              continue;
            }
          else
            {
              /* We have data on the fd waiting to be read. Read and
                 display it. We must read whatever data is available
                 completely, as we are running in edge-triggered mode
                 and won't get a notification again for the same
                 data. */
              int done = 0;

              while (1)
                {
                  ssize_t count;
                  char buf[512];

                  count = read (events[i].data.fd, buf, sizeof buf);
                  if (count == -1)
                    {
                      /* If errno == EAGAIN, that means we have read all
                         data. So go back to the main loop. */
                      if (errno != EAGAIN)
                        {
                          perror ("read");
                          done = 1;
                        }
                      break;
                    }
                  else if (count == 0)
                    {
                      /* End of file. The remote has closed the
                         connection. */
                      done = 1;
                      break;
                    }

                  /* Write the buffer to standard output */
                  s = write (1, buf, count);
                  if (s == -1)
                    {
                      perror ("write");
                      abort ();
                    }
                }

              if (done)
                {
                  printf ("Closed connection on descriptor %d\n",
                          events[i].data.fd);

                  /* Closing the descriptor will make epoll remove it
                     from the set of descriptors which are monitored. */
                  close (events[i].data.fd);
                }
            }
        }
    }

  free (events);

  close (sfd);

  return EXIT_SUCCESS;
}
</code>```

答:
```<code>int bind_and_create(char *port){
    ...
    int s, sfd; // <- one sfd
    ...
    for( rp = result; rp!= NULL; rp->ai_next){ // <- rp->ai_next has no effect
        int sfd = socket(...); // <-- two sfd
        ...
        close(sfd); // <-- two sfd gone
    }
    ...
    return sfd; // <-- one sfd, still completely uninitialised
}
</code>```

If you want to stop wasting your time on this, use -Wall or an equivalent compiler setting.

Body:
i am creating a simple tcp echo server in c using epoll. while compiling it gives error:
Socket operation on non-socket

why does it gives non-socket? i tried but couldn't get my head around it.
below is my code and here is the article that i am following

my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <errno.h>
#include <unistd.h>
#define MAX_LISTEN_BACKLOG 1
#define BUFFER_SIZE 4096

int bind_and_create(char *port){
    struct addrinfo hints;
    struct addrinfo *result, *rp;
    int s, sfd;

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    s = getaddrinfo(NULL, port , &hints, &result);
    if( s != 0 ){
        fprintf(stderr,"getaddrinfo :%s\n",gai_strerror(s));
        return -1;
    }

    for( rp = result; rp!= NULL; rp->ai_next){
          int sfd = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
      if ( sfd == -1)
          continue;
      s = bind(sfd, rp->ai_addr,rp->ai_addrlen);
      if ( s == 0){
          //succefull managed to bind socket
        break;
      }

          close(sfd);
        }

    if ( rp == NULL){
        fprintf(stderr,"could not bind");
    }
    freeaddrinfo(result);
    return sfd;
    }

int make_socket_non_blocking( int sfd ){

    int flags , s;
    flags = fcntl(sfd, F_GETFL, 0);
    if (flags == -1){
        perror("fnctl error");
        return -1;
    }

    flags |= O_NONBLOCK;
    s = fcntl(sfd,F_SETFL,flags);
    if (s == -1){
        perror("fnctl error");
        return -1;
    }
    return 0;
}

#define MAXEVENTS 64

int main (int argc, char *argv[])
{
  int sfd, s;
  int efd;
  struct epoll_event event;
  struct epoll_event *events;

  if (argc != 2)
    {
      fprintf (stderr, "Usage: %s [port]\n", argv[0]);
      exit (EXIT_FAILURE);
    }

  sfd = bind_and_create (argv[1]);
  if (sfd == -1)
    abort ();

  s = make_socket_non_blocking (sfd);
  if (s == -1)
    abort ();

  s = listen (sfd, SOMAXCONN); // error is here but why????
  if (s == -1)
    {
      perror ("listen");
      abort ();
    }

  efd = epoll_create1 (0);
  if (efd == -1)
    {
      perror ("epoll_create");
      abort ();
    }

  event.data.fd = sfd;
  event.events = EPOLLIN | EPOLLET;
  s = epoll_ctl (efd, EPOLL_CTL_ADD, sfd, &event);
  if (s == -1)
    {
      perror ("epoll_ctl");
      abort ();
    }

  /* Buffer where events are returned */
  events = calloc (MAXEVENTS, sizeof event);

  /* The event loop */
  while (1)
    {
      int n, i;

      n = epoll_wait (efd, events, MAXEVENTS, -1);
      for (i = 0; i < n; i++)
    {
      if ((events[i].events & EPOLLERR) ||
              (events[i].events & EPOLLHUP) ||
              (!(events[i].events & EPOLLIN)))
        {
              /* An error has occured on this fd, or the socket is not
                 ready for reading (why were we notified then?) */
          fprintf (stderr, "epoll error\n");
          close (events[i].data.fd);
          continue;
        }

      else if (sfd == events[i].data.fd)
        {
              /* We have a notification on the listening socket, which
                 means one or more incoming connections. */
              while (1)
                {
                  struct sockaddr in_addr;
                  socklen_t in_len;
                  int infd;
                  char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

                  in_len = sizeof in_addr;
                  infd = accept (sfd, &in_addr, &in_len);
                  if (infd == -1)
                    {
                      if ((errno == EAGAIN) ||
                          (errno == EWOULDBLOCK))
                        {
                          /* We have processed all incoming
                             connections. */
                          break;
                        }
                      else
                        {
                          perror ("accept");
                          break;
                        }
                    }

                  s = getnameinfo (&in_addr, in_len,
                                   hbuf, sizeof hbuf,
                                   sbuf, sizeof sbuf,
                                   NI_NUMERICHOST | NI_NUMERICSERV);
                  if (s == 0)
                    {
                      printf("Accepted connection on descriptor %d "
                             "(host=%s, port=%s)\n", infd, hbuf, sbuf);
                    }

                  /* Make the incoming socket non-blocking and add it to the
                     list of fds to monitor. */
                  s = make_socket_non_blocking (infd);
                  if (s == -1)
                    abort ();

                  event.data.fd = infd;
                  event.events = EPOLLIN | EPOLLET;
                  s = epoll_ctl (efd, EPOLL_CTL_ADD, infd, &event);
                  if (s == -1)
                    {
                      perror ("epoll_ctl");
                      abort ();
                    }
                }
              continue;
            }
          else
            {
              /* We have data on the fd waiting to be read. Read and
                 display it. We must read whatever data is available
                 completely, as we are running in edge-triggered mode
                 and won't get a notification again for the same
                 data. */
              int done = 0;

              while (1)
                {
                  ssize_t count;
                  char buf[512];

                  count = read (events[i].data.fd, buf, sizeof buf);
                  if (count == -1)
                    {
                      /* If errno == EAGAIN, that means we have read all
                         data. So go back to the main loop. */
                      if (errno != EAGAIN)
                        {
                          perror ("read");
                          done = 1;
                        }
                      break;
                    }
                  else if (count == 0)
                    {
                      /* End of file. The remote has closed the
                         connection. */
                      done = 1;
                      break;
                    }

                  /* Write the buffer to standard output */
                  s = write (1, buf, count);
                  if (s == -1)
                    {
                      perror ("write");
                      abort ();
                    }
                }

              if (done)
                {
                  printf ("Closed connection on descriptor %d\n",
                          events[i].data.fd);

                  /* Closing the descriptor will make epoll remove it
                     from the set of descriptors which are monitored. */
                  close (events[i].data.fd);
                }
            }
        }
    }

  free (events);

  close (sfd);

  return EXIT_SUCCESS;
}

Body:
int bind_and_create(char *port){
    ...
    int s, sfd; // <- one sfd
    ...
    for( rp = result; rp!= NULL; rp->ai_next){ // <- rp->ai_next has no effect
        int sfd = socket(...); // <-- two sfd
        ...
        close(sfd); // <-- two sfd gone
    }
    ...
    return sfd; // <-- one sfd, still completely uninitialised
}

If you want to stop wasting your time on this, use -Wall or an equivalent compiler setting.


问:
Position fixed not working on Tumblr
I'm trying to make a div position:fixed;but it's not working at all.

Here's the code:

```<code>position: fixed;
top: 16px;
left: 16px;
width: 120px;
z-index: 19999;
</code>```

It's a Tumblr Blog, so my guess is that some script / iframe / animation library is breaking something somehow, but I cannot figure it out.

Here's the blog link: Pale Jane on Tumblr

I've put a little test div give on the left site of the page. My blog is nsfw, so keep minors away if opening it. Sorry, but I just can't recreate it on codepen etc..

答:
Turns out you will have to remove the transforms on your body CSS rule.

I tested this and it works fine. Do you really need transform on the body??

Here is another SO post that suggested it.

Position: fixed nav does not stay fixed

Title: Position fixed not working on Tumblr

Body:
I'm trying to make a div position:fixed;but it's not working at all.

Here's the code:

position: fixed;
top: 16px;
left: 16px;
width: 120px;
z-index: 19999;

It's a Tumblr Blog, so my guess is that some script / iframe / animation library is breaking something somehow, but I cannot figure it out.

Here's the blog link: Pale Jane on Tumblr

I've put a little test div give on the left site of the page. My blog is nsfw, so keep minors away if opening it. Sorry, but I just can't recreate it on codepen etc..


问:
duplicate key value violates unique constraint - Using KnexJS, with Postgresql
I am currently building an app using the KnexJS framework that helps me to write sqlite3 in development and postgresql in production (for Heroku).

My main issue is that my application works fine when on my machine, but as soon as I upload it to heroku it breaks. In Heroku logs I get the message:

```<code>{ error: insert into "contracts" ("contract_desc", "contract_header", "owner_id", "signee_id") values ($1, $2, $3, $4) - duplicate key value violates unique constraint "contracts_pkey"
</code>```

And it leaves me unable to insert data into my database.

My Knex migrations for the table are setup like this:

```<code>exports.up = function(knex, Promise) {
  return knex.schema.createTable('contracts', function (table) {
    table.increments('id').primary()
    table.integer('owner_id')
    table.integer('signee_id')
    table.string('contract_header')
    table.text('contract_desc')
    table.string('signature_url')
    table.string('date_signed')
    table.boolean('isSigned')
      })
   };

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('contracts')
};
</code>```

And the function I am calling to insert the data looks like this:

```<code>function newContract (id, contractDetails) {
  return knex('contracts')
  .select('owner_id', 'signee_id', 'contract_header', 'contract_desc')
  .insert({
    owner_id: id,
    signee_id: contractDetails.signee_id,
    contract_header: contractDetails.contract_header,
    contract_desc:contractDetails.contract_desc
  })
}
</code>```

Any ideas on what could be causing this?

答:
Okay, I got it.

Try to remove id fields from your seed.

Let me explain why this happens

Postgres autoincrement fields take their values from sequences

You can try \d <table_name> command in psql interface. It will give you something like

```<code>...
 id         | bigint                   | not null default nextval('<table_name>_id_seq'::regclass)
...
</code>```

By doing

```<code>insert into table_name (name) values ('Kappa')
</code>```

You actually omit id field and insert default value, which is nextval('<table_name>_id_seq').

By specifying explicitly your id parameter in query you are not using this function and the next time you use it – you can get a collision of ids. You inserted id = 1 and nextval generated 1 as well.

Body:
I am currently building an app using the KnexJS framework that helps me to write sqlite3 in development and postgresql in production (for Heroku).

My main issue is that my application works fine when on my machine, but as soon as I upload it to heroku it breaks. In Heroku logs I get the message:

{ error: insert into "contracts" ("contract_desc", "contract_header", "owner_id", "signee_id") values ($1, $2, $3, $4) - duplicate key value violates unique constraint "contracts_pkey"

And it leaves me unable to insert data into my database.

My Knex migrations for the table are setup like this:

exports.up = function(knex, Promise) {
  return knex.schema.createTable('contracts', function (table) {
    table.increments('id').primary()
    table.integer('owner_id')
    table.integer('signee_id')
    table.string('contract_header')
    table.text('contract_desc')
    table.string('signature_url')
    table.string('date_signed')
    table.boolean('isSigned')
      })
   };

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('contracts')
};

And the function I am calling to insert the data looks like this:

function newContract (id, contractDetails) {
  return knex('contracts')
  .select('owner_id', 'signee_id', 'contract_header', 'contract_desc')
  .insert({
    owner_id: id,
    signee_id: contractDetails.signee_id,
    contract_header: contractDetails.contract_header,
    contract_desc:contractDetails.contract_desc
  })
}

Any ideas on what could be causing this?

Body:
Okay, I got it.

Try to remove id fields from your seed.

Let me explain why this happens

Postgres autoincrement fields take their values from sequences

You can try \d <table_name> command in psql interface. It will give you something like

...
 id         | bigint                   | not null default nextval('<table_name>_id_seq'::regclass)
...

By doing

insert into table_name (name) values ('Kappa')

You actually omit id field and insert default value, which is nextval('<table_name>_id_seq').

By specifying explicitly your id parameter in query you are not using this function and the next time you use it – you can get a collision of ids. You inserted id = 1 and nextval generated 1 as well.


问:
How to make an object move in relation to image_angle?
Note: I'm using GameMaker 1.4, not 2. I don't know if this makes a difference, but I'm pointing it out just in case.

Okay, so I'm having an issue in my GameMaker game where I'm making an object move up and down in relation to image_angle. For some reason, it really wants to move across the y axis as normal and completetly disregards the image_angle. This is really annoying and could change the game entirely if not fixed.

My code is for the step event is:

```<code>// Mouse controls.
image_angle = point_direction(x, y, mouse_x, mouse_y);

if(keyboard_check(ord('W')))
{
    y -= playerSpeed;
}

if(keyboard_check(ord('S')))
{
    y += playerSpeed;
}
</code>```

My code for the create event is:

```<code>globalvar fuelRemaining;
fuelRemaining = 60;

playerSpeed = 3;
</code>```

答:
```<code>image_angle = point_direction(x, y, mouse_x, mouse_y);
direction = image_angle;

if(keyboard_check(ord('W'))){
    speed = -playerSpeed;
}
if(keyboard_check_release(ord('W'))){
    speed = 0;
}

if(keyboard_check(ord('S'))){
    speed = playerSpeed;
}
if(keyboard_check_release(ord('S'))){
    speed = 0;
}
</code>```

Body:
Note: I'm using GameMaker 1.4, not 2. I don't know if this makes a difference, but I'm pointing it out just in case.

Okay, so I'm having an issue in my GameMaker game where I'm making an object move up and down in relation to image_angle. For some reason, it really wants to move across the y axis as normal and completetly disregards the image_angle. This is really annoying and could change the game entirely if not fixed.

My code is for the step event is:

// Mouse controls.
image_angle = point_direction(x, y, mouse_x, mouse_y);

if(keyboard_check(ord('W')))
{
    y -= playerSpeed;
}

if(keyboard_check(ord('S')))
{
    y += playerSpeed;
}

My code for the create event is:

globalvar fuelRemaining;
fuelRemaining = 60;

playerSpeed = 3;


问:
Filezilla stop connecting after MLSD
I have problem in filezilla connecting to the server through FTP client called FTP.

When i try to connect to server i am getting following

```<code>Status: Connecting to xxx.xxx.xxx.xx:21...
Status: Connection established, waiting for welcome message...
Response:   220 ProFTPD 1.3.4a Server (ProFTPD) [xxx.xxx.xxx.xx]
Command:    USER username
Response:   331 Password required for password
Command:    PASS **********
Response:   230 User username logged in
Command:    SYST
Response:   215 UNIX Type: L8
Command:    FEAT
Response:   211-Features:
Response:    MDTM
Response:    MFMT
Response:    TVFS
Response:    UTF8
Response:    MFF modify;UNIX.group;UNIX.mode;
Response:    MLST modify*;perm*;size*;type*;unique*;UNIX.group*;UNIX.mode*;UNIX.owner*;
Response:    LANG ko-KR;it-IT;ja-JP;ru-RU;bg-BG;zh-CN;fr-FR;zh-TW;en-US*
Response:    REST STREAM
Response:    SIZE
Response:   211 End
Command:    OPTS UTF8 ON
Response:   200 UTF8 set to on
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is the current directory
Command:    TYPE I
Response:   200 Type set to I
Command:    PASV
Response:   227 Entering Passive Mode (xxx,xxx,xxx,xx,xxx,xxx).
Command:    MLSD
</code>```

And it stop after MLSD and after some time says

```<code>Error:  Connection timed out
Error:  Failed to retrieve directory listing
</code>```

I am able to connect to  server through ftp when i connect internet from my mobile.but i dont want to do like that.i need to work with my cable net.

I am using Windows 7 and Laptop.

Please help me to connect.

答:
I had that problem trying to connect to ubuntu server 16 behind a NAT in VirtualBox, the fix was to use passive mode in filezilla and configure file:/etc/proftpd/proftpd.conf

PassivePorts 65532 65534

->Change the range as necessary

MasqueradeAddress [MyHost IPAddress or Router external IP in real NAT]

->127.0.0.1 will throw "ECONNREFUSED" instead of "Connection timed out"

Title: Filezilla stop connecting after MLSD

Body:
I have problem in filezilla connecting to the server through FTP client called FTP.

When i try to connect to server i am getting following

Status: Connecting to xxx.xxx.xxx.xx:21...
Status: Connection established, waiting for welcome message...
Response:   220 ProFTPD 1.3.4a Server (ProFTPD) [xxx.xxx.xxx.xx]
Command:    USER username
Response:   331 Password required for password
Command:    PASS **********
Response:   230 User username logged in
Command:    SYST
Response:   215 UNIX Type: L8
Command:    FEAT
Response:   211-Features:
Response:    MDTM
Response:    MFMT
Response:    TVFS
Response:    UTF8
Response:    MFF modify;UNIX.group;UNIX.mode;
Response:    MLST modify*;perm*;size*;type*;unique*;UNIX.group*;UNIX.mode*;UNIX.owner*;
Response:    LANG ko-KR;it-IT;ja-JP;ru-RU;bg-BG;zh-CN;fr-FR;zh-TW;en-US*
Response:    REST STREAM
Response:    SIZE
Response:   211 End
Command:    OPTS UTF8 ON
Response:   200 UTF8 set to on
Status: Connected
Status: Retrieving directory listing...
Command:    PWD
Response:   257 "/" is the current directory
Command:    TYPE I
Response:   200 Type set to I
Command:    PASV
Response:   227 Entering Passive Mode (xxx,xxx,xxx,xx,xxx,xxx).
Command:    MLSD

And it stop after MLSD and after some time says

Error:  Connection timed out
Error:  Failed to retrieve directory listing

I am able to connect to  server through ftp when i connect internet from my mobile.but i dont want to do like that.i need to work with my cable net.

I am using Windows 7 and Laptop.

Please help me to connect.


问:
UWP app doesn't receive UDP Datagram from a .NET desktop app on localhost
I've been trying to setup a client server between a UWP app as the client and a .NET desktop app as the server. I'm using UDP Datagrams as the messaging system between the two.

Here my UWP code to listen for Datagrams on the localhost IP at port 22222:

```<code>private async void listenToServer()
{
    // Setup UDP Listener
    socketListener = new DatagramSocket();
    socketListener.MessageReceived += MessageReceived;

    await socketListener.BindEndpointAsync(new HostName("127.0.0.1"),"22222");
    Debug.WriteLine("Listening: " + socketListener.Information.LocalAddress + " " + socketListener.Information.LocalPort);
 }

private async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
    // Interpret the incoming datagram's entire contents as a string.
    uint stringLength = args.GetDataReader().UnconsumedBufferLength;
    string receivedMessage = args.GetDataReader().ReadString(stringLength);
    Debug.WriteLine("Received " + receivedMessage);
}
</code>```

Here is my WinForm .NET desktop app to send Datagrams on localhost on port 2222:

```<code>public async void sendToClient()
{
    // Setup UDP Talker
    talker = new UdpClient();
    sending_end_point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
    talker.Connect(sending_end_point);

    byte[] send_buffer = Encoding.ASCII.GetBytes("Hello!");
    await talker.SendAsync(send_buffer, send_buffer.Length);
}
</code>```

Here is what I've tried, and what I know from my troubleshooting:

Sending a UDP datagram from UWP to .NET desktop works.

UWP code to send message to .NET desktop over localhost port 11111:

```<code>public async void sendToServer()
{
    // Connect to the server
    socketTalker = new DatagramSocket();
    await socketTalker.ConnectAsync(new HostName("127.0.0.1"), "11111");
    Debug.WriteLine("Connected: " + socketTalker.Information.RemoteAddress + " " + socketTalker.Information.RemotePort);

    // Setup Writer
    writer = new DataWriter(socketTalker.OutputStream);
    writer.WriteString("Ping!");

    await writer.StoreAsync();

    writer.DetachStream();
    writer.Dispose();
}
</code>```

.NET desktop code to listen for message from UWP over same IP and port:

```<code>private async Task listenToClient()
{
    // Setup listener
    listener = new UdpClient(11111);
    UdpReceiveResult receiveResult = await listener.ReceiveAsync();
    Debug.WriteLine(" Received: " + Encoding.ASCII.GetString(receiveResult.Buffer));

}
</code>```

Sending UDP Datagram from .NET desktop to UWP works across different IPs (2 different computers)

I've tested this by setting the listener and talker IP addresses to the same IP address where the server was running, and it works flawlessly. This lead to research which got me to #3...

Loopback exemption didn't make a difference

Running CheckNetIsolation.exe and the Loopback exemption tool to exempt the UWP app from loopback IP restriction didn't fix this issue. It seems it shouldn't matter, from what I read (Problems with UDP in windows 10. UWP), running in the Visual Studio environment should already be exempt from loopback, but I tried anyways, and not luck.

答:
As much as this sucks, it is blocked by Microsoft by design.

Loopback is permitted only for development purposes. Usage by a
  Windows Runtime app installed outside of Visual Studio is not
  permitted. Further, a Windows Runtime app can use an IP loopback only
  as the target address for a client network request. So a Windows
  Runtime app that uses a DatagramSocket or StreamSocketListener to
  listen on an IP loopback address is prevented from receiving any
  incoming packets.

Source: https://msdn.microsoft.com/en-us/library/windows/apps/hh780593.aspx

The best workaround you can do is to use TCP sockets and connect from the UWP app to your desktop app (not the other way around).

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to setup a client server between a UWP app as the client and a .NET desktop app as the server. I'm using UDP Datagrams as the messaging system between the two.

Here my UWP code to listen for Datagrams on the localhost IP at port 22222:

private async void listenToServer()
{
    // Setup UDP Listener
    socketListener = new DatagramSocket();
    socketListener.MessageReceived += MessageReceived;

    await socketListener.BindEndpointAsync(new HostName("127.0.0.1"),"22222");
    Debug.WriteLine("Listening: " + socketListener.Information.LocalAddress + " " + socketListener.Information.LocalPort);
 }

private async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
    // Interpret the incoming datagram's entire contents as a string.
    uint stringLength = args.GetDataReader().UnconsumedBufferLength;
    string receivedMessage = args.GetDataReader().ReadString(stringLength);
    Debug.WriteLine("Received " + receivedMessage);
}

Here is my WinForm .NET desktop app to send Datagrams on localhost on port 2222:

public async void sendToClient()
{
    // Setup UDP Talker
    talker = new UdpClient();
    sending_end_point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 22222);
    talker.Connect(sending_end_point);

    byte[] send_buffer = Encoding.ASCII.GetBytes("Hello!");
    await talker.SendAsync(send_buffer, send_buffer.Length);
}

Here is what I've tried, and what I know from my troubleshooting:

Sending a UDP datagram from UWP to .NET desktop works.

UWP code to send message to .NET desktop over localhost port 11111:

public async void sendToServer()
{
    // Connect to the server
    socketTalker = new DatagramSocket();
    await socketTalker.ConnectAsync(new HostName("127.0.0.1"), "11111");
    Debug.WriteLine("Connected: " + socketTalker.Information.RemoteAddress + " " + socketTalker.Information.RemotePort);

    // Setup Writer
    writer = new DataWriter(socketTalker.OutputStream);
    writer.WriteString("Ping!");

    await writer.StoreAsync();

    writer.DetachStream();
    writer.Dispose();
}

.NET desktop code to listen for message from UWP over same IP and port:

private async Task listenToClient()
{
    // Setup listener
    listener = new UdpClient(11111);
    UdpReceiveResult receiveResult = await listener.ReceiveAsync();
    Debug.WriteLine(" Received: " + Encoding.ASCII.GetString(receiveResult.Buffer));

}

Sending UDP Datagram from .NET desktop to UWP works across different IPs (2 different computers)

I've tested this by setting the listener and talker IP addresses to the same IP address where the server was running, and it works flawlessly. This lead to research which got me to #3...

Loopback exemption didn't make a difference

Running CheckNetIsolation.exe and the Loopback exemption tool to exempt the UWP app from loopback IP restriction didn't fix this issue. It seems it shouldn't matter, from what I read (Problems with UDP in windows 10. UWP), running in the Visual Studio environment should already be exempt from loopback, but I tried anyways, and not luck.


问:
Removing specific integers from columns in a dataframe using R
Here is what my current dataframe looks like:

```<code>Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("001001", "001002", "001002", "002002")
Loc2 <- c("001002", "002002", "001002", "001001")
Loc3 <- c("002002", "001002", "001002", "001001")
dat <- data.frame(Name, Loc1, Loc2, Loc3)
dat
</code>```

And this is my desired result:

```<code>Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("11", "12", "12", "22")
Loc2 <- c("12", "22", "12", "11")
Loc3 <- c("22", "12", "12", "11")
result <- data.frame(Name, Loc1, Loc2, Loc3)
result
</code>```

Note that the number remain the same, but I am looking for a way fro remove the "0" characters from multiple columns and leave behind other integers. I have tried using various incarnations of the strstring() and substr() functions for this, but seem to keep getting stuck because  "0" is not recognized as a character. It seems a fairly simple problem but I need some advice. Thanks in advance.

答:
Quick and easy gsub over all columns except the first.

```<code>dat[-1] <- lapply(dat[-1], gsub, pattern = "0", replacement = "")
dat
#     Name Loc1 Loc2 Loc3
# 1   John   11   12   22
# 2   Paul   12   22   12
# 3  Ringo   12   12   12
# 4 George   22   11   11
</code>```

Body:
Here is what my current dataframe looks like:

Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("001001", "001002", "001002", "002002")
Loc2 <- c("001002", "002002", "001002", "001001")
Loc3 <- c("002002", "001002", "001002", "001001")
dat <- data.frame(Name, Loc1, Loc2, Loc3)
dat

And this is my desired result:

Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("11", "12", "12", "22")
Loc2 <- c("12", "22", "12", "11")
Loc3 <- c("22", "12", "12", "11")
result <- data.frame(Name, Loc1, Loc2, Loc3)
result

Note that the number remain the same, but I am looking for a way fro remove the "0" characters from multiple columns and leave behind other integers. I have tried using various incarnations of the strstring() and substr() functions for this, but seem to keep getting stuck because  "0" is not recognized as a character. It seems a fairly simple problem but I need some advice. Thanks in advance.

Body:
Quick and easy gsub over all columns except the first.

dat[-1] <- lapply(dat[-1], gsub, pattern = "0", replacement = "")
dat
#     Name Loc1 Loc2 Loc3
# 1   John   11   12   22
# 2   Paul   12   22   12
# 3  Ringo   12   12   12
# 4 George   22   11   11


问:
SQL - How to find which page is the first for users?
I have a table like this:

```<code>+----------+-------------------------------------+----------------------------------+
| user_id  | time                                | url                              |
+----------+-------------------------------------+----------------------------------+
| 1        | 02.04.2017 8:56                     | www.landingpage.com/              |
| 1        | 02.04.2017 8:57                     | www.landingpage.com/about-us     |
| 1        | 02.04.2017 8:58                     | www.landingpage.com/faq          |
| 2        | 02.04.2017 6:34                     | www.landingpage.com/about-us     |
| 2        | 02.04.2017 6:35                     | www.landingpage.com/how-to-order |
| 3        | 03.04.2017 9:11                     | www.landingpage.com/             |
| 3        | 03.04.2017 9:12                     | www.landingpage.com/contact      |
| 3        | 03.04.2017 9:13                     | www.landingpage.com/about-us     |
| 3        | 03.04.2017 9:14                     | www.landingpage.com/our-legacy   |
| 3        | 03.04.2017 9:15                     | www.landingpage.com/             |
+----------+-------------------------------------+----------------------------------+
</code>```

I want to figure out which page is the first for most users (first page a user see when he comes to the site) and count the number of times it is viewed as the first page.

Is there a way to write a query to do this? I guess I need to use

```<code>MIN(time)
</code>```

in conjunction with grouping but I don't know how.

So regarding the sample I provided it should be like:

```<code>url                                       url_count
---------------------------------------------------
www.landingpage.com/                      2
www.landingpage.com/about-us              1
</code>```

Thanks!

答:
You're correct, you'll need to use the min() aggregate function within a subselect.

```<code>select
  my_table.url
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )
</code>```

replace my_table with whatever your table is actually named.

To include how many pages the user has seen, you'll need something like this:

```<code>select
  my_table.url
  , (
    select
      count(t.url)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  ) as url_count
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )
</code>```

Body:
I have a table like this:

+----------+-------------------------------------+----------------------------------+
| user_id  | time                                | url                              |
+----------+-------------------------------------+----------------------------------+
| 1        | 02.04.2017 8:56                     | www.landingpage.com/              |
| 1        | 02.04.2017 8:57                     | www.landingpage.com/about-us     |
| 1        | 02.04.2017 8:58                     | www.landingpage.com/faq          |
| 2        | 02.04.2017 6:34                     | www.landingpage.com/about-us     |
| 2        | 02.04.2017 6:35                     | www.landingpage.com/how-to-order |
| 3        | 03.04.2017 9:11                     | www.landingpage.com/             |
| 3        | 03.04.2017 9:12                     | www.landingpage.com/contact      |
| 3        | 03.04.2017 9:13                     | www.landingpage.com/about-us     |
| 3        | 03.04.2017 9:14                     | www.landingpage.com/our-legacy   |
| 3        | 03.04.2017 9:15                     | www.landingpage.com/             |
+----------+-------------------------------------+----------------------------------+

I want to figure out which page is the first for most users (first page a user see when he comes to the site) and count the number of times it is viewed as the first page.

Is there a way to write a query to do this? I guess I need to use

MIN(time)

in conjunction with grouping but I don't know how.

So regarding the sample I provided it should be like:

url                                       url_count
---------------------------------------------------
www.landingpage.com/                      2
www.landingpage.com/about-us              1

Thanks!

Body:
You're correct, you'll need to use the min() aggregate function within a subselect.

select
  my_table.url
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )

replace my_table with whatever your table is actually named.

To include how many pages the user has seen, you'll need something like this:

select
  my_table.url
  , (
    select
      count(t.url)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  ) as url_count
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )


问:
JSON file is fetched correctly but fetched data are not displayed in console log
I am trying to do a simple ajax request to retrieve a json file from the server and store it in a javascript object.

I have tried 2 different methods .ajax() method and .getJSON().
Both methods in the Network console seem to fetch the file with result HTTP/1.1 200 OK.

But when I tried to output the received data in the console with console.log(data) nothing shows up.

I have enabled the cross-origin requests in Firefox as I run my code locally and the web server is on a Rpi(Wordpress).

```<code>$.ajax({
            url: 'http://192.168.0.227/json/sysC01.json',
            dataType: 'json',
            type: 'GET',
            cache: false,
            crossDomain: true,
            success: function(data){
                console.log(data);
            },

        });

$.getJSON("http://192.168.0.227/json/sysC01.json", function(result){
                console.log(result);
            });
</code>```

As a first step I want to see that the data are received, which I can't at the moment, and afterwards I would like to store the data in a Javascript object and output them inside a div element with a certain format.

Any suggestion is highly appreciated.

答:
After trying a lot of different things what fixed the issue was running Chrome from the command line with web security disabled.

The relative command:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Body:
I am trying to do a simple ajax request to retrieve a json file from the server and store it in a javascript object.

I have tried 2 different methods .ajax() method and .getJSON().
Both methods in the Network console seem to fetch the file with result HTTP/1.1 200 OK.

But when I tried to output the received data in the console with console.log(data) nothing shows up.

I have enabled the cross-origin requests in Firefox as I run my code locally and the web server is on a Rpi(Wordpress).

$.ajax({
            url: 'http://192.168.0.227/json/sysC01.json',
            dataType: 'json',
            type: 'GET',
            cache: false,
            crossDomain: true,
            success: function(data){
                console.log(data);
            },

        });

$.getJSON("http://192.168.0.227/json/sysC01.json", function(result){
                console.log(result);
            });

As a first step I want to see that the data are received, which I can't at the moment, and afterwards I would like to store the data in a Javascript object and output them inside a div element with a certain format.

Any suggestion is highly appreciated.


问:
IdentationError: Unexpected indent following Django Tutorial
I'm following the tutorial on django on the following link:

https://docs.djangoproject.com/en/1.11/intro/tutorial02/

Specifically the part where its adding the str methods on both classes, but I'm getting the indent error!

I used python before and after looking for a while I still can't see my error!

See the image with the hidden characters of my code, what is it!? It's been driving me crazy:

See the error when trying to run the python shell:

So what could it be? I am legit running out of ideas.

Thank you!

答:
From the Python documentation https://docs.python.org/3/reference/lexical_analysis.html

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

if you are consistent in your use of tabs and spaces this problem will go away.


Title: Removing specific integers from columns in a dataframe using R

Body:
in order for this to work you need both gsub and a member of the apply family, like this:

Name <- c("John", "Paul", "Ringo", "George")
Loc1 <- c("001001", "001002", "001002", "002002")
Loc2 <- c("001002", "002002", "001002", "001001")
Loc3 <- c("002002", "001002", "001002", "001001")
dat <- data.frame(Name, Loc1, Loc2, Loc3)

data.frame(sapply(dat, function(x) {gsub("0", "", x)}))

# Name Loc1 Loc2 Loc3
# 1   John   11   12   22
# 2   Paul   12   22   12
# 3  Ringo   12   12   12
# 4 George   22   11   11


答:
The problem is that your are defining the function after you call it, this would do: </p>

```<code>def main():

  userName = ("u123")
  userPass = ("p123")

  userNameInput = input("Username: ")
  userPassInput = input("Password: ")

  def access():

      print("Welcome, " + userName)

  if userPassInput == userPass and userNameInput == userName:
      print("Access granted")
      access()

  else:
      print("Access denied")
      return main()

  access()

main()
</code>```

<p>(asuming you aren't just confusing the spaces and actually didn't wanted to define one function inside the other) </p>

Title: Error when If statement to definition. (Python)

Body:
The problem is that your are defining the function after you call it, this would do:

def main():

  userName = ("u123")
  userPass = ("p123")

  userNameInput = input("Username: ")
  userPassInput = input("Password: ")

  def access():

      print("Welcome, " + userName)

  if userPassInput == userPass and userNameInput == userName:
      print("Access granted")
      access()

  else:
      print("Access denied")
      return main()

  access()

main()

(asuming you aren't just confusing the spaces and actually didn't wanted to define one function inside the other)


问:
Transforming JSON from API into an activity stream
I am doing a project for fun and one of the requirements is to the JSON data from an API of my choice and transform it into an activity stream using angularjs.

I've googled and read what an activity stream is and I believe I have a basic understanding of it. It's essentially transforming an action into a specific JSON format using the keywords "actor", "verb", "object", and "target".

When I look at examples, I understand why that specific JSON string is considered an activity stream.

Example:

```<code>  {
"published": "2011-02-10T15:04:55Z",
"actor": {
  "url": "http://example.org/martin",
  "objectType" : "person",
  "id": "tag:example.org,2011:martin",
  "image": {
    "url": "http://example.org/martin/image",
    "width": 250,
    "height": 250
  },
  "displayName": "Martin Smith"
},
"verb": "post",
"object" : {
  "url": "http://example.org/blog/2011/02/entry",
  "id": "tag:example.org,2011:abc123/xyz"
},
"target" : {
  "url": "http://example.org/blog/",
  "objectType": "blog",
  "id": "tag:example.org,2011:abc123",
  "displayName": "Martin's Blog"
}
</code>```

}

But I'm confused in terms of how to transform my JSON Data into an activity stream.

My JSON doesn't have an "actor", nor does it have a "verb". If anyone can please explain or provide a solution that would be greatly appreciated. Thank you!

Weather API

```<code>{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 300,
      "main": "Drizzle",
      "description": "light intensity drizzle",
      "icon": "09d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 280.32,
    "pressure": 1012,
    "humidity": 81,
    "temp_min": 279.15,
    "temp_max": 281.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 4.1,
    "deg": 80
  },
  "clouds": {
    "all": 90
  },
  "dt": 1485789600,
  "sys": {
    "type": 1,
    "id": 5091,
    "message": 0.0103,
    "country": "GB",
    "sunrise": 1485762037,
    "sunset": 1485794875
  },
  "id": 2643743,
  "name": "London",
  "cod": 200
}
</code>```

答:
ActivityStream is just a specification for activities. Weather is just a model. A model can either be a subject/actor or an object that an actor acts upon to. In this case, weather can only be an object.

An example of activity that deals with weather is:

Martin checks the weather for London at 3:04 PM UTC on February 10, 2015.

The corresponding activity JSON is:

```<code>{
  "published": "2015-02-10T15:04:55Z",
  "actor": {
    "url": "http://example.org/martin",
    "objectType" : "person",
    "id": "tag:example.org,2011:martin",
    "image": {
      "url": "http://example.org/martin/image",
      "width": 250,
      "height": 250
    },
    "displayName": "Martin Smith"
  },
  "verb": "search",
  "object" : {
    "url": "http://api.openweathermap.org/data/2.5/weather?q=London",
    "name": "London's weather",
    "published": "2015-02-10T15:04:55Z"
  }
}
</code>```

Note that this is only an example. You may have different activities, depending on how you want to use the weather data.

Body:
I am doing a project for fun and one of the requirements is to the JSON data from an API of my choice and transform it into an activity stream using angularjs.

I've googled and read what an activity stream is and I believe I have a basic understanding of it. It's essentially transforming an action into a specific JSON format using the keywords "actor", "verb", "object", and "target".

When I look at examples, I understand why that specific JSON string is considered an activity stream.

Example:

  {
"published": "2011-02-10T15:04:55Z",
"actor": {
  "url": "http://example.org/martin",
  "objectType" : "person",
  "id": "tag:example.org,2011:martin",
  "image": {
    "url": "http://example.org/martin/image",
    "width": 250,
    "height": 250
  },
  "displayName": "Martin Smith"
},
"verb": "post",
"object" : {
  "url": "http://example.org/blog/2011/02/entry",
  "id": "tag:example.org,2011:abc123/xyz"
},
"target" : {
  "url": "http://example.org/blog/",
  "objectType": "blog",
  "id": "tag:example.org,2011:abc123",
  "displayName": "Martin's Blog"
}

}

But I'm confused in terms of how to transform my JSON Data into an activity stream.

My JSON doesn't have an "actor", nor does it have a "verb". If anyone can please explain or provide a solution that would be greatly appreciated. Thank you!

Weather API

{
  "coord": {
    "lon": -0.13,
    "lat": 51.51
  },
  "weather": [
    {
      "id": 300,
      "main": "Drizzle",
      "description": "light intensity drizzle",
      "icon": "09d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 280.32,
    "pressure": 1012,
    "humidity": 81,
    "temp_min": 279.15,
    "temp_max": 281.15
  },
  "visibility": 10000,
  "wind": {
    "speed": 4.1,
    "deg": 80
  },
  "clouds": {
    "all": 90
  },
  "dt": 1485789600,
  "sys": {
    "type": 1,
    "id": 5091,
    "message": 0.0103,
    "country": "GB",
    "sunrise": 1485762037,
    "sunset": 1485794875
  },
  "id": 2643743,
  "name": "London",
  "cod": 200
}

Body:
ActivityStream is just a specification for activities. Weather is just a model. A model can either be a subject/actor or an object that an actor acts upon to. In this case, weather can only be an object.

An example of activity that deals with weather is:

Martin checks the weather for London at 3:04 PM UTC on February 10, 2015.

The corresponding activity JSON is:

{
  "published": "2015-02-10T15:04:55Z",
  "actor": {
    "url": "http://example.org/martin",
    "objectType" : "person",
    "id": "tag:example.org,2011:martin",
    "image": {
      "url": "http://example.org/martin/image",
      "width": 250,
      "height": 250
    },
    "displayName": "Martin Smith"
  },
  "verb": "search",
  "object" : {
    "url": "http://api.openweathermap.org/data/2.5/weather?q=London",
    "name": "London's weather",
    "published": "2015-02-10T15:04:55Z"
  }
}

Note that this is only an example. You may have different activities, depending on how you want to use the weather data.


问:
How to select area within a plot (Python) and extract the data within the area
I am currently working with a dataset that includes signals with a duration of around 10 seconds and a sampling time of 0.1 seconds.
My goal is to extract a specific part of this data and save it into a python dictionary. The relevant part is about 4 seconds long.

Ideally this is what I would like to do:

Plot the whole 10 seconds of data.

Mark the relevant part of the signals for example with a bounding box.

Extract the data within the bounding box after closing the plot window or pushing a button.

Go back to 1. and take new data.

I saw that matplotlib has the ability to draw patches and extract the data points within the patch. Is it maybe possible to add a patch to the plot after the plot was created (after the plt.show() command was executed)?

Thank you in advance and best regards,

Manuel

答:
You may use a SpanSelector.

You basically only need to add a line for saving to the matplotlib example.

```<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211)

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2, 2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212)
line2, = ax2.plot(x, y, '-')

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw_idle()

    # save
    np.savetxt("text.out", np.c_[thisx, thisy])

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red'))

plt.show()
</code>```

Body:
You may use a SpanSelector.

You basically only need to add a line for saving to the matplotlib example.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211)

x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2, 2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212)
line2, = ax2.plot(x, y, '-')

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(x, (xmin, xmax))
    indmax = min(len(x) - 1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw_idle()

    # save
    np.savetxt("text.out", np.c_[thisx, thisy])

# set useblit True on gtkagg for enhanced performance
span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red'))

plt.show()


问:
How to get the Rows cell value from columnHeaderNames in excel using c#
my requirement is to read the rows of a specified column from an excel sheet. eg

from the above excel if i need to get rows values of column (ie) B how to get it.
am getting the column header names using the below code.

```<code>     Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(FileNameTextBox.Text);
        Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
        int columnCount = xlWorksheet.UsedRange.Columns.Count;
        List<string> columnNames = new List<string>();
        for (int c = 1; c < columnCount; c++)
        {
            if (xlWorksheet.Cells[1, c].Value2 != null)
            {
                string columnName = xlWorksheet.Columns[c].Address;
                Regex reg = new Regex(@"(\$)(\w*):");
                if (reg.IsMatch(columnName))
                {
                    Match match = reg.Match(columnName);
                    columnNames.Add(match.Groups[2].Value);
                }
            }
        }
</code>```

where it gives me a output of  list contains A,B,C,D,E,F .from this if i need to get the value of column C alone ,then how to get it..?

答:
This Method returns the values of cells in the first row of an excel sheet:

```<code>public static string[] FirstRowInWorkSheet(string filename, int sheetNumber)
    {
        Application xlsApp = new Application();
        Workbook wb = xlsApp.Workbooks.Open(filename,
            0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);

        var sheets= wb.Worksheets;
        Worksheet xlWorksheet =sheets[sheetNumber];

        int columnCount = xlWorksheet.UsedRange.Columns.Count;
        Range xlRange = xlWorksheet.UsedRange;
        string[] firstRow = new string[columnCount];

        for (int c = 0; c < columnCount; c++)
        {
            if (xlRange.Cells[1, c + 1].Value2 != null)
            {
                firstRow[c] = xlRange.Cells[1, c + 1].Value2.ToString();
            }
        }
        return firstRow;
    }
</code>```

This code helps you get the header of your table as an array. When the user selects the column, take its index, and then manipulate the cells for one column- the same way it was manipulated for the 1st row- just change what you fix in Cell[i,j]: fix j according to what the user choose.

Body:
my requirement is to read the rows of a specified column from an excel sheet. eg

from the above excel if i need to get rows values of column (ie) B how to get it.
am getting the column header names using the below code.

     Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(FileNameTextBox.Text);
        Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // assume it is the first sheet
        int columnCount = xlWorksheet.UsedRange.Columns.Count;
        List<string> columnNames = new List<string>();
        for (int c = 1; c < columnCount; c++)
        {
            if (xlWorksheet.Cells[1, c].Value2 != null)
            {
                string columnName = xlWorksheet.Columns[c].Address;
                Regex reg = new Regex(@"(\$)(\w*):");
                if (reg.IsMatch(columnName))
                {
                    Match match = reg.Match(columnName);
                    columnNames.Add(match.Groups[2].Value);
                }
            }
        }

where it gives me a output of  list contains A,B,C,D,E,F .from this if i need to get the value of column C alone ,then how to get it..?

Body:
This Method returns the values of cells in the first row of an excel sheet:

public static string[] FirstRowInWorkSheet(string filename, int sheetNumber)
    {
        Application xlsApp = new Application();
        Workbook wb = xlsApp.Workbooks.Open(filename,
            0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);

        var sheets= wb.Worksheets;
        Worksheet xlWorksheet =sheets[sheetNumber];

        int columnCount = xlWorksheet.UsedRange.Columns.Count;
        Range xlRange = xlWorksheet.UsedRange;
        string[] firstRow = new string[columnCount];

        for (int c = 0; c < columnCount; c++)
        {
            if (xlRange.Cells[1, c + 1].Value2 != null)
            {
                firstRow[c] = xlRange.Cells[1, c + 1].Value2.ToString();
            }
        }
        return firstRow;
    }

This code helps you get the header of your table as an array. When the user selects the column, take its index, and then manipulate the cells for one column- the same way it was manipulated for the 1st row- just change what you fix in Cell[i,j]: fix j according to what the user choose.


问:
How to push Credentials to an APP with Airwatch
We have an App that is normally used with login + password.
But when we want to deploy this app to a customer who has airwatch (which we can handle things through their API), what would be the way to push individual creditals to the Mobile Devices through the Airwatch integration?

Or can I push the App to the iOS Devices with pre-configured individual credentials through Airwatch?
The Apple EMM Features seem to cover this topic, but they don't have examples how to do this without the help of an MDM.

答:
Here is what I have done to make it work with AirWatch. This concept uses "App Configuration" mechanism provided by Apple's MDM Protocol

Login to Airwatch Console

Click "Apps & Books" section

Click "List View" under the "Application" Tab

Here we have to add the application, which needs custom info(in your case it is credentials). It allows you for both AppStore apps as well as Internal(Enterprise profile signed) app.

Click on the application which we just added

Look for option "Assign", this is like a app-delivery-configuration profile.

If you dont have one already, create one with what ever config details you need

In our context we need to Enable "Application Configuration" Tab, which will enable us to enter key-value pairs. Here we can enter any custom key-value pair parameters.

Then click add, then Save and Publish.

Now the app should receive these custom key-values pairs in com.apple.configuration.managed in NSUserDefaults dictionary.


问:
How do you index into a var in LINQ?
I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?</p>

```<code>string[] sa = {"one", "two", "three"};
sa[1].Dump();

var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
</code>```

答: As the comment says, you cannot apply indexing with [] to an expression of type System.Collections.Generic.IEnumerable<T>. The IEnumerable interface only supports the method GetEnumerator(). However with LINQ you can call the extension method ElementAt(int).

OwnerDisplayName: Guy

Title: How do you index into a var in LINQ?

Body:
I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?

string[] sa = {"one", "two", "three"};
sa[1].Dump();

var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'

OwnerDisplayName: Joseph Daigle


问:
Blackberry Platform
Currently i am working on Blackberry JDE 4.3 and i want to know that is there any other platform for Blacberry onwhich we can easily make applications with short time. Such as in Blacberrry JDE, to handle graphics you have to include so many api's and there exists many complexities in the JDE platform.</p>

答:
have you tried working with blackberry eclipse plugin
i feel it better than the jde</p>

Title: Blackberry Platform


问:
rpm build will remove .symtab/.strtab section?
I'm trying to build a binary with .symtab and .strtab section to trace functions.
I'm using "make && make install", the binary is ok.
But when I use "make rpm" and install rpm package, both of .symtab and .strtab section are gone which is weired.
I track the rpm build log, and saw those:

```<code>libtool: install: /usr/bin/install -c mybinary /root/rpmbuild/BUILDROOT/mybinary.el7.centos.x86_64/usr/sbin/mybinary
</code>```

and here, I executed it manually again, the .symtab section exists.

```<code>extracting debug info from /root/rpmbuild/BUILDROOT/mybinary.el7.centos.x86_64/usr/sbin/mybinary
</code>```

After this step, the .symtab section is gone, I guess there's something wrong here. But I don't know why.
Please help.

答: rpmbuild automatically strip debuging info and place it in -debug subpackage. If you want to preserve it for some reason follow https://imvoid.wordpress.com/2013/06/05/stripping-and-stopping-stripping-of-binaries-in-rpm-build/</p>

Body:
I'm trying to build a binary with .symtab and .strtab section to trace functions.
I'm using "make && make install", the binary is ok.
But when I use "make rpm" and install rpm package, both of .symtab and .strtab section are gone which is weired.
I track the rpm build log, and saw those:

libtool: install: /usr/bin/install -c mybinary /root/rpmbuild/BUILDROOT/mybinary.el7.centos.x86_64/usr/sbin/mybinary

and here, I executed it manually again, the .symtab section exists.

extracting debug info from /root/rpmbuild/BUILDROOT/mybinary.el7.centos.x86_64/usr/sbin/mybinary

After this step, the .symtab section is gone, I guess there's something wrong here. But I don't know why.
Please help.