问:
globalize my node variable express and route
Hello guys so i have this two variables i am requiring them for every route i have so i want to globalize them and just add them to the app.js but when i do that it didn't work.

```<code>var express = require('express');
var router = express.Router();
</code>```

i tried to addd them in to my separate file config.js and then i require it in my route and assign it to variable and use it but it is not working.

my config file look like this

```<code>/**
 * Module dependencies.
 */
var express = require('express'),
  favicon = require('serve-favicon'),
  logger = require('morgan'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  errorHandler = require('errorhandler'),
  path = require('path');

module.exports = function() {
  var app = express();
var router = app.Router();

  return app;
}();
</code>```

i get this error all the time :
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');

答:
TLDR: Your router variable is an instance of Router, and should to be initialized inside each of your route files. I can appreciate trying to be as DRY as possible, but doing it this way will not work the way you expect it to. You can save a bit of typing by writing it this way:

```<code>var router = require('express').Router();
</code>```

The longer explanation is that use multiple routes, you need a router for each route. This is to help break up the whole path associated with a request (i.e. /bar/foo/baz) into more manageable chunks.

Let's say your path can start with either /cats or /dogs. In the file where you declare all your middleware, you could write:

```<code>var catRoute = require(./routes/cats)
var dogRoute = require(./routes/dogs)

app.use('/cats', catRoute)
app.use('/dogs', dogRoute)
</code>```

Then, inside cats.js:

```<code>var router = require('express').Router();
router.get('/whiskers', (req, res) => {
  res.send('Cat whiskers!')
}
module.exports = router;
</code>```

What this does is tell the app if it gets a path starting with /cats, use the cats route, which is just another piece of middleware. Within the route itself, we don't have to specify /cats/whiskers, only /whiskers because app is only passing down the part of the path after /cats to the cats.

You can nest as many routers as you want. Check out this article for a good example of how to do that.

Hypothetically, you could use only one router

Body:
Hello guys so i have this two variables i am requiring them for every route i have so i want to globalize them and just add them to the app.js but when i do that it didn't work.

var express = require('express');
var router = express.Router();

i tried to addd them in to my separate file config.js and then i require it in my route and assign it to variable and use it but it is not working.

my config file look like this

/**
 * Module dependencies.
 */
var express = require('express'),
  favicon = require('serve-favicon'),
  logger = require('morgan'),
  bodyParser = require('body-parser'),
  methodOverride = require('method-override'),
  errorHandler = require('errorhandler'),
  path = require('path');

module.exports = function() {
  var app = express();
var router = app.Router();

  return app;
}();

i get this error all the time :
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');

Body:
TLDR: Your router variable is an instance of Router, and should to be initialized inside each of your route files. I can appreciate trying to be as DRY as possible, but doing it this way will not work the way you expect it to. You can save a bit of typing by writing it this way:

var router = require('express').Router();

The longer explanation is that use multiple routes, you need a router for each route. This is to help break up the whole path associated with a request (i.e. /bar/foo/baz) into more manageable chunks.

Let's say your path can start with either /cats or /dogs. In the file where you declare all your middleware, you could write:

var catRoute = require(./routes/cats)
var dogRoute = require(./routes/dogs)

app.use('/cats', catRoute)
app.use('/dogs', dogRoute)

Then, inside cats.js:

