问:
Dynamically changing the constraint of a view in ConstraintLayout
I am trying to change the left constraint (guideline) of a view inside my ConstraintLayout on press of a button. My layout XML (relevant parts) looks like this:

```<code><ProgressBar
  android:id="@+id/progress_bar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="0dp"
  android:layout_marginRight="8dp"
  android:layout_marginTop="8dp"
  android:indeterminate="true"
  android:visibility="gone"
  app:layout_constraintBottom_toTopOf="@+id/guideline_bcrumbs_bottom"
  app:layout_constraintHorizontal_bias="0.0"
  app:layout_constraintLeft_toLeftOf="@+id/guideline_group_left"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_group_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.2"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="205dp"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_category_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.45"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="461dp"/>
</code>```

Here, I want to change the progress bar's constraintLeft_toLeftOf property from guideline_group_left to guideline_category_left dynamically. Is there a way to achieve this?

EDIT:

I have added the following lines to adjust the constraint (based on this link: http://www.techotopia.com/index.php/Managing_Constraints_using_ConstraintSet)

```<code>ConstraintSet set = new ConstraintSet();
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);
</code>```

However, after these changes, the progress bar does not show up at all. I feel like I am close, but am probably missing something.

EDIT 2

I realized I forgot to add the following line, which is why it did not work.

```<code>set.clone(mConstraintLayout);
</code>```

答:
SOLUTION:

I managed to solve my issue with the following lines of code, it might help someone else if they face a similar problem.

```<code>ConstraintSet set = new ConstraintSet();
set.clone(mConstraintLayout);
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);
</code>```

Body:
I am trying to change the left constraint (guideline) of a view inside my ConstraintLayout on press of a button. My layout XML (relevant parts) looks like this:

<ProgressBar
  android:id="@+id/progress_bar"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginBottom="8dp"
  android:layout_marginLeft="0dp"
  android:layout_marginRight="8dp"
  android:layout_marginTop="8dp"
  android:indeterminate="true"
  android:visibility="gone"
  app:layout_constraintBottom_toTopOf="@+id/guideline_bcrumbs_bottom"
  app:layout_constraintHorizontal_bias="0.0"
  app:layout_constraintLeft_toLeftOf="@+id/guideline_group_left"
  app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_group_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.2"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="205dp"/>

<android.support.constraint.Guideline
  android:id="@+id/guideline_category_left"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  app:layout_constraintGuide_percent="0.45"
  tools:layout_editor_absoluteY="0dp"
  tools:layout_editor_absoluteX="461dp"/>

Here, I want to change the progress bar's constraintLeft_toLeftOf property from guideline_group_left to guideline_category_left dynamically. Is there a way to achieve this?

EDIT:

I have added the following lines to adjust the constraint (based on this link: http://www.techotopia.com/index.php/Managing_Constraints_using_ConstraintSet)

ConstraintSet set = new ConstraintSet();
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);

However, after these changes, the progress bar does not show up at all. I feel like I am close, but am probably missing something.

EDIT 2

I realized I forgot to add the following line, which is why it did not work.

set.clone(mConstraintLayout);

Body:
SOLUTION:

I managed to solve my issue with the following lines of code, it might help someone else if they face a similar problem.

ConstraintSet set = new ConstraintSet();
set.clone(mConstraintLayout);
set.connect(mProgressBar.getId(), ConstraintSet.LEFT, R.id.guideline_category_left, ConstraintSet.LEFT, 0);
set.connect(mProgressBar.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);


来源: stackexchange

问:
Techniques for having a node module return a "stream" of data?
I hope I'm asking the question correctly, but essentially, is there a way in NodeJS to have a CommonJS module return a stream of data instead of a finalized chunk of data after a (long) computation? Assuming there is more than one way, what are those techniques?

For example, say I have a findPrimes function, written as a CommonJS module:

find-primes.js

```<code>/**
 * @module  findPrimes
 * @param {int} n - Find all primes less than this number
 * @return {array}
 */
module.exports = function(n) {
    if (n < 2) {
        return [];
    } else if (n === 2) {
        return [2];
    }

    var primes = [2];

    for (let i = 3; i < n; i += 2) {
        let is_prime = true;
        let sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t++) {
            if (i % t === 0) {
                is_prime = false;
                break;
            }
        }

        if (is_prime) {
            primes.push(i);
        }
    }

    return primes;
};
</code>```

As you can see, this function returns an array of all the prime numbers less than its input. It returns the array after it has computed all those numbers.

So, say I go to use this module in a node script

index.js

```<code>const primes = require('./find-primes.js');

// Usage: `node index.js <num>`
let primes_less_than = process.argv[2];

console.log(primes(primes_less_than));
</code>```

When I run the above script with an arg of 25, I get the following (expected) output:

```<code>$ node index.js 25
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
</code>```

However, say I passed in a much larger number, like 10,000,000

```<code>$ node index.js 10000000
# Takes a while to run before outputting the numbers...
</code>```

While this works, ideally I'd like the program to start writing out the numbers it has computed before it finishes.

So my program would still take a while to run, but it would start outputting information to the screen much faster than "compute EVERYTHING first, then output ALL results".

What is the best way to achieve this effect? Streams? Promises?

I'm open to any and all techniques for this, thanks.

答:
You'll have to use the Stream class from nodejs, and the method should export a callback with a stream as the commentaries said:</p>

```<code>const stream = require('stream');

function getPrimesStream(n, cb) {
    const primesStream = new stream.Stream();
    cb(null, primesStream);
    if (n >= 2) {
        primesStream.emit('data', 2);
    }

    const primes = [2];

    for (let i = 3; i < n; i += 2) {
        let isPrime = true;
        const sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t += 1) {
            if (i % t === 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            primesStream.emit('data', i);
            primes.push(i);
        }
    }

    return primes;
}

getPrimesStream(1000, function (err, stream) {
    stream.on('data', function (data) {
        console.log(data);
    });
    stream.on('end', function() {
        console.log('finished');
    });
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I hope I'm asking the question correctly, but essentially, is there a way in NodeJS to have a CommonJS module return a stream of data instead of a finalized chunk of data after a (long) computation? Assuming there is more than one way, what are those techniques?

For example, say I have a findPrimes function, written as a CommonJS module:

find-primes.js

/**
 * @module  findPrimes
 * @param {int} n - Find all primes less than this number
 * @return {array}
 */
module.exports = function(n) {
    if (n < 2) {
        return [];
    } else if (n === 2) {
        return [2];
    }

    var primes = [2];

    for (let i = 3; i < n; i += 2) {
        let is_prime = true;
        let sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t++) {
            if (i % t === 0) {
                is_prime = false;
                break;
            }
        }

        if (is_prime) {
            primes.push(i);
        }
    }

    return primes;
};

As you can see, this function returns an array of all the prime numbers less than its input. It returns the array after it has computed all those numbers.

So, say I go to use this module in a node script

index.js

const primes = require('./find-primes.js');

// Usage: `node index.js <num>`
let primes_less_than = process.argv[2];

console.log(primes(primes_less_than));

When I run the above script with an arg of 25, I get the following (expected) output:

$ node index.js 25
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]

However, say I passed in a much larger number, like 10,000,000

$ node index.js 10000000
# Takes a while to run before outputting the numbers...

While this works, ideally I'd like the program to start writing out the numbers it has computed before it finishes.

So my program would still take a while to run, but it would start outputting information to the screen much faster than "compute EVERYTHING first, then output ALL results".

What is the best way to achieve this effect? Streams? Promises?

I'm open to any and all techniques for this, thanks.

Body:
You'll have to use the Stream class from nodejs, and the method should export a callback with a stream as the commentaries said:

const stream = require('stream');

function getPrimesStream(n, cb) {
    const primesStream = new stream.Stream();
    cb(null, primesStream);
    if (n >= 2) {
        primesStream.emit('data', 2);
    }

    const primes = [2];

    for (let i = 3; i < n; i += 2) {
        let isPrime = true;
        const sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t += 1) {
            if (i % t === 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            primesStream.emit('data', i);
            primes.push(i);
        }
    }

    return primes;
}

getPrimesStream(1000, function (err, stream) {
    stream.on('data', function (data) {
        console.log(data);
    });
    stream.on('end', function() {
        console.log('finished');
    });
});


问:
Adding ng-model directive to dynamically created input tag using AngularJs
I am trying that on a button click, a div and and input tag are created and the input tag contain ng-model and the div has binding with that input.
Kindly suggest some solution.</p>

答:
Here is another solution, in which there's no need to create a div and an input explicitly. Loop through an array of elements with ng-repeat. The advantage is that you will have all the values of the inputs in that array.

angular.module('app', [])
.controller('AppController', AppController);

AppController.$inject = ['$scope'];
function AppController($scope) {
  $scope.values = [];
  $scope.add = function() {
    $scope.values.push('');
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppController">
  <button ng-click="add()">Click</button>
  <div ng-repeat="value in values track by $index">
    <input type="text" ng-model="values[$index]"/>
    <div>{{values[$index]}}</div>
  </div>
  ```{{values}}```
</div></code>```

UPDATE. And if you want only one input, it's even simpler, using ng-show.

angular.module('app', []);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <button ng-click="show = true">Click</button>
  <div ng-show="show">
    <input type="text" ng-model="value"/>
    <div>{{value}}</div>
  </div>
</div></code>```

Body:
Here is another solution, in which there's no need to create a div and an input explicitly. Loop through an array of elements with ng-repeat. The advantage is that you will have all the values of the inputs in that array.

angular.module('app', [])
.controller('AppController', AppController);

AppController.$inject = ['$scope'];
function AppController($scope) {
  $scope.values = [];
  $scope.add = function() {
    $scope.values.push('');
  };
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="AppController">
  <button ng-click="add()">Click</button>
  <div ng-repeat="value in values track by $index">
    <input type="text" ng-model="values[$index]"/>
    <div>{{values[$index]}}</div>
  </div>
  <pre>{{values}}</pre>
</div>

UPDATE. And if you want only one input, it's even simpler, using ng-show.

angular.module('app', []);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <button ng-click="show = true">Click</button>
  <div ng-show="show">
    <input type="text" ng-model="value"/>
    <div>{{value}}</div>
  </div>
</div>


问:
Yii2 dektrium user registration with 3 options
I tried to found answer on google but without success. What i want to say with this title is: I have ordinary user, doctor(for example) and hospital(for example). As i know when i register an user the information goes to my profile table.But if i register a doctor i want the information to be saved in my doctor_profile table. Same with the hospital registration. I can make difference between registration types by $flag(1, 2 or 3). So what i want to understand is is it possible to redirect doctor information to doctor_profile.Hospital => hospital_profile.
I hope i explain it well. Tons of thanks and appreciating any advice if that plan is not a good idea :)

答: You can easily log in using different submissions and POSTs (eg using different buttons) that call for different controller / action links that handle the data in POST appropriately. This essentially depends on how you intend to design the application and its registration form (s).</p>


问:
Passing state info into a service worker before `install`
Background

I'm new to service workers but working on a library that is intended to become "offline-first" (really, almost "offline-only") (FWIW, the intent is to allow consumers of the library to provide JSON config representing tabular multilinear texts and get in return an app which allows their users to browse these texts in a highly customizable manner by paragraph/verse ranges.)

Other projects are to install the library as a dependency and then supply information via our JavaScript API such as the path of a JSON config file indicating the files that our app will consume to produce an (offline) app for them.

While I know we could do any of the following:

require users provide a hard-coded path from which our service worker's install script could use waitUntil with its own JSON request to retrieve the user's necessary files

skip the service worker's install step of the service worker for the JSON file, and rely on fetch events to update the cache, providing a fallback display if the user completed the install and went offline before the fetches could occur.

Post some state info from our main script to a server which the service worker, once registered, would query before completing its install event.

...but all choices seems less than ideal because, respectively:

Our library's consumers may prefer to be able to designate their own location for their JSON config.

Given that the JSON config designates files critical to showing their users anything useful, I'd rather not allow an install to complete only to say that the user has to go back online to get the rest of the files if they were not able to remain online after the install event to see all the required fetches occur.

Besides wanting to avoid more trips to the server and extra code, I'd prefer for our code to be so offline-oriented as to be able to work entirely on mere static file servers.

Question:

Is there some way to pass a message or state information into a service worker before the install event occurs, whether as part of the query string of the service worker URL, or through a messaging event? The messaging event could even technically arrive after the install event begins as long as it can occur before a waitUntil within the install is complete.

I know I could test this myself, but I'd like to know what best practices might be anyways when the critical app files must themselves be dynamically obtained as in such libraries as ours.

I'm guessing indexedDB might be the sole alternative here (i.e., saving the config info or path of the JSON config to indexedDB, registering a service worker, and retrieving the indexedDB data from within the install event)? Even this would not be ideal as I'm letting users define a namespace for their storage, but I need a way for it too to be passed into the worker, or otherwise, multiple such apps on the origin could clash.

答:
Using a Query Parameter

If you find it useful, then yes, you can provide state during service worker installation by including a query parameter to your service worker when you register it, like so:

```<code>// Inside your main page:
const pathToJson = '/path/to/file.json';
const swUrl = '/sw.js?pathToJson=' + encodeURIComponent(pathToJson);
navigator.serviceWorker.register(swUrl);

// Inside your sw.js:
self.addEventListener('install', event => {
  const pathToJson = new URL(location).searchParams.get('pathToJson');
  event.waitUntil(
    fetch(pathToJson)
      .then(response => response.json())
      .then(jsonData => /* Do something with jsonData */)
  );
});
</code>```

A few things to note about this approach:

If you fetch() the JSON file in your install handler (as in the code sample), that will effectively happen once per version of your service worker script (sw.js). If the contents of the JSON file change, but everything else stays the same, the service worker won't automatically detect that and repopulate your caches.

Following from the first point, if you work around that by, e.g., including hash-based versioning in your JSON file's URL, each time you change that URL, you'll end up installing a new service worker. This isn't a bad thing, per se, but you need to keep it in mind if you have logic in your web app that listens for service worker lifecycle events.

Alternative Approaches

You also might find it easier to just add files to your caches from within the context of your main page, since browsers that support the Cache Storage API expose it via window.caches. Precaching the files within the install handler of a service worker does have the advantage of ensuring that all the files have been cached successfully before the service worker installs, though.

Another approach is to write the state information to IndexedDB from the window context, and then read from IndexedDB inside of your service worker's install handler.

Body:
Using a Query Parameter

If you find it useful, then yes, you can provide state during service worker installation by including a query parameter to your service worker when you register it, like so:

// Inside your main page:
const pathToJson = '/path/to/file.json';
const swUrl = '/sw.js?pathToJson=' + encodeURIComponent(pathToJson);
navigator.serviceWorker.register(swUrl);

// Inside your sw.js:
self.addEventListener('install', event => {
  const pathToJson = new URL(location).searchParams.get('pathToJson');
  event.waitUntil(
    fetch(pathToJson)
      .then(response => response.json())
      .then(jsonData => /* Do something with jsonData */)
  );
});

A few things to note about this approach:

If you fetch() the JSON file in your install handler (as in the code sample), that will effectively happen once per version of your service worker script (sw.js). If the contents of the JSON file change, but everything else stays the same, the service worker won't automatically detect that and repopulate your caches.

Following from the first point, if you work around that by, e.g., including hash-based versioning in your JSON file's URL, each time you change that URL, you'll end up installing a new service worker. This isn't a bad thing, per se, but you need to keep it in mind if you have logic in your web app that listens for service worker lifecycle events.

Alternative Approaches

You also might find it easier to just add files to your caches from within the context of your main page, since browsers that support the Cache Storage API expose it via window.caches. Precaching the files within the install handler of a service worker does have the advantage of ensuring that all the files have been cached successfully before the service worker installs, though.

Another approach is to write the state information to IndexedDB from the window context, and then read from IndexedDB inside of your service worker's install handler.

ContentLicense: CC BY-SA 4.0


问:
Why use JS for Image Rollovers When I can use CSS?
I am making my way through Lynda.com's JS tutorial, and they have a whole chapter on image rollevers for buttons.  Why would I use JS when I could just use CSS-- to create image rollevers?</p>

答:
Why would I use JS when I could just use CSS-- to create image rollevers?

You shouldn't, it sounds like the tutorial may be simply using it as an example to teach you JS. There is no case where you should prefer JS to CSS when identical results can be achieved with CSS.

ContentLicense: CC BY-SA 2.5


问:
The most efficient way of obtaining multiple averages and counts from rethinkdb
I am creating a web application which collects information from a form, inserts them (e.g. age, height, and weight) into a rethinkdb database, and then displays simple descriptive statistics via socket.io.

Currently, I'm using r.expr() to run multiple queries, e.g.

```<code>r.expr({
mean1: r.db(…).table(…).avg(…),
mean2: r.db(…).table(…).group(…).avg(…).mul(10).round().div(10).ungroup(),
count: r.db(…).table(…).count()
}).run(conn, (err, res) => {
...
</code>```

to construct an object which contains the counts and averages I'm interested in and then use io.emit() to send them to the client for display, which is updated every time a new entry is added.

This doesn't look very efficient to me and I'm guessing there is a better way of doing this—perhaps with just one query—but I'm very inexperienced with ReQL and query languages in general.

Moreover, is there a better way of doing rounding with arbitrary precision or more complex numerical operations after grouping than like I did above?

答:
To perform multiple reductions at once, you can manually split them into individual map and reduce operations. Something like:

```<code>r.table(...).map(
    row => ({
        count: 1,
        sum: row('a'),
        groups: r.object(row('group'), {count: 1, sum: r.row('a')})
    })
).reduce(
    (left, right) => ({
        count: left('count').add(right('count')),
        sum: left('sum').add(right('sum')),
        groups: left.keys().setUnion(right.keys()).map(
                key => [key, {
                    count: left(key)('count').default(0).add(right(key)('count').default(0)),
                    sum: left(key)('sum').default(0).add(right(key)('sum').default(0))
                }]
            ).coerceTo('object')
    })
).do(
    res => ({
        count: res('count'),
        mean1: res('sum').div(res('count')),
        mean2: res('groups').coerceTo('array').map(
            pair => [pair(0), pair(1).do(x => x('sum').div(x('count')).mul(10).round().div(10)]
    }).coerceTo('object')
)
</code>```

It may not be more efficient as-is, but could be optimized further.

You can perform more complex mathematical operations using r.js

Body:
I am creating a web application which collects information from a form, inserts them (e.g. age, height, and weight) into a rethinkdb database, and then displays simple descriptive statistics via socket.io.

Currently, I'm using r.expr() to run multiple queries, e.g.

r.expr({
mean1: r.db(…).table(…).avg(…),
mean2: r.db(…).table(…).group(…).avg(…).mul(10).round().div(10).ungroup(),
count: r.db(…).table(…).count()
}).run(conn, (err, res) => {
...

to construct an object which contains the counts and averages I'm interested in and then use io.emit() to send them to the client for display, which is updated every time a new entry is added.

This doesn't look very efficient to me and I'm guessing there is a better way of doing this—perhaps with just one query—but I'm very inexperienced with ReQL and query languages in general.

Moreover, is there a better way of doing rounding with arbitrary precision or more complex numerical operations after grouping than like I did above?

Body:
To perform multiple reductions at once, you can manually split them into individual map and reduce operations. Something like:

r.table(...).map(
    row => ({
        count: 1,
        sum: row('a'),
        groups: r.object(row('group'), {count: 1, sum: r.row('a')})
    })
).reduce(
    (left, right) => ({
        count: left('count').add(right('count')),
        sum: left('sum').add(right('sum')),
        groups: left.keys().setUnion(right.keys()).map(
                key => [key, {
                    count: left(key)('count').default(0).add(right(key)('count').default(0)),
                    sum: left(key)('sum').default(0).add(right(key)('sum').default(0))
                }]
            ).coerceTo('object')
    })
).do(
    res => ({
        count: res('count'),
        mean1: res('sum').div(res('count')),
        mean2: res('groups').coerceTo('array').map(
            pair => [pair(0), pair(1).do(x => x('sum').div(x('count')).mul(10).round().div(10)]
    }).coerceTo('object')
)

It may not be more efficient as-is, but could be optimized further.

You can perform more complex mathematical operations using r.js


问:
How do I create a GoogleCredential from an authorized access_token?
I have an OAuth2 token like this...

```<code>{{
  "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in": "3600",
  "refresh_token": "xxxxxxxxxxxxxxxxxx",
  "token_type": "Bearer",
}}
</code>```

and I'm trying to create a DriveService object...

```<code>Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "foo",
});
</code>```

(like this?)

but I'm clearly not doing this properly and I'm having trouble finding documentation.

When I attempt to create a GoogleCredential to pass to the DriveService

```<code>GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);
</code>```

I get the following exception:

{System.InvalidOperationException: Error creating credential from JSON. Unrecognized credential type .

Am I going about this the wrong way entirely?

(This is the sample code context)

答:
I have managed to figure this out.

The solution was to create a Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow with my ClientID and ClientSecret...

```<code>Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow googleAuthFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
  ClientSecrets = new ClientSecrets()
  {
    ClientId = ClientID,
    ClientSecret = ClientSecret,
  }
});
</code>```

and also a Google.Apis.Auth.OAuth2.Responses.TokenResponse:

```<code>Google.Apis.Auth.OAuth2.Responses.TokenResponse responseToken = new TokenResponse()
{
  AccessToken = SavedAccount.Properties["access_token"],
  ExpiresInSeconds = Convert.ToInt64(SavedAccount.Properties["expires_in"]),
  RefreshToken = SavedAccount.Properties["refresh_token"],
  Scope = GoogleDriveScope,
  TokenType = SavedAccount.Properties["token_type"],
};
</code>```

and use each to create a UserCredential that is, in turn, used to initialize the DriveService...

```<code>var credential = new UserCredential(googleAuthFlow, "", responseToken);

