答:
You have to separate in two function, and think the first one will return the complete check for each value of the other:

```<code>def check_sequence(lis):
  ret = True
  for row in lis:
    ret = ret and check_rows(row)
  return ret

def check_rows(row):
  ret = True
  for elem in row:
    pass #do your checking
  return ret
</code>```

a concrete example could be:

```<code>l = [[1,2,3],[1,2],[1,4,5,6,7]]
def check_sequence(lis):
  ret = True
  for row in lis:
    ret = ret and check_rows(row)
  return ret

def check_rows(row):
  return 1 in row #ask if 1 belongs to the list

check_sequence(l) ---> True
check_sequence([[1],[2,3]]) ---> False
</code>```

Title: How to run a function for each row in a nested list?

Body:
You have to separate in two function, and think the first one will return the complete check for each value of the other:

def check_sequence(lis):
  ret = True
  for row in lis:
    ret = ret and check_rows(row)
  return ret

def check_rows(row):
  ret = True
  for elem in row:
    pass #do your checking
  return ret

a concrete example could be:

l = [[1,2,3],[1,2],[1,4,5,6,7]]
def check_sequence(lis):
  ret = True
  for row in lis:
    ret = ret and check_rows(row)
  return ret

def check_rows(row):
  return 1 in row #ask if 1 belongs to the list

check_sequence(l) ---> True
check_sequence([[1],[2,3]]) ---> False


来源: stackexchange

问:
How to fix broken Ruby commenting in TextMate?
Whenever I open a Ruby file in TextMate 2, although it is correctly recognized, the syntax coloring and the commenting are both screwed up.  Instead of command/ putting a # at the beginning of all selected lines, I get them wrapped in /* and */, as though I was working in JavaScript.

I can live with the broken syntax coloring, but the commenting is driving me crazy, so I want to focus on fixing that in this question (although I won't turn down any solutions that fix both or ignore solutions to the syntax highlighting problem).  I suspect they have the same root cause, so I mention the syntax highlighting in case it provides a valuable clue.

Apparently others have had a similar problem with commenting CSS in TextMate (2) mentioned in "Textmate "comment" command not working properly for css code", but the fixes there didn't help me. There's "TextMate toggle comment macro is broken" as well, but that has very different symptoms.

TextMate was using my system Ruby (2.0.0 on OS X 10.10), in case that's relevant, but I switched it to using 2.2.3 through rbenv and the problem remains.

答: I started having the exact same problem, and I just recently installed this Crystal bundle the other day. I deleted the bundle and it fixed the problem. I also submitted an issue for that bundle, so, hopefully it gets fixed soon!

ContentLicense: CC BY-SA 3.0


问:
Replace HTML Comment along with string variable
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.

I am having trouble getting the regex to work.

Here is an html line I am working on:

```<code><td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
</code>```

Now, here is the javascript/jquery that I have at the moment:

```<code>var thisval = $(this).val();  //gets replacement text from a text box
var thistoken = "firstname";

currentTemplate = $("#gentextCodeArea").text();  //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate);   //put the new text back
</code>```

I think I'm pretty close, but I don't have the regex right yet.

The regex ought to replace the firstname with whatever is entered in the textbox for $thisval  (method is attached to keyup procedure on textbox).

答:
$(function(){
  function onKeyUp(event)
  {
    if(event.which === 38)  // if key press was the up key
    {
      $('.firstname_placeholder').text($(this).val());
    }
  }

  $('#firstname_input').keyup(onKeyUp);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=text]{width:200px}</code>```

<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>

    Harrison Ford

```

Body:
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.

I am having trouble getting the regex to work.

Here is an html line I am working on:

Harrison Ford

Now, here is the javascript/jquery that I have at the moment:

var thisval = $(this).val();  //gets replacement text from a text box
var thistoken = "firstname";

currentTemplate = $("#gentextCodeArea").text();  //fetch the text
var tokenstring = ""
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate);   //put the new text back

I think I'm pretty close, but I don't have the regex right yet.

The regex ought to replace the firstname with whatever is entered in the textbox for $thisval  (method is attached to keyup procedure on textbox).

Body:
$(function(){
  function onKeyUp(event)
  {
    if(event.which === 38)  // if key press was the up key
    {
      $('.firstname_placeholder').text($(this).val());
    }
  }

  $('#firstname_input').keyup(onKeyUp);
});

input[type=text]{width:200px}

<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
  <tr>
    <td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
  </tr>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


问:
two way communication through channels in golang
I have several functions that I want them to be executed atomically since they deal with sensitive data structures. Suppose the following scenario:
There are two functions: lock(sth) and unlock(sth) that can be called anytime by a goroutine to lock or unlock sth in a global array. I was thinking about having a command channel so that goroutines send lock and unlock commands into the channel, and on the receive side of the channel, some kind of handler handles lock, unlock requests, sequentially, by grabbing commands from the channel. That's fine, but what if the handler wants to send the result back to the requester? Is it possible to do so use golang channels? I know that it is possible to use some kind of lock mechanism like mutex, but I was wondering if it's possible to use channels for such use-case? I saw somewhere that it is recommended to use channel instead of goland low-level lock structs.

In a single sentence:

In a channel with the capacity of 1, I want the receiver side to be able to reply back to the goroutine which sent the message.

or equivalently:

A goroutine sends something to a channel; the message is received by another goroutine and handled leading to some result; how does the sender become aware of the result?

答:
The sync package includes a Mutex lock, sync.Mutex, which can be locked and unlocked from any goroutine in a threadsafe way. Instead of using a channel to send a command to lock something, how about just using a mutex lock from the sender?

```<code>mutex := new(sync.Mutex)
sensitiveData := make([]string, 0)
// when someone wants to operate on a sensitiveData,
// ...
mutex.Lock()
operate(sensitiveData)
mutex.Unlock()
</code>```

When you say how does the sender become aware of the result, I think you're talking about how does the handler receive the result -- that would be with a chan. You can send data through channels.

Alternatively, if you just want to be aware, a semaphore, sync.WaitGroup might do the job. This struct can be Add()ed to, and then the sender can wg.Wait() until the handler calls wg.Done(), which will indicate to the sender (which is waiting) that the handler is done doing such and such.

If your question is about whether to use locks or channels, the wiki has a terse answer:

A common Go newbie mistake is to over-use channels and goroutines just because it's possible, and/or because it's fun. Don't be afraid to use a sync.Mutex if that fits your problem best. Go is pragmatic in letting you use the tools that solve your problem best and not forcing you into one style of code.

As a general guide, though:

Channel: passing ownership of data, distributing units of work, communicating async results

Mutex: caches, state

If you absolutely want to avoid anything but chans :), try not altering the sensitive array to begin with. Rather, use channels to send data to different goroutines, at each step processing the data, and then funneling the processed data into a final type goroutine. That is, avoid using an array at all and store the data in chans.

As the motto goes,

Do not communicate by sharing memory; instead, share memory by communicating.

Body:
The sync package includes a Mutex lock, sync.Mutex, which can be locked and unlocked from any goroutine in a threadsafe way. Instead of using a channel to send a command to lock something, how about just using a mutex lock from the sender?

mutex := new(sync.Mutex)
sensitiveData := make([]string, 0)
// when someone wants to operate on a sensitiveData,
// ...
mutex.Lock()
operate(sensitiveData)
mutex.Unlock()

When you say how does the sender become aware of the result, I think you're talking about how does the handler receive the result -- that would be with a chan. You can send data through channels.

Alternatively, if you just want to be aware, a semaphore, sync.WaitGroup might do the job. This struct can be Add()ed to, and then the sender can wg.Wait() until the handler calls wg.Done(), which will indicate to the sender (which is waiting) that the handler is done doing such and such.

If your question is about whether to use locks or channels, the wiki has a terse answer:

A common Go newbie mistake is to over-use channels and goroutines just because it's possible, and/or because it's fun. Don't be afraid to use a sync.Mutex if that fits your problem best. Go is pragmatic in letting you use the tools that solve your problem best and not forcing you into one style of code.

As a general guide, though:

Channel: passing ownership of data, distributing units of work, communicating async results

Mutex: caches, state

If you absolutely want to avoid anything but chans :), try not altering the sensitive array to begin with. Rather, use channels to send data to different goroutines, at each step processing the data, and then funneling the processed data into a final type goroutine. That is, avoid using an array at all and store the data in chans.

As the motto goes,

Do not communicate by sharing memory; instead, share memory by communicating.


问:
Trying to put DQL query into Highcharts array, returns 0 despite array being populated
Here is the var_dump for my query in my code:

```<code>array (size=2)
  0 =>
    array (size=4)
  0 =>
    array (size=1)
      'barbell_curl_1_weight' => int 15
  1 =>
    array (size=1)
      'barbell_curl_1_weight' => int 20
  2 =>
    array (size=1)
      'barbell_curl_1_weight' => int 25
  3 =>
    array (size=1)
      'barbell_curl_1_weight' => int 20
</code>```

Here's my query:

```<code>/**
 * @param User $user
 * @param String $col
 * @return array
 */
public function getStatsForStatsByDQL(User $user,  String $col)
{

    $parameters = (array('user' => $user,
    ));
    $em2 = $this->getDoctrine()->getManager()
        ->getRepository('AppBundle:ExerciseStats')
        ->createQueryBuilder('g')
        ->setParameters($parameters)
        ->where('g.user = :user')
        ->select('g.'. $col)
        ->setMaxResults(12)
        ->join('g.user', 'user')
        ->orderBy( 'g.'. 'timestamp','ASC')
        ->getQuery()->getResult(Query::HYDRATE_ARRAY);
    return $em2;
  }
</code>```

As you see from the var_dump, I'm getting the data I need back. Here's the  Highcharts function it goes in:

```<code>/**
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route ("user/stats", name="user_stats")
 */
public function chartAction()
{
    $user = $this->getUser();
    // Chart
    $query = $this->getStatsForStatsByDQL($user,
ExerciseConsts::BARBELL_CURL_1_WEIGHT);

    $series = array($query, array("name" => "weight", "data" =>
$query));

    $ob = new Highchart();
    $ob->chart->renderTo('linechart');
    $ob->title->text('Barbell Curl Weight');
    $ob->xAxis->title(array('text'  => "Workouts"));
    $ob->yAxis->title(array('text'  => "Weight"));
    $ob->series($series);

    return $this->render('user/stats.html.twig', array(
        'chart' => $ob
    ));
}
</code>```

So all I'm getting back is 0. When using breakpoints in xdebug, I get back this:

```<code>1 = {array} [2]
  name = "weight"
  data = {array} [4]
  0 = {array} [1]
    barbell_curl_1_weight = 15
  1 = {array} [1]
    barbell_curl_1_weight = 20
  2 = {array} [1]
    barbell_curl_1_weight = 25
  3 = {array} [1]
    barbell_curl_1_weight = 20
</code>```

How do I extract the weights and get it into the Highchart graph? Documentation for the Highcharts Bundle is completely lacking in this regard. Let me know if anyone has any clues. Thanks!

Here's the var_dump of json_encode($series, JSON_NUMERIC_CHECK). Maybe this will help:

string '[[{"barbell_curl_1_weight":15},{"barbell_curl_1_weight":20},{"barbell_curl_1_weight":25},{"barbell_curl_1_weight":20}],{"name":"weight","data":[{"barbell_curl_1_weight":15},{"barbell_curl_1_weight":20},{"barbell_curl_1_weight":25},{"barbell_curl_1_weight":20}]}]' (length=266)

答:
I found the solution. As we are dealing with a multi-dimensional array, Highcharts is not drilling down beyond the first array, which returns 0. Here's my iteration to return the values of each array: </p>

```<code> $temp = array();
    foreach($array as $k=>$v){
        if(is_array($v)){
            foreach($v as $key=>$value){
                $temp[] = $value;
            }
        }
    }
</code>```

<p>So now, I just need to replace   $temp with $query and voila', the chart is rendered with all values correctly. </p>

Body:
Here is the var_dump for my query in my code:

array (size=2)
  0 =>
    array (size=4)
  0 =>
    array (size=1)
      'barbell_curl_1_weight' => int 15
  1 =>
    array (size=1)
      'barbell_curl_1_weight' => int 20
  2 =>
    array (size=1)
      'barbell_curl_1_weight' => int 25
  3 =>
    array (size=1)
      'barbell_curl_1_weight' => int 20

Here's my query:

/**
 * @param User $user
 * @param String $col
 * @return array
 */
public function getStatsForStatsByDQL(User $user,  String $col)
{

    $parameters = (array('user' => $user,
    ));
    $em2 = $this->getDoctrine()->getManager()
        ->getRepository('AppBundle:ExerciseStats')
        ->createQueryBuilder('g')
        ->setParameters($parameters)
        ->where('g.user = :user')
        ->select('g.'. $col)
        ->setMaxResults(12)
        ->join('g.user', 'user')
        ->orderBy( 'g.'. 'timestamp','ASC')
        ->getQuery()->getResult(Query::HYDRATE_ARRAY);
    return $em2;
  }

As you see from the var_dump, I'm getting the data I need back. Here's the  Highcharts function it goes in:

/**
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route ("user/stats", name="user_stats")
 */
public function chartAction()
{
    $user = $this->getUser();
    // Chart
    $query = $this->getStatsForStatsByDQL($user,
ExerciseConsts::BARBELL_CURL_1_WEIGHT);

    $series = array($query, array("name" => "weight", "data" =>
$query));

    $ob = new Highchart();
    $ob->chart->renderTo('linechart');
    $ob->title->text('Barbell Curl Weight');
    $ob->xAxis->title(array('text'  => "Workouts"));
    $ob->yAxis->title(array('text'  => "Weight"));
    $ob->series($series);

    return $this->render('user/stats.html.twig', array(
        'chart' => $ob
    ));
}

So all I'm getting back is 0. When using breakpoints in xdebug, I get back this:

1 = {array} [2]
  name = "weight"
  data = {array} [4]
  0 = {array} [1]
    barbell_curl_1_weight = 15
  1 = {array} [1]
    barbell_curl_1_weight = 20
  2 = {array} [1]
    barbell_curl_1_weight = 25
  3 = {array} [1]
    barbell_curl_1_weight = 20

How do I extract the weights and get it into the Highchart graph? Documentation for the Highcharts Bundle is completely lacking in this regard. Let me know if anyone has any clues. Thanks!

Here's the var_dump of json_encode($series, JSON_NUMERIC_CHECK). Maybe this will help:

string '[[{"barbell_curl_1_weight":15},{"barbell_curl_1_weight":20},{"barbell_curl_1_weight":25},{"barbell_curl_1_weight":20}],{"name":"weight","data":[{"barbell_curl_1_weight":15},{"barbell_curl_1_weight":20},{"barbell_curl_1_weight":25},{"barbell_curl_1_weight":20}]}]' (length=266)

Body:
I found the solution. As we are dealing with a multi-dimensional array, Highcharts is not drilling down beyond the first array, which returns 0. Here's my iteration to return the values of each array:

 $temp = array();
    foreach($array as $k=>$v){
        if(is_array($v)){
            foreach($v as $key=>$value){
                $temp[] = $value;
            }
        }
    }

So now, I just need to replace   $temp with $query and voila', the chart is rendered with all values correctly.


问:
Username authentication instead of email
With Firebase I can sign up and login users using email addresses. However what if I want the app to be username based. For example, you would log in with "Bobzilla" instead of "Bob@mail.com"?

Is this possible with Firebase?

答:
You can use firebase custom auth. Custom auth is a method which user can login into app using custom token.

But, you need backend code, to create custom token when user send username and password to that backend.

Fortunately, now there is firebase cloud function, with http event, that can solve your problem easily. The step is :

User send username and password to cloud function url via query params (GET) or request body (POST)

Cloud funtion will check whether username and password is valid (ex: from realtime database)

If the username and password valid, cloud function will create custom token using userId (you need to save the userId). And then send it to response body

Client then can login using that customToken


问:
Does the order of functions in a Python script matter?
Let's say I have two functions in my script: sum_numbers and print_sum. Their implementation is like this:

```<code>def sum_numbers(a, b):
    return a + b

def print_sum(a, b):
    print(sum_numbers(a, b))
</code>```

So my question is: does the order in which the function are written matter? If I had written the print_sum function first and then the sum_numbers, would the code still work? If the answer is yes, does it always work?

答:
The only thing that Python cares about is that the name is defined when it is actually looked up. That's all.

In your case, this is just fine, order doesn't really matter since you are just defining two functions. That is, you are just introducing two new names, no look-ups.

Now, if you called one of these (in effect, performed a look-up) and switched the order around:

```<code>def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(2, 4)

def sum_numbers(a, b):
    return a + b
</code>```

you'd be in trouble (NameError) because it will try to find a name (sum_numbers) that just doesn't exist yet.

So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript).

Body:
Let's say I have two functions in my script: sum_numbers and print_sum. Their implementation is like this:

def sum_numbers(a, b):
    return a + b

def print_sum(a, b):
    print(sum_numbers(a, b))

So my question is: does the order in which the function are written matter? If I had written the print_sum function first and then the sum_numbers, would the code still work? If the answer is yes, does it always work?

Body:
The only thing that Python cares about is that the name is defined when it is actually looked up. That's all.

In your case, this is just fine, order doesn't really matter since you are just defining two functions. That is, you are just introducing two new names, no look-ups.

Now, if you called one of these (in effect, performed a look-up) and switched the order around:

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(2, 4)

def sum_numbers(a, b):
    return a + b

you'd be in trouble (NameError) because it will try to find a name (sum_numbers) that just doesn't exist yet.

So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript).


问:
Chat server for Rails
As it is evident that AJAX based chats do not scale, so what would you use for chats? Custom servers? Or any other methods?

Since with Rails each chat connection will take lots of memory, it won't be feasible to even have Rails run for each message. What do you recommend for use here?

答: Unfortunately your post is based on a false premise. AJAX based chat certainly can scale, you just have to do it the right way. Juggernaut 2, for example, uses Node.js to handle many concurrent connections. You're right, you won't be able to handle 10,000 connections on a single server. That's what load balancing is for.</p>

ContentLicense: CC BY-SA 4.0

Title: Chat server for Rails

ContentLicense: CC BY-SA 2.5


问:
Gulp lint takes too much time
I have a problem with the linting and live reloading in my gulp file. They take to much time to finish.

Here is my gulp file, what do I do wrong :

```<code>    'use strict';

console.time("Loading plugins"); //start measuring

var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");

var config = {
    port: 8001,
    devBaseUrl: 'http://localhost',
    paths: {
        html: "./src/*.html",
        externals: "./src/assets/externals/*.js",
        js: "./src/**/*.js",
        images: './src/assets/images/**/*',
        fonts: './src/assets/css/fonts/*',
        css: [
            "./src/assets/css/*",
        ],
        sass: './src/assets/css/*.scss',
        dist: "./dist",
        mainJS: "./src/main.js"
    }
};

gulp.task('connect', ['watch'], function () {
    connect.server({
        root: ['dist'],
        port: config.port,
        base: config.devBaseUrl,
        livereload: true,
        fallback: './dist/index.html'
    })
});

gulp.task('open', ['connect'], function () {
    gulp.src('dist/index.html')
        .pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});

gulp.task('html', function () {
    gulp.src(config.paths.html)
        .pipe(gulp.dest(config.paths.dist))
        .pipe(connect.reload());
});

gulp.task('externals', function () {
    gulp.src(config.paths.externals)
        .on('error', console.error.bind(console))
        .pipe(concat('external.js'))
        .pipe(gulp.dest(config.paths.dist + '/externals'))
        .pipe(connect.reload());
});

gulp.task('js', function () {
    browserify(config.paths.mainJS)
        .transform('babelify', {presets: ['es2015', 'react']})
        .bundle()
        .on('error', console.error.bind(console))
        .pipe(source('bundle.js'))
        .pipe(gulp.dest(config.paths.dist + '/scripts'))
        .pipe(connect.reload());
});

gulp.task('images', function () {
    gulp.src(config.paths.images)
        .pipe(gulp.dest(config.paths.dist + '/images'));
});

gulp.task('styles', function () {
    gulp.src(config.paths.css)
        .pipe(sass())
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest(config.paths.dist + '/css'))
        .pipe(connect.reload());

});

gulp.task('fonts', function () {
    gulp.src(config.paths.fonts)
        .pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});

gulp.task('lint', function () {
    return gulp.src(config.paths.js)
        .pipe(lint())
        .pipe(lint.format());
});

gulp.task('watch', function () {
    gulp.watch(config.paths.js, ['js', 'lint']);
    gulp.watch(config.paths.css, ['styles']);
});

console.timeEnd('Loading plugins');

gulp.task('default', ['js', 'styles', 'lint', 'open', 'watch']);
</code>```