var router = require('express').Router();
router.get('/whiskers', (req, res) => {
  res.send('Cat whiskers!')
}
module.exports = router;

What this does is tell the app if it gets a path starting with /cats, use the cats route, which is just another piece of middleware. Within the route itself, we don't have to specify /cats/whiskers, only /whiskers because app is only passing down the part of the path after /cats to the cats.

You can nest as many routers as you want. Check out this article for a good example of how to do that.

Hypothetically, you could use only one router


来源: stackexchange

问:
Python seemingly not reading from text file
```<code>files = []
with open("[...].log", "a+") as posshell:
    for line in files:
        print(line)
        posshell_files.append(line)
</code>```

I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.

答:
Try this</p>

```<code>with open('posshell.log') as p:
    content = p.readlines()
    content = [x.strip() for x in content]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
files = []
with open("[...].log", "a+") as posshell:
    for line in files:
        print(line)
        posshell_files.append(line)

I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.

Body:
Try this

with open('posshell.log') as p:
    content = p.readlines()
    content = [x.strip() for x in content]


问:
Firebase Cloud functions to avoid client side work is always worth?
I'm recently working with Firebase Cloud functions to delegate lot of work from my client side to the server, reducing the data cost for the user. But recently I wondered if it's worth it or not, or maybe a better database structure could fix it.

I have a social app where the user can workout and post their results, you can follow users and all kind of "typical" social media stuffs. Well, my problem appear when I want to implement pagination retrieving the last X workouts that I should show to each user on their feed.

My question is : How expensive could be update from 1-1000(worst case) fields on the database on a common event trigger on Firebase Cloud functions. It's enough expensive at client side to look for avoid it and look for better ways talking about performance even if it's more expensive at client side?

I will explain it looking at my example:

Database Structure

```<code>"privateUserData" : {
    "user1" : {
      "messagingTokens": {
        "someToken": true,
        "someToken2": true,
      },
      "accountCreationDate" : 1495819217216,
      "email" : "abcd@gmail.com",
      "followedBy" : {
        "user2": true,
        "user3": true,
      },
      "following" : {
        "user2": true,
        "user3": true,
      },
      "lastLogin" : 1498654134543,
      "photoUrl" : "photo.png",
      "username" : "Francisco Durdin Garcia"
    },
  },
  "publicUserData": {
    "user1": {
      "username": "someUserName",
      "followersCount": 5,
      "followingCount": 1,
      "photoUrl" : "someUrl"
    }
    ...
  },
  "workouts" : {
    "workout1" : {
      "likes": {
        "user1": true,
        "user2": true,
        ...
      },
      "followers": {
        "user1": true,
        "user2": true,
        ...
      },
      "comments": {
        "comment1": {
          "owner": "user1",
          "content": "somecomment",
          "time": 1493153530311,
          "replies": {
            "reply1": {
              "owner": "user1",
              "content": "somecomment",
              "time": 1493153530311,
            }
          }
        }
      }
      "authorUid" : "user1",
      "description" : "desc",
      "points" : 63,
      "time" : "00:03",
      "createdAt" : 1493153530311,
      "title" : "someTitle",
      "workoutJson" : "workoutJsonDataHere"
    }
  }
</code>```

To be able to do that query I should do individual queries for each user I follow:

The problem is that I can do a "global" query and limit it to just X dataSnapshots. I can just filter few workouts for each individual query:

```<code>mDatabase.child("workouts").orderByChild("authorId).equalTo("userIFollow").limitToLast(10)
</code>```

This query will return me a filter applied just for one userIFollow it's not possible to do it over all of them, so I have three options:

1. Create a table which stores relation between usersId and workoutsId visible by them with a timeStamp value. But I should
    keep track of this values thought a Firebase cloud function, and
    obviously maybe I follow an user with Thousands of workouts I my
    cloud functions would need to copy ALL OF THEM to the right
    reference.

This was the way I wanted to go, but I don't know if it's
    the proper way talking about client side cost.

2. I can add a lastActivityTimeStamp on publicUserData and filtering by that retrieve just a few workouts of the last users with activity, growing this query with a pagination too.

3. Finally I can always retrieve all the workouts from this user and filter on client side, this will be expensive just one, because later the cache will do everything easier.

This are the ways I found to resolve my problem, and my question is still how expensive and useful are Firebase Cloud functions to copy large amounts of data with common triggers.

答:
From the way you worded your question, you seem familiar with the Database Cloud Functions for Firebase and it also seems that 'workouts' is your payload (the biggest chunk of data that you don't want to download repeatedly).

I would recommend the following approach based roughly off how GitHub's API works.

Prerequisites

In your /privateUserData/{user} data, you seem to have the list of followed user IDs (at /privateUserData/{user}/following). To make your queries simpler, I'd recommend implementing a list of workout IDs authored by that user (under something like /publicUserData/{user}/authorOf).

Implementation

I'd recommend building  a HTTP Cloud Function, at say https://FUNCTION_URL/followedWorkouts. When called you would generate a list of workout IDs for a given user by checking who they follow and then getting the list of workouts authored by each followed user and return them as one array. To identify the user, you could pass in their ID using a GET parameter such as ?user=<someUserId> or through some form of authentication. How you go about it is up to you.

The function should return data in the following (or similar) format (in this case I'm using JSON):

```<code>[{"id": "workoutId1", "lastMod": "1493153530311"}, {"id": "workoutId2", "lastMod": "1493153530521"}, ...]
</code>```

id is the the workout ID.

lastMod (short form of last modified) is the last time that workout's data was updated (from {workoutId}/lastModificationDate). See the 'caching' section below.

Filtering

I'd also implement the following 'filters' on the Cloud Function:

Since (?since=<someTimeStamp>): will return workout IDs that have been modified since that timestamp. (Say you downloaded some information at some time, T, you would then set since=T to then only receive workouts changed after that time.

Max (?max=X): will return the X most recent entries.

Start At (?startAt=X): will return the most recent entries starting at the index X (I'd make it a 1-based index).

So if you wanted to grab the 10 most recent entries, you could call https://FUNCTION_URL/followedWorkouts?max=10 which would give you the IDs for the 1st-10th most recently updated workouts. For the next 'page' of entries, you would call https://FUNCTION_URL/followedWorkouts?startAt=10&max=10 which would give you the 11th-20th most recently updated workout IDs.

Caching

As each workout is a payload, it doesn't make sense to download the multiple times. I would recommend caching this data to prevent this. In the response I suggested above, the field lastMod (last modified) allows you to check if a locally cached version needs updating. How you go about this, is yet again up to you.

Extending

If you need more of these paginated feeds, you could name the function more generally such as https://FUNCTION_URL/feeds and pass in the feed type as a parameter https://FUNCTION_URL/feeds?type=workouts. You could use this for things like followers, following, comments, etc.

Feel free to reach out if you need some more information.

ContentLicense: CC BY-SA 4.0

Body:
I'm recently working with Firebase Cloud functions to delegate lot of work from my client side to the server, reducing the data cost for the user. But recently I wondered if it's worth it or not, or maybe a better database structure could fix it.

I have a social app where the user can workout and post their results, you can follow users and all kind of "typical" social media stuffs. Well, my problem appear when I want to implement pagination retrieving the last X workouts that I should show to each user on their feed.

My question is : How expensive could be update from 1-1000(worst case) fields on the database on a common event trigger on Firebase Cloud functions. It's enough expensive at client side to look for avoid it and look for better ways talking about performance even if it's more expensive at client side?

I will explain it looking at my example:

Database Structure

"privateUserData" : {
    "user1" : {
      "messagingTokens": {
        "someToken": true,
        "someToken2": true,
      },
      "accountCreationDate" : 1495819217216,
      "email" : "abcd@gmail.com",
      "followedBy" : {
        "user2": true,
        "user3": true,
      },
      "following" : {
        "user2": true,
        "user3": true,
      },
      "lastLogin" : 1498654134543,
      "photoUrl" : "photo.png",
      "username" : "Francisco Durdin Garcia"
    },
  },
  "publicUserData": {
    "user1": {
      "username": "someUserName",
      "followersCount": 5,
      "followingCount": 1,
      "photoUrl" : "someUrl"
    }
    ...
  },
  "workouts" : {
    "workout1" : {
      "likes": {
        "user1": true,
        "user2": true,
        ...
      },
      "followers": {
        "user1": true,
        "user2": true,
        ...
      },
      "comments": {
        "comment1": {
          "owner": "user1",
          "content": "somecomment",
          "time": 1493153530311,
          "replies": {
            "reply1": {
              "owner": "user1",
              "content": "somecomment",
              "time": 1493153530311,
            }
          }
        }
      }
      "authorUid" : "user1",
      "description" : "desc",
      "points" : 63,
      "time" : "00:03",
      "createdAt" : 1493153530311,
      "title" : "someTitle",
      "workoutJson" : "workoutJsonDataHere"
    }
  }

To be able to do that query I should do individual queries for each user I follow:

The problem is that I can do a "global" query and limit it to just X dataSnapshots. I can just filter few workouts for each individual query:

mDatabase.child("workouts").orderByChild("authorId).equalTo("userIFollow").limitToLast(10)

This query will return me a filter applied just for one userIFollow it's not possible to do it over all of them, so I have three options:

1. Create a table which stores relation between usersId and workoutsId visible by them with a timeStamp value. But I should
    keep track of this values thought a Firebase cloud function, and
    obviously maybe I follow an user with Thousands of workouts I my
    cloud functions would need to copy ALL OF THEM to the right
    reference.

This was the way I wanted to go, but I don't know if it's
    the proper way talking about client side cost.

2. I can add a lastActivityTimeStamp on publicUserData and filtering by that retrieve just a few workouts of the last users with activity, growing this query with a pagination too.

3. Finally I can always retrieve all the workouts from this user and filter on client side, this will be expensive just one, because later the cache will do everything easier.

This are the ways I found to resolve my problem, and my question is still how expensive and useful are Firebase Cloud functions to copy large amounts of data with common triggers.

Body:
From the way you worded your question, you seem familiar with the Database Cloud Functions for Firebase and it also seems that 'workouts' is your payload (the biggest chunk of data that you don't want to download repeatedly).

I would recommend the following approach based roughly off how GitHub's API works.

Prerequisites

In your /privateUserData/{user} data, you seem to have the list of followed user IDs (at /privateUserData/{user}/following). To make your queries simpler, I'd recommend implementing a list of workout IDs authored by that user (under something like /publicUserData/{user}/authorOf).

Implementation

I'd recommend building  a HTTP Cloud Function, at say https://FUNCTION_URL/followedWorkouts. When called you would generate a list of workout IDs for a given user by checking who they follow and then getting the list of workouts authored by each followed user and return them as one array. To identify the user, you could pass in their ID using a GET parameter such as ?user=<someUserId> or through some form of authentication. How you go about it is up to you.

The function should return data in the following (or similar) format (in this case I'm using JSON):

[{"id": "workoutId1", "lastMod": "1493153530311"}, {"id": "workoutId2", "lastMod": "1493153530521"}, ...]

id is the the workout ID.

lastMod (short form of last modified) is the last time that workout's data was updated (from {workoutId}/lastModificationDate). See the 'caching' section below.

Filtering

I'd also implement the following 'filters' on the Cloud Function:

Since (?since=<someTimeStamp>): will return workout IDs that have been modified since that timestamp. (Say you downloaded some information at some time, T, you would then set since=T to then only receive workouts changed after that time.

Max (?max=X): will return the X most recent entries.

Start At (?startAt=X): will return the most recent entries starting at the index X (I'd make it a 1-based index).

So if you wanted to grab the 10 most recent entries, you could call https://FUNCTION_URL/followedWorkouts?max=10 which would give you the IDs for the 1st-10th most recently updated workouts. For the next 'page' of entries, you would call https://FUNCTION_URL/followedWorkouts?startAt=10&max=10 which would give you the 11th-20th most recently updated workout IDs.

Caching

As each workout is a payload, it doesn't make sense to download the multiple times. I would recommend caching this data to prevent this. In the response I suggested above, the field lastMod (last modified) allows you to check if a locally cached version needs updating. How you go about this, is yet again up to you.

Extending

If you need more of these paginated feeds, you could name the function more generally such as https://FUNCTION_URL/feeds and pass in the feed type as a parameter https://FUNCTION_URL/feeds?type=workouts. You could use this for things like followers, following, comments, etc.

Feel free to reach out if you need some more information.


问:
How to create split and morph animation together using bezier curves in android
Music widget by JIE LIU

I want to add a similar gooey and morphing effect to my android app.

答: You can create a gooey animation easily using Canvas animations which is supported by android. </p>


问:
Download a song directly to visitor's computer using youtube-dl
I'm looking to convert a youtube video to mp3 and download it directly to visitor's / user's computer.

The conversion and downloading to the server is pretty easy using a command like that:

youtube-dl --extract-audio --audio-format mp3 [video]

I'm wondering what would be the fastest option to get that mp3 file to the user's computer using php.

答:
I'm doing about the same thing for one of my websites, I use the following function to download & convert the video to mp3. It takes the video link as a param and returns the downloaded file location. It also checks if the file is already downloaded and returns its location if yes.

```<code>function downloadMP3($videolink){
    parse_str( parse_url( $videolink, PHP_URL_QUERY ), $parms );
    $id = $parms['v'];
    $output = "download/".$id.".mp3";
    if (file_exists($output)) {
        return $output;
    }else {
        $descriptorspec = array(
            0 => array(
                "pipe",
                "r"
            ) , // stdin
            1 => array(
                "pipe",
                "w"
            ) , // stdout
            2 => array(
                "pipe",
                "w"
            ) , // stderr
        );
        $cmd = 'youtube-dl --extract-audio --audio-quality 0 --audio-format mp3 --output download/"'.$id.'.%(ext)s" '.$videolink;
        $process = proc_open($cmd, $descriptorspec, $pipes);
        $errors = stream_get_contents($pipes[2]);
        fclose($pipes[2]);
        $ret = proc_close($process);
        if ($errors) {
            //print($errors);
        }
        return $output;
    }
}
</code>```

Now whenever the user tries to download a file, I simply get the link from $link = $_GET['link'] pass it to the function and use the following code to serve the file :

```<code>$downloadpath = downloadMP3($videolink);
$song_name = "song";
header('X-Accel-Redirect: /' . $downloadpath);
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
header('Content-length: ' . filesize($_SERVER["DOCUMENT_ROOT"]."/".$downloadpath));
header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
</code>```

I highly recommend using the X-Accel-Redirect header for Nginx or x-sendfile for Apache to serve the file.

Body:
I'm doing about the same thing for one of my websites, I use the following function to download & convert the video to mp3. It takes the video link as a param and returns the downloaded file location. It also checks if the file is already downloaded and returns its location if yes.

function downloadMP3($videolink){
    parse_str( parse_url( $videolink, PHP_URL_QUERY ), $parms );
    $id = $parms['v'];
    $output = "download/".$id.".mp3";
    if (file_exists($output)) {
        return $output;
    }else {
        $descriptorspec = array(
            0 => array(
                "pipe",
                "r"
            ) , // stdin
            1 => array(
                "pipe",
                "w"
            ) , // stdout
            2 => array(
                "pipe",
                "w"
            ) , // stderr
        );
        $cmd = 'youtube-dl --extract-audio --audio-quality 0 --audio-format mp3 --output download/"'.$id.'.%(ext)s" '.$videolink;
        $process = proc_open($cmd, $descriptorspec, $pipes);
        $errors = stream_get_contents($pipes[2]);
        fclose($pipes[2]);
        $ret = proc_close($process);
        if ($errors) {
            //print($errors);
        }
        return $output;
    }
}

Now whenever the user tries to download a file, I simply get the link from $link = $_GET['link'] pass it to the function and use the following code to serve the file :

$downloadpath = downloadMP3($videolink);
$song_name = "song";
header('X-Accel-Redirect: /' . $downloadpath);
header("Content-Type: audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3");
header('Content-length: ' . filesize($_SERVER["DOCUMENT_ROOT"]."/".$downloadpath));
header('Content-Disposition: attachment; filename="'.$song_name.'.mp3"');
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');

I highly recommend using the X-Accel-Redirect header for Nginx or x-sendfile for Apache to serve the file.


问:
Autodesk Data Management API 403-Error
I am trying to receive data via Autodesk Data Management API. So far I've created an Forge-App and connected it with a BIM360 Integration.
Then I wanted to get a list of all hubs, but when I do so, I receive an JSON-Object which contains a warning:

```<code>warnings: [{
     "AboutLink":null,
     "Detail":""You don't have permission to access this API",
     "ErrorCode": "BIM360DM_ERROR",
     "HttpStatusCode": "403",
     ...
}]
</code>```

I called the webservice via AJAX wich looks like that:

```<code>this.getToken(function(token) {
        $.ajax({
            url: "https://developer.api.autodesk.com/project/v1/hubs",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "Bearer "+token);
            }
        }).done(...);
</code>```

The token is a 3-legged one. I am not sure which API I do not have permission for because I am pretty sure, that I have permission for BIM360.(I created the Integration as an administrator).

答:
In addition to was ZHong mentioned, I would suggest you try this sample. It will ask you to provision your Forge Client ID under your BIM 360 settings, just follow the steps that the app will present.

On both 2- or 3-legged, the app accessing the data (Forge Client ID) needs authorization from the account admin. Without that, the Hubs endpoint will not return your BIM 360 hub, and inside that, the sample applies for Projects endpoint.

Title: Autodesk Data Management API 403-Error

Body:
I am trying to receive data via Autodesk Data Management API. So far I've created an Forge-App and connected it with a BIM360 Integration.
Then I wanted to get a list of all hubs, but when I do so, I receive an JSON-Object which contains a warning:

warnings: [{
     "AboutLink":null,
     "Detail":""You don't have permission to access this API",
     "ErrorCode": "BIM360DM_ERROR",
     "HttpStatusCode": "403",
     ...
}]

I called the webservice via AJAX wich looks like that:

this.getToken(function(token) {
        $.ajax({
            url: "https://developer.api.autodesk.com/project/v1/hubs",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "Bearer "+token);
            }
        }).done(...);

The token is a 3-legged one. I am not sure which API I do not have permission for because I am pretty sure, that I have permission for BIM360.(I created the Integration as an administrator).


问:
String matching objective-c
I need to match my string in this way: *myString*
where * mean any substring.
which method should I use?

can you help me, please?

答:
You can't do an actual search using a * (wildcard character), but you can usually do something that is equivalent:

Equivalent to searching for theTerm*:

```<code>if ([theString hasPrefix:@"theTerm"]) {
</code>```

Equivalent to searching for *theTerm:

```<code>if ([theString hasSuffix:@"theTerm"]) {
</code>```

Or, using the category on NSString shown below, the following is equivalent to searching for *theTerm*:

```<code>if ([theString containsString:@"theTerm"]) {
</code>```

A category is simply a new method (like a function) that we add to class. I wrote the following one because it generally makes more sense to me to think of one string containing another rather than dealing with NSRanges.

```<code>// category on NSString
@interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
@end

@implementation NSString (MDSearchAdditions)

- (BOOL)containsString:(NSString *)aString {
  return [self rangeOfString:aString].location != NSNotFound;
}

@end
</code>```

ContentLicense: CC BY-SA 2.5

Title: String matching objective-c

Body:
You can't do an actual search using a * (wildcard character), but you can usually do something that is equivalent:

Equivalent to searching for theTerm*:

if ([theString hasPrefix:@"theTerm"]) {

Equivalent to searching for *theTerm:

if ([theString hasSuffix:@"theTerm"]) {

Or, using the category on NSString shown below, the following is equivalent to searching for *theTerm*:

if ([theString containsString:@"theTerm"]) {

A category is simply a new method (like a function) that we add to class. I wrote the following one because it generally makes more sense to me to think of one string containing another rather than dealing with NSRanges.

// category on NSString
@interface NSString (MDSearchAdditions)
- (BOOL)containsString:(NSString *)aString;
@end

@implementation NSString (MDSearchAdditions)

- (BOOL)containsString:(NSString *)aString {
  return [self rangeOfString:aString].location != NSNotFound;
}

@end


问:
React autofocus input after enabling a disabled input
I'm trying to autofocus a text input (the input is enabled upon selecting a relevant radio option).

The autofocus works when toggling between options that will enable the text input. However, autofocus fails when switching from an option that disables the text input to an option that enables the text input.

In the sample link below:

option 1, option 2: disable the text input

option 3, option 4: enable the text input

Failure case:

option 1 is default

choose option 3 or option 4

input gets enabled

autofocus fails (looking for pointer to fix this behaviour)

Success case:

choose option 3

input is enabled

switch to option 4

input is autoFocussed

sample code for the problem on codesandbox

答:
This does not work, cause you immediately set it after the setState call, but at this point of lifecycle the component has not re-rendered and the ref to the input is still in a state where it is disabled.

What you need to do is, trigger the focus handling after the component did update in the componentDidUpdate hook.

Something like this (pseudo code)

```<code>componentDidUpdate(prevProps, prevState) {

  if (this.state.enabled) {
     this.inputValue.focus();
  }
}
</code>```

It might be possible that you need additional checks like only focus on a transition from disabled to enabled. This could be achieved by doing something like this:

```<code>componentDidUpdate(prevProps, prevState) {
  if (!prevState.enabled && this.state.enabled) {
    this.inputValue.focus();
  }}
</code>```

Here a link to the updated codesandbox: https://codesandbox.io/s/31RnlkJW4

Body:
This does not work, cause you immediately set it after the setState call, but at this point of lifecycle the component has not re-rendered and the ref to the input is still in a state where it is disabled.

What you need to do is, trigger the focus handling after the component did update in the componentDidUpdate hook.

Something like this (pseudo code)

componentDidUpdate(prevProps, prevState) {

  if (this.state.enabled) {
     this.inputValue.focus();
  }
}

It might be possible that you need additional checks like only focus on a transition from disabled to enabled. This could be achieved by doing something like this:

componentDidUpdate(prevProps, prevState) {
  if (!prevState.enabled && this.state.enabled) {
    this.inputValue.focus();
  }}

Here a link to the updated codesandbox: https://codesandbox.io/s/31RnlkJW4


问:
SQLite speed up select with collate nocase
I have SQLite db:

```<code>CREATE TABLE IF NOT EXISTS Commits
(
    GlobalVer INTEGER PRIMARY KEY,
    Data blob NOT NULL
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS Streams
(
    Name char(40) NOT NULL,
    GlobalVer INTEGER NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;
</code>```

I want to make 1 select:

```<code>SELECT Commits.Data
  FROM Streams JOIN Commits ON Streams.GlobalVer=Commits.GlobalVer
 WHERE
    Streams.Name = ?
ORDER BY Streams.GlobalVer
LIMIT ? OFFSET ?
</code>```

after that i want to make another select:

```<code>SELECT Commits.Data,Streams.Name
  FROM Streams JOIN Commits ON Streams.GlobalVer=Commits.GlobalVer
 WHERE
    Streams.Name = ? COLLATE NOCASE
ORDER BY Streams.GlobalVer
LIMIT ? OFFSET ?
</code>```

The problem is that 2nd select works super slow. I think this is because COLLATE NOCASE. I want to speed up it. I tried to add index but it doesn't help (may be i did sometinhg wrong?). How to execute 2nd query with speed approximately equals to 1st query's speed?

答:
An index can be used to speed up a search only if it uses the same collation as the query.

By default, an index takes the collation from the table column, so you could change the table definition:

```<code>CREATE TABLE IF NOT EXISTS Streams
(
    Name      char(40) NOT NULL COLLATE NOCASE,
    GlobalVer INTEGER  NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;
</code>```

However, this would make the first query slower.

To speed up both queries, you need two indexes, one for each collation. So to use the default collation for the implicit index, and NOCASE for the explicit index:

```<code>CREATE TABLE IF NOT EXISTS Streams
(
    Name      char(40) NOT NULL COLLATE NOCASE,
    GlobalVer INTEGER  NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS Streams_nocase_idx ON Streams(Name COLLATE NOCASE, GlobalVar);
</code>```

(Adding the second column to the index speeds up the ORDER BY in this query.)

Body:
I have SQLite db:

CREATE TABLE IF NOT EXISTS Commits
(
    GlobalVer INTEGER PRIMARY KEY,
    Data blob NOT NULL
) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS Streams
(
    Name char(40) NOT NULL,
    GlobalVer INTEGER NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;

I want to make 1 select:

SELECT Commits.Data
  FROM Streams JOIN Commits ON Streams.GlobalVer=Commits.GlobalVer
 WHERE
    Streams.Name = ?
ORDER BY Streams.GlobalVer
LIMIT ? OFFSET ?

after that i want to make another select:

SELECT Commits.Data,Streams.Name
  FROM Streams JOIN Commits ON Streams.GlobalVer=Commits.GlobalVer
 WHERE
    Streams.Name = ? COLLATE NOCASE
ORDER BY Streams.GlobalVer
LIMIT ? OFFSET ?

The problem is that 2nd select works super slow. I think this is because COLLATE NOCASE. I want to speed up it. I tried to add index but it doesn't help (may be i did sometinhg wrong?). How to execute 2nd query with speed approximately equals to 1st query's speed?

Body:
An index can be used to speed up a search only if it uses the same collation as the query.

By default, an index takes the collation from the table column, so you could change the table definition:

CREATE TABLE IF NOT EXISTS Streams
(
    Name      char(40) NOT NULL COLLATE NOCASE,
    GlobalVer INTEGER  NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;

However, this would make the first query slower.

To speed up both queries, you need two indexes, one for each collation. So to use the default collation for the implicit index, and NOCASE for the explicit index:

CREATE TABLE IF NOT EXISTS Streams
(
    Name      char(40) NOT NULL COLLATE NOCASE,
    GlobalVer INTEGER  NOT NULL,
    PRIMARY KEY(Name, GlobalVer)
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS Streams_nocase_idx ON Streams(Name COLLATE NOCASE, GlobalVar);

(Adding the second column to the index speeds up the ORDER BY in this query.)


问:
Is There an HBase 1.2 Equivalent to Accumulo's Authorizations Class?
In Accumulo 1.6, there is an org.apache.accumulo.core.security.Authorizations class. It basically wraps a collection of authorization strings.

The Authorizations object can be passed to methods such as:

org.apache.accumulo.core.client.Connector.createScanner(String, Authorizations)

org.apache.accumulo.core.client.Connector.createBatchDeleter(String, Authorizations, int, BatchWriterConfig)

Does HBase 1.2 have a similar concept?

None of the constructors of org.apache.hadoop.hbase.client.Scan takes an argument of a type that's an obvious counterpart to Accumulo's Authorizations class.

None of the createConnection methods of org.apache.hadoop.hbase.client.ConnectionFactory takes an argument that's an obvious counterpart to Accumulo's Authorizations class.

What is the HBase equivalent to org.apache.accumulo.core.security.Authorizations, if any?

答:
After finding this page -- https://blogs.apache.org/hbase/entry/hbase_cell_security -- I think I've found most of what I'm looking for.

HBase has an org.apache.hdoop.hbase.security.visibility.Authorizations class that seems to be an approximate equivalent to Accumulo's Authorizations class. This class is used in places like:

org.apache.hadoop.hbase.client.Get.setAuthorizations(Authorizations)

org.apache.hadoop.hbase.client.Scan.setAuthorizations(Authorizations)

What I've not yet figured out is how to make HBase actually apply Authorizations when working with cells having visibility settings -- that is, for cells created via org.apache.hadoop.hbase.client.Mutation objects (through the Put sub-class) for which setCellVisibility(org.apache.hadoop.hbase.security.visibility.CellVisibility) method had been invoked.

It seems HBase ignores visibility/authorizations logic by default.


问:
PowerShell array count not zero
I'm trying to understand why this array count is not resulting in 0

```<code>@($null).Count
</code>```

Output:

```<code>1
</code>```

答: @($null) is an array with a single $null element (hence the Count property is 1). Likewise @($null,$null).Count is 2, and @().Count is 0. Keep in mind that @($null) emits $null to the pipeline, so the Count property returned from @($null) | Measure-Object will be 0.

Title: PowerShell array count not zero

Body:
I'm trying to understand why this array count is not resulting in 0

@($null).Count

Output:

1


问:
Is this the right way to get string resources from within a Fragment?
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

```<code>public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}
</code>```

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

```<code>public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}
</code>```

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.

答:
When Fragments is onCreate() method, it already has the Activity's context, so it is not necessary set the context previously. Unless you need to do an specific (and inusual) implementation of Context, like parsing variables/values from portrait screen mode to landscape mode I guess...

However you're getting an string resource from last context, wich is already set up, so well the parsed variables/values indeed.

Body:
Which method is generally better / safer for reading string resources while in a Fragment?

Here I read getResources().getString() directly:

public class SomeFragment extends Fragment {

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = getResources().getString(R.string.my_string_id);
    }

}

Or is it better to do it this way, by setting a Context field first and then reading the resources from that:

public class SomeFragment extends Fragment {
    private Context context;

    public static SomeFragment newInstance() {
        Bundle args = new Bundle();
        SomeFragment fragment = new SomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String someString = context.getResources().getString(R.string.my_string_id);
    }

}

Any tradeoffs/drawbacks to either of these methods?

The reason I ask is because sometimes I've run into nullpointer issues with the first approach that were resolved by using the second approach; so I wasn't sure if it was problematic to use the first one.


问:
NGINX based sample website in a container
I am using Docker and tried to use James Turnbull's book to create a container with a working nginx. After creating and running container I have tried to access HTML page on the public port, but I've got 403 Forbidden status code.
Dockerfile is here:

```<code>FROM ubuntu:14.04

RUN apt-get -yqq update && apt-get -yqq install nginx

RUN mkdir -p /var/www/html/website
ADD nginx/global.conf /etc/nginx/conf.d/
ADD nginx/nginx.conf /etc/nginx/

EXPOSE 80
</code>```

global.conf:

```<code>server {
        listen          0.0.0.0:80;
        server_name     _;

        root            /var/www/html/website;
        index           index.html index.htm;

        access_log      /var/log/nginx/default_access.log;
        error_log       /var/log/nginx/default_error.log;
}
</code>```

nginx.conf:

```<code>user www-data;
worker_processes 4;
pid /run/nginx.pid;
daemon off;

events {  }

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;
  gzip on;
  gzip_disable "msie6";
  include /etc/nginx/conf.d/*.conf;
}
</code>```

I have used above command to run new container:

```<code>sudo docker run -d -p 80 --name website -v $PWD/website:/var/www/html/website:rw user007/website nginx
</code>```

答:
It cause by SELinux.

Using Volumes with Docker can Cause Problems with SELinux.

See this link for the full story.

When using SELinux for controlling processes within a container, you need to make sure any content that gets volume mounted into the container is readable, and potentially writable, depending on the use case.

You can temporarily issue by running:

```<code>su -c "setenforce 0"
</code>```

This got easier recently since Docker finally merged a patch in docker >1.7

This patch adds support for "z" and "Z" as options on the volume mounts (-v).

For example:

```<code>docker run -d -p 80 --name website -v $PWD/website:/var/www/html/website:z user007/website nginx
</code>```

Will automatically do the

```<code>chcon -Rt svirt_sandbox_file_t /var/db
</code>```

Body:
I am using Docker and tried to use James Turnbull's book to create a container with a working nginx. After creating and running container I have tried to access HTML page on the public port, but I've got 403 Forbidden status code.
Dockerfile is here:

FROM ubuntu:14.04

RUN apt-get -yqq update && apt-get -yqq install nginx

RUN mkdir -p /var/www/html/website
ADD nginx/global.conf /etc/nginx/conf.d/
ADD nginx/nginx.conf /etc/nginx/

EXPOSE 80

global.conf:

server {
        listen          0.0.0.0:80;
        server_name     _;

        root            /var/www/html/website;
        index           index.html index.htm;

        access_log      /var/log/nginx/default_access.log;
        error_log       /var/log/nginx/default_error.log;
}

nginx.conf:

user www-data;
worker_processes 4;
pid /run/nginx.pid;
daemon off;

events {  }

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 65;
  types_hash_max_size 2048;
  include /etc/nginx/mime.types;
  default_type application/octet-stream;
  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log;
  gzip on;
  gzip_disable "msie6";
  include /etc/nginx/conf.d/*.conf;
}

I have used above command to run new container:

sudo docker run -d -p 80 --name website -v $PWD/website:/var/www/html/website:rw user007/website nginx

Body:
It cause by SELinux.

Using Volumes with Docker can Cause Problems with SELinux.

See this link for the full story.

When using SELinux for controlling processes within a container, you need to make sure any content that gets volume mounted into the container is readable, and potentially writable, depending on the use case.

You can temporarily issue by running:

su -c "setenforce 0"

This got easier recently since Docker finally merged a patch in docker >1.7

This patch adds support for "z" and "Z" as options on the volume mounts (-v).

For example:

docker run -d -p 80 --name website -v $PWD/website:/var/www/html/website:z user007/website nginx

Will automatically do the

chcon -Rt svirt_sandbox_file_t /var/db


问:
In Perl, how can I find the index of a given value in an array?
```<code>$VAR1 = [
          '830974',
          '722065',
          '722046',
          '716963'
        ];
</code>```

How can I calculate the array index for the value "722065"?

答:
```<code>use strict;
use Data::Dumper;

sub invert
{
 my $i=0;
 map { $i++ => $_ } @_;
}

my @a = ('a','b','c','d','e');

print Dumper @a;

print Dumper invert @a;
</code>```

Body:
$VAR1 = [
          '830974',
          '722065',
          '722046',
          '716963'
        ];

How can I calculate the array index for the value "722065"?


问:
Why is hovering over a static Win32 control increasing memory and removing my GUI?
Windows API resources can cause memory leaks if not taken care of properly. Whether that's the case or not in this issue, I'm assuming it's related. Although I show how I pinned down to where the issue is coming from, I haven't been able to solve it.

I have two types of static class controls using the Win32 API, which is abstracted in my classes:

```<code>Label
LinkLabel
</code>```

The issue: Whenever I add these two controls, Visual Studio 2017's Diagnostic Tools shows Process Memory (MB) increasing from 3MB to 11MB when I have either both setFont() or setHoverColor() lines enabled, and eventually everything in my GUI space disappears -- gone from existence, like some well-known bookstores.

This code is fine (3MB stays the same constant rate in Process Memory):

```<code> // Linked Label
 myLinkLabel.init("http://www.google.com", 50, 450);
 myLinkLabel.setColor(0, 0, 255);
 myLinkLabel.onClick(lbl_Click);
 myLinkLabel.setFont("Arial", 40, true);
 //lbl.setHoverColor(255, 0, 0);

 // label
 myLabel.init("A regular static label", 0, 0);
 myLabel.setColor(0, 255, 0);
 myLabel.setFont("Arial", 40);
 //myLabel.setHoverColor(255, 0, 0);
</code>```

This next code uncomments the last line. After hovering over myLabel, and the red highlight color appears, Process Memory's 3MB increases to 7MB+. It sits for a bit, then goes up to 9MB+. So, something is wrong in it.

```<code>// Linked Label
myLinkLabel.init("http://www.google.com", 50, 450);
myLinkLabel.setColor(0, 0, 255);
myLinkLabel.onClick(lbl_Click);
myLinkLabel.setFont("Arial", 40, true);
//lbl.setHoverColor(255, 0, 0);

// label
myLabel.init("A regular static label", 0, 0);
myLabel.setColor(0, 255, 0);
myLabel.setFont("Arial", 48);
myLabel.setHoverColor(255, 0, 0);
</code>```

So, let's dig into my setHoverColor():

```<code>void Label::setHoverColor(const BYTE red, const BYTE blue, const BYTE green)
{
 m_hoverColorEnabled = true;
 m_hoverColor = RGB(red, green, blue);
}
</code>```

Okay, nothing too amazing in the code above. This tells me to look in WndProc.

The events this static control uses is WM_SETCURSOR.

```<code> case WM_SETCURSOR:
 {
 HWND m_handle = (HWND)wParam;
 // Label
 for (int i = 0; i < frm.getLabelControlCount(); i++)
 {
     if (frm.getLabelControl(i).getHandle() == m_handle)
     {
          if (frm.getLinkLabelControl(i).isLink())
          {
               // Set hover color to link
              if (frm.getLabelControl(i).isHoverColorEnabled())
                       frm.getLabelControl(i).setColor(frm.getLabelControl(i).getHoverColor());
                       // Update cursor to hand
                       SetClassLongPtr(frm.getLabelControl(i).getHandle(),   GCLP_HCURSOR, (LONG_PTR)frm.getLabelControl(i).getHoverCursor());
          }
      }
      else
      {
          // Set link to blue and use default arrow
          if (frm.getLabelControl(i).isHoverColorEnabled())
             frm.getLabelControl(i).setColor(0, 0, 255);
          SetClassLongPtr(frm.getLabelControl(i).getHandle(), GCLP_HCURSOR,
         (LONG_PTR)LoadCursor(NULL, IDC_ARROW));
      }
}
</code>```

When commenting this section of code, Process Memory stays constant at 3MB. When uncommenting this section, Process Memory increases. So, this is the main code that's causing the problem apparently.

This section of code is basically updating the label's text color based on its current mouse hovering state. It's blue when not hovered over, and it's red when hovered over.

setColor() is the following code:

```<code>void Label::setColor(const COLORREF color)
{
 m_foreColor = color;
 setFont(m_fontName, m_fontSize, m_bold, m_italic, m_underlined);
}
</code>```

Which is also calling setFont() to update it:

```<code>bool Label::setFont(const std::string &fontName, const int size, const bool bold,
 const bool italic, const bool underlined)
{
 DWORD dwItalic;
 DWORD dwBold;
 DWORD dwUnderlined;
 SIZE linkSize;
 dwItalic = (italic) ? TRUE : FALSE;
 dwBold = (bold) ? FW_BOLD : FW_DONTCARE;
 dwUnderlined = (underlined) ? TRUE : FALSE;
 m_font = CreateFont(size, 0, 0, 0, dwBold, dwItalic, dwUnderlined, FALSE,
  ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
  DEFAULT_PITCH | FF_SWISS, fontName.c_str());
 SendMessage(m_handle, WM_SETFONT, WPARAM(m_font), TRUE);

 // Calculate the correct width and height size
 HDC hDC = GetDC(m_handle);
 SelectFont(hDC, m_font);
 GetTextExtentPoint32(hDC, m_text.c_str(), (int) m_text.length(), &linkSize);
 setSize(linkSize.cx, size);

 // Store font information
 m_fontName = fontName;
 m_fontSize = size;
 m_bold = bold;
 m_underlined = underlined;
 m_italic = italic;

 return true;
}
</code>```

My guess is this is a lot of updating for creating a font and re-creating it based on every hover. My reasoning was it wouldn't update the font color unless setting the font again. Although I see room for this in the near future, am I forgetting to delete a resource or something here? Any thoughts are welcomed. Pretty sure this will solve LinkLabel as well.

答:
Your basic problem is that you keep generating new fonts and never releasing the old ones.

Each time setfont is called you allocate and select a new font. But when you select the NEW font into the HDC you never clean up the old font.

SelectFont returns the previously selected font which you need (unless it is a stock font) to do a DeleteFont on.

Additionally you have a bigger resource leak on the GetDC call - the MS documentation for getDC suggests that you use a releaseDC when you have completed the usage.

As far as I understand it is NOT required to reset the font just to reset the color.

Body:
Windows API resources can cause memory leaks if not taken care of properly. Whether that's the case or not in this issue, I'm assuming it's related. Although I show how I pinned down to where the issue is coming from, I haven't been able to solve it.

I have two types of static class controls using the Win32 API, which is abstracted in my classes:

Label
LinkLabel

The issue: Whenever I add these two controls, Visual Studio 2017's Diagnostic Tools shows Process Memory (MB) increasing from 3MB to 11MB when I have either both setFont() or setHoverColor() lines enabled, and eventually everything in my GUI space disappears -- gone from existence, like some well-known bookstores.

This code is fine (3MB stays the same constant rate in Process Memory):

 // Linked Label
 myLinkLabel.init("http://www.google.com", 50, 450);
 myLinkLabel.setColor(0, 0, 255);
 myLinkLabel.onClick(lbl_Click);
 myLinkLabel.setFont("Arial", 40, true);
 //lbl.setHoverColor(255, 0, 0);

 // label
 myLabel.init("A regular static label", 0, 0);
 myLabel.setColor(0, 255, 0);
 myLabel.setFont("Arial", 40);
 //myLabel.setHoverColor(255, 0, 0);

This next code uncomments the last line. After hovering over myLabel, and the red highlight color appears, Process Memory's 3MB increases to 7MB+. It sits for a bit, then goes up to 9MB+. So, something is wrong in it.

// Linked Label
myLinkLabel.init("http://www.google.com", 50, 450);
myLinkLabel.setColor(0, 0, 255);
myLinkLabel.onClick(lbl_Click);
myLinkLabel.setFont("Arial", 40, true);
//lbl.setHoverColor(255, 0, 0);

// label
myLabel.init("A regular static label", 0, 0);
myLabel.setColor(0, 255, 0);
myLabel.setFont("Arial", 48);
myLabel.setHoverColor(255, 0, 0);

So, let's dig into my setHoverColor():

void Label::setHoverColor(const BYTE red, const BYTE blue, const BYTE green)
{
 m_hoverColorEnabled = true;
 m_hoverColor = RGB(red, green, blue);
}

Okay, nothing too amazing in the code above. This tells me to look in WndProc.

The events this static control uses is WM_SETCURSOR.

 case WM_SETCURSOR:
 {
 HWND m_handle = (HWND)wParam;
 // Label
 for (int i = 0; i < frm.getLabelControlCount(); i++)
 {
     if (frm.getLabelControl(i).getHandle() == m_handle)
     {
          if (frm.getLinkLabelControl(i).isLink())
          {
               // Set hover color to link
              if (frm.getLabelControl(i).isHoverColorEnabled())
                       frm.getLabelControl(i).setColor(frm.getLabelControl(i).getHoverColor());
                       // Update cursor to hand
                       SetClassLongPtr(frm.getLabelControl(i).getHandle(),   GCLP_HCURSOR, (LONG_PTR)frm.getLabelControl(i).getHoverCursor());
          }
      }
      else
      {
          // Set link to blue and use default arrow
          if (frm.getLabelControl(i).isHoverColorEnabled())
             frm.getLabelControl(i).setColor(0, 0, 255);
          SetClassLongPtr(frm.getLabelControl(i).getHandle(), GCLP_HCURSOR,
         (LONG_PTR)LoadCursor(NULL, IDC_ARROW));
      }
}

When commenting this section of code, Process Memory stays constant at 3MB. When uncommenting this section, Process Memory increases. So, this is the main code that's causing the problem apparently.

This section of code is basically updating the label's text color based on its current mouse hovering state. It's blue when not hovered over, and it's red when hovered over.

setColor() is the following code:

void Label::setColor(const COLORREF color)
{
 m_foreColor = color;
 setFont(m_fontName, m_fontSize, m_bold, m_italic, m_underlined);
}

Which is also calling setFont() to update it:

bool Label::setFont(const std::string &fontName, const int size, const bool bold,
 const bool italic, const bool underlined)
{
 DWORD dwItalic;
 DWORD dwBold;
 DWORD dwUnderlined;
 SIZE linkSize;
 dwItalic = (italic) ? TRUE : FALSE;
 dwBold = (bold) ? FW_BOLD : FW_DONTCARE;
 dwUnderlined = (underlined) ? TRUE : FALSE;
 m_font = CreateFont(size, 0, 0, 0, dwBold, dwItalic, dwUnderlined, FALSE,
  ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
  DEFAULT_PITCH | FF_SWISS, fontName.c_str());
 SendMessage(m_handle, WM_SETFONT, WPARAM(m_font), TRUE);

 // Calculate the correct width and height size
 HDC hDC = GetDC(m_handle);
 SelectFont(hDC, m_font);
 GetTextExtentPoint32(hDC, m_text.c_str(), (int) m_text.length(), &linkSize);
 setSize(linkSize.cx, size);

 // Store font information
 m_fontName = fontName;
 m_fontSize = size;
 m_bold = bold;
 m_underlined = underlined;
 m_italic = italic;

 return true;
}

My guess is this is a lot of updating for creating a font and re-creating it based on every hover. My reasoning was it wouldn't update the font color unless setting the font again. Although I see room for this in the near future, am I forgetting to delete a resource or something here? Any thoughts are welcomed. Pretty sure this will solve LinkLabel as well.


问:
Not able to do proper path monitoring or querying with Firebase and ElasticSearch (with Flashlight)
I'm trying to integrate ElasticSearch wit Firebase. I'm using the Flashlight integration from Firebase to set ut all up. I have deployed the code to Heroku as described in the Github repo linked above.

It works in the sense that when I insert a query objet to /search/request/ I get a /search/response result. But the results are a bit messy, not correct. But I can't figure out what is wrong.

This is what is defined in config.js where I define the paths to monitor:

```<code>/** Paths to Monitor
 *
 * Each path can have these keys:
 * {string}   path:    [required] the Firebase path to be monitored, for example, `users/profiles`
 *                     would monitor https://<instance>.firebaseio.com/users/profiles
 * {string}   index:   [required] the name of the ES index to write data into
 * {string}   type:    [required] name of the ES object type this document will be stored as
 * {Array}    fields:  list of fields to be monitored and indexed (defaults to all fields, ignored if "parser" is specified)
 * {Array}    omit:    list of fields that should not be indexed in ES (ignored if "parser" is specified)
 * {Function} filter:  if provided, only records that return true are indexed
 * {Function} parser:  if provided, the results of this function are passed to ES, rather than the raw data (fields is ignored if this is used)
 *
 * To store your paths dynamically, rather than specifying them all here, you can store them in Firebase.
 * Format each path object with the same keys described above, and store the array of paths at whatever
 * location you specified in the FB_PATHS variable. Be sure to restrict that data in your Security Rules.
 ****************************************************/

exports.paths = [{
    path: "users",
    index: "firebase",
    type: "user"
}, {
    path: "messages",
    index: "firebase",
    type: "message",
    fields: ['msg', 'name'],
    filter: function(data) {
        return data.name !== 'system';
    }
}];
</code>```

This is the structure of the user node in Firebase (it's located at the root).

```<code>"users" : {
    "userid123" : {
      "friends" : {
        "userid42" : 1
      },
      "recs" : {
        "-recid1234" : 0
      },
      "user_info" : {
        "createdAt" : 1475157596,
        "email" : "e@male.org",
        "name" : "Firstname Lastname Johnson",
        "profilePicture" : "png.jpg",
        "pushId" : {
        },
        "username" : "userLooser"
      }
    },
    "userid42" : {
      "friends" : {
        "userid123" : 1,
        "test1" : 1
      },
      "recs" : {
        "-recid5678" : 0
      },
      "user_info" : {
        "email" : "email@icloud.com",
        "name" : "Firstname Lastname",
        "phoneNumber" : "",
        "profilePicture" : "jpg.png",
        "pushId" : {

        },
        "username" : "userName"
      }
    }
  }
}
</code>```

What I want to achieve is to search for username, and return the top results. All i really need in return is the username and user id's.

But I get the response below, when I query with the object in the image above:

```<code>  "search" : {
    "response" : {
      "index" : {
        ".priority" : 1.477326417519E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid123",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "email" : "",
              "name" : "Firstname Lastname",
              "phoneNumber" : "",
              "profilePicture" : "",
              "pushId" : {
              },
              "username" : "profileName"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "createdAt" : 1475157596,
              "email" : "e@male.org",
              "name" : "Firstname Lastname Johnson",
              "profilePicture" : "",
              "pushId" : {
              },
              "username" : "userLooser"
            }
          },
          "_type" : "user"
        } ],
        "max_score" : 1,
        "total" : 3
      },
      "query" : {
        ".priority" : 1.477326417484E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {

            },
            "recs" : {

            },
            "user_info" : {
              "email" : "",
              "name" : "Firstname Lastname",
              "phoneNumber" : "",
              "profilePicture" : "",
              "pushId" : {

              },
              "username" : "profileName"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid123",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "createdAt" : 1475157596,
              "email" : "e@male.org",
              "name" : "Firstname Lastname Johnson",
              "profilePicture" : "",
              "pushId" : {

              },
              "username" : "userLooser"
            }
          },
          "_type" : "user"
        } ],
        "max_score" : 1,
        "total" : 3
      },
      "type" : {
        ".priority" : 1.477326417503E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          // Same content as above
        }, {
          "_id" : "userid123",
          // Same content as above
        } ],
        "max_score" : 1,
        "total" : 3
      }
    }
  }