Service = new DriveService(new BaseClientService.Initializer()
{
  HttpClientInitializer = credential,
  ApplicationName = "com.companyname.testxamauthgoogledrive",
});
</code>```

I updated the TestXamAuthGoogleDrive test harness project to reflect these changes.

Body:
I have an OAuth2 token like this...

{{
  "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "expires_in": "3600",
  "refresh_token": "xxxxxxxxxxxxxxxxxx",
  "token_type": "Bearer",
}}

and I'm trying to create a DriveService object...

Service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "foo",
});

(like this?)

but I'm clearly not doing this properly and I'm having trouble finding documentation.

When I attempt to create a GoogleCredential to pass to the DriveService

GoogleCredential credential = GoogleCredential.FromJson(credentialAsSerializedJson).CreateScoped(GoogleDriveScope);

I get the following exception:

{System.InvalidOperationException: Error creating credential from JSON. Unrecognized credential type .

Am I going about this the wrong way entirely?

(This is the sample code context)

Body:
I have managed to figure this out.

The solution was to create a Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow with my ClientID and ClientSecret...

Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow googleAuthFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
  ClientSecrets = new ClientSecrets()
  {
    ClientId = ClientID,
    ClientSecret = ClientSecret,
  }
});

and also a Google.Apis.Auth.OAuth2.Responses.TokenResponse:

Google.Apis.Auth.OAuth2.Responses.TokenResponse responseToken = new TokenResponse()
{
  AccessToken = SavedAccount.Properties["access_token"],
  ExpiresInSeconds = Convert.ToInt64(SavedAccount.Properties["expires_in"]),
  RefreshToken = SavedAccount.Properties["refresh_token"],
  Scope = GoogleDriveScope,
  TokenType = SavedAccount.Properties["token_type"],
};

and use each to create a UserCredential that is, in turn, used to initialize the DriveService...

var credential = new UserCredential(googleAuthFlow, "", responseToken);

Service = new DriveService(new BaseClientService.Initializer()
{
  HttpClientInitializer = credential,
  ApplicationName = "com.companyname.testxamauthgoogledrive",
});

I updated the TestXamAuthGoogleDrive test harness project to reflect these changes.


问:
function that removes spaces and tabs
im trying to make a function that removes spaces and tabs from a given string except for the first tab or space in the string. when im using my function it removes the spaces and tabs except for the first one but it also removes the first letter after the first space or tab.
for example > "ad ad  ad"> "ad dad" instead of "ad adad"
why is that?</p>

```<code>void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    int spcflg = 0;

    while(*j != 0) {
        *i = *j++;

        if((*i != ' ') && (*i != '\t'))
            i++;
        if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) {
            i++;
            spcflg = 1;
        }
    }
    *i = 0;
}
</code>```

答:
You will need to separate your source and destination arrays as they will become different lengths. You could find the starting position before copying characters like this, lets say you pass the source and the length of the source as char* source, int length (you could also calculate the length of the source with strlen(source), then your function could look like this:

```<code>int i = 0;
char* dest = malloc(sizeof(char) * length);
// Increment i until not space to find starting point.
while (i < length && (source[i] == '\t' || source[i] == ' ')) i++;