The lint takes almost 20s to finish and liverolading takes 5-6s to refresh the browser after I make some changes.

Any advice?

答:
We've recently come across the same issue on my team. The best workaround was to run ESLint only on the modified files, instead of all js files.

We use nodemon to watch for changed files, though gulp-watch has the same idea.

See the change event on gulp-watch.

Then you'd just run a lint function on the changed file.
You may need to resolve the relative file path.

```<code>gulp.watch(config.paths.js, ['js'])
    .on('change', lintFile);

const lintFile = (file) => {
  return gulp.src(file)
             .pipe(eslint());
};
</code>```

Title: Gulp lint takes too much time

Body:
I have a problem with the linting and live reloading in my gulp file. They take to much time to finish.

Here is my gulp file, what do I do wrong :

    'use strict';

console.time("Loading plugins"); //start measuring

var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");

var config = {
    port: 8001,
    devBaseUrl: 'http://localhost',
    paths: {
        html: "./src/*.html",
        externals: "./src/assets/externals/*.js",
        js: "./src/**/*.js",
        images: './src/assets/images/**/*',
        fonts: './src/assets/css/fonts/*',
        css: [
            "./src/assets/css/*",
        ],
        sass: './src/assets/css/*.scss',
        dist: "./dist",
        mainJS: "./src/main.js"
    }
};

gulp.task('connect', ['watch'], function () {
    connect.server({
        root: ['dist'],
        port: config.port,
        base: config.devBaseUrl,
        livereload: true,
        fallback: './dist/index.html'
    })
});

gulp.task('open', ['connect'], function () {
    gulp.src('dist/index.html')
        .pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});

gulp.task('html', function () {
    gulp.src(config.paths.html)
        .pipe(gulp.dest(config.paths.dist))
        .pipe(connect.reload());
});

gulp.task('externals', function () {
    gulp.src(config.paths.externals)
        .on('error', console.error.bind(console))
        .pipe(concat('external.js'))
        .pipe(gulp.dest(config.paths.dist + '/externals'))
        .pipe(connect.reload());
});

gulp.task('js', function () {
    browserify(config.paths.mainJS)
        .transform('babelify', {presets: ['es2015', 'react']})
        .bundle()
        .on('error', console.error.bind(console))
        .pipe(source('bundle.js'))
        .pipe(gulp.dest(config.paths.dist + '/scripts'))
        .pipe(connect.reload());
});

gulp.task('images', function () {
    gulp.src(config.paths.images)
        .pipe(gulp.dest(config.paths.dist + '/images'));
});

gulp.task('styles', function () {
    gulp.src(config.paths.css)
        .pipe(sass())
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest(config.paths.dist + '/css'))
        .pipe(connect.reload());

});

gulp.task('fonts', function () {
    gulp.src(config.paths.fonts)
        .pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});

gulp.task('lint', function () {
    return gulp.src(config.paths.js)
        .pipe(lint())
        .pipe(lint.format());
});

gulp.task('watch', function () {
    gulp.watch(config.paths.js, ['js', 'lint']);
    gulp.watch(config.paths.css, ['styles']);
});

console.timeEnd('Loading plugins');

gulp.task('default', ['js', 'styles', 'lint', 'open', 'watch']);

The lint takes almost 20s to finish and liverolading takes 5-6s to refresh the browser after I make some changes.

Any advice?

Body:
We've recently come across the same issue on my team. The best workaround was to run ESLint only on the modified files, instead of all js files.

We use nodemon to watch for changed files, though gulp-watch has the same idea.

See the change event on gulp-watch.

Then you'd just run a lint function on the changed file.
You may need to resolve the relative file path.

gulp.watch(config.paths.js, ['js'])
    .on('change', lintFile);

const lintFile = (file) => {
  return gulp.src(file)
             .pipe(eslint());
};


问:
jsonapi-resources—overriding fields
There's a field in my resource that I want to set to 1 if it's nil in the model. I have the following code, but the resource is still producing minimum_approvers: nil

Any ideas on what's going on?

```<code>module V1
  class EntityResource < BaseResource
    model_hint model: Entity

    attribute :logo
    attribute :minimum_approvers

    def minimum_approvers
      @model.minimum_approvers.nil? ? 1 : @model.minimum_approvers
    end
</code>```

答: If the method you want to call has the same name as the model's attribute, you can't override it. The best you can do is make a method in the model that does the logic, then call the method in your resource.</p>

Title: jsonapi-resources—overriding fields

Body:
There's a field in my resource that I want to set to 1 if it's nil in the model. I have the following code, but the resource is still producing minimum_approvers: nil

Any ideas on what's going on?

module V1
  class EntityResource < BaseResource
    model_hint model: Entity

    attribute :logo
    attribute :minimum_approvers

    def minimum_approvers
      @model.minimum_approvers.nil? ? 1 : @model.minimum_approvers
    end


问:
Conditionally Applying class with ternary operator
I've got a Button component that I'd like to assign an active class to if the state is 'true'. </p>

```<code><Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>
</code>```

答:
You need the false expression in there:</p>

```<code>className={"col-sm-12 text-center " + (this.state.straight ? "active" : "") }
</code>```

Body:
I've got a Button component that I'd like to assign an active class to if the state is 'true'.

<Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>

Straight

</Button>

Body:
You need the false expression in there:

className={"col-sm-12 text-center " + (this.state.straight ? "active" : "") }


问:
SearchView filter for Recyclerview inside fragment
Hello friends.

I have navigation drawer with a menu item when clicking on each menu nav item, one fragment loaded, inside this fragments, I have recycled view items. Now I want use searchView filter for this items. I created a searchView icon in the toolbar, and write codes for  SearchView inside Adapter(setFilter) and etc, but nothing happen when writing names item.

this is my fragment.

AfricaFragment`

```<code>public class AfricaFragment extends Fragment implements SearchView.OnQueryTextListener {

public static final String AFRICA_FRAGMENT = "africa_fragment";

ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
//FastScroller fastScroller;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    //The parameter value of false indicates that container is to be used
    // only for the layout parameters.
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.africa_fragment, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    // fastScroller = (FastScroller) view.findViewById(R.id.fast_scrollview);

    isListView = true;

    loadDataBase();

    return view;

}

public void toggle() {
    MenuItem item = menu.findItem(R.id.grid);
    if (isListView) {
        staggeredGridLayoutManager.setSpanCount(2);
        item.setIcon(R.drawable.ic_vertical);
        item.setTitle("Show as list");
        isListView = false;
    } else {
        staggeredGridLayoutManager.setSpanCount(1);
        item.setIcon(R.drawable.ic_grid);
        item.setTitle("Show grid");
        isListView = true;
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.grid_item, menu);
    this.menu = menu;
    Log.d("Menu created", "grid");
    final MenuItem menuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView)
    MenuItemCompat.getActionView(menuItem);
    searchView.setOnQueryTextListener(this);

    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.grid) {
        Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
        toggle();
        return true;
    }
    if (id == R.id.settings) {
        Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
        return true;
    }

    if (id == R.id.search) {

        return true;
    }

    return onOptionsItemSelected(item);
}

public void loadDataBase() {
    WorldCountry worldCountry = new WorldCountry(getActivity());
    try {

        worldCountry.createDatabase();
        worldCountry.openDataBase();
        Log.d("TAG", "Database open");
    } catch (SQLiteException o) {
        o.printStackTrace();
        Log.d("Tag", o.getMessage());
    }
    try {

        Cursor cursor = worldCountry.QueryData("SELECT name, viewImage   FROM country WHERE continent ='آفریقا'");
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {

                    AsiaCountry asiaCountry = new AsiaCountry();
                    asiaCountry.setName(cursor.getString(0));
                    asiaCountry.setImageResourceID(cursor.getString(1));
                    asiaCountries.add(asiaCountry);
                } while (cursor.moveToNext());
                worldCountry.close();

            }

        }
    } catch (SQLiteException o) {
        o.printStackTrace();
        Log.d("TAG", o.getMessage());
    }
    staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
    contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
    contentAdapter.notifyDataSetChanged();
    contentAdapter.setListener(new ContentAdapter.Listener() {
        @Override
        public void onClick(int position) {

        }
    });

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(staggeredGridLayoutManager);
    recyclerView.setAdapter(contentAdapter);

}