</code>```

Which:

A) Does not return the correct sorting. The first result didn't match my search query at all, it just looks like it returns all users in random order.

B) The response is really messy. under /response there is three nodes query, type and index all containing lot's of hits.

So, anyone know what's wrong? How can I create a query, or craft the path monitor so the search will work? And maybe get a simpler response?

答:
I tryed everthing and after hours trying I discovered:

In my file .config of the project Flashlight, I set:

```<code>exports.paths = [
  {
    path : "albuns",
    index: "firebase",
    type : "album",
    fields: ['nome']
  }
];
</code>```

Now, you need send call http PUT for Firebase <URL_PROJECT>/search/request/<ID_CREATED_FOR_YOU>.json (use application/json), you can test it using Postman Extension, the body stayed:

```<code>{
  "index": "firebase",
  "type": "album",
  "q": "John*"
}
</code>```

Body:
I'm trying to integrate ElasticSearch wit Firebase. I'm using the Flashlight integration from Firebase to set ut all up. I have deployed the code to Heroku as described in the Github repo linked above.

It works in the sense that when I insert a query objet to /search/request/ I get a /search/response result. But the results are a bit messy, not correct. But I can't figure out what is wrong.

This is what is defined in config.js where I define the paths to monitor:

/** Paths to Monitor
 *
 * Each path can have these keys:
 * {string}   path:    [required] the Firebase path to be monitored, for example, `users/profiles`
 *                     would monitor https://<instance>.firebaseio.com/users/profiles
 * {string}   index:   [required] the name of the ES index to write data into
 * {string}   type:    [required] name of the ES object type this document will be stored as
 * {Array}    fields:  list of fields to be monitored and indexed (defaults to all fields, ignored if "parser" is specified)
 * {Array}    omit:    list of fields that should not be indexed in ES (ignored if "parser" is specified)
 * {Function} filter:  if provided, only records that return true are indexed
 * {Function} parser:  if provided, the results of this function are passed to ES, rather than the raw data (fields is ignored if this is used)
 *
 * To store your paths dynamically, rather than specifying them all here, you can store them in Firebase.
 * Format each path object with the same keys described above, and store the array of paths at whatever
 * location you specified in the FB_PATHS variable. Be sure to restrict that data in your Security Rules.
 ****************************************************/

exports.paths = [{
    path: "users",
    index: "firebase",
    type: "user"
}, {
    path: "messages",
    index: "firebase",
    type: "message",
    fields: ['msg', 'name'],
    filter: function(data) {
        return data.name !== 'system';
    }
}];

This is the structure of the user node in Firebase (it's located at the root).

"users" : {
    "userid123" : {
      "friends" : {
        "userid42" : 1
      },
      "recs" : {
        "-recid1234" : 0
      },
      "user_info" : {
        "createdAt" : 1475157596,
        "email" : "e@male.org",
        "name" : "Firstname Lastname Johnson",
        "profilePicture" : "png.jpg",
        "pushId" : {
        },
        "username" : "userLooser"
      }
    },
    "userid42" : {
      "friends" : {
        "userid123" : 1,
        "test1" : 1
      },
      "recs" : {
        "-recid5678" : 0
      },
      "user_info" : {
        "email" : "email@icloud.com",
        "name" : "Firstname Lastname",
        "phoneNumber" : "",
        "profilePicture" : "jpg.png",
        "pushId" : {

        },
        "username" : "userName"
      }
    }
  }
}

What I want to achieve is to search for username, and return the top results. All i really need in return is the username and user id's.

But I get the response below, when I query with the object in the image above:

  "search" : {
    "response" : {
      "index" : {
        ".priority" : 1.477326417519E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid123",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "email" : "",
              "name" : "Firstname Lastname",
              "phoneNumber" : "",
              "profilePicture" : "",
              "pushId" : {
              },
              "username" : "profileName"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "createdAt" : 1475157596,
              "email" : "e@male.org",
              "name" : "Firstname Lastname Johnson",
              "profilePicture" : "",
              "pushId" : {
              },
              "username" : "userLooser"
            }
          },
          "_type" : "user"
        } ],
        "max_score" : 1,
        "total" : 3
      },
      "query" : {
        ".priority" : 1.477326417484E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {

            },
            "recs" : {

            },
            "user_info" : {
              "email" : "",
              "name" : "Firstname Lastname",
              "phoneNumber" : "",
              "profilePicture" : "",
              "pushId" : {

              },
              "username" : "profileName"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid123",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
            },
            "recs" : {

            },
            "user_info" : {
              "createdAt" : 1475157596,
              "email" : "e@male.org",
              "name" : "Firstname Lastname Johnson",
              "profilePicture" : "",
              "pushId" : {

              },
              "username" : "userLooser"
            }
          },
          "_type" : "user"
        } ],
        "max_score" : 1,
        "total" : 3
      },
      "type" : {
        ".priority" : 1.477326417503E12,
        "hits" : [ {
          "_id" : "test1",
          "_index" : "firebase",
          "_score" : 1,
          "_source" : {
            "friends" : {
              "test1" : 1
            },
            "recs" : {
            },
            "user_info" : {
              "createdAt" : 1475157596,
              "name" : "Testbruker 1",
              "username" : "testuzer"
            }
          },
          "_type" : "user"
        }, {
          "_id" : "userid42",
          // Same content as above
        }, {
          "_id" : "userid123",
          // Same content as above
        } ],
        "max_score" : 1,
        "total" : 3
      }
    }
  }

Which:

A) Does not return the correct sorting. The first result didn't match my search query at all, it just looks like it returns all users in random order.

B) The response is really messy. under /response there is three nodes query, type and index all containing lot's of hits.

So, anyone know what's wrong? How can I create a query, or craft the path monitor so the search will work? And maybe get a simpler response?

Body:
I tryed everthing and after hours trying I discovered:

In my file .config of the project Flashlight, I set:

exports.paths = [
  {
    path : "albuns",
    index: "firebase",
    type : "album",
    fields: ['nome']
  }
];

Now, you need send call http PUT for Firebase <URL_PROJECT>/search/request/<ID_CREATED_FOR_YOU>.json (use application/json), you can test it using Postman Extension, the body stayed:

{
  "index": "firebase",
  "type": "album",
  "q": "John*"
}


问:
fetching parameter in a link php codeigniter
Say I have this url

```<code>http://localhost/newtkt/index.php/welcome/gettkt/PfIfiETYXzUpYRJf6RPvyncN4PgdN3
</code>```

and a controller function

```<code>public function gettkt()
{
  //mydata
}
</code>```

how can i retrieve the parameter PfIfiETYXzUpYRJf6RPvyncN4PgdN3 that comes with the url and make it a variable in my controller function gettkt() so that i can use the parameter within the function like gettkt(thisparameter). I hope I've structured my question in the best way possible. thank you.

答:
You can use

```<code>$this->uri->segment('3'); //where 3 is for 3rd param
</code>```

for more information visit URI

Body:
Say I have this url

http://localhost/newtkt/index.php/welcome/gettkt/PfIfiETYXzUpYRJf6RPvyncN4PgdN3

and a controller function

public function gettkt()
{
  //mydata
}

how can i retrieve the parameter PfIfiETYXzUpYRJf6RPvyncN4PgdN3 that comes with the url and make it a variable in my controller function gettkt() so that i can use the parameter within the function like gettkt(thisparameter). I hope I've structured my question in the best way possible. thank you.

Body:
You can use

$this->uri->segment('3'); //where 3 is for 3rd param

for more information visit URI


问:
How do I compare the value of string array?
I have declared a string array and I want to compare with name given by user,

```<code>string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}
</code>```

The resulting output is not what I am expecting, any ideas how I can go about it?

答:
Why not use the Contains method?

Add the following line to your using directives first:

```<code>using System.Linq;
</code>```

And then, remove the for loop and use the following line instead:

```<code>if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Your name is not among the list")
}
</code>```

Body:
I have declared a string array and I want to compare with name given by user,

string[] MasterList = new string[] {
  "Askay", "Puram", "Raman", "Srinivasa",
  "Gopal", "Rajesh", "Anju", "Nagara",
};

string YourName;
Console.WriteLine("Enter your name: ");
YourName = Console.ReadLine();

for(i=0; i<5; i++)
{
    a = String.Compare(MasterList[i], YourName);
    Console.WriteLine("Your name is not among the list")
}

The resulting output is not what I am expecting, any ideas how I can go about it?

Body:
Why not use the Contains method?

Add the following line to your using directives first:

using System.Linq;

And then, remove the for loop and use the following line instead:

if (!MasterList.Contains(YourName, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Your name is not among the list")
}


问:
onlogin event not being triggered
I have this page (most of it is from the facebook documentation, with minor changes). Since I'm a n00b with this, I'm posting the whole code:

```<code><html>
<head>
    <title>Reportes para Anunciantes</title>
    <meta charset="UTF-8">
