问:
Need to design a table with loads of attributes which must all be searchable by SQL
I'm in a fix here. I'm building a home reservation site and the client requires a filter search facility to allow visitors to search and filter through properties based upon criteria. The thing is that his list of criteria is exceedingly long, largely boolean values and calculable values stuff like:

Attached bathroom, balcony, smoking, alcoholic, maximum number of occupants, cable TV, Internet, carpeted, airconditioning, central heating, room service, etc., etc., etc...

I'm thinking of having to create a field for each of these, but there's a very strong chance that the number of preferences might even go up. I dished out the idea of storing everying in a serialised object as a string as then it would be impossible to search using an SQL query. Do I have any options apart from setting up individual fields for each preference here?

Thanks. I'm using PHP MySQL.

答:
I did exactly the same search a couple years back for a hotel catalogue. We used a BitMask for that, e.g. we stored a single number representing all the possible values, e.g.

```<code>HotelTable
ID Name         …    Features
 1 SuperHotel   …    5

Features
ID Name
 1 Balcony
 2 Shower
 4 Barrier-Free
 8 Whatever
 … …
</code>```

In the example above SuperHotel would have a Balcony and be Barrier-Free (4+1).

While this worked well, I am not sure I'd handle it this way again. Basically, all these features are the same as tags, so you could just as well use the known approaches to create a tagging table.

Body:
I did exactly the same search a couple years back for a hotel catalogue. We used a BitMask for that, e.g. we stored a single number representing all the possible values, e.g.

HotelTable
ID Name         …    Features
 1 SuperHotel   …    5

Features
ID Name
 1 Balcony
 2 Shower
 4 Barrier-Free
 8 Whatever
 … …

In the example above SuperHotel would have a Balcony and be Barrier-Free (4+1).

While this worked well, I am not sure I'd handle it this way again. Basically, all these features are the same as tags, so you could just as well use the known approaches to create a tagging table.


来源: stackexchange

问:
Angular - Showing Hiding Spinner when RxJs Subscription is active
I want to implement a directive to show a spinner on top of a container element.
e.g. consider the following scenario

```<code><component [spinner]="{subs: [usersSub, accountsSub], latency: 500}"></component>
</code>```

Here [spinner] is the directive that receives object as param which contains:

subs: array of RxJS Subscriptions to show spinner whenever any of these subscriptions are loading.

latency: time in ms to show spinner if request exceeds this time.

I know how to show a spinner's dom on top of components dom. I need help in monitoring subscriptions.

答:
How to monitor subscriptions

The library you referenced in comments, angular-2-busy, monitors subscriptions by adding them to an array and also using the subscription's add() method to add a teardown method which is called when the subscription unsubscribes.

See this from RxJs 5.5.2 source, Subscription.ts