int dest_size = 0;
while (i < length) {
    if (source[i] != '\t' && source[i] != ' ') {
        // Copy character if not space to dest array
        dest[dest_size++] = source[i];
    }
    i++;
}
dest[dest_size++] = 0; // null terminator
// Feel free to realloc to the right length with
//   realloc(dest, dest_size * sizeof(char))
return dest;
</code>```

Title: function that removes spaces and tabs

Body:
im trying to make a function that removes spaces and tabs from a given string except for the first tab or space in the string. when im using my function it removes the spaces and tabs except for the first one but it also removes the first letter after the first space or tab.
for example > "ad ad  ad"> "ad dad" instead of "ad adad"
why is that?

void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    int spcflg = 0;

    while(*j != 0) {
        *i = *j++;

        if((*i != ' ') && (*i != '\t'))
            i++;
        if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) {
            i++;
            spcflg = 1;
        }
    }
    *i = 0;
}

Body:
You will need to separate your source and destination arrays as they will become different lengths. You could find the starting position before copying characters like this, lets say you pass the source and the length of the source as char* source, int length (you could also calculate the length of the source with strlen(source), then your function could look like this:

int i = 0;
char* dest = malloc(sizeof(char) * length);
// Increment i until not space to find starting point.
while (i < length && (source[i] == '\t' || source[i] == ' ')) i++;

int dest_size = 0;
while (i < length) {
    if (source[i] != '\t' && source[i] != ' ') {
        // Copy character if not space to dest array
        dest[dest_size++] = source[i];
    }
    i++;
}
dest[dest_size++] = 0; // null terminator
// Feel free to realloc to the right length with
//   realloc(dest, dest_size * sizeof(char))
return dest;


问:
Detect Object Color Various Lighting OpenCV Java
I would like to create a simple openCV application that is able to detect the color red (think red solo cup) accurately in various lighting conditions.

Which would be the best color space to use (RGB,HSV,etc) and how should i go about implementing something like this?

I'm new to use openCV and this would be my first project so any examples would be greatly appreciated.

There are examples out there for detecting but none of them  address how colors can appear different shades and hues based on bright light, shadows, low light, etc and how to compensate for that.

I plan on using this in a embedded project so i could have a photodiode to detect the amount of ambient light, if that information helps...

Thanks!

答:
Try out this tutorial project. It detects color using OpenCV in the simplest way possible:

```<code># find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
</code>```

It's Python but that code is straightforward enough to show how it works.

Try this with the pictures your setup is getting first. It's fast and simple for a first attempt.

Detecting red is fairly straightforward until you mess with illumination. At that point, the problem can get REALLY hairy like the dress.

So it's best to ignore that problem until you've had a chance to see how it affects your setup. Your illumination constraints may be simple (e.g. bright vs dim pictures) or it could be complex (e.g. blue tinted in the dark, yellow tinted in bright light).

Body:
Try out this tutorial project. It detects color using OpenCV in the simplest way possible:

# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)

It's Python but that code is straightforward enough to show how it works.

Try this with the pictures your setup is getting first. It's fast and simple for a first attempt.

Detecting red is fairly straightforward until you mess with illumination. At that point, the problem can get REALLY hairy like the dress.

So it's best to ignore that problem until you've had a chance to see how it affects your setup. Your illumination constraints may be simple (e.g. bright vs dim pictures) or it could be complex (e.g. blue tinted in the dark, yellow tinted in bright light).


问:
How do I get the data to return with multiple elements?
How do I get the data to return in multiple title elements rather than one title element?

Returns this

```<code><title>
    Title 1
    Title 2
    Title 3