</head>
<body>
    <script type="text/javascript">
        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);
            if (response.status === 'connected') {
                // Logged into your app and Facebook.
                testAPI();
            } else if (response.status === 'not_authorized') {
                // The person is logged into Facebook, but not your app.
                document.getElementById('status').innerHTML = 'Please log into this app.';
            } else {
                // The person is not logged into Facebook, so we're not sure if
                // they are logged into this app or not.
                document.getElementById('status').innerHTML = 'Please log into Facebook.';
            }
        }

        // This function is called when someone finishes with the Login
        // Button.  See the onlogin handler attached to it in the sample
        // code below.
        function checkLoginState() {
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        }

        window.fbAsyncInit = function() {
            FB.init({
                appId      : '284483341757738',
                cookie     : true,  // enable cookies to allow the server to access
                // the session
                xfbml      : true,  // parse social plugins on this page
                version    : 'v2.0' // use version 2.0
            });

            checkLoginState();

            FB.Event.subscribe('auth.authResponseChange', function(response) {
                statusChangeCallback(response);
            });
        };

        // Load the SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        // Here we run a very simple test of the Graph API after login is
        // successful.  See statusChangeCallback() for when this call is made.
        function testAPI() {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);
                document.getElementById('status').innerHTML =
                    'Thanks for logging in, ' + response.name + '!';
            });
        }
    </script>
    <fb:login-button scope="public_profile,email,ads_management" onlogin="checkLoginState();"></fb:login-button>
    <div id="status">
    </div>