@Override
public boolean onQueryTextSubmit(String query) {
    if (contentAdapter != null) {

        query = String.valueOf(query.equals(""));
    }
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    newText = newText.toLowerCase();
    ArrayList<AsiaCountry> asiaCountryArrayList = new ArrayList<>();
    for (AsiaCountry asiaCountry : asiaCountries) {

        String name = asiaCountry.getName().toLowerCase();
        if (name.contains(newText))

            asiaCountryArrayList.add(asiaCountry);
    }

    contentAdapter.setFilter(asiaCountryArrayList);
    return true;
}
</code>```

}

this my adapter.

ContentAdapter

```<code>public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {

public Context context;
private List<AsiaCountry> item = Collections.emptyList();
private int mLastPosition = -1;
private Listener listener;

public ContentAdapter(Context context, List<AsiaCountry> item) {
    this.context = context;
    this.item = item;

}

public void setListener(Listener listener) {
    this.listener = listener;
}

@Override
public ContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
    //Defain the view for take layout
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
            parent, false);
    Log.d("Adapter", "Loaded");
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    AsiaCountry asia = item.get(position);

    holder.titleNameCountry.setText(asia.getName());
    Log.d("TAG", asia.getName());
    //  String imageFile = asia.getImageResourceID();

    holder.titleImageCountry.setImageBitmap(loadBitmapFromAssets(context, asia.getImageResourceID()));

   /* Glide.with(context)
            .load(loadBitmapFromAssets(context, asia.getImageResourceID()))
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                    holder.titleImageCountry.setImageBitmap(resource);

                }
            });*/

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onClick(position);

                Toast.makeText(context, holder.titleNameCountry.getText().toString() + "is clicked",
                        Toast.LENGTH_LONG).show();

                String nameCountry = holder.titleNameCountry.getText().toString();

                Intent intent = new Intent(context, DetialsCountry.class);
                intent.putExtra("name", nameCountry);
                Log.d("CONT", nameCountry);

                context.startActivity(intent);
            }
        }
    });

    // When items loading, must be show in animation, for UX better.
    if (position > mLastPosition) {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(holder.itemView, "translationY",
                        holder.itemView.getMeasuredHeight() * 2, 0));
        ObjectAnimator.ofFloat(holder.itemView, "alpha", 0, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleX", 0.5f, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleY", 0.5f, 1);

        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();

        mLastPosition = position;
    } else {

        ViewHolder.clear(holder.itemView);
    }

  /*  Bitmap photo = BitmapFactory.decodeResource(context.getResources(), asia.getImageResourceID(context));

    Palette.from(photo).generate(new Palette.PaletteAsyncListener() {
        @Override
        public void onGenerated(Palette palette) {
            int bgColor = palette.getDarkMutedColor(ContextCompat.getColor(context, android.R.color.black));
            holder.titleNameCountry.setBackgroundColor(bgColor);

        }
    });*/

   /* Bitmap photo = BitmapFactory.decodeResource(context.getResources(), country.getTitleCountry(context));

    Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
        public void onGenerated(Palette palette) {
            int mutedLight = palette.getMutedColor(context.getResources().getColor(android.R.color.black));
            holder.titleNameCountry.setBackgroundColor(mutedLight);
        }
    });*/

}

@Override
public int getItemCount() {
    return item.size();
}

//This method take getAssets from assets folder and compare with cursor.getString(1), and show in recyclerview.
@Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
    InputStream stream = null;
    try {
        stream = context.getAssets().open(path);
        return BitmapFactory.decodeStream(stream);

    } catch (Exception ignored) {
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (Exception ignored) {
        }
    }
    return null;
}

public void setFilter(ArrayList<AsiaCountry> arrayList) {

    arrayList = new ArrayList<>();
    item.addAll(arrayList);
    notifyDataSetChanged();
}

public static interface Listener {
    public void onClick(int position);
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    private ImageView titleImageCountry;
    private TextView titleNameCountry;

    // Defian the viewHolder
    private ViewHolder(View itemView) {
        super(itemView);

        titleImageCountry = (ImageView) itemView.findViewById(R.id.imageHolder);
        titleNameCountry = (TextView) itemView.findViewById(R.id.titleCountry);
    }

    // public static class ViewHolder {
    private static void clear(View itemView) {
        ViewCompat.setAlpha(itemView, 1);
        ViewCompat.setTranslationY(itemView, 0);
        itemView.setPivotY(itemView.getMeasuredHeight() / 2);
        ViewCompat.setScaleX(itemView, 1);
        ViewCompat.setScaleY(itemView, 1);
        ViewCompat.animate(itemView).setInterpolator(null);
        Log.d("Animationg", "Loaded");

    }
}
</code>```

}

Please help me :)

答:
In your setFilter in Adapter method, you are again creating object for the parameter you sent, So remove that and made the global item as empty

```<code>public void setFilter(ArrayList<AsiaCountry> arrayList) {

    //arrayList = new ArrayList<>(); // remove this line
    item.clear(); // add this so that it will clear old data
    item.addAll(arrayList);
    notifyDataSetChanged();
}
</code>```

To reset the text we should handle in 2 place one is when user press ok, it will call onQueryTextSubmit, second way is user click back arrow at the top, So we should handle both,

```<code>                @Override
                public boolean onQueryTextSubmit(String query) {
//                    Log.d(TAG, "onQueryTextSubmit() called with: query = [" + query + "]");

                    if (mAdapter != null)
                        // reset your complete list here

                    return true;
                }
</code>```

Second place is,

```<code>            MenuItemCompat.setOnActionExpandListener(mSearchItem,
                    new MenuItemCompat.OnActionExpandListener() {
                        @Override
                        public boolean onMenuItemActionExpand(MenuItem menuItem) {
//                            Log.d(TAG, "onMenuItemActionExpand() called with: menuItem = [" + menuItem + "]");
                            return true;
                        }

                        @Override
                        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
//                            Log.d(TAG, "onMenuItemActionCollapse() called with: menuItem = [" + menuItem + "]");
                           // update your list with complete list
                            return true;
                        }
                    });
</code>```

Body:
Hello friends.

I have navigation drawer with a menu item when clicking on each menu nav item, one fragment loaded, inside this fragments, I have recycled view items. Now I want use searchView filter for this items. I created a searchView icon in the toolbar, and write codes for  SearchView inside Adapter(setFilter) and etc, but nothing happen when writing names item.

this is my fragment.

AfricaFragment`

public class AfricaFragment extends Fragment implements SearchView.OnQueryTextListener {

public static final String AFRICA_FRAGMENT = "africa_fragment";

ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
//FastScroller fastScroller;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    //The parameter value of false indicates that container is to be used
    // only for the layout parameters.
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.africa_fragment, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    // fastScroller = (FastScroller) view.findViewById(R.id.fast_scrollview);

    isListView = true;

    loadDataBase();

    return view;

}

public void toggle() {
    MenuItem item = menu.findItem(R.id.grid);
    if (isListView) {
        staggeredGridLayoutManager.setSpanCount(2);
        item.setIcon(R.drawable.ic_vertical);
        item.setTitle("Show as list");
        isListView = false;
    } else {
        staggeredGridLayoutManager.setSpanCount(1);
        item.setIcon(R.drawable.ic_grid);
        item.setTitle("Show grid");
        isListView = true;
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.grid_item, menu);
    this.menu = menu;
    Log.d("Menu created", "grid");
    final MenuItem menuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView)
    MenuItemCompat.getActionView(menuItem);
    searchView.setOnQueryTextListener(this);

    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.grid) {
        Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
        toggle();
        return true;
    }
    if (id == R.id.settings) {
        Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
        return true;
    }

    if (id == R.id.search) {

        return true;
    }

    return onOptionsItemSelected(item);
}

public void loadDataBase() {
    WorldCountry worldCountry = new WorldCountry(getActivity());
    try {

        worldCountry.createDatabase();
        worldCountry.openDataBase();
        Log.d("TAG", "Database open");
    } catch (SQLiteException o) {
        o.printStackTrace();
        Log.d("Tag", o.getMessage());
    }
    try {

        Cursor cursor = worldCountry.QueryData("SELECT name, viewImage   FROM country WHERE continent ='آفریقا'");
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {

                    AsiaCountry asiaCountry = new AsiaCountry();
                    asiaCountry.setName(cursor.getString(0));
                    asiaCountry.setImageResourceID(cursor.getString(1));
                    asiaCountries.add(asiaCountry);
                } while (cursor.moveToNext());
                worldCountry.close();

            }

        }
    } catch (SQLiteException o) {
        o.printStackTrace();
        Log.d("TAG", o.getMessage());
    }
    staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
    contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
    contentAdapter.notifyDataSetChanged();
    contentAdapter.setListener(new ContentAdapter.Listener() {
        @Override
        public void onClick(int position) {

        }
    });

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(staggeredGridLayoutManager);
    recyclerView.setAdapter(contentAdapter);

}

@Override
public boolean onQueryTextSubmit(String query) {
    if (contentAdapter != null) {

        query = String.valueOf(query.equals(""));
    }
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    newText = newText.toLowerCase();
    ArrayList<AsiaCountry> asiaCountryArrayList = new ArrayList<>();
    for (AsiaCountry asiaCountry : asiaCountries) {

        String name = asiaCountry.getName().toLowerCase();
        if (name.contains(newText))

            asiaCountryArrayList.add(asiaCountry);
    }

    contentAdapter.setFilter(asiaCountryArrayList);
    return true;
}

}

this my adapter.

ContentAdapter

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {

public Context context;
private List<AsiaCountry> item = Collections.emptyList();
private int mLastPosition = -1;
private Listener listener;

public ContentAdapter(Context context, List<AsiaCountry> item) {
    this.context = context;
    this.item = item;

}

public void setListener(Listener listener) {
    this.listener = listener;
}

@Override
public ContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
    //Defain the view for take layout
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
            parent, false);
    Log.d("Adapter", "Loaded");
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    AsiaCountry asia = item.get(position);

    holder.titleNameCountry.setText(asia.getName());
    Log.d("TAG", asia.getName());
    //  String imageFile = asia.getImageResourceID();

    holder.titleImageCountry.setImageBitmap(loadBitmapFromAssets(context, asia.getImageResourceID()));

   /* Glide.with(context)
            .load(loadBitmapFromAssets(context, asia.getImageResourceID()))
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                    holder.titleImageCountry.setImageBitmap(resource);

                }
            });*/

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onClick(position);

                Toast.makeText(context, holder.titleNameCountry.getText().toString() + "is clicked",
                        Toast.LENGTH_LONG).show();

                String nameCountry = holder.titleNameCountry.getText().toString();

                Intent intent = new Intent(context, DetialsCountry.class);
                intent.putExtra("name", nameCountry);
                Log.d("CONT", nameCountry);

                context.startActivity(intent);
            }
        }
    });

    // When items loading, must be show in animation, for UX better.
    if (position > mLastPosition) {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(holder.itemView, "translationY",
                        holder.itemView.getMeasuredHeight() * 2, 0));
        ObjectAnimator.ofFloat(holder.itemView, "alpha", 0, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleX", 0.5f, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleY", 0.5f, 1);

        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();

        mLastPosition = position;
    } else {

        ViewHolder.clear(holder.itemView);
    }

  /*  Bitmap photo = BitmapFactory.decodeResource(context.getResources(), asia.getImageResourceID(context));

    Palette.from(photo).generate(new Palette.PaletteAsyncListener() {
        @Override
        public void onGenerated(Palette palette) {
            int bgColor = palette.getDarkMutedColor(ContextCompat.getColor(context, android.R.color.black));
            holder.titleNameCountry.setBackgroundColor(bgColor);

        }
    });*/

   /* Bitmap photo = BitmapFactory.decodeResource(context.getResources(), country.getTitleCountry(context));

    Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
        public void onGenerated(Palette palette) {
            int mutedLight = palette.getMutedColor(context.getResources().getColor(android.R.color.black));
            holder.titleNameCountry.setBackgroundColor(mutedLight);
        }
    });*/

}