</title>
</code>```

Want to return this

```<code><title>Title 1</title>
<title>Title 2</title>
<title>Title 3</title>
</code>```

Code

```<code>(: This gets coordinates from $latLon :)
  let $result := for $coordinates in $latLon/location
                let $lat := $coordinates/lat/text()
                let $lon := $coordinates/lon/text()
(: This uses the coordinates to retrieve a title :)
                let $data := titleDoc:getTitle($lat, $lon)
                let $title := $data//div[@class="title"]/text()
                return
                  <title>{$title}</title>
</code>```

答:
As @chrisis says, it's hard to tell without looking at your code, but I think you want a for instead of a let here:

```<code>  let $title := $data//div[@class="title"]/text()
  return <title>{$title}</title>
</code>```

The let makes one sequence with all the text nodes, and places them in the <title> element.  That's not what you want, you want to iterate over them, creating one title element for each one:

```<code>  for $title in $data//div[@class="title"]/text()
  return <title>{$title}</title>
</code>```

Body:
How do I get the data to return in multiple title elements rather than one title element?

Returns this

<title>
    Title 1
    Title 2
    Title 3
</title>

Want to return this

<title>Title 1</title>
<title>Title 2</title>
<title>Title 3</title>

Code

(: This gets coordinates from $latLon :)
  let $result := for $coordinates in $latLon/location
                let $lat := $coordinates/lat/text()
                let $lon := $coordinates/lon/text()
(: This uses the coordinates to retrieve a title :)
                let $data := titleDoc:getTitle($lat, $lon)
                let $title := $data//div[@class="title"]/text()
                return
                  <title>{$title}</title>

Body:
As @chrisis says, it's hard to tell without looking at your code, but I think you want a for instead of a let here:

  let $title := $data//div[@class="title"]/text()
  return <title>{$title}</title>

The let makes one sequence with all the text nodes, and places them in the <title> element.  That's not what you want, you want to iterate over them, creating one title element for each one:

  for $title in $data//div[@class="title"]/text()
  return <title>{$title}</title>


问:
Preventing variable overwriting in recursive Makefiles
I have the following project structure:

```<code>project/
  - Makefile
  - foo/
    - foo.mk
  - bar/
    - bar.mk
</code>```

Contents of Makefile:

```<code>.PHONY: all foo bar

all: foo bar

include foo/foo.mk
include bar/bar.mk
</code>```

Contents of foo/foo.mk:

```<code>SOME_VAR=foo

foo:
        @echo $(SOME_VAR)
</code>```

Contents of bar/bar.mk:

```<code>SOME_VAR=bar

bar:
        @echo $(SOME_VAR)
</code>```

Running the command make in yields the output

```<code>bar
bar
</code>```

The observed output is easy to explain: variables in recipes are expanded only when the rule is executed, so when SOME_VAR is overwritten in bar.mk the rule for foo prints bar. Is there any way of preventing this behaviour?

答:
One way is to use target-specific variable values.

Change your sub-makefiles to

```<code>bar: SOME_VAR=bar
bar:
    @echo $(SOME_VAR)
</code>```

```<code>foo: SOME_VAR=foo
foo:
    @echo $(SOME_VAR)
</code>```

Recursive make will also work

```<code>all:
    $(MAKE) -C foo -f foo.mk
    $(MAKE) -C bar -f bar.mk
</code>```

Body:
I have the following project structure:

project/
  - Makefile
  - foo/
    - foo.mk
  - bar/
    - bar.mk

Contents of Makefile:

.PHONY: all foo bar

all: foo bar

include foo/foo.mk
include bar/bar.mk

Contents of foo/foo.mk:

SOME_VAR=foo

foo:
        @echo $(SOME_VAR)

Contents of bar/bar.mk:

SOME_VAR=bar

bar:
        @echo $(SOME_VAR)

Running the command make in yields the output

bar
bar

The observed output is easy to explain: variables in recipes are expanded only when the rule is executed, so when SOME_VAR is overwritten in bar.mk the rule for foo prints bar. Is there any way of preventing this behaviour?

Body:
One way is to use target-specific variable values.

Change your sub-makefiles to

bar: SOME_VAR=bar
bar:
    @echo $(SOME_VAR)

foo: SOME_VAR=foo
foo:
    @echo $(SOME_VAR)

Recursive make will also work

all:
    $(MAKE) -C foo -f foo.mk
    $(MAKE) -C bar -f bar.mk


问:
Making postgresql logs in JSON format
I am using postgresql 9.5 on ubuntu 16.04.

Is there any way in postgresql so that it's logs can be stored in JSON format ?

I need to send it to elasticsearch, that's why I need to make postgresql logs in JSON format.

I followed this tutorial, but did not quite understood that what and where it was asking me to make changes in the conf file.

答: PostgreSQL self doesn't support any other formats than plain text and CSV. When you need other formats, then you need to get somewhere (or write by self) special extension that is able to touch log API and format and push PostgreSQL logs. One extension was developed by Michael and it is described in mentioned link. Here is link to source code: https://github.com/michaelpq/pg_plugins/tree/master/jsonlog . You have to compile this extension like any other (PostgreSQL extension) - code is in C language, and then you can use it.</p>

Title: Making postgresql logs in JSON format


问:
"Position: fixed" in CSS changes "justify-content-end"
I'm trying to make a navigation bar with the content on the right of the page. This worked until I added position:fixed in CSS. After I added position:fixed, the content got relocated to the left of the page. Can someone tell me why this happened?

.header {
  position: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active">About</li>
    <li> Portfolio</li>
    <li>Contact</li>
  </ul>
</div></code>```

答:
Add right: 0px to the header css (or however many pixels from the edge you want it).