</body>
</html>
</code>```

It's time to analyze by parts.

A function which checks the facebook state and updates a div depending on if the user is not logged in @ facebook, if is logged in but the app not authorized, or finally if is logged in and authorized the app. The change is reflected in the dom. Such function is statusChangeCallback. Such callback is only called inside checkLoginState so each time the login state is checked, the callback is called.

A test api call, with a callback which updates the DOM with the results. The function is called testAPI.

The asynchronous load bunch. Once it is loaded, an initial call to checkLoginState is successfully performed.

A login button, with an onlogin event. The event calls, again, checkLoginState. This is to reflect the new login state in the dom.

My issue: onlogin event is not being triggered. Everything else works fine. If I update the page after logging in (facebook displays a login pop-up), I see the expected state (logged in), as a product of calling testAPI, but that's not reflected until I refresh the page. There's another way how I note this: after logging in, I should see a console message coming from statusChangeCallback, but such message neither appears, so I conclude such event is never triggered.

Additional notes: I'm testing my application in localhost (http://localhost). I enabled the localhost domain in my app (at developers.facebook.com), and enabled a "website" platform with base url of http://localhost (I'm not using this app in a canvas). The entry point of my site where I test everything is / (an index.html page). However, these messages appear in console:

```<code>Uncaught SecurityError: Blocked a frame with origin "http://static.ak.facebook.com" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match. VM3437:1
Uncaught SecurityError: Blocked a frame with origin "https://s-static.ak.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.
 VM3461:1