add(teardown: TeardownLogic): Subscription {
  ...
```

<p>The teardown function removes the subscription from the monitor array, so when this array is empty the spinner stops.  </p>

<p>I am wondering what it is about <strong><em>angular-2-busy</em></strong> that you don't like or will improve upon in your own directive?<br>
<br/></p>

<p><strong>When does a subscription unsubscribe</strong>  </p>

<p>On this question, the source for Subscriber has these internal functions so the subscription unsubscribes on either complete or error events (and of course when unsubscribe is called explicitly).</p>

<pre class="lang-js prettyprint-override"><code>Subscriber.prototype._complete = function () {
    this.destination.complete();
    this.unsubscribe();
};

Subscriber.prototype._error = function (err) {
    this.destination.error(err);
    this.unsubscribe();
};
</code>```

Subscriptions that don't complete or error will keep the spinner spinning.

ContentLicense: CC BY-SA 3.0

Body:
I want to implement a directive to show a spinner on top of a container element.
e.g. consider the following scenario

<component [spinner]="{subs: [usersSub, accountsSub], latency: 500}"></component>

Here [spinner] is the directive that receives object as param which contains:

subs: array of RxJS Subscriptions to show spinner whenever any of these subscriptions are loading.

latency: time in ms to show spinner if request exceeds this time.

I know how to show a spinner's dom on top of components dom. I need help in monitoring subscriptions.

Body:
How to monitor subscriptions

The library you referenced in comments, angular-2-busy, monitors subscriptions by adding them to an array and also using the subscription's add() method to add a teardown method which is called when the subscription unsubscribes.

See this from RxJs 5.5.2 source, Subscription.ts

add(teardown: TeardownLogic): Subscription {
  ...

The teardown function removes the subscription from the monitor array, so when this array is empty the spinner stops.

I am wondering what it is about angular-2-busy that you don't like or will improve upon in your own directive?

When does a subscription unsubscribe

On this question, the source for Subscriber has these internal functions so the subscription unsubscribes on either complete or error events (and of course when unsubscribe is called explicitly).

Subscriber.prototype._complete = function () {
    this.destination.complete();
    this.unsubscribe();
};

Subscriber.prototype._error = function (err) {
    this.destination.error(err);
    this.unsubscribe();
};

Subscriptions that don't complete or error will keep the spinner spinning.


问:
creating a many to one relationship in django with an existing model
How can I create a many to one relationship with an existing model in django? Looking at the documentation, You can see that you can create a foreign key and create and object with a reference to the other model.

For example,

```<code>r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
r.save()
a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
</code>```

You can then access the id of r with a.reporter.id.

One problem with this, however is that if you wanted to check the id of r through a, you have to create a in order to do it.

How would you do this with an already existing model?

As an example, if I have a user and I want the user to be able to create multiple characters for a game, how can I assign the character a foreign key to the user if the user already exists?

Looking at this answer, you see that you need to give the model that you want to reference to the foreign key, but it doesn't actually explain how to do it.

答:
How would you do this with an already existing model?

It's unclear which model you're referring to. If you mean an existing reporter, you'd get it and do it exactly the same way:

```<code>r = Reporter.objects.get(email='john@example.com')
a = Article(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
</code>```

If you mean an existing article, you can change the foreign key just like any model instance field:

```<code>a = Article.objects.get(headline="This is a test")
a.r = Reporter.objects.create(...)   # or .get() depending on what you want.
a.save()
</code>```

How can I assign the character a foreign key to the user if the user already exists?

Using the same logic, you'd get the user and create a new character with this existing user object:

```<code># Get user, or if this was the logged in user maybe just request.user
user = User.objects.get(username='wanderer')

# Create the character, using the existing user as a foreign key
# (the .create is just shorthand for creating the object then saving it)
Character.objects.create(character_name='Trogdor', user=user)

# Or alternatively, you can simply use the implicit reverse relationship
user.character_set.create(character_name='Homestar Runner')
</code>```

Body:
How can I create a many to one relationship with an existing model in django? Looking at the documentation, You can see that you can create a foreign key and create and object with a reference to the other model.

For example,

r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
r.save()
a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()

You can then access the id of r with a.reporter.id.

One problem with this, however is that if you wanted to check the id of r through a, you have to create a in order to do it.

How would you do this with an already existing model?

As an example, if I have a user and I want the user to be able to create multiple characters for a game, how can I assign the character a foreign key to the user if the user already exists?

Looking at this answer, you see that you need to give the model that you want to reference to the foreign key, but it doesn't actually explain how to do it.

Body:
How would you do this with an already existing model?

It's unclear which model you're referring to. If you mean an existing reporter, you'd get it and do it exactly the same way:

r = Reporter.objects.get(email='john@example.com')
a = Article(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()

If you mean an existing article, you can change the foreign key just like any model instance field:

a = Article.objects.get(headline="This is a test")
a.r = Reporter.objects.create(...)   # or .get() depending on what you want.
a.save()

How can I assign the character a foreign key to the user if the user already exists?

Using the same logic, you'd get the user and create a new character with this existing user object:

# Get user, or if this was the logged in user maybe just request.user
user = User.objects.get(username='wanderer')

# Create the character, using the existing user as a foreign key
# (the .create is just shorthand for creating the object then saving it)
Character.objects.create(character_name='Trogdor', user=user)

# Or alternatively, you can simply use the implicit reverse relationship
user.character_set.create(character_name='Homestar Runner')


问:
Insert, select & ON Duplicate KEY
i'am always getting syntax error when execute this query. Any Ideas what i'm doing wrong?

```<code>INSERT INTO cookies (cookie, buy, orders, ordervalue) SELECT o.uid cookie,  'eby' as a, COUNT(o.price ) as b , ROUND( SUM(o.price) , 2 ) umsatz
        FROM  `Orders` o
        WHERE uid !=  ''
        GROUP BY uid ON DUPLICATE KEY UPDATE  buy=VALUES(a), orders=VALUES(b);
</code>```

I'm not sure ift its possible to use alias in "on duplicate". I ve tried also to calculate the values again in the "on duplicate" part. But also  get an error.

答:
The problem is here:

```<code>  ... UPDATE buy=VALUES(a), orders=VALUES(b)
                        ^                 ^
</code>```

a and b aren't valid in this context. Reference the name of the column in the column list of the INSERT to get the value that would have been inserted into that column (if the insert had succeeded)

```<code>  ... UPDATE buy=VALUES(buy), orders=VALUES(orders)
                        ^^^                 ^^^^^^
</code>```

(It doesn't matter if the expressions in the SELECT have aliases or not; it's not valid to reference expressions from the SELECT in the ON DUPLICATE KEY clause.

Title: Insert, select & ON Duplicate KEY

Body:
i'am always getting syntax error when execute this query. Any Ideas what i'm doing wrong?

INSERT INTO cookies (cookie, buy, orders, ordervalue) SELECT o.uid cookie,  'eby' as a, COUNT(o.price ) as b , ROUND( SUM(o.price) , 2 ) umsatz
        FROM  `Orders` o
        WHERE uid !=  ''
        GROUP BY uid ON DUPLICATE KEY UPDATE  buy=VALUES(a), orders=VALUES(b);

I'm not sure ift its possible to use alias in "on duplicate". I ve tried also to calculate the values again in the "on duplicate" part. But also  get an error.

Body:
The problem is here:

  ... UPDATE buy=VALUES(a), orders=VALUES(b)
                        ^                 ^

a and b aren't valid in this context. Reference the name of the column in the column list of the INSERT to get the value that would have been inserted into that column (if the insert had succeeded)

  ... UPDATE buy=VALUES(buy), orders=VALUES(orders)
                        ^^^                 ^^^^^^

(It doesn't matter if the expressions in the SELECT have aliases or not; it's not valid to reference expressions from the SELECT in the ON DUPLICATE KEY clause.


问:
How do you make an HTML button behave just like a hyperlink?
How do you make an HTML button behave just like a hyperlink where, if you click on it, it will open a browser window showing a page you want?

I understand this much.  I think I will use this

but instead of a link to some javascript code inside the quotes for "onclick" I want to put something simple that will launch a new browser window.

答:
I'm 7 years late, I realize, but I had a similar issue and thought I comment for those who may follow.

If you're using Bootstrap, you can attach Bootstrap button classnames to anchor tags and make them look just like buttons:

I Look Like A Button

Bootstrap supports basic sizes as well, including btn-sm or btn-lg. Granted, not everyone uses Bootstrap but even then the default styles are free, easy to find, and can be copied into your own stylesheet even if you're using a custom boilerplate layout.

ContentLicense: CC BY-SA 2.5

Body:
I'm 7 years late, I realize, but I had a similar issue and thought I comment for those who may follow.

If you're using Bootstrap, you can attach Bootstrap button classnames to anchor tags and make them look just like buttons:

<a href="path/file.ext" class="btn btn-md btn-link">I Look Like A Button</a>

Bootstrap supports basic sizes as well, including btn-sm or btn-lg. Granted, not everyone uses Bootstrap but even then the default styles are free, easy to find, and can be copied into your own stylesheet even if you're using a custom boilerplate layout.


问:
jQuery slide, how to not slide at beginning or end?
I have a jquery function which slides a certain div to the right or left when I click a button.

```<code>$(function(){
    $("#prev").click(function(){
        $("#contentcont").animate({'left': '-=110'});
        return false;
    });
    $("#next").click(function(){
        $("#contentcont").animate({'left': '+=110'});
        return false;
    });
});
</code>```

Everything works fine. But what can I do if I havent slided anything yet, I can just slide the whole thing to one side? Right now I can slide to both sides. But I just want to do that if I already slided at least one. Also the same for the end... how can I tell jquery to stop the sliding when I just reached the end?

Thanks in advance. I'm still not a jquery pro...

答:
You could set up a variable to track whether the user has engaged with the UI or not.  Then test the variable in a conditional before executing the function contents.</p>

```<code>var userEngagedUI = false;
$(function(){
    $("#prev").click(function(){
        if(userEngagedUI){
            $("#contentcont").animate({'left': '-=110'});
        }
        return false;
    });
    $("#next").click(function(){
        userEngagedUI = true;
        $("#contentcont").animate({'left': '+=110'});
        return false;
    });
});
</code>```

Body:
I have a jquery function which slides a certain div to the right or left when I click a button.

$(function(){
    $("#prev").click(function(){
        $("#contentcont").animate({'left': '-=110'});
        return false;
    });
    $("#next").click(function(){
        $("#contentcont").animate({'left': '+=110'});
        return false;
    });
});

Everything works fine. But what can I do if I havent slided anything yet, I can just slide the whole thing to one side? Right now I can slide to both sides. But I just want to do that if I already slided at least one. Also the same for the end... how can I tell jquery to stop the sliding when I just reached the end?

Thanks in advance. I'm still not a jquery pro...

Body:
You could set up a variable to track whether the user has engaged with the UI or not.  Then test the variable in a conditional before executing the function contents.

var userEngagedUI = false;
$(function(){
    $("#prev").click(function(){
        if(userEngagedUI){
            $("#contentcont").animate({'left': '-=110'});
        }
        return false;
    });
    $("#next").click(function(){
        userEngagedUI = true;
        $("#contentcont").animate({'left': '+=110'});
        return false;
    });
});


问:
How can I emit Socket.io events from a router file?
I am working on a socket.io project in which I need to emit an event when the / page is requested. But all my routings are in a separate file router/index.js. Now, I want to emit a socket event on the page request from the router file.

I can't find a way to sort this out. Can anyone help?

答:
put your socket object in separate file and export it.
//let io.js

```<code>var http = require('http').Server(app);
var io = require('socket.io')(http);
module.export.io = io;
</code>```

now in route/index.js;

```<code>var io = require('io.js')
  app.get('/', function(req, res){
  io.sockets.emit('home.accessed');
})
</code>```

simlarly if socket code was in server.js

require it from io.js likewise.

Body:
put your socket object in separate file and export it.
//let io.js

var http = require('http').Server(app);
var io = require('socket.io')(http);
module.export.io = io;

now in route/index.js;

var io = require('io.js')
  app.get('/', function(req, res){
  io.sockets.emit('home.accessed');
})

simlarly if socket code was in server.js

require it from io.js likewise.


问:
How to know all concurrent NSOperations are completed
My situation is:

I have users

Each user has some history data that can be fetched via user objects

What I want to do is:

Max 2 users must be fetching their history data at the same time (this is the reason that I want to use NSOperationQueue)

I need to get notified when any user finished fetching its history data

I need to get notified when every user finished fetching their history data

What I ask is:

How can I achieve what I want to do since I can't make it thru with the code below?

Any help is appreciated.

```<code>    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue setMaxConcurrentOperationCount:2];

    for (User *user in users) {
        NSBlockOperation *operationObject = [NSBlockOperation blockOperationWithBlock:^{
            [user loadHistoryData:^{
                [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
            }];
        }];

        [operationQueue addOperation:operationObject];
    }
</code>```

This question differs from this question because I don't want to chain any requests. I just want to know when they are all finished executing.

This answer has a completion block for only one operation queue.

This answer offers a way to make operation block to wait until async call to loadHistoryData is completed. As writing setSuspended

I could not find an answer for my need. Is there any?

答:
I've used AsyncBlockOperation and NSOperationQueue+CompletionBlock

Combining them is working for me like this:

```<code>  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  [queue setMaxConcurrentOperationCount:1];
  // 1 is serial, more is concurrent

  queue.completionBlock = ^{
    [NSNotificationCenter postNotificationToMainThread:@"allUsersFetchedHistory"];
  };

  for (User *user in users){
   [queue addOperationWithAsyncBlock:^(AsyncBlockOperation *op) {
     [user loadHistoryData:^{
       [op complete];
       [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
      }];
    }];
  }
</code>```

Body:
My situation is:

I have users

Each user has some history data that can be fetched via user objects

What I want to do is:

Max 2 users must be fetching their history data at the same time (this is the reason that I want to use NSOperationQueue)

I need to get notified when any user finished fetching its history data

I need to get notified when every user finished fetching their history data

What I ask is:

How can I achieve what I want to do since I can't make it thru with the code below?

Any help is appreciated.

    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue setMaxConcurrentOperationCount:2];

    for (User *user in users) {
        NSBlockOperation *operationObject = [NSBlockOperation blockOperationWithBlock:^{
            [user loadHistoryData:^{
                [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
            }];
        }];

        [operationQueue addOperation:operationObject];
    }

This question differs from this question because I don't want to chain any requests. I just want to know when they are all finished executing.

This answer has a completion block for only one operation queue.

This answer offers a way to make operation block to wait until async call to loadHistoryData is completed. As writing setSuspended

I could not find an answer for my need. Is there any?

Body:
I've used AsyncBlockOperation and NSOperationQueue+CompletionBlock

Combining them is working for me like this:

  NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  [queue setMaxConcurrentOperationCount:1];
  // 1 is serial, more is concurrent

  queue.completionBlock = ^{
    [NSNotificationCenter postNotificationToMainThread:@"allUsersFetchedHistory"];
  };

  for (User *user in users){
   [queue addOperationWithAsyncBlock:^(AsyncBlockOperation *op) {
     [user loadHistoryData:^{
       [op complete];
       [NSNotificationCenter postNotificationToMainThread:@"oneUserFetchedHistory"];
      }];
    }];
  }


问:
Why do I get empty reponse from this http request
I am working on my first node.js script which simply makes a http request to https://www.swapi.co/api/people/?search=Luke+ and parses the response data.

The endpoint is as follows:

```<code>var options = {
  host: 'www.swapi.co',
  path: `/api/people/?search=`+firstName+'+'+lastName
};
</code>```

The logic is to get the data from response and parse it to a person object:

```<code>makeRequest(options, function( data, error) {
    let person = data.results[0];
    if (person) {
        let height = person.height;
        let response = person.name + " is " + height + " centimeters tall.";
        callback(null, {"speech": response});
    }
    else {
        callback(null, {"speech": "I'm not sure!"});
    }
  });
</code>```

The definition of makerequest function is below:

```<code>function makeRequest(options, callback) {
    var request = http.request(options,
    function(response) {
        var responseString = '';
        response.on('data', function(data) {
            responseString += data;
        });
         response.on('end', function() {
            console.log('end: $$$' + responseString + '$$$');
            var responseJSON = JSON.parse(responseString);
            callback(responseJSON, null);
        });
    });
    request.end();
}
</code>```

When I run the script I got the error about parsing the JSON.

```<code>Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)
</code>```

I tested the endpoint using Postman and got the following JSON as response:

```<code>{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "https://www.swapi.co/api/planets/1/",
            "films": [
                "https://www.swapi.co/api/films/2/",
                "https://www.swapi.co/api/films/6/",
                "https://www.swapi.co/api/films/3/",
                "https://www.swapi.co/api/films/1/",
                "https://www.swapi.co/api/films/7/"
            ],
            "species": [
                "https://www.swapi.co/api/species/1/"
            ],
            "vehicles": [
                "https://www.swapi.co/api/vehicles/14/",
                "https://www.swapi.co/api/vehicles/30/"
            ],
            "starships": [
                "https://www.swapi.co/api/starships/12/",
                "https://www.swapi.co/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "https://www.swapi.co/api/people/1/"
        }
    ]
}
</code>```

However, when I debug my code, the response data is an empty string. And that explains the JSON error.

What is wrong with my http request? Why am I not getting the correct response?

答:
That URL you are using returns HTML by default.

Instead you need to call: https://www.swapi.co/api/people/?format=json&search=Luke+

(Note the format=json parameter)

Body:
I am working on my first node.js script which simply makes a http request to https://www.swapi.co/api/people/?search=Luke+ and parses the response data.

The endpoint is as follows:

var options = {
  host: 'www.swapi.co',
  path: `/api/people/?search=`+firstName+'+'+lastName
};

The logic is to get the data from response and parse it to a person object:

makeRequest(options, function( data, error) {
    let person = data.results[0];
    if (person) {
        let height = person.height;
        let response = person.name + " is " + height + " centimeters tall.";
        callback(null, {"speech": response});
    }
    else {
        callback(null, {"speech": "I'm not sure!"});
    }
  });

The definition of makerequest function is below:

function makeRequest(options, callback) {
    var request = http.request(options,
    function(response) {
        var responseString = '';
        response.on('data', function(data) {
            responseString += data;
        });
         response.on('end', function() {
            console.log('end: $$$' + responseString + '$$$');
            var responseJSON = JSON.parse(responseString);
            callback(responseJSON, null);
        });
    });
    request.end();
}

When I run the script I got the error about parsing the JSON.

Unexpected end of JSON input
    at Object.parse (native)
    at IncomingMessage.<anonymous> (/var/task/index.js:42:37)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)

I tested the endpoint using Postman and got the following JSON as response:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "name": "Luke Skywalker",
            "height": "172",
            "mass": "77",
            "hair_color": "blond",
            "skin_color": "fair",
            "eye_color": "blue",
            "birth_year": "19BBY",
            "gender": "male",
            "homeworld": "https://www.swapi.co/api/planets/1/",
            "films": [
                "https://www.swapi.co/api/films/2/",
                "https://www.swapi.co/api/films/6/",
                "https://www.swapi.co/api/films/3/",
                "https://www.swapi.co/api/films/1/",
                "https://www.swapi.co/api/films/7/"
            ],
            "species": [
                "https://www.swapi.co/api/species/1/"
            ],
            "vehicles": [
                "https://www.swapi.co/api/vehicles/14/",
                "https://www.swapi.co/api/vehicles/30/"
            ],
            "starships": [
                "https://www.swapi.co/api/starships/12/",
                "https://www.swapi.co/api/starships/22/"
            ],
            "created": "2014-12-09T13:50:51.644000Z",
            "edited": "2014-12-20T21:17:56.891000Z",
            "url": "https://www.swapi.co/api/people/1/"
        }
    ]
}

However, when I debug my code, the response data is an empty string. And that explains the JSON error.

What is wrong with my http request? Why am I not getting the correct response?


问:
Word counter Program In Java
While creating a word counter in java through collecting user input from a scanner I've been running into the error of having my program display that there was one extra word entered when there is a space entered in after the final word in the char.  Is there a way to check the user input for a space and remove it before entering my word count loop? </p>

答:
```<code>    Scanner in = new Scanner (System.in);
    System.out.println("Write something");
    String x = in.nextLine();
    char y;
    char z;
    int n =1;
    boolean t = true;
    boolean f = false;
    boolean o = false;
    for (int i = 0; i<x.length();i++){
    y = x.charAt(i);
    if(t){
    if(' ' == y){n--;}
    else if(y != ' '){ t=false; f = true;}
    }
    if(' ' == y){n++;}
    if(o){
        z = x.charAt(i-1);
    if(' ' == y && ' '== z){n--;}
    }
    if (o){
    if(' ' == y && i == x.length()-1){n--;}
    }
    if(f){o = true;}

    }
    System.out.println(n);
</code>```

This actually works lol

Title: Word counter Program In Java

Body:
    Scanner in = new Scanner (System.in);
    System.out.println("Write something");
    String x = in.nextLine();
    char y;
    char z;
    int n =1;
    boolean t = true;
    boolean f = false;
    boolean o = false;
    for (int i = 0; i<x.length();i++){
    y = x.charAt(i);
    if(t){
    if(' ' == y){n--;}
    else if(y != ' '){ t=false; f = true;}
    }
    if(' ' == y){n++;}
    if(o){
        z = x.charAt(i-1);
    if(' ' == y && ' '== z){n--;}
    }
    if (o){
    if(' ' == y && i == x.length()-1){n--;}
    }
    if(f){o = true;}

    }
    System.out.println(n);

This actually works lol


问:
How to log IP address in text file
```<code><?php
header ('Location: http://proxy4free.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, "=");
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
</code>```

This is my code currently i'm practicing and i would like to know how to log ip address in text file with PHP. I have no idea, but made attempts.

答:
```<code><?php

$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP

$handle = fopen("log.txt", "a"); //open log file

foreach($_POST as $variable => $value) { //loop through POST vars
   fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);

header ('Location: http://proxy4free.com');
exit;
</code>```

Note that file_put_contents is a wrapper around fopen/fwrite/fclose and will simplify your code (although I've not benchmarked it to see if it's slower, as you're writing multiple lines ... of course, you could just concatenate to one string and write all-at-once).  You might wish to try that.

Your header() call should be reserved until AFTER PHP's had time to write your log, and then followed by an "exit" as you'd done previously.

Security hasn't been addressed here at all.  If someone posted something unexpected, they might do all manner of mischief (just as an example, a huge POST var might fill up precious disk space your server must have to run --- and there might be more nefarious stuff too).  Consider using an input filter for each of those $_POST vars at a bare minimum (http://php.net/filter_input).  If you know what you're expecting from them, do something further (intval, preg_match testing, etc.)

Title: How to log IP address in text file

Body:
<?php
header ('Location: http://proxy4free.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
   fwrite($handle, $variable);
   fwrite($handle, "=");
   fwrite($handle, $value);
   fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>

This is my code currently i'm practicing and i would like to know how to log ip address in text file with PHP. I have no idea, but made attempts.

Body:
<?php

$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP

$handle = fopen("log.txt", "a"); //open log file

foreach($_POST as $variable => $value) { //loop through POST vars
   fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);

header ('Location: http://proxy4free.com');
exit;

Note that file_put_contents is a wrapper around fopen/fwrite/fclose and will simplify your code (although I've not benchmarked it to see if it's slower, as you're writing multiple lines ... of course, you could just concatenate to one string and write all-at-once).  You might wish to try that.

Your header() call should be reserved until AFTER PHP's had time to write your log, and then followed by an "exit" as you'd done previously.

Security hasn't been addressed here at all.  If someone posted something unexpected, they might do all manner of mischief (just as an example, a huge POST var might fill up precious disk space your server must have to run --- and there might be more nefarious stuff too).  Consider using an input filter for each of those $_POST vars at a bare minimum (http://php.net/filter_input).  If you know what you're expecting from them, do something further (intval, preg_match testing, etc.)


问:
matplotlib selecting wrong font style/weight
I want to change the default font used in matplotlib plots to be Segoe UI under Windows. I can do so by altering rcParams like so

```<code>import matplotlib
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['Segoe UI'] + matplotlib.rcParams['font.sans-serif']
matplotlib.rcParams['font.weight'] = 'normal'
</code>```

This works, however the weight of the font appears to be wrong. Using the following code I can confirm that matplotlib is picking up the 'Semibold' version of the font rather than the 'Regular' variant that I would expect from setting matplotlib.rcParams['font.weight'] = 'normal'.

```<code>from matplotlib.font_manager import findfont, FontProperties
font = findfont(FontProperties(family=['sans-serif']))
print font

>>> c:\windows\fonts\seguisb.ttf
</code>```

How can I force matplotlib to use the 'Regular' variant? Is this possible with rcParams?

答:
I figured out a hack that fixes the problem with Segoe UI without needing to set kwargs every time...

For some reason, the tf2font module (which is a .pyd) attributes a font weight of 400 to the Segoe UI Black, Ultralight, Light and Semi-bold fonts, which really should have a font weight of 1000, 100, 200 and 500, respectively.

First delete your fontList.json file. (For me it was in .matplotlib\fontList.json).

Then, right before this line in font_manager.py:

```<code>return FontEntry(font.fname, name, style, variant, weight, stretch, size)
</code>```

Insert the following code:

```<code>switch = lambda x: {
    #Correct the font-weight for these fonts
    'seguibl.ttf': 1000,
    'segouisl.ttf': 100,
    'seguisb.ttf':500,
    'segoeuil.ttf':200
}[x]

f =  os.path.split(font.fname)[1]
if f in ['seguibl.ttf', 'segouisl.ttf', 'seguisb.ttf', 'segoeuil.ttf']:
    weight = switch(f)
</code>```

The end result will look like:

```<code>switch = lambda x: {
    #Correct the font-weight for these fonts
    'seguibl.ttf': 1000,
    'segouisl.ttf': 100,
    'seguisb.ttf':500,
    'segoeuil.ttf':200
}[x]

f =  os.path.split(font.fname)[1]
if f in ['seguibl.ttf', 'segouisl.ttf', 'seguisb.ttf', 'segoeuil.ttf']:
    weight = switch(f)
return FontEntry(font.fname, name, style, variant, weight, stretch, size)
</code>```

Body:
I want to change the default font used in matplotlib plots to be Segoe UI under Windows. I can do so by altering rcParams like so

import matplotlib
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['Segoe UI'] + matplotlib.rcParams['font.sans-serif']
matplotlib.rcParams['font.weight'] = 'normal'

This works, however the weight of the font appears to be wrong. Using the following code I can confirm that matplotlib is picking up the 'Semibold' version of the font rather than the 'Regular' variant that I would expect from setting matplotlib.rcParams['font.weight'] = 'normal'.

from matplotlib.font_manager import findfont, FontProperties
font = findfont(FontProperties(family=['sans-serif']))
print font

>>> c:\windows\fonts\seguisb.ttf

How can I force matplotlib to use the 'Regular' variant? Is this possible with rcParams?

Body:
I figured out a hack that fixes the problem with Segoe UI without needing to set kwargs every time...

For some reason, the tf2font module (which is a .pyd) attributes a font weight of 400 to the Segoe UI Black, Ultralight, Light and Semi-bold fonts, which really should have a font weight of 1000, 100, 200 and 500, respectively.

First delete your fontList.json file. (For me it was in .matplotlib\fontList.json).

Then, right before this line in font_manager.py:

return FontEntry(font.fname, name, style, variant, weight, stretch, size)

Insert the following code:

switch = lambda x: {
    #Correct the font-weight for these fonts
    'seguibl.ttf': 1000,
    'segouisl.ttf': 100,
    'seguisb.ttf':500,
    'segoeuil.ttf':200
}[x]

f =  os.path.split(font.fname)[1]
if f in ['seguibl.ttf', 'segouisl.ttf', 'seguisb.ttf', 'segoeuil.ttf']:
    weight = switch(f)

The end result will look like:

switch = lambda x: {
    #Correct the font-weight for these fonts
    'seguibl.ttf': 1000,
    'segouisl.ttf': 100,
    'seguisb.ttf':500,
    'segoeuil.ttf':200
}[x]

f =  os.path.split(font.fname)[1]
if f in ['seguibl.ttf', 'segouisl.ttf', 'seguisb.ttf', 'segoeuil.ttf']:
    weight = switch(f)
return FontEntry(font.fname, name, style, variant, weight, stretch, size)


问:
Is it real to dynamically define width of image by his URL?
How to define width of image before it loads as background-image property of DIV?

```<code>function nn() {
  if (arr !== null) {
    var el = document.getElementById("n");
    var x = Math.floor((Math.random() * 10) + 1);
    var img = new Image();
    img.src = arr[x];
    el.style.width = img.width;
    el.style.backgroundImage = arr[x];
  }
}

$(window).on({
  load: function() {
    resizeBind(width);
    nn(arr);
    return width;
  }
});
</code>```

Where arr[] has few URLs of images?

答:
You have to load the image into the img tag, wait its load event, and only then query for the image properties:

var img = document.createElement("img");
img.classList.add("obj");
img.src = "http://www.parisilabs.com/colors2/images/30892183_350_350.jpg";
img.addEventListener('load', function() {
  console.log("Width:%d Height:%d", document.getElementById('test').width,
    document.getElementById('test').height);
}, false);
img.id = "test";
document.getElementById("content").appendChild(img);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content" /></code>```

Body:
How to define width of image before it loads as background-image property of DIV?

function nn() {
  if (arr !== null) {
    var el = document.getElementById("n");
    var x = Math.floor((Math.random() * 10) + 1);
    var img = new Image();
    img.src = arr[x];
    el.style.width = img.width;
    el.style.backgroundImage = arr[x];
  }
}

$(window).on({
  load: function() {
    resizeBind(width);
    nn(arr);
    return width;
  }
});

Where arr[] has few URLs of images?

Body:
You have to load the image into the img tag, wait its load event, and only then query for the image properties:

var img = document.createElement("img");
img.classList.add("obj");
img.src = "http://www.parisilabs.com/colors2/images/30892183_350_350.jpg";
img.addEventListener('load', function() {
  console.log("Width:%d Height:%d", document.getElementById('test').width,
    document.getElementById('test').height);
}, false);
img.id = "test";
document.getElementById("content").appendChild(img);

<div id="content" />


问:
Java code style for open stream try/finally block
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

```<code>InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}
</code>```

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

```<code>InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}
</code>```

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.

答: If your acquireStream() returned null, You will get NPE when you will try to close your stream in finally block and it will be uncaught. </p>

Body:
This is a code style question.  I notice much example code including some examples from Oracle ensure that a stream is closed in the following manner:

InputStream in = null;
try {
    in = acquireStream();
    ...
} finally {
    if (in != null) in.close();
}

Note the initialization to null and check for null in the finally block.

I tend to write code like this:

InputStream in = acquireStream();
try {
    ...
} finally {
    in.close();
}

Are there advantages or disadvantages to either approach?  I like my style because I don't need the null check.  Also I like to avoid null when possible.  But since the Oracle style is so common in online examples, I'm wondering if mine has some hidden error.

I ask the same question for InputStream, OutputStream, java.sql.Connection, java.sql.PreparedStatement, etc.  I tend to acquired the resource outside the try block and then close it in finally without a null check.  Is there anything I am missing other than stylistic differences?

Thanks.


问:
Getting values out of view model structs
I'm pretty new to swift. Currently, I'm attempting to create a view screen programmatically in Swift 4. The screen is supposed to have a number of images and textlabels. I created a view model with a struct of several declared images and strings.

The struct setup thats in my view model:

```<code>import Foundation
import UIKit

struct ShareUIModel {

    let heroImage: UIImage
    let secondHeroImage: UIImage
    let longHeroText: String
    let shortHeroText: String

}

extension ShareUIModel {

    static func testObject() -> ShareUIModel {
        let heroImageImage = placeholderImage
        let secondHeroImageImage = placeholderImage
        let longHeroTextText = "long words"
        let shortHeroTextText = "short words"
        return ShareUIModel(heroImage: heroImageImage, secondHeroImageImage: secondHeroImage, longHeroText: longHeroTextText, shortHeroText: shortHeroTextText)
    }
}
</code>```

Question: How can I create an instance of ShareUIModel in a view controller and access the values?

答:
Generally, you can apply a MVM object to it's view in many ways. Personnaly, I recommend either a convenience initializer, or a custom variable with what's called a didSet value observer. Didset observers are called when their parameters are applied, without modifying the stored value.

So given a uivew subclass that can handle your model :

```<code>class ShareUIView : UIView {

    var model : ShareUIModel? {
        didSet {
            guard let mode = model else { return }
            applyModel(mode)
        }
    }

    let heroImage = UIImageView()
    let secondHeroImage = UIImageView()
    let longHeroLabel = UILabel()
    let shortHeroLabel = UILabel()

    //Initializer
    convenience init(model: ShareUIModel) {
        self.init()
        self.addSubview(heroImage)
        self.addSubview(secondHeroImage)
        self.addSubview(longHeroLabel)
        self.addSubview(shortHeroLabel)
        self.model = model
    }

    private func applyModel(_ model: ShareUIModel) {
        self.heroImage.image = model.heroImage
        self.secondHeroImage.image = model.heroImage
        self.longHeroLabel.text = model.longHeroText
        self.shortHeroLabel.text = model.shortHeroText
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        buildYourComponents()
    }

    func buildYourComponents() {
        //This will be called whenever ShareUIView's size or layout is applied.
        //code to build out your labels and imageViews
    }

}
</code>```

So from here, you can either apply it onto your UIViewController's view by initializing it:

```<code>class Controller : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let shareview = ShareUIView(model: ShareUIModel.testObject())
        view.addSubview(shareview)
        shareview.frame = //whatever you want here..
    }

}
</code>```

This method means you have to set the size afterwards.

Or, you can build out the ShareView first, then apply the model object afterwards (say, from a user's selection, or from a network task) by applying the model onto ShareView's model parameter. This requires you to have a strong reference to it however, as in initializing it into your Controller class:

```<code>class Controller : UIViewController {

    var shareView : ShareUIView = { //Initialized as a parameter of Controller instead
        var v = ShareUIView()
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(shareView) //You add the view
        shareView.frame = .zero//you build the view - .zero is just an example here.
    }

    func applyTheModelFromWherever() {
        shareView.model = ShareUIModel.testObject() //you apply the model object.
    }

}
</code>```

From this you should have ample examples to get creative with how to update a MVVM view with it's model object content. You would then also create methods to clear the content, dismiss it etc, depending on the use-case of the view itself.

Body:
I'm pretty new to swift. Currently, I'm attempting to create a view screen programmatically in Swift 4. The screen is supposed to have a number of images and textlabels. I created a view model with a struct of several declared images and strings.

The struct setup thats in my view model:

import Foundation
import UIKit

struct ShareUIModel {

    let heroImage: UIImage
    let secondHeroImage: UIImage
    let longHeroText: String
    let shortHeroText: String

}

extension ShareUIModel {

    static func testObject() -> ShareUIModel {
        let heroImageImage = placeholderImage
        let secondHeroImageImage = placeholderImage
        let longHeroTextText = "long words"
        let shortHeroTextText = "short words"
        return ShareUIModel(heroImage: heroImageImage, secondHeroImageImage: secondHeroImage, longHeroText: longHeroTextText, shortHeroText: shortHeroTextText)
    }
}

Question: How can I create an instance of ShareUIModel in a view controller and access the values?

Body:
Generally, you can apply a MVM object to it's view in many ways. Personnaly, I recommend either a convenience initializer, or a custom variable with what's called a didSet value observer. Didset observers are called when their parameters are applied, without modifying the stored value.

So given a uivew subclass that can handle your model :

class ShareUIView : UIView {

    var model : ShareUIModel? {
        didSet {
            guard let mode = model else { return }
            applyModel(mode)
        }
    }

    let heroImage = UIImageView()
    let secondHeroImage = UIImageView()
    let longHeroLabel = UILabel()
    let shortHeroLabel = UILabel()

    //Initializer
    convenience init(model: ShareUIModel) {
        self.init()
        self.addSubview(heroImage)
        self.addSubview(secondHeroImage)
        self.addSubview(longHeroLabel)
        self.addSubview(shortHeroLabel)
        self.model = model
    }

    private func applyModel(_ model: ShareUIModel) {
        self.heroImage.image = model.heroImage
        self.secondHeroImage.image = model.heroImage
        self.longHeroLabel.text = model.longHeroText
        self.shortHeroLabel.text = model.shortHeroText
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        buildYourComponents()
    }

    func buildYourComponents() {
        //This will be called whenever ShareUIView's size or layout is applied.
        //code to build out your labels and imageViews
    }

}

So from here, you can either apply it onto your UIViewController's view by initializing it:

class Controller : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let shareview = ShareUIView(model: ShareUIModel.testObject())
        view.addSubview(shareview)
        shareview.frame = //whatever you want here..
    }

}

This method means you have to set the size afterwards.

Or, you can build out the ShareView first, then apply the model object afterwards (say, from a user's selection, or from a network task) by applying the model onto ShareView's model parameter. This requires you to have a strong reference to it however, as in initializing it into your Controller class:

class Controller : UIViewController {

    var shareView : ShareUIView = { //Initialized as a parameter of Controller instead
        var v = ShareUIView()
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(shareView) //You add the view
        shareView.frame = .zero//you build the view - .zero is just an example here.
    }

    func applyTheModelFromWherever() {
        shareView.model = ShareUIModel.testObject() //you apply the model object.
    }

}

From this you should have ample examples to get creative with how to update a MVVM view with it's model object content. You would then also create methods to clear the content, dismiss it etc, depending on the use-case of the view itself.


问:
IOError: [Errno 2] No such file or directory: u'/........./RetroApp-debug.apk'
I'm beginner in kivy library programming, but I have done very simple application, like in Kivy tutorial. On desktop it works cool. But than I wanted to do .apk file(Hadn't used Linux). I've tried a lot of steps to do an .apk file, but finally when I've installed and opened this program. It had an error. I've tried a lot of specs and new_android, but nothing worked. Finally I've updated my buildozer to the last version. But now, after buildozer android debug, he writes this error:

IOError: [Errno 2] No such file or directory: u'/home/kivy/reyyy/.buildozer/android/platform/build/dists/RetroApp/build/outputs/apk/RetroApp-debug.apk'.

*************buildozer.spec***************

```<code>[app]

title = Retro App

package.name = retroapp

package.domain = org.test

source.dir = .

source.include_exts = py,png,jpg,kv,atlas

version = 1.0

requirements = kivy

orientation = landscape

osx.python_version = 3

osx.kivy_version = 1.9.1

fullscreen = 1

android.arch = armeabi-v7a

[buildozer]

log_level = 2

warn_on_root = 1
</code>```

******python3: main.py*******

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty,ObjectProperty,ReferenceListProperty,StringProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from random import randint,choice

class RetryButton(Button):
    pass

class PongBall(Widget):
    velocity_y = NumericProperty(0)
    velocity_x = NumericProperty(0)

    velocity = ReferenceListProperty(velocity_x,velocity_y)
    def move(self):
        self.pos = Vector(*self.velocity)+self.pos

class PongPaddle(Widget):
    score = NumericProperty(0)

    def bounce_ball(self,ball):
        if self.collide_widget(ball):
            vx,vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height /10.0)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    win = NumericProperty(0)
    middle_rectangle_opacity = NumericProperty(1)
    winner = StringProperty('')
    def __init__(self,**q):
    super().__init__(**q)
        self.btn = RetryButton(width = self.width)
        self.btn.count = 0
        self.max_score = 10

    def serve_ball(self,vel = (10,0)):
        self.ball.center =  self.center
        self.ball.velocity = Vector(*vel).rotate(choice([randint(0,30),randint(330,360)]))

    def update(self,dt):
        if self.win == 0:

            self.ball.move()
            self.player1.bounce_ball(self.ball)
            self.player2.bounce_ball(self.ball)
            if self.player1.score >= self.max_score or self.player2.score >=self.max_score:
                if self.player1.score >= self.max_score:
                    self.winner = '1'
                else:
                    self.winner = '2'
                self.win = 1
                self.middle_rectangle_opacity = 0

            if (self.ball.y < self.y) or (self.ball.top > self.height):
                self.ball.velocity_y *= -1

            if self.ball.x<self.x:
                self.player2.score += 1
                self.serve_ball((10,0))
            if self.ball.x > self.width - self.ball.width:
                self.player1.score += 1
                self.serve_ball((-10,0))
        else:
            if self.btn.count == 0:
                self.btn.bind(on_press=self.retry)
                self.add_widget(self.btn)
                self.btn.count += 1

    def on_touch_move(self, touch):
        if touch.x < self.width/3.0:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width/3.0:
            self.player2.center_y = touch.y

    def retry(self,*q):

        self.player1.score = 0
        self.player2.score = 0
        self.win = 0
        self.middle_rectangle_opacity = 1
        self.serve_ball()
        self.remove_widget(self.btn)
        self.btn.count = 0

class PongApp(App):
    def build(self):
        game = PongGame()
        game.serve_ball()
        Clock.schedule_interval(game.update, 1/30.0)
        return game

if __name__ == '__main__':
    PongApp().run()`
</code>```

********KV pong.kv*********

```<code>#:kivy 1.0.9
<RetryButton>:
    text: 'Retry'
    font_size: 17
    size: self.width, '100dp'
<PongBall>:
    size:50,50
    canvas.before:
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: '25dp','200dp'
    canvas:
        Rectangle:
            pos:self.pos
            size: self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right
    canvas:
        Color:
            rgba: 1,1,1,root.middle_rectangle_opacity
        Rectangle:
            pos:self.center_x - 5,0
            size: 10, self.height
    Label:
        font_size:35
        center_x: root.center_x
        center_y: root.height/4*3
        text: "Player {} wins!!".format(root.winner)
        color: 1,1,1,root.win
    Label:
        font_size: 70
        center_x: root.width/4
        top: root.top - 50
        text: str(root.player1.score)
    Label:
        font_size: 70
        center_x: root.width/4*3
        top: root.top - 50
        text: str(root.player2.score)
    PongBall:
        id: pong_ball
        center: self.parent.center
    PongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y
    PongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y
</code>```

Please, help me!
Vadim.

答:
Please change your Python script as follow:

main.py

```<code>class PongGame(Widget):
...
    def __init__(self, **kwargs):
        super(PongGame, self).__init__(**kwargs)
...

    def retry(self):
</code>```

Since you are using Python 3.x, you need to do the following:

Install Buildozer with python3 support

git clone https://github.com/kivy/buildozer

cd buildozer

python setup.py build

sudo pip install -e .

Download and extract the Crystax NDK somewhere (~/opt/ is one option): https://www.crystax.net/en/download

Specify the following in your buildozer.spec:

buildozer.spec

requirements = python3crystax,kivy

android.ndk = 10.3.2

android.ndk_path = /opt/crystax-ndk-10.3.2

Body:
I'm beginner in kivy library programming, but I have done very simple application, like in Kivy tutorial. On desktop it works cool. But than I wanted to do .apk file(Hadn't used Linux). I've tried a lot of steps to do an .apk file, but finally when I've installed and opened this program. It had an error. I've tried a lot of specs and new_android, but nothing worked. Finally I've updated my buildozer to the last version. But now, after buildozer android debug, he writes this error:

IOError: [Errno 2] No such file or directory: u'/home/kivy/reyyy/.buildozer/android/platform/build/dists/RetroApp/build/outputs/apk/RetroApp-debug.apk'.

*************buildozer.spec***************

[app]

title = Retro App

package.name = retroapp

package.domain = org.test

source.dir = .

source.include_exts = py,png,jpg,kv,atlas

version = 1.0

requirements = kivy

orientation = landscape

osx.python_version = 3

osx.kivy_version = 1.9.1

fullscreen = 1

android.arch = armeabi-v7a

[buildozer]

log_level = 2

warn_on_root = 1

******python3: main.py*******

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty,ObjectProperty,ReferenceListProperty,StringProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.button import Button
from random import randint,choice

class RetryButton(Button):
    pass

class PongBall(Widget):
    velocity_y = NumericProperty(0)
    velocity_x = NumericProperty(0)

    velocity = ReferenceListProperty(velocity_x,velocity_y)
    def move(self):
        self.pos = Vector(*self.velocity)+self.pos

class PongPaddle(Widget):
    score = NumericProperty(0)

    def bounce_ball(self,ball):
        if self.collide_widget(ball):
            vx,vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height /10.0)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)
    win = NumericProperty(0)
    middle_rectangle_opacity = NumericProperty(1)
    winner = StringProperty('')
    def __init__(self,**q):
    super().__init__(**q)
        self.btn = RetryButton(width = self.width)
        self.btn.count = 0
        self.max_score = 10

    def serve_ball(self,vel = (10,0)):
        self.ball.center =  self.center
        self.ball.velocity = Vector(*vel).rotate(choice([randint(0,30),randint(330,360)]))

    def update(self,dt):
        if self.win == 0:

            self.ball.move()
            self.player1.bounce_ball(self.ball)
            self.player2.bounce_ball(self.ball)
            if self.player1.score >= self.max_score or self.player2.score >=self.max_score:
                if self.player1.score >= self.max_score:
                    self.winner = '1'
                else:
                    self.winner = '2'
                self.win = 1
                self.middle_rectangle_opacity = 0

            if (self.ball.y < self.y) or (self.ball.top > self.height):
                self.ball.velocity_y *= -1

            if self.ball.x<self.x:
                self.player2.score += 1
                self.serve_ball((10,0))
            if self.ball.x > self.width - self.ball.width:
                self.player1.score += 1
                self.serve_ball((-10,0))
        else:
            if self.btn.count == 0:
                self.btn.bind(on_press=self.retry)
                self.add_widget(self.btn)
                self.btn.count += 1

    def on_touch_move(self, touch):
        if touch.x < self.width/3.0:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width/3.0:
            self.player2.center_y = touch.y

    def retry(self,*q):

        self.player1.score = 0
        self.player2.score = 0
        self.win = 0
        self.middle_rectangle_opacity = 1
        self.serve_ball()
        self.remove_widget(self.btn)
        self.btn.count = 0