@Override
public int getItemCount() {
    return item.size();
}

//This method take getAssets from assets folder and compare with cursor.getString(1), and show in recyclerview.
@Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
    InputStream stream = null;
    try {
        stream = context.getAssets().open(path);
        return BitmapFactory.decodeStream(stream);

    } catch (Exception ignored) {
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (Exception ignored) {
        }
    }
    return null;
}

public void setFilter(ArrayList<AsiaCountry> arrayList) {

    arrayList = new ArrayList<>();
    item.addAll(arrayList);
    notifyDataSetChanged();
}

public static interface Listener {
    public void onClick(int position);
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    private ImageView titleImageCountry;
    private TextView titleNameCountry;

    // Defian the viewHolder
    private ViewHolder(View itemView) {
        super(itemView);

        titleImageCountry = (ImageView) itemView.findViewById(R.id.imageHolder);
        titleNameCountry = (TextView) itemView.findViewById(R.id.titleCountry);
    }

    // public static class ViewHolder {
    private static void clear(View itemView) {
        ViewCompat.setAlpha(itemView, 1);
        ViewCompat.setTranslationY(itemView, 0);
        itemView.setPivotY(itemView.getMeasuredHeight() / 2);
        ViewCompat.setScaleX(itemView, 1);
        ViewCompat.setScaleY(itemView, 1);
        ViewCompat.animate(itemView).setInterpolator(null);
        Log.d("Animationg", "Loaded");

    }
}

}

Please help me :)

Body:
In your setFilter in Adapter method, you are again creating object for the parameter you sent, So remove that and made the global item as empty

public void setFilter(ArrayList<AsiaCountry> arrayList) {

    //arrayList = new ArrayList<>(); // remove this line
    item.clear(); // add this so that it will clear old data
    item.addAll(arrayList);
    notifyDataSetChanged();
}

To reset the text we should handle in 2 place one is when user press ok, it will call onQueryTextSubmit, second way is user click back arrow at the top, So we should handle both,

                @Override
                public boolean onQueryTextSubmit(String query) {
//                    Log.d(TAG, "onQueryTextSubmit() called with: query = [" + query + "]");

                    if (mAdapter != null)
                        // reset your complete list here

                    return true;
                }

Second place is,

            MenuItemCompat.setOnActionExpandListener(mSearchItem,
                    new MenuItemCompat.OnActionExpandListener() {
                        @Override
                        public boolean onMenuItemActionExpand(MenuItem menuItem) {
//                            Log.d(TAG, "onMenuItemActionExpand() called with: menuItem = [" + menuItem + "]");
                            return true;
                        }

                        @Override
                        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
//                            Log.d(TAG, "onMenuItemActionCollapse() called with: menuItem = [" + menuItem + "]");
                           // update your list with complete list
                            return true;
                        }
                    });


问:
How to compare variable from js and twig
I need to check statement of two variables one comes from my server and I access this from TWIG, second, comes from javascript (data table column value). I need to check like this

```<code>{% if key.orderid == 19 %}
</code>```

Where 19 should be replaced with js variable.

Code for research:

```<code>// format function for row details
var fnFormatDetails = function( datatable, tr ) {
var data = datatable.fnGetData( tr );
            return [
                    '<table class="table mb-none">',
                    '<tr class="b-top-none">',
                    '<td><label class="mb-none">Produkt:</label></td>',
                    '<td>Ilość:</td>',
                    '</tr>',
                    '{% for index, key in orderProducts %}{% if key.orderid == 19 %}<tr class="b-top-none">',
                    '<td><label class="mb-none">{{ index }}</label></td>',
                    '<td>{{ key.productid }}   {{ key.amount }}</td>',
                    '</tr>{% endif %}{% endfor %}',
                    '</table>'
                ].join('');
};
</code>```

答:
you can does that</p>

```<code><script>var test = {{ valueToGet }};<script>
</code>```

Body:
I need to check statement of two variables one comes from my server and I access this from TWIG, second, comes from javascript (data table column value). I need to check like this

{% if key.orderid == 19 %}

Where 19 should be replaced with js variable.

Code for research:

// format function for row details
var fnFormatDetails = function( datatable, tr ) {
var data = datatable.fnGetData( tr );
            return [
                    '
',
                    '
',
                    'Produkt:	',
                    'Ilość:	',
                    '
',
                    '{% for index, key in orderProducts %}{% if key.orderid == 19 %}
',
                    '{{ index }}	',
                    '{{ key.productid }}   {{ key.amount }}	',
                    '
{% endif %}{% endfor %}',
                    '
'
                ].join('');
};

Body:
you can does that

<script>var test = {{ valueToGet }};<script>


问:
Update float array from C++ native plugin
I am seeing a pretty bizarre issue while trying to pass an array from C++ to C#. I am using Marshal.Copy (specifically: https://msdn.microsoft.com/en-us/library/a53bd6cz(v=vs.110).aspx).

Problem: float array from C++ to C# is yielding a few NaN's in the resulting array.
(Note: I am working in the context of the Unity game engine)

Code

Example C++ code:

```<code>extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
        std::vector<float> results;
        std::vector<SOME_TYPE> key_points = <SOME_POINTS>

        for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
            results.push_back(static_cast<float>(iter->pt.x));
            results.push_back(static_cast<float>(iter->pt.y));
        }

        *points = results.data();
        *count = results.size();

        //<Print results to csv here>

        return true;
}
</code>```

Example C# code:

```<code>[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

private static float[] getFloatArrayFromNative() {
        IntPtr ptrResultItems = IntPtr.Zero;
        int resultItemsLength = 0;
        bool success = getSomeFloats (ref ptrResultItems, ref resultItemsLength);
        float[] resultItems = null;
        if (success) {
            // Load the results into a managed array.
            resultItems = new float[resultItemsLength];
            Marshal.Copy (ptrResultItems
                , resultItems
                , 0
                , resultItemsLength);

            // <PRINT out resultItems to csv here>

            return resultItems;
        } else {
            Debug.Log ("Something went wrong getting some floats");
            return new float[] { -1, -2 };
        }
    }
</code>```

Example Ouput:
Take the following example:
C++ output (print_out.csv):

123, 456, 789

C# output (print_out_cs.csv):

123, NaN, 789

I'm completely stumped on this one. I just don't understand why only some (roughly 7/100) floats are returning NaN. Does anyone have any advice/insight that might help?

Thanks!

答: The pointer you return in getSomeFloats is owned by results.  Before getSomeFloats returns, the vector destructor for results will free that memory.  When the C# code tries to use the pointer, you are accessing unallocated memory, which results in Undefined Behavior.  In your case most of the data hasn't been changed yet, but some of it has.  Potentially any or all of the data could have been changed (if the memory has been reused), or even a program crash (if the freed memory has been returned to the OS).

Body:
I am seeing a pretty bizarre issue while trying to pass an array from C++ to C#. I am using Marshal.Copy (specifically: https://msdn.microsoft.com/en-us/library/a53bd6cz(v=vs.110).aspx).

Problem: float array from C++ to C# is yielding a few NaN's in the resulting array.
(Note: I am working in the context of the Unity game engine)

Code

Example C++ code:

extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
        std::vector<float> results;
        std::vector<SOME_TYPE> key_points = <SOME_POINTS>

        for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
            results.push_back(static_cast<float>(iter->pt.x));
            results.push_back(static_cast<float>(iter->pt.y));
        }

        *points = results.data();
        *count = results.size();

        //<Print results to csv here>

        return true;
}

Example C# code:

[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

private static float[] getFloatArrayFromNative() {
        IntPtr ptrResultItems = IntPtr.Zero;
        int resultItemsLength = 0;
        bool success = getSomeFloats (ref ptrResultItems, ref resultItemsLength);
        float[] resultItems = null;
        if (success) {
            // Load the results into a managed array.
            resultItems = new float[resultItemsLength];
            Marshal.Copy (ptrResultItems
                , resultItems
                , 0
                , resultItemsLength);

            // <PRINT out resultItems to csv here>

            return resultItems;
        } else {
            Debug.Log ("Something went wrong getting some floats");
            return new float[] { -1, -2 };
        }
    }

Example Ouput:
Take the following example:
C++ output (print_out.csv):

123, 456, 789

C# output (print_out_cs.csv):

123, NaN, 789

I'm completely stumped on this one. I just don't understand why only some (roughly 7/100) floats are returning NaN. Does anyone have any advice/insight that might help?

Thanks!


问:
Read-Only ADO.NET Connection String for Excel
I'm trying to prevent the following from coming up when reading an Excel file using ADO.NET:

The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data.

I know it is happening because another user has the file open, but I can't get rid of it.  I've tried adding Read Only=True; to my connection string, but that doesn't work.  I've also tried to set the Mode of the connection to read-only, but I can't figure out how to in C#.

Here is my connection string:

```<code>Provider=Microsoft.Jet.OLEDB.4.0; data source=test.xls; Extended Properties="Excel 8.0;HDR=No;IMEX=1"
</code>```

Thanks for the help!

答:
This can also come up if you don't have permissions for the file, not just when it's exclusively open. In any event, I always found the best workaround for this problem was to automate a copy of the file to a new temp file. Copies are almost instantaneous, even for large files, so they shouldn't slow you down much, and since your application is only read-only, you don't have to worry about discarding the temp file afterwards.

Furthermore, this will clear up any permissions issues that can be cleared up. If you have read permissions, the copy will work, if not, then there's no workaround anyways. You will have full permissions for the copied file if you make the destination path of the temp copy the same path as the workbook. (Application.Path)

Use the FileCopy srcFile, destName command for this.

Body:
I'm trying to prevent the following from coming up when reading an Excel file using ADO.NET:

The Microsoft Jet database engine cannot open the file ''.  It is already opened exclusively by another user, or you need permission to view its data.

I know it is happening because another user has the file open, but I can't get rid of it.  I've tried adding Read Only=True; to my connection string, but that doesn't work.  I've also tried to set the Mode of the connection to read-only, but I can't figure out how to in C#.

Here is my connection string:

Provider=Microsoft.Jet.OLEDB.4.0; data source=test.xls; Extended Properties="Excel 8.0;HDR=No;IMEX=1"

Thanks for the help!


问:
Powershell & Regex - How to find and delete uppercase characters from file names in directory
I need a Powershell script that will find and replace uppercase characters within all the filenames within a directory with nothing.

The script would do something like this:

Filename BEFORE: CAPITAL-letters.jpg

Filename AFTER: -letters.jpg

Edit: I tried running this script, but it didn't work

```<code>dir | rename-item -NewName {$_.name -replace [Regex]::Escape("[A-Z"),""}
</code>```

答:
since this got answers, for full clarity:

Remove -WhatIf when you're running it.

```<code>Get-ChildItem | Rename-Item -NewName {$_.Name -creplace "[A-Z]"} -WhatIf
</code>```

This pipes Get-ChildItem into Rename-Item and then Sets the NewName to be the old name, except we've case-sensitively replaced any capital letters with nothing.

Body:
I need a Powershell script that will find and replace uppercase characters within all the filenames within a directory with nothing.

The script would do something like this:

Filename BEFORE: CAPITAL-letters.jpg

Filename AFTER: -letters.jpg

Edit: I tried running this script, but it didn't work

dir | rename-item -NewName {$_.name -replace [Regex]::Escape("[A-Z"),""}

Body:
since this got answers, for full clarity:

Remove -WhatIf when you're running it.

Get-ChildItem | Rename-Item -NewName {$_.Name -creplace "[A-Z]"} -WhatIf

This pipes Get-ChildItem into Rename-Item and then Sets the NewName to be the old name, except we've case-sensitively replaced any capital letters with nothing.


问:
How difficult would it be to add a generic code-gen backend to Julia?
How difficult would it be to add a generic code-gen backend to Julia in the vein of go and chez-schemei.e. without the LLVM.

Would LLVM be a better way to do it - given that rust and crystal are also almost entirely self hosted and they can leverage the LLVM to emit binaries, even cross compile.

For a background, I've asked a question specifically about code-gen in case of various LLVM front-ends here What are the issues faced while implementing a self-hosted language on LLVM?

答:
rustc links and uses LLVM, both via the LLVM C API and via an extended wrapper in C++, exposed as a C ABI. I don't know about crystal, but some languages do target textual or bytecode LLVM IR directly, which has some potential advantages, but also performance and compatibility issues.

As far as "how difficult": NaN, I guess? The most straightforward approach would be to start with Julia's type-inferred lowered form, which is already close to SSA. Someone with a good compiler background could probably write an un-optimized (spilling, no code motion, etc.), one-architecture template assembler in a short time (~months). Someone with no compiler background would probably need a fair amount of study to properly formulate the question.


问:
Google Script reading from json object
I am reading a json object such as this:

```<code>var url = "not really important"
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var data = JSON.parse(json);
var var seeds = data.entities.seeds;
</code>```

Now the seeds have the values, ton of them so I know that all my code works up until this point. Now my problem is parsing a certain piece of the information that I need. In this specific case I need to get the name of each entrant. Each seed has a 1:1 ratio with an entrant and as such I have to naviagte this API to get it.

If I run the following code Logger.log(seeds[0].mutations.entrants); I will get the following output:

{745803={isPlaceholder=null, name=My Team Name, participantIds=[827364, 827540, 827994], initialSeedNum=1, id=745803, playerIds={827364=179632, 827540=139681, 827994=268019}}}

As you can see the name is under object called 745803. My problem is that that object name changes and I have no idea what it is for each seed. As such, I need to grab the very first result that is listed under entrants as it will always be the entrant that I need. How can I do this?  I tried the following but it just comes back as undefined:

seeds[0].mutations.entrants[0].name

Bottom line is, how do I get the first element in the json based object without knowing the name of that element?

答:
You can retrieve JSON keys using "for in". In this case, you can retrieve it even if the keys are changed. Although I don't know the detailed information of your JSON structure, from your question, following 2 patterns are thought.

Pattern 1 :

```<code>var json1 = {
  "entrants": {
    "745803": {
      "isPlaceholder": null,
      "name": "My Team Name",
      "participantIds": [
        827364,
        827540,
        827994
      ],
      "initialSeedNum": 1,
      "id": 745803,
      "playerIds": {
        "827364": 179632,
        "827540": 139681,
        "827994": 268019
      }
    }
  }
};
for (var i in json1.entrants){
  Logger.log(json1.entrants[i].name)
}

>>> My Team Name
</code>```

Pattern 2 :

```<code>var json2 = {
  "entrants": [
    {
      "745803": {
        "isPlaceholder": null,
        "name": "My Team Name",
        "participantIds": [
          827364,
          827540,
          827994
        ],
        "initialSeedNum": 1,
        "id": 745803,
        "playerIds": {
          "827364": 179632,
          "827540": 139681,
          "827994": 268019
        }
      }
    }
  ]
};
for (var i in json2.entrants){
  for (var j in json2.entrants[i]){
    Logger.log(json2.entrants[i][j].name)
  }
}

>>> My Team Name
</code>```

If I misunderstand your question, I'm sorry.

Title: Google Script reading from json object

Body:
I am reading a json object such as this:

var url = "not really important"
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var data = JSON.parse(json);
var var seeds = data.entities.seeds;

Now the seeds have the values, ton of them so I know that all my code works up until this point. Now my problem is parsing a certain piece of the information that I need. In this specific case I need to get the name of each entrant. Each seed has a 1:1 ratio with an entrant and as such I have to naviagte this API to get it.

If I run the following code Logger.log(seeds[0].mutations.entrants); I will get the following output:

{745803={isPlaceholder=null, name=My Team Name, participantIds=[827364, 827540, 827994], initialSeedNum=1, id=745803, playerIds={827364=179632, 827540=139681, 827994=268019}}}

As you can see the name is under object called 745803. My problem is that that object name changes and I have no idea what it is for each seed. As such, I need to grab the very first result that is listed under entrants as it will always be the entrant that I need. How can I do this?  I tried the following but it just comes back as undefined:

seeds[0].mutations.entrants[0].name

Bottom line is, how do I get the first element in the json based object without knowing the name of that element?

Body:
You can retrieve JSON keys using "for in". In this case, you can retrieve it even if the keys are changed. Although I don't know the detailed information of your JSON structure, from your question, following 2 patterns are thought.

Pattern 1 :

var json1 = {
  "entrants": {
    "745803": {
      "isPlaceholder": null,
      "name": "My Team Name",
      "participantIds": [
        827364,
        827540,
        827994
      ],
      "initialSeedNum": 1,
      "id": 745803,
      "playerIds": {
        "827364": 179632,
        "827540": 139681,
        "827994": 268019
      }
    }
  }
};
for (var i in json1.entrants){
  Logger.log(json1.entrants[i].name)
}

>>> My Team Name

Pattern 2 :

var json2 = {
  "entrants": [
    {
      "745803": {
        "isPlaceholder": null,
        "name": "My Team Name",
        "participantIds": [
          827364,
          827540,
          827994
        ],
        "initialSeedNum": 1,
        "id": 745803,
        "playerIds": {
          "827364": 179632,
          "827540": 139681,
          "827994": 268019
        }
      }
    }
  ]
};
for (var i in json2.entrants){
  for (var j in json2.entrants[i]){
    Logger.log(json2.entrants[i][j].name)
  }
}

>>> My Team Name

If I misunderstand your question, I'm sorry.


问:
MVC DisplayTemplate does not display C# string variable
My main model, called Project, has two variables of type Address which is a class I defined. Since I wanted dynamic formatting of addresses based on which fields were defined. The code for my DisplayTemplate is:

```<code>@model ProjectClearanceApp.Models.Project.Address

@{
    string addr = "";
    if (!String.IsNullOrEmpty(Model.Line1))
    {
        addr += (Model.Line1 + "\n");
    }
    if (!String.IsNullOrEmpty(Model.Line2))
    {
        addr += (Model.Line2 + "\n");
    }
    if (!String.IsNullOrEmpty(Model.City))
    {
        addr += Model.City;
    }
    if (!String.IsNullOrEmpty(Model.State))
    {
        addr += (", " + Model.State);
    }
    if (Model.ZipCode != 0)
    {
        addr += (", " + Model.ZipCode);
    }
    Html.Raw(addr);
}
</code>```

The reason I'm using a string variable and appending to it is because I originally had my display template defined as:

```<code>@model ProjectClearanceApp.Models.Project.Address

@if (!String.IsNullOrEmpty(Model.Line1))
{
    @Html.DisplayFor(model => model.Line1)
    <br />
}
@if (!String.IsNullOrEmpty(Model.Line2))
{
    @Html.DisplayFor(model => model.Line2)
    <br />
}
@if (!String.IsNullOrEmpty(Model.City))
{
    @Html.DisplayFor(model => model.City)
}
@if (!String.IsNullOrEmpty(Model.State))
{
    @:, @Html.DisplayFor(model => model.State)
}
@if (Model.ZipCode != 0)
{
    @:, @Html.DisplayFor(model => model.ZipCode)
}
</code>```

but because the last three DisplayFor's are on separate lines (at least that's my thought, I could be wrong), the addresses would display as FakeCity , FakeState , 12345 with a space before each comma (if someone has a quick fix for that, that would solve all my problems).