Uncaught SecurityError: Blocked a frame with origin "https://www.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.
 VM3571:1
Uncaught SecurityError: Blocked a frame with origin "http://static.ak.facebook.com" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match.
 VM3627:1
statusChangeCallback
 (index):9
Object {authResponse: undefined, status: "unknown"}
 (index):10
Uncaught SecurityError: Blocked a frame with origin "https://www.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.
</code>```

So my questions are:

Why does the onlogin event not trigger after I log in?

Are these errors in console related? I'm using Apache. How can I solve them?

Is there a way -after a Graph API query (i.e. a GET call)- to know whether the user has logged out?

答:
You need to subscribe facebook's event handler. Add below code

```<code>FB.Event.subscribe('auth.login', function(){
// This alert box will appears if user successfully logined
// Do anything here....
alert("Successful Login");
});
</code>```

so the updated code will be

```<code>  <html>
 <head>
  <title>Reportes para Anunciantes</title>
  <meta charset="UTF-8">
 </head>
  <body>
 <script type="text/javascript">
    function statusChangeCallback(response) {
        console.log('statusChangeCallback');
        console.log(response);
        if (response.status === 'connected') {
            // Logged into your app and Facebook.
            testAPI();
        } else if (response.status === 'not_authorized') {
            // The person is logged into Facebook, but not your app.
            document.getElementById('status').innerHTML = 'Please log into this app.';
        } else {
            // The person is not logged into Facebook, so we're not sure if
            // they are logged into this app or not.
            document.getElementById('status').innerHTML = 'Please log into Facebook.';
        }
    }

    // This function is called when someone finishes with the Login
    // Button.  See the onlogin handler attached to it in the sample
    // code below.
    function checkLoginState() {
        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });
    }

    window.fbAsyncInit = function() {
        FB.init({
            appId      : '284483341757738',
            cookie     : true,  // enable cookies to allow the server to access
            // the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v2.0' // use version 2.0
        });

        checkLoginState();

        FB.Event.subscribe('auth.authResponseChange', function(response) {
            statusChangeCallback(response);
        });

         FB.Event.subscribe('auth.login', function(){
       // This alert box will appears if user successfully logined
       // Do anything here....
       alert("Successful Login");
        });
    };

    // Load the SDK asynchronously
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    // Here we run a very simple test of the Graph API after login is
    // successful.  See statusChangeCallback() for when this call is made.
    function testAPI() {
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me', function(response) {
            console.log('Successful login for: ' + response.name);
            document.getElementById('status').innerHTML =
                'Thanks for logging in, ' + response.name + '!';
        });
    }