class PongApp(App):
    def build(self):
        game = PongGame()
        game.serve_ball()
        Clock.schedule_interval(game.update, 1/30.0)
        return game

if __name__ == '__main__':
    PongApp().run()`

********KV pong.kv*********

#:kivy 1.0.9
<RetryButton>:
    text: 'Retry'
    font_size: 17
    size: self.width, '100dp'
<PongBall>:
    size:50,50
    canvas.before:
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: '25dp','200dp'
    canvas:
        Rectangle:
            pos:self.pos
            size: self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right
    canvas:
        Color:
            rgba: 1,1,1,root.middle_rectangle_opacity
        Rectangle:
            pos:self.center_x - 5,0
            size: 10, self.height
    Label:
        font_size:35
        center_x: root.center_x
        center_y: root.height/4*3
        text: "Player {} wins!!".format(root.winner)
        color: 1,1,1,root.win
    Label:
        font_size: 70
        center_x: root.width/4
        top: root.top - 50
        text: str(root.player1.score)
    Label:
        font_size: 70
        center_x: root.width/4*3
        top: root.top - 50
        text: str(root.player2.score)
    PongBall:
        id: pong_ball
        center: self.parent.center
    PongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y
    PongPaddle:
        id: player_right
        x: root.width - self.width
        center_y: root.center_y

Please, help me!
Vadim.

Body:
Please change your Python script as follow:

main.py

class PongGame(Widget):
...
    def __init__(self, **kwargs):
        super(PongGame, self).__init__(**kwargs)
...

    def retry(self):

Since you are using Python 3.x, you need to do the following:

Install Buildozer with python3 support

git clone https://github.com/kivy/buildozer

cd buildozer

python setup.py build

sudo pip install -e .

Download and extract the Crystax NDK somewhere (~/opt/ is one option): https://www.crystax.net/en/download

Specify the following in your buildozer.spec:

buildozer.spec

requirements = python3crystax,kivy

android.ndk = 10.3.2

android.ndk_path = /opt/crystax-ndk-10.3.2


问:
Why does a map only job in hive results in a single output file
When I execute the following query, I get only one file as output although I have 8 mappers and 0 reducers.

```<code>create table table_2 as select * from table_1.
</code>```

8 mappers are invoked and there is no reducer phase.
There is just only one file in the location of table_2, shouldn't there be 8 files as we have 8 mappers and 0 reducers.

答:
From Hive documentation, Configuration Properties...

hive.merge.mapfiles
   Default Value: true

    Merge small files at the end of a map-only job.

hive.merge.tezfiles

    Default Value: false

    Merge small files at the end of a Tez DAG

hive.merge.smallfiles.avgsize
   Default Value:
  16000000
   When the average output file size of a job
  is less than this number,
  Hive will start an additional map-reduce job
  to merge the output files into bigger files...

So, if (a) your test dataset is very small and (b) you don't use TEZ but plain old MapReduce, then Hive will run a post-Map step just to merge the (intermediate) results, by default.

Whereas it would not happen after a Reduce step, unless you force hive.merge.mapredfiles to true.

Body:
When I execute the following query, I get only one file as output although I have 8 mappers and 0 reducers.

create table table_2 as select * from table_1.

8 mappers are invoked and there is no reducer phase.
There is just only one file in the location of table_2, shouldn't there be 8 files as we have 8 mappers and 0 reducers.


问:
Rotating an image matrix around its center in MATLAB
Assume I have a 2x2 matrix filled with values which will represent a plane. Now I want to rotate the plane around itself in a 3-D way, in the "z-Direction". For a better understanding, see the following image:

I wondered if this is possible by a simple affine matrix, thus I created the following simple script:

```<code>%Create a random value matrix
A = rand*ones(200,200);