.header {
  position: fixed;
  right: 0px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active">About</li>
    <li> Portfolio</li>
    <li>Contact</li>
  </ul>
</div></code>```

Body:
I'm trying to make a navigation bar with the content on the right of the page. This worked until I added position:fixed in CSS. After I added position:fixed, the content got relocated to the left of the page. Can someone tell me why this happened?

.header {
  position: fixed;
}

About

 Portfolio

Contact

Body:
Add right: 0px to the header css (or however many pixels from the edge you want it).

.header {
  position: fixed;
  right: 0px
}

<div class="header">
  <ul class="nav nav-pills justify-content-end">
    <li class="active"><a data-toggle="pill" class="nav-link active" href="#">About</a></li>
    <li> <a data-toggle="pill" class="nav-link" href="#">Portfolio</a></li>
    <li><a data-toggle="pill" class="nav-link" href="#">Contact</a></li>
  </ul>
</div>


问:
get continues reading from continues touch
I want to get continues reading from a continues touch down event.
I mean that I want to get event every 0.01 sec.
I've tried to use GestureDetector and I got down, show and long events during a continues
touch. After the long event I don't get any events.
Please help...</p>

答: You need to listen for TouchMotion events in the Activity's onTouch() method.


问:
XSL node selection thows an XPath syntax error
I'm generating a PDF using Apache FOP.

I have the following XSL transformation:

```<code><fo:block>
    <xsl:choose>
        <xsl:when test="$data/mainNode/childNode/code = someFeature/someCode">
            <xsl:value-of select="$data/mainNode/childNode/[code=someFeature/someCode]/value" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>Bar</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</fo:block>
</code>```

Sample of XML structure:

```<code><mainNode>
    <childNode>
        <code>A</code>
        <value>1</value>
    </childNode>
    <childNode>
        <code>B</code>
        <value>2</value>
    </childNode>
    <childNode>
        <code>C</code>
        <value>3</value>
    </childNode>
</mainNode>
</code>```

When running it through Oxygen XML Editor I get an error saying: XPST0003: To use XPath 3.1 syntax, you must configure the XPath parser to handle it. The engine is Saxon-PE 9.7.0.15.

The problem is the 4th line, where I'm trying to get the value from a childNode with the same code as the one returned by someFeature/someCode.

Is there any way I can rewrite this so I won't receive an error?

答: I think instead of $data/mainNode/childNode/[code=someFeature/someCode]/value you want $data/mainNode/childNode[code=current()/someFeature/someCode]/value.

Body:
I'm generating a PDF using Apache FOP.

I have the following XSL transformation:

<fo:block>
    <xsl:choose>
        <xsl:when test="$data/mainNode/childNode/code = someFeature/someCode">
            <xsl:value-of select="$data/mainNode/childNode/[code=someFeature/someCode]/value" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:text>Bar</xsl:text>
        </xsl:otherwise>
    </xsl:choose>
</fo:block>

Sample of XML structure:

<mainNode>
    <childNode>
        A
        <value>1</value>
    </childNode>
    <childNode>
        B
        <value>2</value>
    </childNode>
    <childNode>
        C
        <value>3</value>
    </childNode>
</mainNode>

When running it through Oxygen XML Editor I get an error saying: XPST0003: To use XPath 3.1 syntax, you must configure the XPath parser to handle it. The engine is Saxon-PE 9.7.0.15.

The problem is the 4th line, where I'm trying to get the value from a childNode with the same code as the one returned by someFeature/someCode.

Is there any way I can rewrite this so I won't receive an error?


问:
How can I optimize my Travis CI matrix for Django and Python versions?
I have a .travis.yml file that looks like this:

https://gist.github.com/dyve/d79e5cd4f81bb2675181

(original: https://github.com/dyve/django-bootstrap3/blob/develop/.travis.yml)

I have to type several Python and Django versions more than once. I would like to:

Automatically pick the newest Django 1.4, 1.5, 1.6 and 1.7

Exclude Python>2 && Django<1.6

Exclude Python<2.7 && Django>1.6

Is there a more DRY way to do this in a Travis CI file?

答:
You can set up a matrix in your .travis.yml file with Python and Django versions. Here is an example .travis.yml that I am using.

You can also tell Travis CI to install the latest version of Django up to a certain release by using something similar to the following. Note that Django<1.11 will install the latest 1.10.x release.

matrix:
   - DJANGO="Django<1.8"
   - DJANGO="Django<1.9"
   - DJANGO="Django<1.10"
   - DJANGO="Django<1.11"
   - DJANGO="Django<1.12"

Also, note that not all combinations need to pass and not all combinations are officially supported. A list of Python/Django combinations that should be covered can be found in the Django docs.

Exclusions can be handled using something similar to the following:

matrix:
  exclude:
    - python: "3.5"
      env: DJANGO="Django<1.8"


问:
udev cdrom rules failing to run scripts
The following is my rules file in /etc/udev/rules.d/10-autodvd.rules

```<code>SUBSYSTEM=="block", KERNEL=="sr0", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr0"
SUBSYSTEM=="block", KERNEL=="sr1", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr1"
SUBSYSTEM=="block", KERNEL=="sr2", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr2"
SUBSYSTEM=="block", KERNEL=="sr3", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr3"
SUBSYSTEM=="block", KERNEL=="sr4", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr4"
</code>```

It seems to be really hit or miss on actually running the scripts, is there a better way to do this?

答:
Udev sorts the rules files lexically, and at the time your rules are applied, the ID_CDROM_MEDIA_DVD variable probably isn't set yet. This is the case on a default install of systemd udev. The ID_CDROM* variables are set in 60-cdrom_id.rules, so you should rename your rules file to sort after this.

Note that you're not supposed to start a long running program with the RUN+= key.

```<code>   RUN{type}
   [...]
       This can only be used for very short-running
       foreground tasks. Running an event process for
       a long period of time may block all further
       events for this or a dependent device.

       Starting daemons or other long-running
       processes is not appropriate for udev; the
       forked processes, detached or not, will be
       unconditionally killed after the event handling
       has finished.
</code>```

Your rules may be written as one rule:

```<code>SUBSYSTEM=="block", KERNEL=="sr[0-4]", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh %k"
</code>```

Title: udev cdrom rules failing to run scripts

Body:
The following is my rules file in /etc/udev/rules.d/10-autodvd.rules

SUBSYSTEM=="block", KERNEL=="sr0", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr0"
SUBSYSTEM=="block", KERNEL=="sr1", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr1"
SUBSYSTEM=="block", KERNEL=="sr2", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr2"
SUBSYSTEM=="block", KERNEL=="sr3", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr3"
SUBSYSTEM=="block", KERNEL=="sr4", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh sr4"

It seems to be really hit or miss on actually running the scripts, is there a better way to do this?

Body:
Udev sorts the rules files lexically, and at the time your rules are applied, the ID_CDROM_MEDIA_DVD variable probably isn't set yet. This is the case on a default install of systemd udev. The ID_CDROM* variables are set in 60-cdrom_id.rules, so you should rename your rules file to sort after this.

Note that you're not supposed to start a long running program with the RUN+= key.

   RUN{type}
   [...]
       This can only be used for very short-running
       foreground tasks. Running an event process for
       a long period of time may block all further
       events for this or a dependent device.

       Starting daemons or other long-running
       processes is not appropriate for udev; the
       forked processes, detached or not, will be
       unconditionally killed after the event handling
       has finished.

Your rules may be written as one rule:

SUBSYSTEM=="block", KERNEL=="sr[0-4]", ENV{ID_CDROM_MEDIA_DVD}=="1", ACTION=="change", RUN+="/usr/local/bin/makemkv.sh %k"


问:
Heroku deploy error
Hi, I have some problems: I tried to deploy a nodejs app on heroku, but when I try to open it, I get this error :

```<code>2017-06-08T16:08:43.221350+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xmpp-discord.herokuapp.com request_id=6692a6c4-2563-474d-90e2-1657d83c7393 fwd="92.157.13.75" dyno= connect= service= status=503 bytes= protocol=https

2017-06-08T16:08:43.433802+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=xmpp-discord.herokuapp.com request_id=ab1f0f7d-4eed-4948-94e2-bb80fcd9887b fwd="92.157.13.75" dyno= connect= service= status=503 bytes= protocol=https
</code>```

My app is a bridge between Discord and XMPP: here It's github base: Github but I ran it and setuped it, it does work in local but I want to run the program all day even if my PC isn't on.

What should or could I do?

If you need more infos tell me !

Thanks

答:
It's right there in the logs "missing script 'start'". Either in your procfile or due to Heroku defaults your app is trying to launch using "npm start", but your package.json does not define a start script.  </p>

<p>Either update your procfile to the correct start command or add to your package.json, in the "scripts" object something like:  "start": "node server.js" or whatever command you normally use to start the app.  </p>

Title: Heroku deploy error

Body:
Hi, I have some problems: I tried to deploy a nodejs app on heroku, but when I try to open it, I get this error :

2017-06-08T16:08:43.221350+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xmpp-discord.herokuapp.com request_id=6692a6c4-2563-474d-90e2-1657d83c7393 fwd="92.157.13.75" dyno= connect= service= status=503 bytes= protocol=https

2017-06-08T16:08:43.433802+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=xmpp-discord.herokuapp.com request_id=ab1f0f7d-4eed-4948-94e2-bb80fcd9887b fwd="92.157.13.75" dyno= connect= service= status=503 bytes= protocol=https

My app is a bridge between Discord and XMPP: here It's github base: Github but I ran it and setuped it, it does work in local but I want to run the program all day even if my PC isn't on.

What should or could I do?

If you need more infos tell me !

Thanks

Body:
It's right there in the logs "missing script 'start'". Either in your procfile or due to Heroku defaults your app is trying to launch using "npm start", but your package.json does not define a start script.

Either update your procfile to the correct start command or add to your package.json, in the "scripts" object something like:  "start": "node server.js" or whatever command you normally use to start the app.


问:
Create Maven configuration on IDEA intellij
I using IDEA to dev my springboot app, so I create one maven configuration with the code:

```<code>mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
</code>```

but this configuration is valid only to that project, can I make this configuration global? to every maven project that I open or import in my IDEA?

答:
In intellij idea, you can create a custom run configuration and then save it:

Steps:

With the Navigation bar visible (View | Navigation Bar), the available run/debug configurations are displayed in the run/debug configuration selector in the Run area,
-> go to "edit configurations"
-> there select Run/Debug Configuration: Maven

In the open dialog, put your mvn command, without mvn:

```<code>spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
</code>```

And put a name for it (example, "mvnspringboot"), then in the Run/Debug Configuration selector, choose Save mvnspringboot.

sources:

https://www.jetbrains.com/help/idea/2017.1/creating-and-saving-temporary-run-debug-configurations.html

https://www.jetbrains.com/help/idea/2017.1/creating-and-editing-run-debug-configurations.html

Body:
I using IDEA to dev my springboot app, so I create one maven configuration with the code:

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

but this configuration is valid only to that project, can I make this configuration global? to every maven project that I open or import in my IDEA?

Body:
In intellij idea, you can create a custom run configuration and then save it:

Steps:

With the Navigation bar visible (View | Navigation Bar), the available run/debug configurations are displayed in the run/debug configuration selector in the Run area,
-> go to "edit configurations"
-> there select Run/Debug Configuration: Maven

In the open dialog, put your mvn command, without mvn:

spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"

And put a name for it (example, "mvnspringboot"), then in the Run/Debug Configuration selector, choose Save mvnspringboot.

sources:

https://www.jetbrains.com/help/idea/2017.1/creating-and-saving-temporary-run-debug-configurations.html

https://www.jetbrains.com/help/idea/2017.1/creating-and-editing-run-debug-configurations.html


问:
How to check QtDesigner-generated widget point for validity in QTimer?
Inside my QDialog code I've got the following:

```<code>QTimer::singleShot(2 * 1000, [&] {
    if (theme_download_label) {
        theme_download_label->hide();
        theme_download_label->setText("text");
    }
});
</code>```

The issue is that if I close the dialog before the timer fires, theme_download_label->setText crashes. How to deal with this?

I've already tried setting theme_download_label to Q_NULLPR before the close() method to no effect.

答:
It doesn't matter where the widget originates from, or whether it's a widget. The solution is the same for any QObject.

Provide a QObject context to the connection. When the context object dies, it gets disconnected, and thus the functor will not be invoked.

Pass the pointer to the label by value, not by reference, in case the timer outlives this. That was the likely cause of the crash.

There's no need to check whether theme_download_label is null: it can't be. That's the invariant of a connection with a context object: it is guaranteed by design that the context object is alive.

```<code>QTimer::singleShot(2 * 1000, theme_download_label, [label = theme_download_label] {
    label->hide();
    label->setText("text");
});
</code>```

Body:
Inside my QDialog code I've got the following:

QTimer::singleShot(2 * 1000, [&] {
    if (theme_download_label) {
        theme_download_label->hide();
        theme_download_label->setText("text");
    }
});

The issue is that if I close the dialog before the timer fires, theme_download_label->setText crashes. How to deal with this?

I've already tried setting theme_download_label to Q_NULLPR before the close() method to no effect.

Body:
It doesn't matter where the widget originates from, or whether it's a widget. The solution is the same for any QObject.

Provide a QObject context to the connection. When the context object dies, it gets disconnected, and thus the functor will not be invoked.

Pass the pointer to the label by value, not by reference, in case the timer outlives this. That was the likely cause of the crash.

There's no need to check whether theme_download_label is null: it can't be. That's the invariant of a connection with a context object: it is guaranteed by design that the context object is alive.

QTimer::singleShot(2 * 1000, theme_download_label, [label = theme_download_label] {
    label->hide();
    label->setText("text");
});


问:
Maven Unable to Find Dependencies For Stash Plugin
I'm trying to make a Stash (Bitbucket Server) hook following this tutorial.

I installed the Atlassian SDK and ran both atlas-create-stash-plugin and atlas-create-stash-plugin-module.

However, Maven is unable to find any dependencies, despite them being in my local repository. I mean, look at this screenshot:

As you can see, the dependencies have successfully been installed to my local Maven repo, but IntelliJ (and Maven when I try to compile the plugin) are unable to locate the dependencies. Why?

答:
It can be cache issue. So please try to do following in Intellij Idea:

```<code>File -> Invalidate Caches / Restart.
</code>```

Also, you can try to reimport your project:

Body:
It can be cache issue. So please try to do following in Intellij Idea:

File -> Invalidate Caches / Restart.

Also, you can try to reimport your project:


问:
change the background-color of every other element
I want to change the background-color of every other element in the following:

```<code><div class="dets">
 <div>Simple Layout</div>
 <div>Few Pictures/Links</div>
 <div>Element Uniformity</div>
</div>
</code>```

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

```<code>$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');
</code>```

答:
Try:

```<code>$(".dets>div:nth-child(odd)").css('background-color', 'white');
$(".dets>div:nth-child(even)").css('background-color', 'black');
</code>```

also you can do it only with css:

```<code>.dets>div:nth-child(odd){
 background-color:white;
}
.dets>div:nth-child(even){
 background-color:black;
}
</code>```

Body:
I want to change the background-color of every other element in the following:

Simple Layout

Few Pictures/Links

Element Uniformity

So the first [Simple Layout] would be white, the second [Few Pictures/Links] would be black, and so on. I have three of these structures nested in some other div elements. I know about the :even,:odd methods, but it doesn't do as expected. It continues through each of the "dets" classes, increasing the index each time. I want odd rows white, even rows black. Is there a way to restart the natural index for each "dets" class? I do not want to use a table.

I am currently using the following jQuery to set the background-color:

$(".dets div:odd").css('background-color', 'white');
$(".dets div:even").css('background-color', 'black');

Body:
Try:

$(".dets>div:nth-child(odd)").css('background-color', 'white');
$(".dets>div:nth-child(even)").css('background-color', 'black');

also you can do it only with css:

.dets>div:nth-child(odd){
 background-color:white;
}
.dets>div:nth-child(even){
 background-color:black;
}


问:
Jquery vertial tabs unknown gap and alignment
Been working on this for awhile and seem to not be able to get it working.

First, there is a gap between the tabs and the content and I am unsure how to go about fixing that without making the right side more left.

Second, tabs themselves have an issue when it comes to being attached to the content area. I currently have the tabs left: -80px; in order to move them out of the content area. However, doing that seems to have caused an issue depending on how large/small the overall screen size of the users browser is.

If anyone could help me out with this issue then that would be great!

I have made a JSFiddle for you to test with.

var tabTitles = ["First Tab", "Second Tab", "Third Tab", "Fourth Tab", "Fifth Tab", "Sixth Tab"];

$(".tabHeader").click(function() {
  $(".tabHeader").removeClass("active");
  var position = $(this).position();
  var top = position.top;
  $(".active").css("top", top);
  $(this).addClass("active");
  var text = $(this).text().trim();
  switch (text) {
    case "Tab 1":
      $(".tabTitle").text(tabTitles[0]);
      break;
    case 'Tab 2':
      $(".tabTitle").text(tabTitles[1]);
      break;
    case 'Tab 3':
      console.log('yo');
      //$('.textBody').html('TEST!');
      $(".textBody").load("https://raw.githubusercontent.com/jiahaog/ajax-test-page/master/index.html", function(responseTxt, statusTxt, xhr) {

      });
      $(".tabTitle").text(tabTitles[2]);
      break;
    case 'Tab 4':
      $(".tabTitle").text(tabTitles[3]);
      break;
    case 'Tab 5':
      $(".tabTitle").text(tabTitles[4]);
      break;
    case 'Tab 6':
      $(".tabTitle").text(tabTitles[5]);
      break;
    default:
      $(".tabTitle").text("Select A TAB");
      break;

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
}

.card {
  display: flex;
  flex-direction: row;
  background-color: white;
  margin: 0 auto;
  margin-top: 10px;
  width: 85%;
  height: 100%;
  box-shadow: 1px 2px 6px #d3d3d3;
  border-radius: 4px;
}

.tabHeader {
  width: 80px;
  height: 50px;
  background-color: #47bc8b;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.verticalTabs {
  position: relative;
  left: -80px;
  right: 0px;
  display: table-cell;
}

.active {
  position: relative;
  z-index: 50;
  width: 80px;
  height: 50px;
  background-color: #259162;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.tabText {
  position: absolute;
  color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
  margin-top: 16px;
  margin-left: 23px;
}

.textHolder {
  margin: 10px;
  text-align: justify;
  overflow: scroll;
  overflow-x: hidden;
  width: 100%;
}

.tabTitle {
  font-size: 20px;
  font-weight: 600;
  padding: 0 0 20px 0;
}</code>```

Tab 1

Tab 2

Tab 3

Tab 4

Tab 5

Tab 6

First Tab

```

答:
All you really need to do is move the border-radius & box-shadow from .card and move it to .textHolder, then you can remove the positioning from .verticalTabs and instead of using a margin to separate .card from .textHolder, use padding instead.

var tabTitles = ["First Tab", "Second Tab", "Third Tab", "Fourth Tab", "Fifth Tab", "Sixth Tab"];

$(".tabHeader").click(function() {
  $(".tabHeader").removeClass("active");
  var position = $(this).position();
  var top = position.top;
  $(".active").css("top", top);
  $(this).addClass("active");
  var text = $(this).text().trim();
  switch (text) {
    case "Tab 1":
      $(".tabTitle").text(tabTitles[0]);
      break;
    case 'Tab 2':
      $(".tabTitle").text(tabTitles[1]);
      break;
    case 'Tab 3':
      console.log('yo');
      //$('.textBody').html('TEST!');
      $(".textBody").load("https://raw.githubusercontent.com/jiahaog/ajax-test-page/master/index.html", function(responseTxt, statusTxt, xhr) {

      });
      $(".tabTitle").text(tabTitles[2]);
      break;
    case 'Tab 4':
      $(".tabTitle").text(tabTitles[3]);
      break;
    case 'Tab 5':
      $(".tabTitle").text(tabTitles[4]);
      break;
    case 'Tab 6':
      $(".tabTitle").text(tabTitles[5]);
      break;
    default:
      $(".tabTitle").text("Select A TAB");
      break;

  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
}

.card {
  display: flex;
  flex-direction: row;
  background-color: white;
  margin: 0 auto;
  margin-top: 10px;
  width: 85%;
  height: 100%;
}

.tabHeader {
  width: 80px;
  height: 50px;
  background-color: #47bc8b;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.verticalTabs {
  position: relative;
  display: table-cell;
}

.active {
  position: relative;
  z-index: 50;
  width: 80px;
  height: 50px;
  background-color: #259162;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.tabText {
  position: absolute;
  color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
  margin-top: 16px;
  margin-left: 23px;
}

.textHolder {
  padding: 10px;
  text-align: justify;
  overflow: scroll;
  overflow-x: hidden;
  width: 100%;
  box-shadow: 1px 2px 6px #d3d3d3;
  border-radius: 4px;
}

.tabTitle {
  font-size: 20px;
  font-weight: 600;
  padding: 0 0 20px 0;
}</code>```

Tab 1

Tab 2

Tab 3

Tab 4

Tab 5

Tab 6

First Tab

```

Body:
Been working on this for awhile and seem to not be able to get it working.

First, there is a gap between the tabs and the content and I am unsure how to go about fixing that without making the right side more left.

Second, tabs themselves have an issue when it comes to being attached to the content area. I currently have the tabs left: -80px; in order to move them out of the content area. However, doing that seems to have caused an issue depending on how large/small the overall screen size of the users browser is.

If anyone could help me out with this issue then that would be great!

I have made a JSFiddle for you to test with.

var tabTitles = ["First Tab", "Second Tab", "Third Tab", "Fourth Tab", "Fifth Tab", "Sixth Tab"];

$(".tabHeader").click(function() {
  $(".tabHeader").removeClass("active");
  var position = $(this).position();
  var top = position.top;
  $(".active").css("top", top);
  $(this).addClass("active");
  var text = $(this).text().trim();
  switch (text) {
    case "Tab 1":
      $(".tabTitle").text(tabTitles[0]);
      break;
    case 'Tab 2':
      $(".tabTitle").text(tabTitles[1]);
      break;
    case 'Tab 3':
      console.log('yo');
      //$('.textBody').html('TEST!');
      $(".textBody").load("https://raw.githubusercontent.com/jiahaog/ajax-test-page/master/index.html", function(responseTxt, statusTxt, xhr) {

      });
      $(".tabTitle").text(tabTitles[2]);
      break;
    case 'Tab 4':
      $(".tabTitle").text(tabTitles[3]);
      break;
    case 'Tab 5':
      $(".tabTitle").text(tabTitles[4]);
      break;
    case 'Tab 6':
      $(".tabTitle").text(tabTitles[5]);
      break;
    default:
      $(".tabTitle").text("Select A TAB");
      break;

  }
});

body {
  background-color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
}

.card {
  display: flex;
  flex-direction: row;
  background-color: white;
  margin: 0 auto;
  margin-top: 10px;
  width: 85%;
  height: 100%;
  box-shadow: 1px 2px 6px #d3d3d3;
  border-radius: 4px;
}

.tabHeader {
  width: 80px;
  height: 50px;
  background-color: #47bc8b;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.verticalTabs {
  position: relative;
  left: -80px;
  right: 0px;
  display: table-cell;
}

.active {
  position: relative;
  z-index: 50;
  width: 80px;
  height: 50px;
  background-color: #259162;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.tabText {
  position: absolute;
  color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
  margin-top: 16px;
  margin-left: 23px;
}

.textHolder {
  margin: 10px;
  text-align: justify;
  overflow: scroll;
  overflow-x: hidden;
  width: 100%;
}

.tabTitle {
  font-size: 20px;
  font-weight: 600;
  padding: 0 0 20px 0;
}

Tab 1

Tab 2

Tab 3

Tab 4

Tab 5

Tab 6

First Tab

Body:
All you really need to do is move the border-radius & box-shadow from .card and move it to .textHolder, then you can remove the positioning from .verticalTabs and instead of using a margin to separate .card from .textHolder, use padding instead.

var tabTitles = ["First Tab", "Second Tab", "Third Tab", "Fourth Tab", "Fifth Tab", "Sixth Tab"];

$(".tabHeader").click(function() {
  $(".tabHeader").removeClass("active");
  var position = $(this).position();
  var top = position.top;
  $(".active").css("top", top);
  $(this).addClass("active");
  var text = $(this).text().trim();
  switch (text) {
    case "Tab 1":
      $(".tabTitle").text(tabTitles[0]);
      break;
    case 'Tab 2':
      $(".tabTitle").text(tabTitles[1]);
      break;
    case 'Tab 3':
      console.log('yo');
      //$('.textBody').html('TEST!');
      $(".textBody").load("https://raw.githubusercontent.com/jiahaog/ajax-test-page/master/index.html", function(responseTxt, statusTxt, xhr) {

      });
      $(".tabTitle").text(tabTitles[2]);
      break;
    case 'Tab 4':
      $(".tabTitle").text(tabTitles[3]);
      break;
    case 'Tab 5':
      $(".tabTitle").text(tabTitles[4]);
      break;
    case 'Tab 6':
      $(".tabTitle").text(tabTitles[5]);
      break;
    default:
      $(".tabTitle").text("Select A TAB");
      break;

  }
});

body {
  background-color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
}

.card {
  display: flex;
  flex-direction: row;
  background-color: white;
  margin: 0 auto;
  margin-top: 10px;
  width: 85%;
  height: 100%;
}

.tabHeader {
  width: 80px;
  height: 50px;
  background-color: #47bc8b;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.verticalTabs {
  position: relative;
  display: table-cell;
}

.active {
  position: relative;
  z-index: 50;
  width: 80px;
  height: 50px;
  background-color: #259162;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.tabText {
  position: absolute;
  color: white;
  font-family: 'Open Sans', sans-serif;
  font-weight: 400;
  font-size: 12px;
  margin-top: 16px;
  margin-left: 23px;
}

.textHolder {
  padding: 10px;
  text-align: justify;
  overflow: scroll;
  overflow-x: hidden;
  width: 100%;
  box-shadow: 1px 2px 6px #d3d3d3;
  border-radius: 4px;
}

.tabTitle {
  font-size: 20px;
  font-weight: 600;
  padding: 0 0 20px 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tab-wrapper">

  <div class="card">
    <div class="verticalTabs">
      <div class="tabHeader active">
        <div class="tabText">Tab 1</div>
      </div>
      <div class="tabHeader">
        <div class="tabText">Tab 2</div>
      </div>
      <div class="tabHeader">
        <div class="tabText">Tab 3</div>
      </div>
      <div class="tabHeader">
        <div class="tabText">Tab 4</div>
      </div>
      <div class="tabHeader">
        <div class="tabText">Tab 5</div>
      </div>
      <div class="tabHeader">
        <div class="tabText">Tab 6</div>
      </div>
    </div>
    <div class="textHolder">
      <div class="tabTitle">First Tab</div>
      <div class="textBody"></div>
    </div>
  </div>

</div>


问:
formatOnSave doesn't work in vscode
I installed C/C++ extensions, and added lines below to user settings:

```<code>"editor.formatOnSave": true
"C_Cpp.clang_format_path": "C:/Progra~2/LLVM/bin/clang-format.exe"
"C_Cpp.clang_format_fallbackStyle": "LLVM"
"C_Cpp.clang_format_formatOnSave": true
</code>```

but alt-shift-F, ctrl-s(save) both don't reformat codes at all.

I tried to remove vscode completely/reinstall/reboot, but didn't work.

And there's no workspace settings seperately.

Is there something I missed?

答:
Also your session:

```<code>// "Default" enables code formatting. "Disabled" disables code formatting.
   "C_Cpp.formatting": "Default",
</code>```

should be 'Default' and not 'Disabled'.

Title: formatOnSave doesn't work in vscode

Body:
I installed C/C++ extensions, and added lines below to user settings:

"editor.formatOnSave": true
"C_Cpp.clang_format_path": "C:/Progra~2/LLVM/bin/clang-format.exe"
"C_Cpp.clang_format_fallbackStyle": "LLVM"
"C_Cpp.clang_format_formatOnSave": true

but alt-shift-F, ctrl-s(save) both don't reformat codes at all.

I tried to remove vscode completely/reinstall/reboot, but didn't work.

And there's no workspace settings seperately.

Is there something I missed?

Body:
Also your session:

// "Default" enables code formatting. "Disabled" disables code formatting.
   "C_Cpp.formatting": "Default",

should be 'Default' and not 'Disabled'.


问:
OnKeyboardActionListener android keys
I'm trying to implement a way to know when there is a press and a release of a key on a soft keyboard.  I have used the onKeyListener to get the down and the up of the key, but the problem with that is that it only works on a hard keyboard.  I have found the OnKeyBoardActionListener which seems to have this functionality.  The problem I am running into with this is that i need to get the KeyboardView from an edittext i am using for simple testing.

```<code>public class testing extends Activity implements KeyboardView.OnKeyboardActionListener{
     EditText testingBox;
     TextView textbox;
     KeyboardView keyView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textbox = (TextView)findViewById(R.id.TextView01);

    testingBox = (EditText)findViewById(R.id.EditText01);

    //keyView is null i need to get it somehow.

    keyView.setOnKeyboardActionListener(this);
}
//methods for the OnKeyBoardActionListener
}
</code>```

if anyone could provide any advice on how i can get this keyBoardView or another way i can capture these soft keyboard presses and releases would be great.  thanks.

答:
I believe the only way to capture the exact press and releases of a softkeyboard is from within the IME. You can see the text changing via a TextWatcher.

I think this is partially because an IME may not have key down and up mechanisms.  An IME does not necessarily need to look like a standard qwerty keyboard.  It might be something like Swype, where you draw a pattern and words come out.

Title: OnKeyboardActionListener android keys

Body:
I'm trying to implement a way to know when there is a press and a release of a key on a soft keyboard.  I have used the onKeyListener to get the down and the up of the key, but the problem with that is that it only works on a hard keyboard.  I have found the OnKeyBoardActionListener which seems to have this functionality.  The problem I am running into with this is that i need to get the KeyboardView from an edittext i am using for simple testing.

public class testing extends Activity implements KeyboardView.OnKeyboardActionListener{
     EditText testingBox;
     TextView textbox;
     KeyboardView keyView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    textbox = (TextView)findViewById(R.id.TextView01);

    testingBox = (EditText)findViewById(R.id.EditText01);

    //keyView is null i need to get it somehow.

    keyView.setOnKeyboardActionListener(this);
}
//methods for the OnKeyBoardActionListener
}

if anyone could provide any advice on how i can get this keyBoardView or another way i can capture these soft keyboard presses and releases would be great.  thanks.


问:
Bug : SpagoBI 5.2 Meta can't add relationship from cube to dimensions while creating OLAP cube
I'm using SpagoBI 5.2 Meta for creating Olap cube.I could create a database connection with Mysql database and imported physical tables.But It doesn't identify foreign key relationships in the physical tables. By right clicking on business classes, I have created dimensions and cube but when I try to edit business model to "Add relationship" ,the "finish" button on the GUI is disabled all the time.What may be the reasons for this.Do I need to add any inbound,outbound relationships first?
Here I've attached screenshot of GUI that has disabled "finish" button
Best Regards!!</p>

答:
First you have to set what is dimension and what is fact in your model.

You can do this by right click in the table (Olap > Create Cube or Create Dimension).

After do this for all tables in your model, you can add relationships with no problem.

Detail of the submenu


问:
Dynamic %%GLOBAL_UPC%% variable on blueprint theme
I would like to know if the global variable %%GLOBAL_UPC%% (UPC/EAN) can be changed dynamically as the SKU variable does too.

The UPC fields appears inside of Options &SKU tab from backend. But only display the first value when i display  %%GLOBAL_UPC%% in product page.

Exist some javascript or method to show the others values when changing options??

Remember that im talking about UPC (Not SKU) using the blueprint theme.

答: It cannot be changed dynamically like the SKU. There is only a single UPC value per parent product in the BigCommerce data model. </p>


问:
Is there an efficient way to round string that has double value inside and get answer as double?
So my question is a bit confusing but still. I get an array of 8 strings from outside source that all contain doubles values inside. Those values are usually in 4 decimal places:

12345.5678

What I would like to do is to convert it to 3 decimal places as well as round it up and have the result on the output:

12345.568

Here is the code example:

```<code>private double[] parseDouble(String[] values) {
    double[] output = new double[values.length];
    for (int i = 0; i < values.length; i++) {
        output[i] = Double.parseDouble(String.format("%.3f",
        Double.parseDouble(values[i]));
    }
    return output;
}
</code>```

So my questions are:

1.Is there any better way than that? Because parsing to double 2 times is pretty redundant in my opinion.

2.Will it anyhow affect the performance if a number of values in the string array is around 100-1000?

Thanks in advance!

答:
For the sanity of the answer I can suggest this but you dont need to declare the array result

```<code>private double[] parseDouble(String[] values) {
    double[] result = Arrays.stream(values).mapToDouble(Double::parseDouble).toArray();
    return result;
}
</code>```

now that will only parse the strings into doubles...

for how they look like you need a formatter:

```<code>DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
double[] x = { 12345.5678, Math.PI, 123.123451, Math.E };
Arrays.stream(x).forEach(n -> System.out.println(df.format(n)));
</code>```

I suggest to combine those 2 approaches and remember a double is a double no matter how many decimal places is getting printed.

Body:
So my question is a bit confusing but still. I get an array of 8 strings from outside source that all contain doubles values inside. Those values are usually in 4 decimal places:

12345.5678

What I would like to do is to convert it to 3 decimal places as well as round it up and have the result on the output:

12345.568

Here is the code example:

private double[] parseDouble(String[] values) {
    double[] output = new double[values.length];
    for (int i = 0; i < values.length; i++) {
        output[i] = Double.parseDouble(String.format("%.3f",
        Double.parseDouble(values[i]));
    }
    return output;
}

So my questions are:

1.Is there any better way than that? Because parsing to double 2 times is pretty redundant in my opinion.

2.Will it anyhow affect the performance if a number of values in the string array is around 100-1000?

Thanks in advance!

Body:
For the sanity of the answer I can suggest this but you dont need to declare the array result

private double[] parseDouble(String[] values) {
    double[] result = Arrays.stream(values).mapToDouble(Double::parseDouble).toArray();
    return result;
}

now that will only parse the strings into doubles...

for how they look like you need a formatter:

DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
double[] x = { 12345.5678, Math.PI, 123.123451, Math.E };
Arrays.stream(x).forEach(n -> System.out.println(df.format(n)));

I suggest to combine those 2 approaches and remember a double is a double no matter how many decimal places is getting printed.


问:
How to distinguish logical or parameters in a cucumber step?
Let say I have the following step definition header for Ruby 2.3:

```<code>When (/^I update user group "([^"]*)" with (groups|users)?$/) do |group_name, type, params|
</code>```

How do I use the "type" variable to distinguish between the case of using groups or users? What is the type of "type"?

答:
in cucumber all the parameters are String, so you must to convert them with reflexion to the type you want.

When Cucumber matches a Step against a pattern in a Step Definition,
  it passes the value of all the capture groups to the Step Definition's
  arguments.

Capture groups are strings (even when they match digits like \d+). For
  statically typed languages, Cucumber will automatically transform
  those strings into the appropriate type. For dynamically typed
  languages, no transformation happens by default, as there is no type
  information.

reference https://cucumber.io/docs/reference

Body:
Let say I have the following step definition header for Ruby 2.3:

When (/^I update user group "([^"]*)" with (groups|users)?$/) do |group_name, type, params|

How do I use the "type" variable to distinguish between the case of using groups or users? What is the type of "type"?


Title: taking minimum and maximum date and time in R data.table group by

Body:
I have a data.table dt which looks like:

>dt <- data.table(grp = c(1,1,1,1,1, 2,2,2,2,2,3,3,3,3,3),
                 date = c("2017-04-24", "2017-04-25", "2017-04-26", "2017-04-27","2017-04-28",
                          "2017-05-11", "2017-05-11", "2017-05-13", "2017-05-14","2017-05-15",
                          "2017-06-16", "2017-06-17", "2017-06-18", "2017-06-20", "2017-06-20"),
                 time = c(1817, 1902, 1704, 1404, 1152, 1344, 1455, 1235, 0844, 0744, 1439,1346, 1525,1211, 1333))
>dt
    grp       date time
 1:   1 2017-04-24 1817
 2:   1 2017-04-25 1902
 3:   1 2017-04-26 1704
 4:   1 2017-04-27 1404
 5:   1 2017-04-28 1152
 6:   2 2017-05-11 1344
 7:   2 2017-05-11 1455
 8:   2 2017-05-13 1235
 9:   2 2017-05-14  844
10:   2 2017-05-15  744
11:   3 2017-06-16 1439
12:   3 2017-06-17 1346
13:   3 2017-06-18 1525
14:   3 2017-06-20 1211
15:   3 2017-06-20 1333

I wanted to find the minimum and maximum date and time for each of the group "grp".

In order to find minimum and maximum date I did:

dt[,"min_date" := min(date), by=c("grp")]
dt[,"max_date" := max(date), by=c("grp")]

I need to calculate the minimum and and maximum time too by each group "grp". the minimum time is the time associated with the record with minimum date, and maximum time is the time associate with the record with maximum date.

If my there is repetition of maximum date and minimum date in the records then the time associated with the final maximum record must be taken for max time and time associated with first minimum record should be taken for minimum time.

My final outcome should look like:

> dt
    grp       date time   min_date   max_date min_time max_time
 1:   1 2017-04-24 1817 2017-04-24 2017-04-28     1817     1152
 2:   1 2017-04-25 1902 2017-04-24 2017-04-28     1817     1152
 3:   1 2017-04-26 1704 2017-04-24 2017-04-28     1817     1152
 4:   1 2017-04-27 1404 2017-04-24 2017-04-28     1817     1152
 5:   1 2017-04-28 1152 2017-04-24 2017-04-28     1817     1152
 6:   2 2017-05-11 1344 2017-05-11 2017-05-15     1344      744
 7:   2 2017-05-11 1455 2017-05-11 2017-05-15     1344      744
 8:   2 2017-05-13 1235 2017-05-11 2017-05-15     1344      744
 9:   2 2017-05-14  844 2017-05-11 2017-05-15     1344      744
10:   2 2017-05-15  744 2017-05-11 2017-05-15     1344      744
11:   3 2017-06-16 1439 2017-06-16 2017-06-20     1439     1333
12:   3 2017-06-17 1346 2017-06-16 2017-06-20     1439     1333
13:   3 2017-06-18 1525 2017-06-16 2017-06-20     1439     1333
14:   3 2017-06-20 1211 2017-06-16 2017-06-20     1439     1333
15:   3 2017-06-20 1333 2017-06-16 2017-06-20     1439     1333

How can I do this in R in data.table

Body:
This should work:

dt[,"min_time" := min(time[which(min_date==date)]), by=grp]
dt[,"max_time" := max(time[which(max_date==date)]), by=grp]
dt
        grp       date time   min_date   max_date min_time max_time
 1:   1 2017-04-24 1817 2017-04-24 2017-04-28     1817     1152
 2:   1 2017-04-25 1902 2017-04-24 2017-04-28     1817     1152
 3:   1 2017-04-26 1704 2017-04-24 2017-04-28     1817     1152
 4:   1 2017-04-27 1404 2017-04-24 2017-04-28     1817     1152
 5:   1 2017-04-28 1152 2017-04-24 2017-04-28     1817     1152
 6:   2 2017-05-11 1344 2017-05-11 2017-05-15     1344      744
 7:   2 2017-05-11 1455 2017-05-11 2017-05-15     1344      744
 8:   2 2017-05-13 1235 2017-05-11 2017-05-15     1344      744
 9:   2 2017-05-14  844 2017-05-11 2017-05-15     1344      744
10:   2 2017-05-15  744 2017-05-11 2017-05-15     1344      744
11:   3 2017-06-16 1439 2017-06-16 2017-06-20     1439     1333
12:   3 2017-06-17 1346 2017-06-16 2017-06-20     1439     1333
13:   3 2017-06-18 1525 2017-06-16 2017-06-20     1439     1333
14:   3 2017-06-20 1211 2017-06-16 2017-06-20     1439     1333
15:   3 2017-06-20 1333 2017-06-16 2017-06-20     1439     1333

Or in one line:

dt[, `:=`(min_time = min(time[which(min_date==date)]), max_time = max(time[which(max_date==date)])), by=grp]


问:
Elegantly handle different parameter types
I have a function that, in the simplest of cases, operates on an iterable of items.

```<code>def foo(items):
    for item in items:
        # do stuff