</script>
<fb:login-button scope="public_profile,email,ads_management" onlogin="checkLoginState();"></fb:login-button>
<div id="status">
</div>
 </body>
</html>
</code>```

Title: onlogin event not being triggered

Body:
I have this page (most of it is from the facebook documentation, with minor changes). Since I'm a n00b with this, I'm posting the whole code:

    <title>Reportes para Anunciantes</title>
    <meta charset="UTF-8">

    <fb:login-button scope="public_profile,email,ads_management" onlogin="checkLoginState();"></fb:login-button>

It's time to analyze by parts.

A function which checks the facebook state and updates a div depending on if the user is not logged in @ facebook, if is logged in but the app not authorized, or finally if is logged in and authorized the app. The change is reflected in the dom. Such function is statusChangeCallback. Such callback is only called inside checkLoginState so each time the login state is checked, the callback is called.

A test api call, with a callback which updates the DOM with the results. The function is called testAPI.

The asynchronous load bunch. Once it is loaded, an initial call to checkLoginState is successfully performed.

A login button, with an onlogin event. The event calls, again, checkLoginState. This is to reflect the new login state in the dom.

My issue: onlogin event is not being triggered. Everything else works fine. If I update the page after logging in (facebook displays a login pop-up), I see the expected state (logged in), as a product of calling testAPI, but that's not reflected until I refresh the page. There's another way how I note this: after logging in, I should see a console message coming from statusChangeCallback, but such message neither appears, so I conclude such event is never triggered.

Additional notes: I'm testing my application in localhost (http://localhost). I enabled the localhost domain in my app (at developers.facebook.com), and enabled a "website" platform with base url of http://localhost (I'm not using this app in a canvas). The entry point of my site where I test everything is / (an index.html page). However, these messages appear in console:

Uncaught SecurityError: Blocked a frame with origin "http://static.ak.facebook.com" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match. VM3437:1
Uncaught SecurityError: Blocked a frame with origin "https://s-static.ak.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.
 VM3461:1
Uncaught SecurityError: Blocked a frame with origin "https://www.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.
 VM3571:1
Uncaught SecurityError: Blocked a frame with origin "http://static.ak.facebook.com" from accessing a frame with origin "http://localhost". Protocols, domains, and ports must match.
 VM3627:1
statusChangeCallback
 (index):9
Object {authResponse: undefined, status: "unknown"}
 (index):10
Uncaught SecurityError: Blocked a frame with origin "https://www.facebook.com" from accessing a frame with origin "http://localhost".  The frame requesting access has a protocol of "https", the frame being accessed has a protocol of "http". Protocols must match.

So my questions are:

Why does the onlogin event not trigger after I log in?

Are these errors in console related? I'm using Apache. How can I solve them?

Is there a way -after a Graph API query (i.e. a GET call)- to know whether the user has logged out?

Body:
You need to subscribe facebook's event handler. Add below code

FB.Event.subscribe('auth.login', function(){
// This alert box will appears if user successfully logined
// Do anything here....
alert("Successful Login");
});

so the updated code will be

  <html>
 <head>
  <title>Reportes para Anunciantes</title>
  <meta charset="UTF-8">
 </head>
  <body>
 <script type="text/javascript">
    function statusChangeCallback(response) {
        console.log('statusChangeCallback');
        console.log(response);
        if (response.status === 'connected') {
            // Logged into your app and Facebook.
            testAPI();
        } else if (response.status === 'not_authorized') {
            // The person is logged into Facebook, but not your app.
            document.getElementById('status').innerHTML = 'Please log into this app.';
        } else {
            // The person is not logged into Facebook, so we're not sure if
            // they are logged into this app or not.
            document.getElementById('status').innerHTML = 'Please log into Facebook.';
        }
    }

    // This function is called when someone finishes with the Login
    // Button.  See the onlogin handler attached to it in the sample
    // code below.
    function checkLoginState() {
        FB.getLoginStatus(function(response) {
            statusChangeCallback(response);
        });
    }

    window.fbAsyncInit = function() {
        FB.init({
            appId      : '284483341757738',
            cookie     : true,  // enable cookies to allow the server to access
            // the session
            xfbml      : true,  // parse social plugins on this page
            version    : 'v2.0' // use version 2.0
        });

        checkLoginState();

        FB.Event.subscribe('auth.authResponseChange', function(response) {
            statusChangeCallback(response);
        });

         FB.Event.subscribe('auth.login', function(){
       // This alert box will appears if user successfully logined
       // Do anything here....
       alert("Successful Login");
        });
    };

    // Load the SDK asynchronously
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    // Here we run a very simple test of the Graph API after login is
    // successful.  See statusChangeCallback() for when this call is made.
    function testAPI() {
        console.log('Welcome!  Fetching your information.... ');
        FB.api('/me', function(response) {
            console.log('Successful login for: ' + response.name);
            document.getElementById('status').innerHTML =
                'Thanks for logging in, ' + response.name + '!';
        });
    }
</script>
<fb:login-button scope="public_profile,email,ads_management" onlogin="checkLoginState();"></fb:login-button>
<div id="status">
</div>
 </body>
</html>


问:
How to use loop to create multiple columns
I am struggling with creating multiple columns in a DRY way.

I have searched google and stack exchange and I am still struggling with the below.

```<code>df <- data.frame(red = 1:10, blue=seq(1,30,3))