%Make a box in the image
A(50:200-50,50:200-50) = 1;
</code>```

Now I can apply transformations in the 2-D room simply by a rotation matrix like this:

```<code>R = affine2d([1 0 0; .5 1 0; 0 0 1])
tform = affine3d(R);
transformed = imwarp(A,tform);
</code>```

However, this will not produce the desired output above, and I am not quite sure how to create the 2-D affine matrix to create such behavior.

I guess that a 3-D affine matrix can do the trick. However, if I define a 3-D affine matrix I cannot work with the 2-D representation of the matrix anymore, since MATLAB will throw the error:

```<code>The number of dimensions of the input image A must be 3 when the
specified geometric transformation is 3-D.
</code>```

So how can I code the desired output with an affine matrix?

答:
You can perform a projective transformation that can be estimated using the position of the corners in the first and second image.

```<code>originalP='peppers.png';
original = imread(originalP);
imshow(original);
s = size(original);
matchedPoints1 = [1 1;1 s(1);s(2) s(1);s(2) 1];
matchedPoints2 = [1 1;1 s(1);s(2) s(1)-100;s(2) 100];
transformType = 'projective';

tform = fitgeotrans(matchedPoints1,matchedPoints2,'projective');

outputView = imref2d(size(original));
Ir = imwarp(original,tform,'OutputView',outputView);
figure; imshow(Ir);
</code>```

This is the result of the code above:

Original image:

Transformed image:

Body:
Assume I have a 2x2 matrix filled with values which will represent a plane. Now I want to rotate the plane around itself in a 3-D way, in the "z-Direction". For a better understanding, see the following image:

I wondered if this is possible by a simple affine matrix, thus I created the following simple script:

%Create a random value matrix
A = rand*ones(200,200);

%Make a box in the image
A(50:200-50,50:200-50) = 1;

Now I can apply transformations in the 2-D room simply by a rotation matrix like this:

R = affine2d([1 0 0; .5 1 0; 0 0 1])
tform = affine3d(R);
transformed = imwarp(A,tform);

However, this will not produce the desired output above, and I am not quite sure how to create the 2-D affine matrix to create such behavior.

I guess that a 3-D affine matrix can do the trick. However, if I define a 3-D affine matrix I cannot work with the 2-D representation of the matrix anymore, since MATLAB will throw the error:

The number of dimensions of the input image A must be 3 when the
specified geometric transformation is 3-D.

So how can I code the desired output with an affine matrix?

Body:
You can perform a projective transformation that can be estimated using the position of the corners in the first and second image.

originalP='peppers.png';
original = imread(originalP);
imshow(original);
s = size(original);
matchedPoints1 = [1 1;1 s(1);s(2) s(1);s(2) 1];
matchedPoints2 = [1 1;1 s(1);s(2) s(1)-100;s(2) 100];
transformType = 'projective';

tform = fitgeotrans(matchedPoints1,matchedPoints2,'projective');

outputView = imref2d(size(original));
Ir = imwarp(original,tform,'OutputView',outputView);
figure; imshow(Ir);

This is the result of the code above:

Original image:

Transformed image:


问:
Separating 'body' of domain name from extension - DOS shell
I tried everything possible, but still failed. I thought I got it at the point which I'll post

as my final attempt, but still isn't good [enough].

A script is being passed three arguments. Domain name, username and password.

But the probles is that I need domain separated in "domain" + ".com" format. Two variables.

I tried to split it using name.extension cheat, but it doesn't work quite well.

Check the simple code:

```<code>@echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.
</code>```

When you try it, you get:

```<code>D:\Scripts\test>test.bat domain.com