However when I use the string it just does not display the variable at all on my page. I set a breakpoint on the last line (Html.Raw(addr);) and addr has the correct value when my code gets to that point in processing the addresses, but when it renders the page itself, nothing shows up. I've tried Html.Display(addr); and Html.DisplayText(addr); but still no luck.

答:
You need to add a leading @ to Html.Raw(). Without that your just executing the method, not returning its value and outputting the result it generates.

```<code>@model ProjectClearanceApp.Models.Project.Address
@{
    string addr = "";
    ....
    @Html.Raw(addr); // add leading `@`
}
</code>```

Body:
My main model, called Project, has two variables of type Address which is a class I defined. Since I wanted dynamic formatting of addresses based on which fields were defined. The code for my DisplayTemplate is:

@model ProjectClearanceApp.Models.Project.Address

@{
    string addr = "";
    if (!String.IsNullOrEmpty(Model.Line1))
    {
        addr += (Model.Line1 + "\n");
    }
    if (!String.IsNullOrEmpty(Model.Line2))
    {
        addr += (Model.Line2 + "\n");
    }
    if (!String.IsNullOrEmpty(Model.City))
    {
        addr += Model.City;
    }
    if (!String.IsNullOrEmpty(Model.State))
    {
        addr += (", " + Model.State);
    }
    if (Model.ZipCode != 0)
    {
        addr += (", " + Model.ZipCode);
    }
    Html.Raw(addr);
}

The reason I'm using a string variable and appending to it is because I originally had my display template defined as:

@model ProjectClearanceApp.Models.Project.Address

@if (!String.IsNullOrEmpty(Model.Line1))
{
    @Html.DisplayFor(model => model.Line1)

}
@if (!String.IsNullOrEmpty(Model.Line2))
{
    @Html.DisplayFor(model => model.Line2)

}
@if (!String.IsNullOrEmpty(Model.City))
{
    @Html.DisplayFor(model => model.City)
}
@if (!String.IsNullOrEmpty(Model.State))
{
    @:, @Html.DisplayFor(model => model.State)
}
@if (Model.ZipCode != 0)
{
    @:, @Html.DisplayFor(model => model.ZipCode)
}

but because the last three DisplayFor's are on separate lines (at least that's my thought, I could be wrong), the addresses would display as FakeCity , FakeState , 12345 with a space before each comma (if someone has a quick fix for that, that would solve all my problems).

However when I use the string it just does not display the variable at all on my page. I set a breakpoint on the last line (Html.Raw(addr);) and addr has the correct value when my code gets to that point in processing the addresses, but when it renders the page itself, nothing shows up. I've tried Html.Display(addr); and Html.DisplayText(addr); but still no luck.

Body:
You need to add a leading @ to Html.Raw(). Without that your just executing the method, not returning its value and outputting the result it generates.

@model ProjectClearanceApp.Models.Project.Address
@{
    string addr = "";
    ....
    @Html.Raw(addr); // add leading `@`
}


问:
How would someone connect their MLAB mongodb database to robomongo when MLAB only provides string URI's
I have been a mongochef user for a while, and setting up URI connections with mongochef is super easy. However this is not the case with robomongo.

How would someone connect their MLAB mongodb database to robobongo when MLAB uses string URI's to connect users to their databases?

in the configuration setup for robomongo it looks like it favors ip addresses and ports as the connection method and does not provide a URI format

答:
Connecting via Robomongo should just be a matter of extracting the relevant hostname and port from the MongoDB connection string URI.

For example, if the connection string were:

```<code>mongodb://r1.example.net:27017,r2.example.net:27017/testdb
</code>```

then the hostname could be r1.example.net or r2.example.net with a port value of 27017 and a database name of testdb.

Body:
Connecting via Robomongo should just be a matter of extracting the relevant hostname and port from the MongoDB connection string URI.

For example, if the connection string were:

mongodb://r1.example.net:27017,r2.example.net:27017/testdb

then the hostname could be r1.example.net or r2.example.net with a port value of 27017 and a database name of testdb.


答:
It doesn't matter in which order the functions are created. It only matters when the call to the function is done:

```<code>def print_sum(a, b):
    print(sum_numbers(a, b))

def sum_numbers(a, b):
    return a + b

print_sum(1, 3)
# 4
</code>```

that works because at the time print_sum is called both functions do exist. However if you call the function before defining sum_numbers it would fail because sum_numbers isn't defined yet:

```<code>def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b
</code>```

throws:

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3
----> 4 print_sum(1, 3)
      5
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3
      4 print_sum(1, 3)
      5

NameError: name 'sum_numbers' is not defined
</code>```

Title: Does the order of functions in a Python script matter?

Body:
Let's say I have two functions in my script: sum_numbers and print_sum. Their implementation is like this:

def sum_numbers(a, b):
    return a + b

def print_sum(a, b):
    print(sum_numbers(a, b))

So my question is: does the order in which the function are written matter? If I had written the print_sum function first and then the sum_numbers, would the code still work? If the answer is yes, does it always work?

Body:
It doesn't matter in which order the functions are created. It only matters when the call to the function is done:

def print_sum(a, b):
    print(sum_numbers(a, b))

def sum_numbers(a, b):
    return a + b

print_sum(1, 3)
# 4

that works because at the time print_sum is called both functions do exist. However if you call the function before defining sum_numbers it would fail because sum_numbers isn't defined yet:

def print_sum(a, b):
    print(sum_numbers(a, b))

print_sum(1, 3)

def sum_numbers(a, b):
    return a + b

throws:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-37c0e3733861> in <module>()
      2     print(sum_numbers(a, b))
      3
----> 4 print_sum(1, 3)
      5
      6 def sum_numbers(a, b):

<ipython-input-34-37c0e3733861> in print_sum(a, b)
      1 def print_sum(a, b):
----> 2     print(sum_numbers(a, b))
      3
      4 print_sum(1, 3)
      5

NameError: name 'sum_numbers' is not defined


问:
Why does this code not optimize for all three points?
Background

I am trying to fit a distribution to a 95% CI and mode.
The cost function that I am using solves three functions for 0: P(X=2.5 | mu, sigma)=0.025, P(X=7.5|mu, sigma)=0.975, and the mode of log-N(mu, sigma) = 3.3. note: mode of a lognormal is = $e^{\mu-\sigma^2)}$:

Approach

First I write a cost function, prior

```<code>prior <- function(parms) {
  a <- abs(plnorm(2.5, parms[1], parms[2]) - 0.025)
  b <- abs(plnorm(7.5, parms[1], parms[2]) - 0.975)
  mode <- exp(parms[1] - parms[2]^2)
  c <- abs(mode-3.3)
  return(a + b + c)
}
</code>```

And then I seek parameters that minimize the cost function

```<code>v = nlm(prior,c(log(3.3),0.14))
</code>```

It is apparent that the function is maximized for the mode an LCL but not the UCL.

```<code>abs(plnorm(7.5, parms[1], parms[2]) - 0.975)
> [1] 0.02499989
</code>```

Here is a plot with dotted lines at the desired 95%CI:

```<code>x <- seq(0,10,0.1)
plot(x,dlnorm(x, v$estimate[1],v$estimate[2]),type='l')
abline(v=c(2.5,7.5), lty=2) #95%CI
</code>```

Question

The optimization two points closely and all of the error is in the third. However, I would like it to fit the points evenly.

How can I get the function to give equal weight to the magnitude of the a, b, and c terms? It appears that the function is only fitting a and c.

note: This question is based on one asked at [cross validated][1] except that this version is specifically about the function of R's nlm() optimization algorithm whereas the CV question is about finding the a more appropriate distribution.

答:
The reason your optimization "does not work" is that the scale of the three parameters, a, b, and c does not match. a and b measure a difference in probabilities, and can always be set to be no larger then 0.025 by chosing a really small value for the standard deviation (parms[2]), since then plnorm(2.5, parms[1], parms[2]) will be 0 (same for 7.5). The same amount of error (0.025) would be unnoticable for c - this is the scaling mismatch.

You can rewrite your optimization function so that the errors are measured on the x scale for all three criteria by comparing the quantiles to 2.5 and 7.5:

```<code>prior2 <- function(parms) {
  a <- abs(qlnorm(0.025, parms[1], parms[2]) - 2.5)
  b <- abs(qlnorm(0.975, parms[1], parms[2]) - 7.5)
  mode <- exp(parms[1] - parms[2]^2)
  c <- abs(mode-3.3)
  return(a + b + c)
}
</code>```

This is similar to what Ramnath suggested, except not on the log scale. This approach does not really do well on the left tail because the distribution is skewed right: small changes in the location of the lower 2.5th percentile lead to large changes of the percentile at 2.5, while this is not the case at 7.5. Ramnath's suggestion of working on the log scale solves this problem, since the log-normal distriburion is symmetric on the log-scale.

Another way to improve your fit is to change the optimization criterion. Right now you are minimizing the average absolute error. This means that one large error is OK-ish as long as the other two error terms are really small. You can impose a bigger penalty on large errors by minimizing the mean squared error (a^2+b^2_c^2) instead. This latest version (on the log scale) produces the best-looking estimate from my point of view.

```<code>prior3 <- function(parms) {
  a <- abs(parms[1] - 1.96*parms[2] - log(2.5))
  b <- abs(parms[1] + 1.96*parms[2] - log(7.5))
  c <- abs(parms[1] - parms[2]^2 - log(3.3))
  return(a^2 + b^2 + c^2)
}
</code>```

Body:
Background

I am trying to fit a distribution to a 95% CI and mode.
The cost function that I am using solves three functions for 0: P(X=2.5 | mu, sigma)=0.025, P(X=7.5|mu, sigma)=0.975, and the mode of log-N(mu, sigma) = 3.3. note: mode of a lognormal is = $e^{\mu-\sigma^2)}$:

Approach

First I write a cost function, prior

prior <- function(parms) {
  a <- abs(plnorm(2.5, parms[1], parms[2]) - 0.025)
  b <- abs(plnorm(7.5, parms[1], parms[2]) - 0.975)
  mode <- exp(parms[1] - parms[2]^2)
  c <- abs(mode-3.3)
  return(a + b + c)
}

And then I seek parameters that minimize the cost function

v = nlm(prior,c(log(3.3),0.14))

It is apparent that the function is maximized for the mode an LCL but not the UCL.

abs(plnorm(7.5, parms[1], parms[2]) - 0.975)
> [1] 0.02499989

Here is a plot with dotted lines at the desired 95%CI:

x <- seq(0,10,0.1)
plot(x,dlnorm(x, v$estimate[1],v$estimate[2]),type='l')
abline(v=c(2.5,7.5), lty=2) #95%CI

Question

The optimization two points closely and all of the error is in the third. However, I would like it to fit the points evenly.

How can I get the function to give equal weight to the magnitude of the a, b, and c terms? It appears that the function is only fitting a and c.

note: This question is based on one asked at [cross validated][1] except that this version is specifically about the function of R's nlm() optimization algorithm whereas the CV question is about finding the a more appropriate distribution.

Body:
The reason your optimization "does not work" is that the scale of the three parameters, a, b, and c does not match. a and b measure a difference in probabilities, and can always be set to be no larger then 0.025 by chosing a really small value for the standard deviation (parms[2]), since then plnorm(2.5, parms[1], parms[2]) will be 0 (same for 7.5). The same amount of error (0.025) would be unnoticable for c - this is the scaling mismatch.

You can rewrite your optimization function so that the errors are measured on the x scale for all three criteria by comparing the quantiles to 2.5 and 7.5:

prior2 <- function(parms) {
  a <- abs(qlnorm(0.025, parms[1], parms[2]) - 2.5)
  b <- abs(qlnorm(0.975, parms[1], parms[2]) - 7.5)
  mode <- exp(parms[1] - parms[2]^2)
  c <- abs(mode-3.3)
  return(a + b + c)
}

This is similar to what Ramnath suggested, except not on the log scale. This approach does not really do well on the left tail because the distribution is skewed right: small changes in the location of the lower 2.5th percentile lead to large changes of the percentile at 2.5, while this is not the case at 7.5. Ramnath's suggestion of working on the log scale solves this problem, since the log-normal distriburion is symmetric on the log-scale.

Another way to improve your fit is to change the optimization criterion. Right now you are minimizing the average absolute error. This means that one large error is OK-ish as long as the other two error terms are really small. You can impose a bigger penalty on large errors by minimizing the mean squared error (a^2+b^2_c^2) instead. This latest version (on the log scale) produces the best-looking estimate from my point of view.

prior3 <- function(parms) {
  a <- abs(parms[1] - 1.96*parms[2] - log(2.5))
  b <- abs(parms[1] + 1.96*parms[2] - log(7.5))
  c <- abs(parms[1] - parms[2]^2 - log(3.3))
  return(a^2 + b^2 + c^2)
}


问:
React Native Clipboard - how to copy an image or anything other than text?
In React Native, with the Clipboard, how can I place an image in the Clipboard? The only method provided to set Clipboard content is "setString". Can you not set images or other content than strings?</p>

答:
It is possible to bridge native iOS clipboard API and expose the setImage method. To do that you need:

Add native module header file Clipboard.h:

#import "RCTBridgeModule.h"
@interface Clipboard : NSObject <RCTBridgeModule>
@end```
</div>
</div>
</p>