myfunction <- function(x){
  log(x) + 10
}

df$green <- myfunction(df$red)
df$yellow <- myfunction(df$blue)
</code>```

My questions are:

how can I create the green and yellow columns using a for loop?

how can I create the green and yellow using an apply function?

答:
I've spent a bit of time working on these kinds of things. Most of the time you're going to want to either know all the names of the new variables or have them work in an orderly pattern so you can just paste together the names with an indexing variable.</p>

```<code>df <- data.frame(red = 1:10, blue=seq(1,30,3))

myfunction <- function(x){
  log(x) + 10
}

newcols = apply(X = df, MARGIN = 2, FUN = myfunction)
colnames(newcols) = c("greeen","yellow")
df = cbind(df,newcols)

# Alternative
df <- data.frame(red = 1:10, blue=seq(1,30,3))
colors = c("green", "yellow")
for(i in 1:length(colors)){
  df[,colors[i]] = myfunction(df[,i])
}
</code>```

Body:
I am struggling with creating multiple columns in a DRY way.

I have searched google and stack exchange and I am still struggling with the below.

df <- data.frame(red = 1:10, blue=seq(1,30,3))

myfunction <- function(x){
  log(x) + 10
}

df$green <- myfunction(df$red)
df$yellow <- myfunction(df$blue)

My questions are:

how can I create the green and yellow columns using a for loop?

how can I create the green and yellow using an apply function?

Body:
I've spent a bit of time working on these kinds of things. Most of the time you're going to want to either know all the names of the new variables or have them work in an orderly pattern so you can just paste together the names with an indexing variable.

df <- data.frame(red = 1:10, blue=seq(1,30,3))

myfunction <- function(x){
  log(x) + 10
}

newcols = apply(X = df, MARGIN = 2, FUN = myfunction)
colnames(newcols) = c("greeen","yellow")
df = cbind(df,newcols)

# Alternative
df <- data.frame(red = 1:10, blue=seq(1,30,3))
colors = c("green", "yellow")
for(i in 1:length(colors)){
  df[,colors[i]] = myfunction(df[,i])
}


问:
How to use generalized projection in a Google docs query?
I wish to use a generalized projection as follows in a Google query with no success
=query('Form Responses 2'!A:N,"Select if(month(F)>6,year(F),year(F)-1) , N,B,C,D,E,F,G,H,I,J,K where F >= date '2011-07-01' and F <= date '2050-06-30' order by F desc, B")

Wishing to list the Year in column F in a required way.

Will be grateful if you can help me correct this.

答:
You need to put the existing columns and your new column into an array

```<code>=arrayformula(query({A:N,if(isdate(F:F),if(month(F:F)>6,year(F:F),year(F:F)-1),F:F) },"Select Col15,Col14,Col2,Col3,Col4,Col5,Col7,Col8,Col9,Col10,Col11 where Col6 >= date '2011-07-01' and Col6 <= date '2050-06-30' order by Col6 desc, Col2",1))
</code>```

I also had to use isdate() because if you have headers in your table the month() and year() functions will give an error.

Body:
You need to put the existing columns and your new column into an array

=arrayformula(query({A:N,if(isdate(F:F),if(month(F:F)>6,year(F:F),year(F:F)-1),F:F) },"Select Col15,Col14,Col2,Col3,Col4,Col5,Col7,Col8,Col9,Col10,Col11 where Col6 >= date '2011-07-01' and Col6 <= date '2050-06-30' order by Col6 desc, Col2",1))

I also had to use isdate() because if you have headers in your table the month() and year() functions will give an error.


问:
Python / Pandas abbreviating my numbers.
Probably a very easy fix, but my english isn't good enough to search for the right answer.

Python/Pandas is changing the numbers that I'm writing from: 6570631401430749 to something like: 6.17063140131e+15

I'm merging hundreds of csv files, and this one column comes out all wrong. The name of the column is "serialnumber" and its the 3rd column.

```<code>import pandas as pd
import glob
import os

interesting_files = glob.glob("*.csv")
df_list = []

for filename in sorted(interesting_files):
    frame = pd.read_csv(filename)
    print(os.path.basename(filename))
    frame['filename'] = os.path.basename(filename)
    df_list.append(frame)
full_df = pd.concat(df_list)
full_df.to_csv('output.csv',encoding='utf-8-sig')
</code>```

答:
You can use dtype = object when you read csv if you want to preserve the data in its original form. You can change your code to

```<code>import pandas as pd
import glob
import os

interesting_files = glob.glob("*.csv")
df_list = []

for filename in sorted(interesting_files):
    frame = pd.read_csv(filename,dtype=object)
    print(os.path.basename(filename))
    frame['filename'] = os.path.basename(filename)
    df_list.append(frame)
full_df = pd.concat(df_list)
full_df.to_csv('output.csv',encoding='utf-8-sig')
</code>```

Body:
Probably a very easy fix, but my english isn't good enough to search for the right answer.

Python/Pandas is changing the numbers that I'm writing from: 6570631401430749 to something like: 6.17063140131e+15

I'm merging hundreds of csv files, and this one column comes out all wrong. The name of the column is "serialnumber" and its the 3rd column.

import pandas as pd
import glob
import os

interesting_files = glob.glob("*.csv")
df_list = []

for filename in sorted(interesting_files):
    frame = pd.read_csv(filename)
    print(os.path.basename(filename))
    frame['filename'] = os.path.basename(filename)
    df_list.append(frame)
full_df = pd.concat(df_list)
full_df.to_csv('output.csv',encoding='utf-8-sig')

Body:
You can use dtype = object when you read csv if you want to preserve the data in its original form. You can change your code to

import pandas as pd
import glob
import os

interesting_files = glob.glob("*.csv")
df_list = []

for filename in sorted(interesting_files):
    frame = pd.read_csv(filename,dtype=object)
    print(os.path.basename(filename))
    frame['filename'] = os.path.basename(filename)
    df_list.append(frame)
full_df = pd.concat(df_list)
full_df.to_csv('output.csv',encoding='utf-8-sig')