domain
.com

D:\Scripts\test>test.bat domain.co.uk

domain.co
.uk
</code>```

First obviously does work, but only because I'm able to cheat my way through.

String operations in DOS Shell are a pain in the ass. I might be able to convince

a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!

答:
Windows ships with the Windows Scripting Host which lets you run javascript.

Change the batch file to:

```<code>@echo off
cscript //Nologo test.js %*
</code>```

Create test.js:

```<code>if (WScript.Arguments.Length > 0) {
    var arg = WScript.Arguments.Item(0);
    var index = arg.indexOf('.');
    if (index != -1) {
        var domain = arg.substring(0, index);
        var ext = arg.substring(index);
        WScript.Echo(domain);
        WScript.Echo(ext);
    } else WScript.Echo("Error: Argument has no dots: " + arg);
} else WScript.Echo("Error: No argument given");
</code>```

And you can use it:

```<code>C:\Documents and Settings\Waqas\Desktop>test.bat domain.com
domain
.com

C:\Documents and Settings\Waqas\Desktop>test.bat domain.co.uk
domain
.co.uk
</code>```

And that does what I think you wanted.

OwnerDisplayName: Six

Body:
I tried everything possible, but still failed. I thought I got it at the point which I'll post

as my final attempt, but still isn't good [enough].

A script is being passed three arguments. Domain name, username and password.

But the probles is that I need domain separated in "domain" + ".com" format. Two variables.

I tried to split it using name.extension cheat, but it doesn't work quite well.

Check the simple code:

@echo off
echo.
set domain=%~n1
set ext=%~x1
echo %DOMAIN%
echo %EXT%
echo.

When you try it, you get:

D:\Scripts\test>test.bat domain.com

domain
.com

D:\Scripts\test>test.bat domain.co.uk

domain.co
.uk

First obviously does work, but only because I'm able to cheat my way through.

String operations in DOS Shell are a pain in the ass. I might be able to convince

a script writer to pass me 4 arguments instead of 3... but in case that fails... HELP!

Body:
Windows ships with the Windows Scripting Host which lets you run javascript.

Change the batch file to:

@echo off
cscript //Nologo test.js %*

Create test.js:

if (WScript.Arguments.Length > 0) {
    var arg = WScript.Arguments.Item(0);
    var index = arg.indexOf('.');
    if (index != -1) {
        var domain = arg.substring(0, index);
        var ext = arg.substring(index);
        WScript.Echo(domain);
        WScript.Echo(ext);
    } else WScript.Echo("Error: Argument has no dots: " + arg);
} else WScript.Echo("Error: No argument given");

And you can use it:

C:\Documents and Settings\Waqas\Desktop>test.bat domain.com
domain
.com

C:\Documents and Settings\Waqas\Desktop>test.bat domain.co.uk
domain
.co.uk

And that does what I think you wanted.


问:
Python PyQt5: How to show an error message with PyQt5
In normal Python (3.x) we always use showerror() from the tkinter module to display an error message but what should I do in PyQt5 to display exactly the same message type as well?</p>

答:
All above options didn't work for me using Komodo Edit 11.0. Just had returned "1" or if not implemented "-1073741819".

Usefull for me was: Vanloc's solution.

```<code>def my_exception_hook(exctype, value, traceback):
    # Print the error and traceback
    print(exctype, value, traceback)
    # Call the normal Exception hook after
    sys._excepthook(exctype, value, traceback)
    sys.exit(1)