<ol start="2">
<li>Add native module implementation file <code>Clipboard.m</code>. We needed to copy base64 encoded images but you can adjust the code use any other image representation:</li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>#import <UIKit/UIKit.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "Clipboard.h"

@implementation Clipboard

RCT_EXPORT_MODULE(BetterClipboard); // this is how our native module will be named

RCT_EXPORT_METHOD(addBase64Image:(NSString *)base64Image) {
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  [pasteboard setPersistent:YES];

  NSData *imageData = [[NSData alloc]initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];

  [pasteboard setImage:[UIImage imageWithData:imageData]];
}

@end</code>```

And then you can use it in your React application:

import { NativeModules } from 'react-native';

NativeModules.BetterClipboard.addBase64Image(base64EncodedImage);```

Unfortunately, I don't know how to do the same for Android.

Body:
It is possible to bridge native iOS clipboard API and expose the setImage method. To do that you need:

Add native module header file Clipboard.h:

#import "RCTBridgeModule.h"
@interface Clipboard : NSObject <RCTBridgeModule>
@end

Add native module implementation file Clipboard.m. We needed to copy base64 encoded images but you can adjust the code use any other image representation:

#import <UIKit/UIKit.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "Clipboard.h"

@implementation Clipboard

RCT_EXPORT_MODULE(BetterClipboard); // this is how our native module will be named

RCT_EXPORT_METHOD(addBase64Image:(NSString *)base64Image) {
  UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  [pasteboard setPersistent:YES];

  NSData *imageData = [[NSData alloc]initWithBase64EncodedString:base64Image options:NSDataBase64DecodingIgnoreUnknownCharacters];

  [pasteboard setImage:[UIImage imageWithData:imageData]];
}

@end

And then you can use it in your React application:

import { NativeModules } from 'react-native';

NativeModules.BetterClipboard.addBase64Image(base64EncodedImage);

Unfortunately, I don't know how to do the same for Android.


问:
Consumer<T> mapped Class<T> in HashMap
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

```<code>private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();
</code>```

but it sucks because then I have to cast the object in the lamba when using it.

Example:

```<code>interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});
</code>```

What I would like to do is

```<code>private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();
</code>```

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

答:
It is possible to implement this in a type-safe manner without any unchecked cast. The solution resides in wrapping the Consumer<T> into a more general Consumer<Object> that casts and then delegates to the original consumer:

```<code>public class ClassToConsumerMap {
    private final Map<Class<?>, Consumer<Object>> map = new IdentityHashMap<>();

    public <T> Consumer<? super T> put(Class<T> key, Consumer<? super T> c) {
        return map.put(key, o -> c.accept(key.cast(o)));
    }

    public <T> Consumer<? super T> get(Class<T> key) {
        return map.get(key);
    }
}
</code>```

Depending on your needs, get() could also simply return a Consumer<Object>. This would be necessary if you only know the type at runtime, e.g.

```<code>classToConsumerMap.get(someObject.getClass()).accept(someObject);
</code>```

I am pretty sure I saw this solution (or something similar) in a talk @ Devoxx Belgium 2016, possibly from Venkat Subramaniam, but I definitively cannot find it back…

Title: Consumer<T> mapped Class<T> in HashMap

Body:
I want to create an IdentityHashMap<Class<T>, Consumer<T>>. Basically, I want to map a type with a method saying what to do with this type.

I want to dynamically be able to say with objects X, execute Y. I can do

private IdentityHashMap<Class<?>, Consumer<?>> interceptor = new IdentityHashMap<>();

but it sucks because then I have to cast the object in the lamba when using it.

Example:

interceptor.put(Train.class, train -> {
    System.out.println(((Train)train).getSpeed());
});

What I would like to do is

private <T> IdentityHashMap<Class<T>, Consumer<T>> interceptor = new IdentityHashMap<>();

But it doesn't seem to be allowed. Is there a way to do this ? What is the best workaround to map types with a method for this type ?

Body:
It is possible to implement this in a type-safe manner without any unchecked cast. The solution resides in wrapping the Consumer<T> into a more general Consumer<Object> that casts and then delegates to the original consumer:

public class ClassToConsumerMap {
    private final Map<Class<?>, Consumer<Object>> map = new IdentityHashMap<>();

    public <T> Consumer<? super T> put(Class<T> key, Consumer<? super T> c) {
        return map.put(key, o -> c.accept(key.cast(o)));
    }

    public <T> Consumer<? super T> get(Class<T> key) {
        return map.get(key);
    }
}

Depending on your needs, get() could also simply return a Consumer<Object>. This would be necessary if you only know the type at runtime, e.g.

classToConsumerMap.get(someObject.getClass()).accept(someObject);

I am pretty sure I saw this solution (or something similar) in a talk @ Devoxx Belgium 2016, possibly from Venkat Subramaniam, but I definitively cannot find it back…


问:
Git revert a commit and add changes even after more commits followed
My use case is very usual.

I added a commit, that went through my build system. Some post-commit tests on the build system failed. The system is configured to revert such a commit.

So the System also added a Reverting back revision my-commit.

Now, I added the fixes to correct the build. But someone else made 2 commits on top of the revert that went in successfully before I could push in mine.

So now my state is:

```<code>$ git log

commit good-commit1
author: good-dev1
...

commit good-commit2
author: good-dev1
...

commit good-revert-commit
author: system
...

commit my-bad-commit
author: me
...
</code>```

Both good-commit1 and good-commit2 change files which I modified in my-bad-commit.

How do I add my fixes on top of my-bad-commit, or revert the good-revert-commit and add fixes on it, and then re-apply the other dev's good commits?

Note: our system doesn't allow -f (force push) to the master branch.

答:
Just revert the revert with

```<code>git revert good-revert-commit -n
</code>```

-n is a synonym for --no-commit here.

So the changes will be in the index, then git add your additional changes, finish the commit and push.

Body:
My use case is very usual.

I added a commit, that went through my build system. Some post-commit tests on the build system failed. The system is configured to revert such a commit.

So the System also added a Reverting back revision my-commit.

Now, I added the fixes to correct the build. But someone else made 2 commits on top of the revert that went in successfully before I could push in mine.

So now my state is:

$ git log

commit good-commit1
author: good-dev1
...

commit good-commit2
author: good-dev1
...

commit good-revert-commit
author: system
...

commit my-bad-commit
author: me
...

Both good-commit1 and good-commit2 change files which I modified in my-bad-commit.

How do I add my fixes on top of my-bad-commit, or revert the good-revert-commit and add fixes on it, and then re-apply the other dev's good commits?

Note: our system doesn't allow -f (force push) to the master branch.

Body:
Just revert the revert with

git revert good-revert-commit -n

-n is a synonym for --no-commit here.

So the changes will be in the index, then git add your additional changes, finish the commit and push.