</code>```

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

```<code>def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above
</code>```

I can merge these two cases like this:

```<code>def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff
</code>```

This works just fine. Now I get a third use case that looks like this:

```<code>def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again
</code>```

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?

答:
Must agree with Chris: the magic understand-everything input is going to turn around and bite you. If you pass it an iterable of objects-with-iterables of iterables, how do you specify at what level to actually start processing data?

Far better to stick with "either a list or a generator" as input, then pre-process your calls to the function.

Body:
I have a function that, in the simplest of cases, operates on an iterable of items.

def foo(items):
    for item in items:
        # do stuff

Sometimes, I do not want to pass it an iterable of items directly, but rather an object that provides a method to get the iterable:

def foo(obj):
    for item in obj.iteritems():
        # do same stuff as above

I can merge these two cases like this:

def foo(obj):
    try:
        items = obj.iteritems()
    except ValueError:
        items = obj
    for item in items:
        # do stuff

This works just fine. Now I get a third use case that looks like this:

def foo(objs):
    for item in itertools.chain.from_iterable(obj.iteritems() for obj in objs):
        # do same stuff again

I can still use the try-except approach, since the interfaces are incompatible. However, the nested try catch would start to become very ugly. More so when I want to add a fourth use-case. Is there any way to solve this without nesting the try-blocks?