# Back up the reference to the exceptionhook
sys._excepthook = sys.excepthook

# Set the exception hook to our wrapping function
sys.excepthook = my_exception_hook
</code>```

Body:
All above options didn't work for me using Komodo Edit 11.0. Just had returned "1" or if not implemented "-1073741819".

Usefull for me was: Vanloc's solution.

def my_exception_hook(exctype, value, traceback):
    # Print the error and traceback
    print(exctype, value, traceback)
    # Call the normal Exception hook after
    sys._excepthook(exctype, value, traceback)
    sys.exit(1)

# Back up the reference to the exceptionhook
sys._excepthook = sys.excepthook

# Set the exception hook to our wrapping function
sys.excepthook = my_exception_hook


问:
variable specific distance matrices compatible with strings
I'm working on a project where I need to group cases together. I have data on npi's, with info on the npi's like address, phone and name.
My goal is to group the npi's which are most alike in the same group. I want to achieve this by first creating a distance matrix and than determine
a treshold from which to group cases together. However I'm encountering difficulties on how to create a distance matrix for string variables.
I basically have two questions:

First, how to make a distance function for comparing similarities between cases in a dataframe creating a distance matrix as output?
The more values they share on the same variables, the closer I want them to be, so the higher/lower score on the distance matrix.

Second, how to make this distance function compatible with string variables?

code:

```<code>#sample data
df <- read.table(text='npi a  b  c
             51  6  2  1
             52  6  2  6
             53 10  9  2
             54  7  4  7
             55  7 10  5
             56  8  5  7
             57  7  2 10
             58  5  9  3
             59  8  4  6
             60  1 10  2', header=T, sep='')

#convert 1st column of data as the row index
df1 <- df[,-1]
rownames(df1) <- df[,1]

#calculate distance
library('proxy')
dist_func <- function(x, y) length(intersect(x,y))/3
proxy::dist(df1, method = dist_func)
</code>```

output:

```<code>          51        52        53        54        55        56        57            58        59
   52 0.6666667
   53 0.3333333 0.3333333
   54 0.0000000 0.0000000 0.0000000
   55 0.0000000 0.0000000 0.3333333 0.3333333
   56 0.0000000 0.0000000 0.0000000 0.3333333 0.6666667
   57 0.3333333 0.3333333 0.6666667 0.3333333 0.6666667 0.3333333
   58 0.0000000 0.0000000 0.3333333 0.0000000 0.3333333 0.3333333 0.0000000
   59 0.3333333 0.3333333 0.0000000 0.3333333 0.0000000 0.3333333 0.0000000 0.0000000
   60 0.6666667 0.3333333 0.6666667 0.0000000 0.3333333 0.0000000 0.6666667 0.0000000 0.0000000
</code>```

Questions:
1. What is defined here as x and y? the rows in contrast to all other rows or something else?
 With this defined function the distance is not variable specific. I only want two cases to 'intersect' if the values appear on the same variable
2. What would I need to add to the function to make it variable specific?

Furthermore this method doens't seem to work on string variables.

code:

```<code>   #create dataset with strings
   df2 <- read.table(text='npi dier  getal  mubilair
             51  "aap"  een  tafel
             52  vis  twee stoel
             53 paard  twee  zetel
             54  kip  drie  fouton
             55  beer vier   fouton
             56  aap  vijf   bureau
             57  tijger  zes bank
             58  zebra  zeven  sofa
             59  olifant  acht  wastafel
             60  mens acht  spiegel', header=T, sep='')
   #convert 1st column of data as the row index
   dfstring <- df2[,-1]
   rownames(dfstring) <- df[,1]
   #calculate distance
   library('proxy')
   dist_func <- function(x, y) length(intersect(x,y))/3
   proxy::dist(dfstring, method = dist_func)
</code>```

Output:

```<code>             51        52        53        54        55        56        57        58        59
   52 0.0000000
   53 0.0000000 0.6666667
   54 0.6666667 0.0000000 0.0000000
   55 0.3333333 0.0000000 0.0000000 0.6666667
   56 0.3333333 0.3333333 0.3333333 0.3333333 0.3333333
   57 1.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.3333333
   58 0.0000000 0.6666667 0.6666667 0.0000000 0.0000000 0.0000000 0.0000000
   59 0.3333333 0.3333333 0.0000000 0.0000000 0.3333333 0.3333333 0.3333333 0.3333333
   60 0.3333333 0.3333333 0.3333333 0.0000000 0.3333333 0.3333333 0.3333333 0.3333333 0.6666667
</code>```

This distance matrix makes no sense
The problem is with the intersect command:

```<code>   > dfstring[1,]
      dier getal mubilair
   51  aap   een    tafel
   > dfstring[2,]
      dier getal mubilair
   52  vis  twee    stoel
   > dfstring[4,]
      dier getal mubilair
   54  kip  drie   fouton
   > intersect(dfstring[1,], dfstring[2,])
   data frame with 0 columns and 0 rows
   > intersect(dfstring[1,], dfstring[4,])
      dier
   54  kip
</code>```

Is there a function like intersect which works with string variables as well?

So, how to make my initial function variable specific and how to make it compatible with string variables?

答:
For x and y, think "row x" compared with "row y". It may be informative to change your function to be

```<code>dist_func <- function(x, y) {
  browser()
  length(intersect(x,y))/3
}
</code>```

and then run it, looking at the actual values of x and y on the first call to your function. (You probably won't need to go beyond the first and second instantiation of your function.)

intersect does not know anything about position within the vector, it is solely set-based, meaning "presence of". The help page is even titled "Sets" and starts with

```<code>Performs *set* union, intersection, ...
</code>```

To get what you want, aren't you just looking for plain equality?

```<code>dist_func <- function(x, y) sum(x == y)/3
</code>```

NB: true equality can be problematic if looking at numeric (non-integer) numbers, per R FAQ 7.31.

Your data is plagued with factors, not characters. You might notice

```<code>str(df2)
# 'data.frame': 10 obs. of  4 variables:
#  $ npi     : int  51 52 53 54 55 56 57 58 59 60
#  $ dier    : Factor w/ 9 levels "aap","beer","kip",..: 1 8 6 3 2 1 7 9 5 4
#  $ getal   : Factor w/ 8 levels "acht","drie",..: 3 4 4 2 5 6 7 8 1 1
#  $ mubilair: Factor w/ 9 levels "bank","bureau",..: 7 6 9 3 3 2 1 4 8 5
</code>```

Notice, for example, that the first value in $getal is "acht", which is an integer 3 internally within the factors. You'll notice that the fourth integer-values for the three columns are 3, 2, 3 (respectively, which matches   the distance metric of 0.667 in column "51" and row "54".

Either use read.table(..., stringsAsFactors = FALSE) or change your distance function to be something like:

```<code>dist_func2 <- function(x, y) {
  if (is.factor(x)) x <- as.character(x)
  if (is.factor(y)) y <- as.character(y)
  sum(x == y)/3
}
</code>```

(I suggest stringsAsFactors personally, but YMMV.)

Body:
I'm working on a project where I need to group cases together. I have data on npi's, with info on the npi's like address, phone and name.
My goal is to group the npi's which are most alike in the same group. I want to achieve this by first creating a distance matrix and than determine
a treshold from which to group cases together. However I'm encountering difficulties on how to create a distance matrix for string variables.
I basically have two questions:

First, how to make a distance function for comparing similarities between cases in a dataframe creating a distance matrix as output?
The more values they share on the same variables, the closer I want them to be, so the higher/lower score on the distance matrix.

Second, how to make this distance function compatible with string variables?

code:

#sample data
df <- read.table(text='npi a  b  c
             51  6  2  1
             52  6  2  6
             53 10  9  2
             54  7  4  7
             55  7 10  5
             56  8  5  7
             57  7  2 10
             58  5  9  3
             59  8  4  6
             60  1 10  2', header=T, sep='')

#convert 1st column of data as the row index
df1 <- df[,-1]
rownames(df1) <- df[,1]

#calculate distance
library('proxy')
dist_func <- function(x, y) length(intersect(x,y))/3
proxy::dist(df1, method = dist_func)

output:

          51        52        53        54        55        56        57            58        59
   52 0.6666667
   53 0.3333333 0.3333333
   54 0.0000000 0.0000000 0.0000000
   55 0.0000000 0.0000000 0.3333333 0.3333333
   56 0.0000000 0.0000000 0.0000000 0.3333333 0.6666667
   57 0.3333333 0.3333333 0.6666667 0.3333333 0.6666667 0.3333333
   58 0.0000000 0.0000000 0.3333333 0.0000000 0.3333333 0.3333333 0.0000000
   59 0.3333333 0.3333333 0.0000000 0.3333333 0.0000000 0.3333333 0.0000000 0.0000000
   60 0.6666667 0.3333333 0.6666667 0.0000000 0.3333333 0.0000000 0.6666667 0.0000000 0.0000000

Questions:
1. What is defined here as x and y? the rows in contrast to all other rows or something else?
 With this defined function the distance is not variable specific. I only want two cases to 'intersect' if the values appear on the same variable
2. What would I need to add to the function to make it variable specific?

Furthermore this method doens't seem to work on string variables.

code:

   #create dataset with strings
   df2 <- read.table(text='npi dier  getal  mubilair
             51  "aap"  een  tafel
             52  vis  twee stoel
             53 paard  twee  zetel
             54  kip  drie  fouton
             55  beer vier   fouton
             56  aap  vijf   bureau
             57  tijger  zes bank
             58  zebra  zeven  sofa
             59  olifant  acht  wastafel
             60  mens acht  spiegel', header=T, sep='')
   #convert 1st column of data as the row index
   dfstring <- df2[,-1]
   rownames(dfstring) <- df[,1]
   #calculate distance
   library('proxy')
   dist_func <- function(x, y) length(intersect(x,y))/3
   proxy::dist(dfstring, method = dist_func)

Output:

             51        52        53        54        55        56        57        58        59
   52 0.0000000
   53 0.0000000 0.6666667
   54 0.6666667 0.0000000 0.0000000
   55 0.3333333 0.0000000 0.0000000 0.6666667
   56 0.3333333 0.3333333 0.3333333 0.3333333 0.3333333
   57 1.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.3333333
   58 0.0000000 0.6666667 0.6666667 0.0000000 0.0000000 0.0000000 0.0000000
   59 0.3333333 0.3333333 0.0000000 0.0000000 0.3333333 0.3333333 0.3333333 0.3333333
   60 0.3333333 0.3333333 0.3333333 0.0000000 0.3333333 0.3333333 0.3333333 0.3333333 0.6666667

This distance matrix makes no sense
The problem is with the intersect command:

   > dfstring[1,]
      dier getal mubilair
   51  aap   een    tafel
   > dfstring[2,]
      dier getal mubilair
   52  vis  twee    stoel
   > dfstring[4,]
      dier getal mubilair
   54  kip  drie   fouton
   > intersect(dfstring[1,], dfstring[2,])
   data frame with 0 columns and 0 rows
   > intersect(dfstring[1,], dfstring[4,])
      dier
   54  kip

Is there a function like intersect which works with string variables as well?

So, how to make my initial function variable specific and how to make it compatible with string variables?

Body:
For x and y, think "row x" compared with "row y". It may be informative to change your function to be

dist_func <- function(x, y) {
  browser()
  length(intersect(x,y))/3
}

and then run it, looking at the actual values of x and y on the first call to your function. (You probably won't need to go beyond the first and second instantiation of your function.)

intersect does not know anything about position within the vector, it is solely set-based, meaning "presence of". The help page is even titled "Sets" and starts with

Performs *set* union, intersection, ...

To get what you want, aren't you just looking for plain equality?

dist_func <- function(x, y) sum(x == y)/3

NB: true equality can be problematic if looking at numeric (non-integer) numbers, per R FAQ 7.31.

Your data is plagued with factors, not characters. You might notice

str(df2)
# 'data.frame': 10 obs. of  4 variables:
#  $ npi     : int  51 52 53 54 55 56 57 58 59 60
#  $ dier    : Factor w/ 9 levels "aap","beer","kip",..: 1 8 6 3 2 1 7 9 5 4
#  $ getal   : Factor w/ 8 levels "acht","drie",..: 3 4 4 2 5 6 7 8 1 1
#  $ mubilair: Factor w/ 9 levels "bank","bureau",..: 7 6 9 3 3 2 1 4 8 5

Notice, for example, that the first value in $getal is "acht", which is an integer 3 internally within the factors. You'll notice that the fourth integer-values for the three columns are 3, 2, 3 (respectively, which matches   the distance metric of 0.667 in column "51" and row "54".

Either use read.table(..., stringsAsFactors = FALSE) or change your distance function to be something like:

dist_func2 <- function(x, y) {
  if (is.factor(x)) x <- as.character(x)
  if (is.factor(y)) y <- as.character(y)
  sum(x == y)/3
}

(I suggest stringsAsFactors personally, but YMMV.)


问:
Dynamic id with ng-repeat
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

```<code><label ng-repeat="x in placeTypes">

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}
    <br>
</label>
</code>```

But when I try to get the element by Id the element is null.

答:
This should suffice:

```<code><label ng-repeat="x in placeTypes">
  <input type="checkbox" id="{{$index}}">
    {{x.display}}
  <br>
</label>
</code>```

You can read more about ngRepeat in the Angular docs: https://docs.angularjs.org/api/ng/directive/ngRepeat

Title: Dynamic id with ng-repeat

Body:
I'm working with AngularJS and I have a form with checkboxes that I generate with ng-repeat. I want to generate the id of each checkbox dynamically, I tried to do it like this:

    <input type="checkbox" id='{{x.value}}'>
    {{x.display}}

But when I try to get the element by Id the element is null.

Body:
This should suffice:

<label ng-repeat="x in placeTypes">
  <input type="checkbox" id="{{$index}}">
    {{x.display}}
  <br>
</label>

You can read more about ngRepeat in the Angular docs: https://docs.angularjs.org/api/ng/directive/ngRepeat


问:
D3.JS Y-axis label issue
To start, I am fairly new to D3.Js. I have spent the past week or so working on a D3.JS issue-specifically making a graph with a Y-axis label. However, I cannot get the graph exactly how I want. It is almost there but inverted or my data comes out wrong. Now I will briefly show some of my code and images of my main problem before showing all of the code. I have spent time looking at other Stack Overflow posts with a similar issue and I do what is on those posts and still have the same issue.

For example, I thought that this post would have the solution: reversed Y-axis D3

The data is the following:

[0,20,3,8] (It is actually an array of objects but I think this may be all that is needed.

So, to start, when the yScale is like this:

```<code>  var yScale = d3.scaleLinear()
             .domain([0, maxPound]) //Value of maxpound is 20
             .range([0, 350]);
</code>```

The bar chart looks like this:

As one can see the Y chart starts with zero at the top and 20 at the bottom-which at first I thought was an easy fix of flipping the values in the domain around to this:

```<code>     var yScale = d3.scaleLinear()
             .domain([0, maxPound]) //Value of maxpound is 20
             .range([0, 350]);
</code>```

I get this image:

In the second image the y-axis is right-20 is on top-Yay! But the graphs are wrong. 0 now returns a value of 350 pixels-the height of the SVG element. That is the value that 20 should be returning! If I try to switch the image range values, I get the same problem!

Now the code:

```<code>  var w = 350;
  var h = 350;
  var barPadding = 1;
  var margin = {top: 5, right: 200, bottom: 70, left: 25}

  var maxPound = d3.max(poundDataArray,
     function(d) {return parseInt(d.Pounds)}
  );

  //Y-Axis Code
  var yScale = d3.scaleLinear()
                 .domain([maxPound, 0])
                 .range([0, h]);

  var yAxis = d3.axisLeft()
                .scale(yScale)
                .ticks(5);

  //Creating SVG element
  var svg = d3.select(".pounds")
              .append('svg')
              .attr("width", w)
              .attr('height', h)
              .append("g")
                 .attr("transform", "translate(" + margin.left + "," +
     margin.top + ")");

    svg.selectAll("rect")
       .data(poundDataArray)
       .enter()
       .append("rect")
       .attr('x',  function(d, i){
            return i * (w / poundDataArray.length);
         })
       .attr('y', function(d) {
            return 350 - yScale(d.Pounds);
        })
       .attr('width', (w / 4) - 25)
       .attr('height', function(d){
           return yScale(d.Pounds);
        })
       .attr('fill', 'steelblue');

   //Create Y axis
   svg.append("g")
      .attr("class", "axis")
      .call(yAxis);
</code>```

Thank you for any help! I believe that the error may be in the y or height values and have spent time messing around there with no results.

答:
That is not a D3 issue, but an SVG feature: in an SVG, the origin (0,0) is at the top left corner, not the bottom left, as in a common Cartesian plane. That's why using [0, h] as the range makes the axis seem to be inverted... actually, it is not inverted: that's the correct orientation in an SVG. By the way, HTML5 Canvas has the same coordinates system, and you would have the same issue using a canvas.

So, you have to flip the range, not the domain:

```<code>var yScale = d3.scaleLinear()
    .domain([0, maxPound])
    .range([h, 0]);//the range goes from the bottom to the top now
</code>```

Or, in your case, using the margins:

```<code>var yScale = d3.scaleLinear()
    .domain([0, maxPound])
    .range([h - margin.bottom, margin.top]);
</code>```

Besides that, the math for the y position and height is wrong. It should be:

```<code>.attr('y', function(d) {
    return yScale(d.Pounds);
})
.attr('height', function(d) {
    return h - margin.bottom - yScale(d.Pounds);
})
</code>```

Also, as a bonus tip, don't hardcode the x position and the width. Use a band scale instead.

Here is your code with those changes:

var poundDataArray = [{
  Pounds: 10
}, {
  Pounds: 20
}, {
  Pounds: 5
}, {
  Pounds: 8
}, {
  Pounds: 14
}, {
  Pounds: 1
}, {
  Pounds: 12
}];

var w = 350;
var h = 350;
var barPadding = 1;
var margin = {
  top: 5,
  right: 20,
  bottom: 70,
  left: 25
}

var maxPound = d3.max(poundDataArray,
  function(d) {
    return parseInt(d.Pounds)
  }
);

//Y-Axis Code
var yScale = d3.scaleLinear()
  .domain([0, maxPound])
  .range([h - margin.bottom, margin.top]);

var xScale = d3.scaleBand()
  .domain(d3.range(poundDataArray.length))
  .range([margin.left, w - margin.right])
  .padding(.2);

var yAxis = d3.axisLeft()
  .scale(yScale)
  .ticks(5);

//Creating SVG element
var svg = d3.select("body")
  .append('svg')
  .attr("width", w)
  .attr('height', h)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," +
    margin.top + ")");

svg.selectAll("rect")
  .data(poundDataArray)
  .enter()
  .append("rect")
  .attr('x', function(d, i) {
    return xScale(i);
  })
  .attr('y', function(d) {
    return yScale(d.Pounds);
  })
  .attr('width', xScale.bandwidth())
  .attr('height', function(d) {
    return h - margin.bottom - yScale(d.Pounds);
  })
  .attr('fill', 'steelblue');

//Create Y axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + margin.left + ",0)")
  .call(yAxis);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Title: D3.JS Y-axis label issue

Body:
To start, I am fairly new to D3.Js. I have spent the past week or so working on a D3.JS issue-specifically making a graph with a Y-axis label. However, I cannot get the graph exactly how I want. It is almost there but inverted or my data comes out wrong. Now I will briefly show some of my code and images of my main problem before showing all of the code. I have spent time looking at other Stack Overflow posts with a similar issue and I do what is on those posts and still have the same issue.

For example, I thought that this post would have the solution: reversed Y-axis D3

The data is the following:

[0,20,3,8] (It is actually an array of objects but I think this may be all that is needed.

So, to start, when the yScale is like this:

  var yScale = d3.scaleLinear()
             .domain([0, maxPound]) //Value of maxpound is 20
             .range([0, 350]);

The bar chart looks like this:

As one can see the Y chart starts with zero at the top and 20 at the bottom-which at first I thought was an easy fix of flipping the values in the domain around to this:

     var yScale = d3.scaleLinear()
             .domain([0, maxPound]) //Value of maxpound is 20
             .range([0, 350]);

I get this image:

In the second image the y-axis is right-20 is on top-Yay! But the graphs are wrong. 0 now returns a value of 350 pixels-the height of the SVG element. That is the value that 20 should be returning! If I try to switch the image range values, I get the same problem!

Now the code:

  var w = 350;
  var h = 350;
  var barPadding = 1;
  var margin = {top: 5, right: 200, bottom: 70, left: 25}

  var maxPound = d3.max(poundDataArray,
     function(d) {return parseInt(d.Pounds)}
  );

  //Y-Axis Code
  var yScale = d3.scaleLinear()
                 .domain([maxPound, 0])
                 .range([0, h]);

  var yAxis = d3.axisLeft()
                .scale(yScale)
                .ticks(5);

  //Creating SVG element
  var svg = d3.select(".pounds")
              .append('svg')
              .attr("width", w)
              .attr('height', h)
              .append("g")
                 .attr("transform", "translate(" + margin.left + "," +
     margin.top + ")");

    svg.selectAll("rect")
       .data(poundDataArray)
       .enter()
       .append("rect")
       .attr('x',  function(d, i){
            return i * (w / poundDataArray.length);
         })
       .attr('y', function(d) {
            return 350 - yScale(d.Pounds);
        })
       .attr('width', (w / 4) - 25)
       .attr('height', function(d){
           return yScale(d.Pounds);
        })
       .attr('fill', 'steelblue');

   //Create Y axis
   svg.append("g")
      .attr("class", "axis")
      .call(yAxis);

Thank you for any help! I believe that the error may be in the y or height values and have spent time messing around there with no results.

Body:
That is not a D3 issue, but an SVG feature: in an SVG, the origin (0,0) is at the top left corner, not the bottom left, as in a common Cartesian plane. That's why using [0, h] as the range makes the axis seem to be inverted... actually, it is not inverted: that's the correct orientation in an SVG. By the way, HTML5 Canvas has the same coordinates system, and you would have the same issue using a canvas.

So, you have to flip the range, not the domain:

var yScale = d3.scaleLinear()
    .domain([0, maxPound])
    .range([h, 0]);//the range goes from the bottom to the top now

Or, in your case, using the margins:

var yScale = d3.scaleLinear()
    .domain([0, maxPound])
    .range([h - margin.bottom, margin.top]);

Besides that, the math for the y position and height is wrong. It should be:

.attr('y', function(d) {
    return yScale(d.Pounds);
})
.attr('height', function(d) {
    return h - margin.bottom - yScale(d.Pounds);
})

Also, as a bonus tip, don't hardcode the x position and the width. Use a band scale instead.

Here is your code with those changes:

var poundDataArray = [{
  Pounds: 10
}, {
  Pounds: 20
}, {
  Pounds: 5
}, {
  Pounds: 8
}, {
  Pounds: 14
}, {
  Pounds: 1
}, {
  Pounds: 12
}];

var w = 350;
var h = 350;
var barPadding = 1;
var margin = {
  top: 5,
  right: 20,
  bottom: 70,
  left: 25
}

var maxPound = d3.max(poundDataArray,
  function(d) {
    return parseInt(d.Pounds)
  }
);

//Y-Axis Code
var yScale = d3.scaleLinear()
  .domain([0, maxPound])
  .range([h - margin.bottom, margin.top]);

var xScale = d3.scaleBand()
  .domain(d3.range(poundDataArray.length))
  .range([margin.left, w - margin.right])
  .padding(.2);

var yAxis = d3.axisLeft()
  .scale(yScale)
  .ticks(5);

//Creating SVG element
var svg = d3.select("body")
  .append('svg')
  .attr("width", w)
  .attr('height', h)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," +
    margin.top + ")");

svg.selectAll("rect")
  .data(poundDataArray)
  .enter()
  .append("rect")
  .attr('x', function(d, i) {
    return xScale(i);
  })
  .attr('y', function(d) {
    return yScale(d.Pounds);
  })
  .attr('width', xScale.bandwidth())
  .attr('height', function(d) {
    return h - margin.bottom - yScale(d.Pounds);
  })
  .attr('fill', 'steelblue');

//Create Y axis
svg.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + margin.left + ",0)")
  .call(yAxis);

<script src="https://d3js.org/d3.v4.min.js"></script>