问:
Is there a way to split one item in a stream into multiple items?
Consider the following stream:

```<code>--'[a,b,c]'--
</code>```

The '[a,b,c]' is one item in the stream. Now I'm looking for a way to map that stream into this:

```<code>--'a'--'b'--'c'--
</code>```

I think at some point I need to use map since I only know how to split the array:

```<code>Observable.from(['[a,b,c]'])
    .map(i => {
        let arr = JSON.parse(i);
        //Somehow inject the arr items into the stream (instead of arr itself)
    })
    .subscribe(console.log);
</code>```

I wish to see three separate entries in the console with a, b and c.

答:
Just use mergeMap instead of map:

Rx.Observable
  .from(['["a", "b", "c"]'])
  .mergeMap(value => JSON.parse(value))
  .subscribe(value => console.log(value));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

mergeMap will flatten an array returned by the project function.

Body:
Consider the following stream:

--'[a,b,c]'--

The '[a,b,c]' is one item in the stream. Now I'm looking for a way to map that stream into this:

--'a'--'b'--'c'--

I think at some point I need to use map since I only know how to split the array:

Observable.from(['[a,b,c]'])
    .map(i => {
        let arr = JSON.parse(i);
        //Somehow inject the arr items into the stream (instead of arr itself)
    })
    .subscribe(console.log);

I wish to see three separate entries in the console with a, b and c.

Body:
Just use mergeMap instead of map:

Rx.Observable
  .from(['["a", "b", "c"]'])
  .mergeMap(value => JSON.parse(value))
  .subscribe(value => console.log(value));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

mergeMap will flatten an array returned by the project function.


来源: stackexchange

问:
How to use Header in Codeigniter
In the example above, we are using “dynamically added data”, which you will see below.

controller

```<code>public function index()
{

    $data['main_menus'] = '';
    if(count($this->menu_model->findActive()) > 0){
        $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
    }

    $data['header'] = $this->load->view('common/header',$data);

    $data['posts'] = $this->home_model->find_active(3);
    $data['content'] = $this->load->view('common/content',$data);

    $this->load->view('layout',$data);

}
</code>```

view

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="DBlog : Material Style Personal Blog Theme from Wowbootstrap">
    <meta name="author" content="wowbootstrap.com">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Merriweather:400,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,500,400italic,700,700italic,900,900italic,300,300italic,500italic" rel="stylesheet" type="text/css">
    <title><?php echo $page_title?> - CI Blog</title>
  </head>
  <body>
    <div id="wrapper">
      <?php echo $header;?>
      <section class="main">
        <div class="container">
          <div class="row">
            <div class="col-md-8">
            <?php //echo $content;?>
            </div>
            <div class="col-md-4">
            <?php //echo $right_sidebar;?>
            </div>
          </div>
        </div>
      </section>
      <?php //echo $footer;?>

    </div>

    <script>
      $.material.init();
    </script>

    <?php if(!empty($home_page)):?>
    <script type="text/javascript">

      $(window).scroll(function(){
        if ($(this).scrollTop() > 1){
          $('.top-navbar').removeClass('navbar-transparent');
        }else{
          $('.top-navbar').addClass('navbar-transparent');
        }
      });
    </script>
    <?php endif;?>

    <script type="text/javascript">
      $(document).ready(function () {
          $('[data-toggle="tooltip"]').tooltip();
      });
    </script>

</body>
</html>
</code>```

I am using codeigniter to develop php web site. Now I have the question.
In controller,$this->load->view('index', $data);
I want $data can also share in header.php that included in index.php.

How to do???

答:
If i do templating on codeigniter I do like this

In Layout.php

```<code><!--Header -->
<?php  $this->load->view('path/to/header'); ?>

<!--Content -->
<?php  $this->load->view($content); ?>

<!--Footer-->
<?php  $this->load->view('path/to/footer'); ?>
</code>```

In controller

```<code>$data['content'] = 'path/to/content/page'; # or any dynamic data with $this->model...

$this->load->view('template',$data);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use Header in Codeigniter

Body:
In the example above, we are using “dynamically added data”, which you will see below.

controller

public function index()
{

    $data['main_menus'] = '';
    if(count($this->menu_model->findActive()) > 0){
        $data['main_menus'] = $this->link_class->bootstrap_menu($this->menu_model->findActive());
    }

    $data['header'] = $this->load->view('common/header',$data);

    $data['posts'] = $this->home_model->find_active(3);
    $data['content'] = $this->load->view('common/content',$data);

    $this->load->view('layout',$data);

}

view

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="DBlog : Material Style Personal Blog Theme from Wowbootstrap">
    <meta name="author" content="wowbootstrap.com">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Merriweather:400,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,500,400italic,700,700italic,900,900italic,300,300italic,500italic" rel="stylesheet" type="text/css">
    <title><?php echo $page_title?> - CI Blog</title>

      <?php echo $header;?>

            <?php //echo $content;?>

            <?php //echo $right_sidebar;?>

      <?php //echo $footer;?>

    <?php if(!empty($home_page)):?>

    <?php endif;?>

I am using codeigniter to develop php web site. Now I have the question.
In controller,$this->load->view('index', $data);
I want $data can also share in header.php that included in index.php.

How to do???

Body:
If i do templating on codeigniter I do like this

In Layout.php

<!--Header -->
<?php  $this->load->view('path/to/header'); ?>

<!--Content -->
<?php  $this->load->view($content); ?>

<!--Footer-->
<?php  $this->load->view('path/to/footer'); ?>

In controller

$data['content'] = 'path/to/content/page'; # or any dynamic data with $this->model...

$this->load->view('template',$data);


问:
What's the difference between PipelinedRDD and normal RDD in Apache Spark?
now i tried to load the data from the hdfs with the code below, and I tried to use the function 'jsonParse' to concatenate values to normal csv, so that i think i can get the normal string RDD as i need, but it seems that this method is not work, and them when i tried to print some of the records, it tells me that the 'data' variable is a PipelinedRDD not iterate-able, any one can tell how can i get the 'data'(normal rdd) want, thanks:</p>
```<code>def jsonParse(x):
    s=json.loads(x)
    print "ssssssssssss"+s['age']+","+s['sex']+","+s['xueya']+","+s['danguchun']+","+s['na']+","+s['k']+","+s['yaowu']
    return s['age']+","+s['sex']+","+s['xueya']+","+s['danguchun']+","+s['na']+","+s['k']+","+s['yaowu']

conf = SparkConf()
sc = SparkContext(conf=conf)
hc = HiveContext(sc)
#json=sc.textFile('hdfs://hacluster/new')
json=hc.sql("select * from default.test_yj_200 limit 1000").toJSON()

data=json.map(jsonParse)
</code>```

答:
PipelinedRDD

PipelinedRDD operations are pipelined and sent to worker; the code is executed from top to bottom. It is a subclass of RDD.

RDD

Represents a constant, partitioned collection of elements that can be worked on in parallel.

ContentLicense: CC BY-SA 4.0

Body:
now i tried to load the data from the hdfs with the code below, and I tried to use the function 'jsonParse' to concatenate values to normal csv, so that i think i can get the normal string RDD as i need, but it seems that this method is not work, and them when i tried to print some of the records, it tells me that the 'data' variable is a PipelinedRDD not iterate-able, any one can tell how can i get the 'data'(normal rdd) want, thanks:

def jsonParse(x):
    s=json.loads(x)
    print "ssssssssssss"+s['age']+","+s['sex']+","+s['xueya']+","+s['danguchun']+","+s['na']+","+s['k']+","+s['yaowu']
    return s['age']+","+s['sex']+","+s['xueya']+","+s['danguchun']+","+s['na']+","+s['k']+","+s['yaowu']

conf = SparkConf()
sc = SparkContext(conf=conf)
hc = HiveContext(sc)
#json=sc.textFile('hdfs://hacluster/new')
json=hc.sql("select * from default.test_yj_200 limit 1000").toJSON()

data=json.map(jsonParse)


问:
Typescript- Creating member function outside of a Class definition with return types
How do you define a member function, outside the definition of a class in Typescript?

To quote an example from c++:

```<code>class A
{
   void runThis();
  //Member variables and constructors here
}

A::runThis()
{
  //code goes here
}
</code>```

How do you achieve the same in typescript? By searching in google I found something like:

```<code>class A
{
  runThis: () => void;
}

A.prototype.runThis = function(){
 //Anonymous function code goes here
}
</code>```

However, I have not found the syntax, to do the same with functions that have a return type (such as a number or a string).

How can this be achieved?

答:
You can definitely use the same syntax to add functions with return types:</p>

```<code>class A {
  add: (a: number, b: number) => number;
}

A.prototype.add = (a: number, b: number): number => {
  return a + b;
}
</code>```

Body:
How do you define a member function, outside the definition of a class in Typescript?

To quote an example from c++:

class A
{
   void runThis();
  //Member variables and constructors here
}

A::runThis()
{
  //code goes here
}

How do you achieve the same in typescript? By searching in google I found something like:

class A
{
  runThis: () => void;
}

A.prototype.runThis = function(){
 //Anonymous function code goes here
}

However, I have not found the syntax, to do the same with functions that have a return type (such as a number or a string).

How can this be achieved?

Body:
You can definitely use the same syntax to add functions with return types:

class A {
  add: (a: number, b: number) => number;
}

A.prototype.add = (a: number, b: number): number => {
  return a + b;
}


问:
Show increasing and decreasing values on noUiSlider
I'm using a noUiSlider with one handle and a range from 0 to 50. I'm trying to show the increasing value of the slider on an input field to the left of the slider and the diminishing value on the right - as in the below example:

Slider

Has anyone else tried to do this or know how it can be achieved?

```<code>var connectSlider = document.getElementById('slider');

noUiSlider.create(connectSlider, {
start: 20,
tooltips: true,
decimals: 0,
connect: [true, false],
range: {
  'min': 0,
  'max': 50,
},
  format: wNumb ({decimals:0})
});

var inputFormat = document.getElementById('slider-value');

 sliderFormat.noUiSlider.on('update', function( values, handle ) {
inputFormat.value = values[handle];
});

inputFormat.addEventListener('change', function(){
sliderFormat.noUiSlider.set(this.value);
});
$("#slider").Link('lower').to('#slider-value',function(value){
$(this).val(Math.abs(value));
});
</code>```

Here it is in jsfiddle

I managed to get the left value to display on the screen but don't know how to bind it to the input field. And I don't know how to get the value on the right. I assume this should be 'max value' minus 'slider value' but don't have enough knowledge of JavaScript so I would really appreciate some help with this :)

答:
I'm working with Slider control from the 0.99.0 Materialize version and I wanted to get that behavior too. So I do some tricks as follow:

My HTML inside a form tag:

```<code><div class="input-field col s12">
    <label for="wmAttendance">Porcentaje de Asistencias</label><br>
    <p class="range-field">
        <input type="range" id="test5" min="0" max="100" oninput="wAttendance.value = test5.value" />
        <output id="wAttendance" name="wAttendance">0<span>% - Mujeres</span></output>
        <output id="mAttendance" name="mAttendance" class="right">0<span>% - Hombres</span></output>
    </p>
</div>
</code>```

JS needed to intercept changes on the range input

```<code>$(document).ready(function() {
    $("#test5").on("input", function() {
        var women = this.value, men = 100 - women;
        $("#a_women").html(women);
        $("#a_men").html(men);
        $("#wAttendance").html(women + "<span>% - Mujeres</span>");
        $("#mAttendance").html(men + "<span>% - Hombres</span>");
    });
});
</code>```

And voila we have make the magic happen and the result is something like this:

In this way we can catch both values to send in the form or to make some operations etc. Here you have my pen for reference.

I hope it could be useful for somebody else.

Body:
I'm using a noUiSlider with one handle and a range from 0 to 50. I'm trying to show the increasing value of the slider on an input field to the left of the slider and the diminishing value on the right - as in the below example:

Slider

Has anyone else tried to do this or know how it can be achieved?

var connectSlider = document.getElementById('slider');

noUiSlider.create(connectSlider, {
start: 20,
tooltips: true,
decimals: 0,
connect: [true, false],
range: {
  'min': 0,
  'max': 50,
},
  format: wNumb ({decimals:0})
});

var inputFormat = document.getElementById('slider-value');

 sliderFormat.noUiSlider.on('update', function( values, handle ) {
inputFormat.value = values[handle];
});

inputFormat.addEventListener('change', function(){
sliderFormat.noUiSlider.set(this.value);
});
$("#slider").Link('lower').to('#slider-value',function(value){
$(this).val(Math.abs(value));
});

Here it is in jsfiddle

I managed to get the left value to display on the screen but don't know how to bind it to the input field. And I don't know how to get the value on the right. I assume this should be 'max value' minus 'slider value' but don't have enough knowledge of JavaScript so I would really appreciate some help with this :)

Body:
I'm working with Slider control from the 0.99.0 Materialize version and I wanted to get that behavior too. So I do some tricks as follow:

My HTML inside a form tag:

<div class="input-field col s12">
    <label for="wmAttendance">Porcentaje de Asistencias</label><br>
    <p class="range-field">
        <input type="range" id="test5" min="0" max="100" oninput="wAttendance.value = test5.value" />
        <output id="wAttendance" name="wAttendance">0<span>% - Mujeres</span></output>
        <output id="mAttendance" name="mAttendance" class="right">0<span>% - Hombres</span></output>
    </p>
</div>

JS needed to intercept changes on the range input

$(document).ready(function() {
    $("#test5").on("input", function() {
        var women = this.value, men = 100 - women;
        $("#a_women").html(women);
        $("#a_men").html(men);
        $("#wAttendance").html(women + "<span>% - Mujeres</span>");
        $("#mAttendance").html(men + "<span>% - Hombres</span>");
    });
});

And voila we have make the magic happen and the result is something like this:

In this way we can catch both values to send in the form or to make some operations etc. Here you have my pen for reference.

I hope it could be useful for somebody else.


问:
Resizing Blogger Homepage Images
I am a amateur blogger and have been attempting to make the images on my homepage a unified (and smaller than in the post body) size. Is there a way to do this?</p>

答:
It all depends on how your template sizes up your image on homepage. The quickest solution though (and the most basic) is you may want to use CSS to resize them "if page is homepage"

```<code><b:if cond='data:blog.url == data:blog.homepageUrl'>
.post-body img {
  width: [PLACE YOUR DESIRED WIDTH];
  height: [PLACE YOUR DESIRED HEIGHT];
}
</b:if>
</code>```

The problem though with this approach is that your image might be stretched or shrink. If that is okay for you then this should work, else, you may need to learn how to edit your own template and set a different code/layout for homepage.

Title: Resizing Blogger Homepage Images

Body:
It all depends on how your template sizes up your image on homepage. The quickest solution though (and the most basic) is you may want to use CSS to resize them "if page is homepage"

<b:if cond='data:blog.url == data:blog.homepageUrl'>
.post-body img {
  width: [PLACE YOUR DESIRED WIDTH];
  height: [PLACE YOUR DESIRED HEIGHT];
}
</b:if>

The problem though with this approach is that your image might be stretched or shrink. If that is okay for you then this should work, else, you may need to learn how to edit your own template and set a different code/layout for homepage.


问:
Facebook bot with multiple senders
Is it possible to make a Facebook bot look like there are multiple senders from the bot side? I couldn't see anything obvious in the Facebook docs. Even if the icon for the bot could be changed on the fly that may work

I'm trying to make a Facebook chat bot where a different 'person' will reply based on user input

EDIT:

As an alternative approach, could it be possible to use two separate facebook bots to have a semi simultaneous conversation with a single user. Take an example scenario where user starts a conversation with Bot A, then midway through the conversation, Bot B in a separate Facebook messenger chat, messages the user?

答: Unfortunately, Messenger Bots are subscribed to individual Facebook Pages, so there is no way to have multiple users. </p>

Title: Facebook bot with multiple senders


问:
Native node module for Electron project compiles against the wrong version of Node.js on Linux
I am trying to install this Electron project. It uses the two package.json structure and is written for Electron 1.7.2. All of the dependencies install fine and the setup instructions include running electron-rebuild, which also runs without complaining. However, when I run npm run dev an empty window opens and the following is in the console:

Uncaught Error: The module '[...]/sciencefair/app/node_modules/webworker-threads/build/Release/WebWorkerThreads.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION 51. This version of Node.js requires
NODE_MODULE_VERSION 54. Please try re-compiling or re-installing
the module (for instance, using `npm rebuild` or`npm install`).
        at process.module.(anonymous function) [as dlopen] (ELECTRON_ASAR.js:173:20)
    at Object.Module._extensions..node (module.js:598:18)
    at Object.module.(anonymous function) [as .node] (ELECTRON_ASAR.js:173:20)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at bindings (/[...]/sciencefair/app/node_modules/bindings/bindings.js:76:44)
    at Object.<anonymous> (/[...]/sciencefair/app/node_modules/webworker-threads/index.js:1:198)

I've tried installing the exact same version of Node.js that Electron 1.7.2 is targetting (7.9.0) but I get the same thing, with and without running electron-rebuild.

I'm a web guy and have no real Electron experience. System: Ubuntu LTS 16.04

答:
Following the longer answer here did it:</p>

```<code>export npm_config_target=1.7.2
export npm_config_arch=x64
export npm_config_target_arch=x64
export npm_config_disturl=https://atom.io/download/electron
export npm_config_runtime=electron
export npm_config_build_from_source=true
HOME=~/.electron-gyp npm install
</code>```

Body:
Following the longer answer here did it:

export npm_config_target=1.7.2
export npm_config_arch=x64
export npm_config_target_arch=x64
export npm_config_disturl=https://atom.io/download/electron
export npm_config_runtime=electron
export npm_config_build_from_source=true
HOME=~/.electron-gyp npm install


问:
Node EventEmitter to EventEmitter emits. Multiple emitters
I am trying to emit from one EventEmitter to another EventEmitter, or find an alternative solution. The code below doesn't function.

Multiple emitter example

```<code>var events = require('events');

var eventEmitterOne = new events.EventEmitter();
var eventEmitterTwo = new events.EventEmitter();

eventEmitterTwo.on('fireEvent', function() {
     console.log('event fired');
});

eventEmitterOne.emit('fireEvent');
</code>```

I'm looking to find out if the following is possible and whats changes I would need to make to the following code to make it functional. Or is there another way of emitting events across multiple emitters. Thanks for your time.

答:
The other answer cannot emit event with arguments. So here is the improvement:

```<code>'use strict';

var eventEmitter = new (require('events').EventEmitter)();

function emitEvent(...args) {
    eventEmitter.emit(...args);
}

function registerEvent(str, callback) {
    eventEmitter.on(str, callback);
}

function registerEventOnce(str, callback) {
    eventEmitter.once(str, callback);
}

exports.emit = emitEvent;
exports.on = registerEvent;
exports.once = registerEventOnce;
</code>```

Body:
I am trying to emit from one EventEmitter to another EventEmitter, or find an alternative solution. The code below doesn't function.

Multiple emitter example

var events = require('events');

var eventEmitterOne = new events.EventEmitter();
var eventEmitterTwo = new events.EventEmitter();

eventEmitterTwo.on('fireEvent', function() {
     console.log('event fired');
});

eventEmitterOne.emit('fireEvent');

I'm looking to find out if the following is possible and whats changes I would need to make to the following code to make it functional. Or is there another way of emitting events across multiple emitters. Thanks for your time.

Body:
The other answer cannot emit event with arguments. So here is the improvement:

'use strict';

var eventEmitter = new (require('events').EventEmitter)();

function emitEvent(...args) {
    eventEmitter.emit(...args);
}

function registerEvent(str, callback) {
    eventEmitter.on(str, callback);
}

function registerEventOnce(str, callback) {
    eventEmitter.once(str, callback);
}

exports.emit = emitEvent;
exports.on = registerEvent;
exports.once = registerEventOnce;


问:
How do I get a call stack of another thread?
Is it possible to get a Kernel#caller output of one thread from another one? Or even better the stack of the main thread from the background one, which would work for me as a kind of profiler.

答:
There is Thread#backtrace method to get function backtrace for some thread:

https://ruby-doc.org/core-2.4.1/Thread.html#method-i-backtrace

backtrace → array click to toggle source

Returns the current backtrace of the target thread.

For usage example check this project: https://github.com/frsyuki/sigdump (it will show backtraces and some memory usage info for ruby and jruby)

sigdump - In short: SIGQUIT of Java VM for Ruby (Use signal to show stacktrace of a Ruby process without restarting it).

... Just sending SIGCONT signal will dump backtrace and memory profile to /tmp/sigdump-.log file.

sigdump dumps following information (see also Sample output):

Backtrace of all threads

https://github.com/frsyuki/sigdump/blob/master/lib/sigdump.rb

```<code>    dump_all_thread_backtrace(io)
...
    Thread.list.each do |thread|
      dump_backtrace(thread, io)
...
  def self.dump_backtrace(thread, io)
    status = thread.status
    if status == nil
      status = "finished"
    elsif status == false
      status = "error"
    end

    io.write "  Thread #{thread} status=#{status} priority=#{thread.priority}\n"
    if thread.backtrace
      thread.backtrace.each {|bt|
        io.write "      #{bt}\n"
      }
    end

    io.flush
    nil
  end
</code>```

Body:
There is Thread#backtrace method to get function backtrace for some thread:

https://ruby-doc.org/core-2.4.1/Thread.html#method-i-backtrace

backtrace → array click to toggle source

Returns the current backtrace of the target thread.

For usage example check this project: https://github.com/frsyuki/sigdump (it will show backtraces and some memory usage info for ruby and jruby)

sigdump - In short: SIGQUIT of Java VM for Ruby (Use signal to show stacktrace of a Ruby process without restarting it).

... Just sending SIGCONT signal will dump backtrace and memory profile to /tmp/sigdump-.log file.

sigdump dumps following information (see also Sample output):

Backtrace of all threads

https://github.com/frsyuki/sigdump/blob/master/lib/sigdump.rb

    dump_all_thread_backtrace(io)
...
    Thread.list.each do |thread|
      dump_backtrace(thread, io)
...
  def self.dump_backtrace(thread, io)
    status = thread.status
    if status == nil
      status = "finished"
    elsif status == false
      status = "error"
    end

    io.write "  Thread #{thread} status=#{status} priority=#{thread.priority}\n"
    if thread.backtrace
      thread.backtrace.each {|bt|
        io.write "      #{bt}\n"
      }
    end

    io.flush
    nil
  end


问:
signInWithPopup does not open a popup window. Instead, it opens a new tab
The code below does not open a pop-up window.

```<code>firebase.auth().signInWithPopup( ... )
</code>```

Anyone has any idea, please help me?

I am using chrome Version 59.0.3071.115 (Official Build) (64-bit)

答: This is a known bug in Chrome 59: https://bugs.chromium.org/p/chromium/issues/detail?id=723655</p>

Body:
The code below does not open a pop-up window.

firebase.auth().signInWithPopup( ... )

Anyone has any idea, please help me?

I am using chrome Version 59.0.3071.115 (Official Build) (64-bit)


问:
unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)
I am getting syntax error in the following code:

```<code>function getFridays($year='', $format='', $timezone = 'UTC') {

$fridays = array();
$startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));

$year++;
$endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));

$int = new DateInterval('P7D');

foreach (new DatePeriod($startDate, $int, $endDate) as $d) {
    $fridays[] = $d->format($format);

}

return $fridays;
}

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');
</code>```

Error: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)

答: The provided code works fine is copied directly into a sandbox because all of the class stuff is missing. Without it, it will work fine. So, you're declaring the variable inside a method, but trying to set it outside of the method, which is a no-go.</p>

Body:
I am getting syntax error in the following code:

function getFridays($year='', $format='', $timezone = 'UTC') {

$fridays = array();
$startDate = new DateTime("{$year}-01-01 Friday", new DateTimezone($timezone));

$year++;
$endDate = new DateTime("{$year}-01-01", new DateTimezone($timezone));

$int = new DateInterval('P7D');

foreach (new DatePeriod($startDate, $int, $endDate) as $d) {
    $fridays[] = $d->format($format);

}

return $fridays;
}

$fridays = getFridays($year, 'Y-m-d', 'America/New_York');

Error: unexpected '$fridays' (T_VARIABLE), expecting function (T_FUNCTION)


问:
How to get Windows version using Node.js?
There are questions about OS version on the Stack Overflow but not about the Windows name, I am looking to find out Windows name using Node.js.

I have looked into so many modules like os, platform, getos and using process etc. and found that these are helpful to get operating system description, process environment etc. I am able to get it is Linux or Windows too i.e. which platform I am using.

But, how can I check, is it Windows 7 or 8 which is installed on my system using Node.js?

I am using kinect2 module in my Node.js project which is working fine on Windows 8 but I am looking to use it on Windows 7.

I have checked that Kinect2 will not work with Windows 7.

答:
Use os.release().

```<code>> os.release();
'10.0.18363'
</code>```

On Windows, the result is in the form major.minor.build

Consult this table (source) to determine the version of Windows:

 Version                                    major.minor
------------------------------------------ -------------
 Windows 10, Windows Server 2016            10.0
 Windows 8.1, Windows Server 2012 R2        6.3
 Windows 8, Windows Server 2012             6.2
 Windows 7, Windows Server 2008 R2          6.1
 Windows Vista, Windows Server 2008         6.0
 Windows XP Professional x64 Edition,       5.2
 Windows Server 2003, Windows Home Server
 Windows XP                                 5.1
 Windows 2000                               5.0
```

<p>For Windows 10 specifically, consult this table (source) to determine the exact version:</p>

<pre class="lang-none prettyprint-override"><code> Version           build
----------------- -------
 Windows 10 1909   18363
 Windows 10 1903   18362
 Windows 10 1809   17763
 Windows 10 1803   17134
 Windows 10 1709   16299
 Windows 10 1703   15063
 Windows 10 1607   14393
 Windows 10 1511   10586
 Windows 10 1507   10240
</code>```

Body:
Use os.release().

> os.release();
'10.0.18363'

On Windows, the result is in the form major.minor.build

Consult this table (source) to determine the version of Windows:

 Version                                    major.minor
------------------------------------------ -------------
 Windows 10, Windows Server 2016            10.0
 Windows 8.1, Windows Server 2012 R2        6.3
 Windows 8, Windows Server 2012             6.2
 Windows 7, Windows Server 2008 R2          6.1
 Windows Vista, Windows Server 2008         6.0
 Windows XP Professional x64 Edition,       5.2
 Windows Server 2003, Windows Home Server
 Windows XP                                 5.1
 Windows 2000                               5.0

For Windows 10 specifically, consult this table (source) to determine the exact version:

 Version           build
----------------- -------
 Windows 10 1909   18363
 Windows 10 1903   18362
 Windows 10 1809   17763
 Windows 10 1803   17134
 Windows 10 1709   16299
 Windows 10 1703   15063
 Windows 10 1607   14393
 Windows 10 1511   10586
 Windows 10 1507   10240


问:
My Firebase/Facebook Auth login works and will not display the users username in my next activity: activity_main.xml
Here is my XML for my activity_sign_in

My task is to assign the user (once logged in) and have the Facebook username displayed in the next activity.

< RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android: id = "@+id/main_layout"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/grey_100"
android: orientation = "vertical"
android: weightSum = "4" >

  <
  ImageView
android: id = "@+id/imageView"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
app: srcCompat = "@drawable/new_green_360" / >

  <
  ProgressBar
android: id = "@+id/progressBar"
style = "?android:attr/progressBarStyleLarge"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_centerHorizontal = "true"
android: layout_centerVertical = "true"
android: indeterminate = "true"
android: visibility = "gone" / >

  <
  RelativeLayout
android: layout_width = "match_parent"
android: layout_height = "0dp"
android: layout_weight = "3"
android: gravity = "center_horizontal"
android: orientation = "vertical" >

  <
  ImageView
android: id = "@+id/icon"
style = "@style/ThemeOverlay.FirebaseIcon"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: contentDescription = "@string/desc_firebase_lockup"
android: src = "@drawable/firebase_lockup_400" / >

  <
  TextView
android: id = "@+id/title_text"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_marginBottom = "@dimen/title_bottom_margin"
android: text = "@string/emailpassword_title_text"
android: theme = "@style/ThemeOverlay.MyTitleText" / >

  <
  TextView
android: id = "@+id/status"
style = "@style/ThemeOverlay.MyTextDetail"
android: text = "@string/signed_out" / >

  <
  TextView
android: id = "@+id/detail"
style = "@style/ThemeOverlay.MyTextDetail"
tools: text = "Firebase User ID: 123456789abc" / >

  <
  /RelativeLayout>

  <
  RelativeLayout
android: layout_width = "fill_parent"
android: layout_height = "0dp"
android: layout_weight = "1"
android: background = "@color/grey_300"
android: gravity = "center_vertical" >

  <
  LinearLayout
android: id = "@+id/email_password_fields"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp" >

  <
  EditText
android: id = "@+id/field_email"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: hint = "@string/hint_email"
android: inputType = "textEmailAddress" / >

  <
  EditText
android: id = "@+id/field_password"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: hint = "@string/hint_password"
android: inputType = "textPassword" / >
  <
  /LinearLayout>

  <
  LinearLayout
android: id = "@+id/email_password_buttons"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: layout_below = "@+id/email_password_fields"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp" >

  <
  Button
android: id = "@+id/email_sign_in_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: text = "@string/sign_in"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  Button
android: id = "@+id/email_create_account_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: text = "@string/create_account"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >
  <
  /LinearLayout>

  <
  LinearLayout
android: id = "@+id/signed_in_buttons"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: layout_centerInParent = "true"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp"
android: visibility = "gone"
android: weightSum = "2.0" >

  <
  Button
android: id = "@+id/sign_out_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1.0"
android: text = "@string/sign_out"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  Button
android: id = "@+id/verify_email_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1.0"
android: text = "@string/verify_email"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  /LinearLayout>

  <
  /RelativeLayout>

  <
  com.facebook.login.widget.LoginButton
android: id = "@+id/loginButton"
android: layout_width = "wrap_content"
android: layout_height = "18dp"
android: layout_alignParentBottom = "true"
android: layout_centerHorizontal = "true"
android: layout_marginBottom = "75dp"
android: paddingBottom = "10dp"
android: paddingTop = "10dp" / >

  <
  />```
</div>
</div>
</p>

<p>Here is my <strong>FacebookLoginActivity.java</strong> code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.Arrays;

/**
 * Created by Stormy Forrester on 8/3/2016.
 */
public class FacebookLoginActivity extends AppCompatActivity {

  private LoginButton loginButton;
  private CallbackManager callbackManager;

  private FirebaseAuth firebaseAuth;
  private FirebaseAuth.AuthStateListener firebaseAuthListner;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.sign_in_layout);

    callbackManager = CallbackManager.Factory.create();

    loginButton = (LoginButton) findViewById(R.id.loginButton);

    loginButton.setReadPermissions(Arrays.asList("email"));
    loginButton.registerCallback(callbackManager, new FacebookCallback < LoginResult > () {
      @Override
      public void onSuccess(LoginResult loginResult) {
        handleFacebookAccessToken(loginResult.getAccessToken());
      }

      @Override
      public void onCancel() {
        Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onError(FacebookException error) {
        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
      }
    });

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseAuthListner = new FirebaseAuth.AuthStateListener() {
      @Override
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
          goMainScreen();
        }
      }
    };
  }

  private void handleFacebookAccessToken(AccessToken accessToken) {
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener < AuthResult > () {
      @Override
      public void onComplete(@NonNull Task < AuthResult > task) {
        if (!task.isSuccessful()) {
          Toast.makeText(getApplicationContext(), R.string.firebase_error_login, Toast.LENGTH_LONG).show();
        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onStart() {
    super.onStart();
    firebaseAuth.addAuthStateListener(firebaseAuthListner);
  }

  @Override
  protected void onStop() {
    super.onStop();
    firebaseAuth.removeAuthStateListener(firebaseAuthListner);
  }

  public void goMainScreen() {
    Intent intent = new Intent(this, SignInActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
  }
}</code>```

Here is the next activity: activity_main.xml

<< ? xml version = "1.0"
encoding = "utf-8" ? >
  <
  RelativeLayout xmlns : android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/color_bg"
tools: context = "com.transcendencetech.juliospizzaprototype.SignInActivity" >

  <
  include
android: id = "@+id/header"
layout = "@layout/header"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentTop = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  RelativeLayout
android: id = "@+id/my_tabs"
android: layout_width = "match_parent"
android: layout_height = "40dp"
android: layout_below = "@id/header"
android: background = "@android:color/black" >

  <
  View
android: id = "@+id/divider_view"
android: layout_width = "1dp"
android: layout_height = "match_parent"
android: layout_centerInParent = "true"
android: layout_margin = "2dp"
android: background = "@android:color/white" / >

  <
  Button
android: id = "@+id/pizza_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true"
android: layout_toLeftOf = "@id/divider_view"
android: layout_toStartOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "textPersonName"
android: text = "List of Pizzas"
android: textColor = "@android:color/white" / >

  <
  Button
android: id = "@+id/deals_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentEnd = "true"
android: layout_alignParentRight = "true"
android: layout_toEndOf = "@id/divider_view"
android: layout_toRightOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "text"
android: text = "List of Deals"
android: textColor = "@android:color/white" / >
  <
  /RelativeLayout>

  <
  ImageView
android: id = "@+id/pizza_list_iv"
android: layout_width = "match_parent"
android: layout_height = "150dp"
android: layout_below = "@id/my_tabs"
android: scaleType = "fitXY"
android: src = "@drawable/list_pizza_header" / >

  <
  ListView
android: id = "@+id/list_view"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_below = "@id/pizza_list_iv"
android: divider = "@color/color_divider"
android: focusable = "true"
android: dividerHeight = "2dp"
android: layout_margin = "15dp" / >

  <
  include
layout = "@layout/footer"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentBottom = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  /RelativeLayout>```
</div>
</div>
</p>

<p>Here is the <strong>SignInActivity.java</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;

import com.facebook.AccessToken;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;

public class SignInActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.activity_main);

    if (AccessToken.getCurrentAccessToken() == null) {
      goLoginScreen();
    }
  }

  private void goLoginScreen() {
    Intent intent = new Intent(this, FacebookLoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
  }

  public void logout(View view) {
    LoginManager.getInstance().logOut();
    goLoginScreen();
  }
}</code>```

答:
The code you are providing doesn't show any code that could set a TextView in your layout

```<code>public void goMainScreen() {
Intent intent = new Intent(this, SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);}
</code>```

I think you have to show the code of SignInActivity

But it should work with something like that:

```<code>FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
((TextView) findViewById(R.id.[YOUR_ID_OF_TEXTVIEW])).setText(user.getDisplayName());
</code>```

Body:
Here is my XML for my activity_sign_in

My task is to assign the user (once logged in) and have the Facebook username displayed in the next activity.

< RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: app = "http://schemas.android.com/apk/res-auto"
xmlns: tools = "http://schemas.android.com/tools"
android: id = "@+id/main_layout"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/grey_100"
android: orientation = "vertical"
android: weightSum = "4" >

  <
  ImageView
android: id = "@+id/imageView"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
app: srcCompat = "@drawable/new_green_360" / >

  <
  ProgressBar
android: id = "@+id/progressBar"
style = "?android:attr/progressBarStyleLarge"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_centerHorizontal = "true"
android: layout_centerVertical = "true"
android: indeterminate = "true"
android: visibility = "gone" / >

  <
  RelativeLayout
android: layout_width = "match_parent"
android: layout_height = "0dp"
android: layout_weight = "3"
android: gravity = "center_horizontal"
android: orientation = "vertical" >

  <
  ImageView
android: id = "@+id/icon"
style = "@style/ThemeOverlay.FirebaseIcon"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: contentDescription = "@string/desc_firebase_lockup"
android: src = "@drawable/firebase_lockup_400" / >

  <
  TextView
android: id = "@+id/title_text"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_marginBottom = "@dimen/title_bottom_margin"
android: text = "@string/emailpassword_title_text"
android: theme = "@style/ThemeOverlay.MyTitleText" / >

  <
  TextView
android: id = "@+id/status"
style = "@style/ThemeOverlay.MyTextDetail"
android: text = "@string/signed_out" / >

  <
  TextView
android: id = "@+id/detail"
style = "@style/ThemeOverlay.MyTextDetail"
tools: text = "Firebase User ID: 123456789abc" / >

  <
  /RelativeLayout>

  <
  RelativeLayout
android: layout_width = "fill_parent"
android: layout_height = "0dp"
android: layout_weight = "1"
android: background = "@color/grey_300"
android: gravity = "center_vertical" >

  <
  LinearLayout
android: id = "@+id/email_password_fields"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp" >

  <
  EditText
android: id = "@+id/field_email"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: hint = "@string/hint_email"
android: inputType = "textEmailAddress" / >

  <
  EditText
android: id = "@+id/field_password"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: hint = "@string/hint_password"
android: inputType = "textPassword" / >
  <
  /LinearLayout>

  <
  LinearLayout
android: id = "@+id/email_password_buttons"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: layout_below = "@+id/email_password_fields"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp" >

  <
  Button
android: id = "@+id/email_sign_in_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: text = "@string/sign_in"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  Button
android: id = "@+id/email_create_account_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1"
android: text = "@string/create_account"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >
  <
  /LinearLayout>

  <
  LinearLayout
android: id = "@+id/signed_in_buttons"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: layout_centerInParent = "true"
android: orientation = "horizontal"
android: paddingLeft = "16dp"
android: paddingRight = "16dp"
android: visibility = "gone"
android: weightSum = "2.0" >

  <
  Button
android: id = "@+id/sign_out_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1.0"
android: text = "@string/sign_out"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  Button
android: id = "@+id/verify_email_button"
android: layout_width = "0dp"
android: layout_height = "wrap_content"
android: layout_weight = "1.0"
android: text = "@string/verify_email"
android: theme = "@style/ThemeOverlay.MyDarkButton" / >

  <
  /LinearLayout>

  <
  /RelativeLayout>

  <
  com.facebook.login.widget.LoginButton
android: id = "@+id/loginButton"
android: layout_width = "wrap_content"
android: layout_height = "18dp"
android: layout_alignParentBottom = "true"
android: layout_centerHorizontal = "true"
android: layout_marginBottom = "75dp"
android: paddingBottom = "10dp"
android: paddingTop = "10dp" / >

  <
  />

Here is my FacebookLoginActivity.java code

package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import java.util.Arrays;

/**
 * Created by Stormy Forrester on 8/3/2016.
 */
public class FacebookLoginActivity extends AppCompatActivity {

  private LoginButton loginButton;
  private CallbackManager callbackManager;

  private FirebaseAuth firebaseAuth;
  private FirebaseAuth.AuthStateListener firebaseAuthListner;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.sign_in_layout);

    callbackManager = CallbackManager.Factory.create();

    loginButton = (LoginButton) findViewById(R.id.loginButton);

    loginButton.setReadPermissions(Arrays.asList("email"));
    loginButton.registerCallback(callbackManager, new FacebookCallback < LoginResult > () {
      @Override
      public void onSuccess(LoginResult loginResult) {
        handleFacebookAccessToken(loginResult.getAccessToken());
      }

      @Override
      public void onCancel() {
        Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onError(FacebookException error) {
        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
      }
    });

    firebaseAuth = FirebaseAuth.getInstance();
    firebaseAuthListner = new FirebaseAuth.AuthStateListener() {
      @Override
      public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
          goMainScreen();
        }
      }
    };
  }

  private void handleFacebookAccessToken(AccessToken accessToken) {
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    firebaseAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener < AuthResult > () {
      @Override
      public void onComplete(@NonNull Task < AuthResult > task) {
        if (!task.isSuccessful()) {
          Toast.makeText(getApplicationContext(), R.string.firebase_error_login, Toast.LENGTH_LONG).show();
        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onStart() {
    super.onStart();
    firebaseAuth.addAuthStateListener(firebaseAuthListner);
  }

  @Override
  protected void onStop() {
    super.onStop();
    firebaseAuth.removeAuthStateListener(firebaseAuthListner);
  }

  public void goMainScreen() {
    Intent intent = new Intent(this, SignInActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
  }
}

Here is the next activity: activity_main.xml

<< ? xml version = "1.0"
encoding = "utf-8" ? >
  <
  RelativeLayout xmlns : android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: background = "@color/color_bg"
tools: context = "com.transcendencetech.juliospizzaprototype.SignInActivity" >

  <
  include
android: id = "@+id/header"
layout = "@layout/header"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentTop = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  RelativeLayout
android: id = "@+id/my_tabs"
android: layout_width = "match_parent"
android: layout_height = "40dp"
android: layout_below = "@id/header"
android: background = "@android:color/black" >

  <
  View
android: id = "@+id/divider_view"
android: layout_width = "1dp"
android: layout_height = "match_parent"
android: layout_centerInParent = "true"
android: layout_margin = "2dp"
android: background = "@android:color/white" / >

  <
  Button
android: id = "@+id/pizza_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true"
android: layout_toLeftOf = "@id/divider_view"
android: layout_toStartOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "textPersonName"
android: text = "List of Pizzas"
android: textColor = "@android:color/white" / >

  <
  Button
android: id = "@+id/deals_list_bt"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content"
android: layout_alignParentEnd = "true"
android: layout_alignParentRight = "true"
android: layout_toEndOf = "@id/divider_view"
android: layout_toRightOf = "@id/divider_view"
android: background = "@android:color/black"
android: inputType = "text"
android: text = "List of Deals"
android: textColor = "@android:color/white" / >
  <
  /RelativeLayout>

  <
  ImageView
android: id = "@+id/pizza_list_iv"
android: layout_width = "match_parent"
android: layout_height = "150dp"
android: layout_below = "@id/my_tabs"
android: scaleType = "fitXY"
android: src = "@drawable/list_pizza_header" / >

  <
  ListView
android: id = "@+id/list_view"
android: layout_width = "match_parent"
android: layout_height = "match_parent"
android: layout_below = "@id/pizza_list_iv"
android: divider = "@color/color_divider"
android: focusable = "true"
android: dividerHeight = "2dp"
android: layout_margin = "15dp" / >

  <
  include
layout = "@layout/footer"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentBottom = "true"
android: layout_alignParentLeft = "true"
android: layout_alignParentStart = "true" / >

  <
  /RelativeLayout>

Here is the SignInActivity.java

package com.transcendencetech.juliospizzaprototype;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;

import com.facebook.AccessToken;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;

public class SignInActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.activity_main);

    if (AccessToken.getCurrentAccessToken() == null) {
      goLoginScreen();
    }
  }

  private void goLoginScreen() {
    Intent intent = new Intent(this, FacebookLoginActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
  }

  public void logout(View view) {
    LoginManager.getInstance().logOut();
    goLoginScreen();
  }
}

Body:
The code you are providing doesn't show any code that could set a TextView in your layout

public void goMainScreen() {
Intent intent = new Intent(this, SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);}

I think you have to show the code of SignInActivity

But it should work with something like that:

FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
((TextView) findViewById(R.id.[YOUR_ID_OF_TEXTVIEW])).setText(user.getDisplayName());


问:
VBA Creating Pivot Table error 1004
I am trying to have a program create several pivot tables for me (since I'd have to do this weekly/monthly) but same type of data.

Based on several websites, I copied some code and edited some code for the following:

```<code>Private Sub CommandButton1_Click()

'Declaration

'Creates new worksheet

Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim DataRange As Range

'Create a new worksheet
  Set sht = Sheets.Add
  sht.Name = "EUPS Report"

'Determine the data range you want to pivot
  Set DataRange = Application.InputBox("Please Select the Data (Please select by pressing any cell in the table then pressing ctrl+a)", Default:=Selection.Address, Type:=8)
  SrcData = sht.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)

'Where do you want Pivot Table to start?
'  StartPvt = "'" & sht.Name & "!" & sht.Range("A15").Address(ReferenceStyle:=xlR1C1) & "'"

'Create Pivot Cache from Source Data
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Create Pivot table from Pivot Cache
  Set pvt = pvtCache.CreatePivotTable( _
    TableDestination:=Worksheets("EUPS Report").Range("A15"))
'   TableName:="PivotTable1")

End Sub
</code>```

However, I'm running into this error:

Run-Time error '1004':

The PivotTable field name is not valid. To create a PivotTable report, you must use data that is organized as a list with labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.

I cannot show you my data since it's company information, but it's a regular data table with column headers but no row headers. I have tested this code on other data but it doesn't work either. And I have tested my data with manually created pivot tables and they do work, so it's the code's problem.

Kindly let me know what's wrong. Thanks!

答:
Use Excel Table Objects to store the data, then you can reference the table by name as the source of the pivot tables. The table will grow and shrink with the data and you only need to refresh the pivot table when the data has changed.

You can manually copy and paste the data into the table, or you can use Power Query to get the data from almost any data source. Power Query is a free add-in from Microsoft for Excel 2010 and 2013 and it is built into Excel 2016 as Get&Transform.

The idea here is that it is easier and more efficient to just refresh the data than having to build pivot tables from scratch every week. That really defeats the purpose of pivot tables. Work smarter, not harder.

Title: VBA Creating Pivot Table error 1004

Body:
I am trying to have a program create several pivot tables for me (since I'd have to do this weekly/monthly) but same type of data.

Based on several websites, I copied some code and edited some code for the following:

Private Sub CommandButton1_Click()

'Declaration

'Creates new worksheet

Dim sht As Worksheet
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim DataRange As Range

'Create a new worksheet
  Set sht = Sheets.Add
  sht.Name = "EUPS Report"

'Determine the data range you want to pivot
  Set DataRange = Application.InputBox("Please Select the Data (Please select by pressing any cell in the table then pressing ctrl+a)", Default:=Selection.Address, Type:=8)
  SrcData = sht.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)

'Where do you want Pivot Table to start?
'  StartPvt = "'" & sht.Name & "!" & sht.Range("A15").Address(ReferenceStyle:=xlR1C1) & "'"

'Create Pivot Cache from Source Data
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Create Pivot table from Pivot Cache
  Set pvt = pvtCache.CreatePivotTable( _
    TableDestination:=Worksheets("EUPS Report").Range("A15"))
'   TableName:="PivotTable1")

End Sub

However, I'm running into this error:

Run-Time error '1004':

The PivotTable field name is not valid. To create a PivotTable report, you must use data that is organized as a list with labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.

I cannot show you my data since it's company information, but it's a regular data table with column headers but no row headers. I have tested this code on other data but it doesn't work either. And I have tested my data with manually created pivot tables and they do work, so it's the code's problem.

Kindly let me know what's wrong. Thanks!


问:
Android correct place to inflate custom view
I have this custom view:

```<code>class BaseView extends FrameLayout() {
     @Override
     void onAttachedToWindow() {
         View.inflate(context, R.layout.view, this)
     }
}
</code>```

The correct place to inflate my custom view is in the onAttachedToWindow method?

I am thinking that maybe inflating it after the onAttach can make the parent layout to be entire redraw.

If it is wrong to inflate in the onAttachedToWindow, where is the right place?

This view is added dynamically (via addView) and in others places it is placed in the xml definition.

答:
The right place to inflate your custom view layout is in the constructor:</p>

```<code>class BaseView extends FrameLayout {
    public BaseView(Context context) { this(context, null); }

    public BaseView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view, this, true);

        ...
    }
}
</code>```

Body:
I have this custom view:

class BaseView extends FrameLayout() {
     @Override
     void onAttachedToWindow() {
         View.inflate(context, R.layout.view, this)
     }
}

The correct place to inflate my custom view is in the onAttachedToWindow method?

I am thinking that maybe inflating it after the onAttach can make the parent layout to be entire redraw.

If it is wrong to inflate in the onAttachedToWindow, where is the right place?

This view is added dynamically (via addView) and in others places it is placed in the xml definition.

Body:
The right place to inflate your custom view layout is in the constructor:

class BaseView extends FrameLayout {
    public BaseView(Context context) { this(context, null); }

    public BaseView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.view, this, true);

        ...
    }
}


问:
Encrypt USB Stick with AES 128/256
I am trying to encrypt my USB stick with AES 128/256 encryption. I am new to the game and need some advice, google has not been my friend so far.

All i would like to do is encrypt the whole USB stick so that i end up with one like this AES USB.

Any help is appreciated.

答:
Here are your choices for encryption:

Hardware encryption - get an USB flash drive that has the encryption logic programmed into its firmware (like the one you linked to).

Pros: Works in any operating system, no software installation necessary.

Cons: This is a more expensive option.

Software encryption - either get a flash drive that comes with a software, or download and install software that will encrypt your drive.

Pros: Less expensive option, some of good software to do this is either free or low-cost.

Cons: The software is operating system specific, so if you need a cross-OS approach, then you will have to find a program that has versions for multiple operating systems. Also the software will either need to be installed on any computer you will stick the flash drive into (most probably requiring you to be an administrator on that computer), or hopefully it can have a portable version that can be run directly from the USB drive.

Most  USB flash sticks manufacturers have hardware-encrypted sticks in their assortment - you can ask around and read some reviews and choose one to your liking.

For software programs - the easiest option for Windows is its built-in BitLocker program, it is available on most recent Windows versions.

For cross-platform - look at tools like VeraCrypt, GNU Privacy Guard and others (again do your research and pick the one you like).

Another viable option is just to put the files you want to restrict access to in a password-protected ZIP archive.

Hope this helps.

Title: Encrypt USB Stick with AES 128/256


问:
Android show marker onClick button
I want to plot all the coordinates of latitude and longitude values I get. Check the first and last of the plot and change with different icons. Add Poly lines on each mark plot and buttons on popup that can hide/dismiss.

The problem I am having now is that whenever I remove the for-loop outside the button I am having a null pointer error.

```<code>      @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
        mapFragment.getMapAsync(this);

        new GetVehicleValue().execute();
    }

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

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
Button b = (Button) v.findViewById(R.id.button3);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        if(vehicleHolder.size() != 0) {
        for(int i =0; i < vehicleHolder.size(); i++) {
            createMarker(i,vehicleHolder.get(i).getLatitude(),vehicleHolder.get(i).getLongitude(),vehicleHolder.get(i).getVehicle());
        }
    }

        return v;
    }

    public void createMarker(int index, String latitude, String longitude, String vehicle) {
        // Adding the taped point to the ArrayList
        BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);
        Double lat = Double.parseDouble(latitude);
        Double Longitude = Double.parseDouble(longitude);
        float color = 0;

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, Longitude))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet"  )
                .icon(image));

    }

    class GetVehicleValue extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONArray jr = new JSONArray(jsonStr);

                    vehicleHolder = new ArrayList<>();
                    for (int i = 0; i < jsonStr.length(); i++) {
                        JSONObject jb = (JSONObject) jr.getJSONObject(i);
                        plate_num = jb.getString("plate_num");
                        gps_num = jb.getString("gps_num");
                        location = jb.getString("location");
                        date = jb.getString("date");
                        time = jb.getString("time");
                        lat = jb.getString("lat");
                        lng = jb.getString("lng");
                        engine = jb.getString("engine");
                        remarks = jb.getString("remarks");

                        vehicleHolder.add(new VehicleHolder(lat, lng));

                    }

                } catch (final JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("JSON:", "is null");
            }

            return null;
        }
</code>```

答:
Make location and direction to be fields

```<code>String lattitude;
String longitude;
</code>```

then in doInBackground change the code to be

```<code>lattitude = c.getString("lattitude");
longitude= c.getString("longitude");
</code>```

then they may be used in onClick

Title: Android show marker onClick button

Body:
I want to plot all the coordinates of latitude and longitude values I get. Check the first and last of the plot and change with different icons. Add Poly lines on each mark plot and buttons on popup that can hide/dismiss.

The problem I am having now is that whenever I remove the for-loop outside the button I am having a null pointer error.

      @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
        mapFragment.getMapAsync(this);

        new GetVehicleValue().execute();
    }

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

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
Button b = (Button) v.findViewById(R.id.button3);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        if(vehicleHolder.size() != 0) {
        for(int i =0; i < vehicleHolder.size(); i++) {
            createMarker(i,vehicleHolder.get(i).getLatitude(),vehicleHolder.get(i).getLongitude(),vehicleHolder.get(i).getVehicle());
        }
    }

        return v;
    }

    public void createMarker(int index, String latitude, String longitude, String vehicle) {
        // Adding the taped point to the ArrayList
        BitmapDescriptor image = BitmapDescriptorFactory.fromResource(R.drawable.bus);
        Double lat = Double.parseDouble(latitude);
        Double Longitude = Double.parseDouble(longitude);
        float color = 0;

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(lat, Longitude))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet"  )
                .icon(image));

    }

    class GetVehicleValue extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            if (jsonStr != null) {
                try {
                    JSONArray jr = new JSONArray(jsonStr);

                    vehicleHolder = new ArrayList<>();
                    for (int i = 0; i < jsonStr.length(); i++) {
                        JSONObject jb = (JSONObject) jr.getJSONObject(i);
                        plate_num = jb.getString("plate_num");
                        gps_num = jb.getString("gps_num");
                        location = jb.getString("location");
                        date = jb.getString("date");
                        time = jb.getString("time");
                        lat = jb.getString("lat");
                        lng = jb.getString("lng");
                        engine = jb.getString("engine");
                        remarks = jb.getString("remarks");

                        vehicleHolder.add(new VehicleHolder(lat, lng));

                    }

                } catch (final JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.d("JSON:", "is null");
            }

            return null;
        }

Body:
Make location and direction to be fields

String lattitude;
String longitude;

then in doInBackground change the code to be

lattitude = c.getString("lattitude");
longitude= c.getString("longitude");

then they may be used in onClick


问:
What is wrong with this IF statement in rails?
I am trying to only show comments if there are any comments as when there are no comments the for loop shows this (the hash table at the bottom)

The if statement in my code is

```<code><h2>Comments</h2>
<% if @article.comments.any? %>

<%= @article.comments.each do |comment| %>

<p>
  <strong>Commenter:</strong>
  <%= comment.commenter %>
 </p>

 <p>
  <strong>Comment:</strong>
  <%= comment.comment %>
 </p>

 <% end %>
<% end %>
</code>```

What is wrong with my code that it still enters the for loop even when there are no comments?

答:
You've likely built a new comment on the article in order for that create comment form to work above it, so the crux of the problem comes down to any? will look in the in-memory association if it exists, as seen in the following example:

```<code>article = Article.create!
=> #<Article id: 1, created_at: "2017-07-05 02:08:31", updated_at: "2017-07-05 02:08:31">
article.comments.any?
=> false
article.comments.build
=> #<Comment id: nil, article_id: 1, created_at: nil, updated_at: nil>
article.comments.any?
=> true
article.comments.exists?
=> false
</code>```

That's why you're entering the conditional in the first place, and then as others have pointed out, you're outputting the results of the loop (all records iterated) afterwards.

To fix this, you can use exists? instead (as also seen in the example on the last line) which will check the database and not included the one you just built for the form.

Body:
I am trying to only show comments if there are any comments as when there are no comments the for loop shows this (the hash table at the bottom)

The if statement in my code is

Comments

<% if @article.comments.any? %>

<%= @article.comments.each do |comment| %>

  Commenter:
  <%= comment.commenter %>

  Comment:
  <%= comment.comment %>

 <% end %>
<% end %>

What is wrong with my code that it still enters the for loop even when there are no comments?

Body:
You've likely built a new comment on the article in order for that create comment form to work above it, so the crux of the problem comes down to any? will look in the in-memory association if it exists, as seen in the following example:

article = Article.create!
=> #<Article id: 1, created_at: "2017-07-05 02:08:31", updated_at: "2017-07-05 02:08:31">
article.comments.any?
=> false
article.comments.build
=> #<Comment id: nil, article_id: 1, created_at: nil, updated_at: nil>
article.comments.any?
=> true
article.comments.exists?
=> false

That's why you're entering the conditional in the first place, and then as others have pointed out, you're outputting the results of the loop (all records iterated) afterwards.

To fix this, you can use exists? instead (as also seen in the example on the last line) which will check the database and not included the one you just built for the form.


问:
VBA/Excel - cells not recognised as blank until I select and press enter
I have a macro which generates an output sheet to drop into a purpose-built (in C#) application for processing sheets of this type.

Essentially, the code copies one of the sheets from the master sheet and then saves it using a user-generated reference.  It then copies and pastes all of the cells in the sheet as values.

Very frustratingly, in two of the columns in the output sheets, the cells with numbers in them are interspersed with supposedly non-blank cells which do not contain any characters or spaces (and are formatted as "general").  When I use an "IsBlank" formula, these return "FALSE".  However, if I manually click on the cells in question and press "enter", these suddenly return a "TRUE" value.

I am considering getting the macro to select every cell in these columns one by one to resolve this, but that seems criminally inefficient.

Is there a better solution to this problem?

答:
If ISBLANK formula is returning "FALSE", but hitting F2 + Enter return the same as "TRUE", then check if formulas => Workbook calculation is set as "Manual".

Also, data copied from external source may contain non-breaking space, with which Excel often struggles.

If clicking the cell is the only thing that works, you may add a small piece of code block like this, which'll refresh the selected range:

```<code>Sub refresh()
    Dim r1 As Range, r2 As Range
    Set r2 = Selection
    For Each r1 In r2
        r1.Select
        Application.SendKeys "{f2}{enter}"
        DoEvents
    Next
End Sub
</code>```

Body:
If ISBLANK formula is returning "FALSE", but hitting F2 + Enter return the same as "TRUE", then check if formulas => Workbook calculation is set as "Manual".

Also, data copied from external source may contain non-breaking space, with which Excel often struggles.

If clicking the cell is the only thing that works, you may add a small piece of code block like this, which'll refresh the selected range:

Sub refresh()
    Dim r1 As Range, r2 As Range
    Set r2 = Selection
    For Each r1 In r2
        r1.Select
        Application.SendKeys "{f2}{enter}"
        DoEvents
    Next
End Sub


问:
Filter words in a sentence that begin with a certain range of letters
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

```<code>famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""
</code>```

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

```<code>Wheresoever you go, go with all your heart
</code>```

Sample output:

```<code>WHERESOEVER
YOU
WITH
YOUR
HEART
</code>```

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()
```

答:
You can define a neat little generator to split your sentence into words and compare the first letter of each.

```<code>def filter_words(sentence, lo, hi):
    lo, hi = map(str.upper, (lo, hi))
    words = sentence.upper().split()

    for word in words:
        if lo <= word[0] <= hi:
            yield word
</code>```

```<code>sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')

WHERESOEVER
YOU
WITH
YOUR
HEART
</code>```

Body:
My task is to print all words in a sentence whose first letter is within a range of letters, for example: h-z.

This is my code so far, however it still prints words which begin with "g" and does not print the last word.

famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""

I'm only allowed to use ASCII comparisons, I've tried to compare the ASCII values but I don't know how to go about it in this context.

Sample input:

Wheresoever you go, go with all your heart

Sample output:

WHERESOEVER
YOU
WITH
YOUR
HEART

Algorithm I've come up with:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha
 - add character to word
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()

Body:
You can define a neat little generator to split your sentence into words and compare the first letter of each.

def filter_words(sentence, lo, hi):
    lo, hi = map(str.upper, (lo, hi))
    words = sentence.upper().split()

    for word in words:
        if lo <= word[0] <= hi:
            yield word

sentence = 'Wheresoever you go, go with all your heart'
print(*filter_words(sentence, 'h', 'z'), sep='\n')

WHERESOEVER
YOU
WITH
YOUR
HEART


问:
Calculate journey time between two locations (co-ordinates) using google maps api
I have co-ordinates of the start and end location. I want to calculate the total time taken to reach the end point. Is there any google maps static api in which i will pass co-ordinates of the start and end location, and in return it will give total time taken to reach the end point from start one ?

An example of google maps static api is something like this :

```<code>https://maps.googleapis.com/maps/api/staticmap?zoom=13&size=600x300&maptype=roadmap&markers=color:red%7Clabel:C%7C<longitude>,<lat>?&key=<api key>
</code>```

This will return the static map of the given co-ordinates.

答:
For this you have to use Google Directions API

If you have two co-ordinates and you want to know about the total time taken to reach one point, you can do this by passing your co-ordinates as a parameter in this query.

```<code>https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY
</code>```

The response will be a object and in this object there will be all the data that is required for this journey i.e total time, checkpoints, etc

Take a look at this example.

Body:
I have co-ordinates of the start and end location. I want to calculate the total time taken to reach the end point. Is there any google maps static api in which i will pass co-ordinates of the start and end location, and in return it will give total time taken to reach the end point from start one ?

An example of google maps static api is something like this :

https://maps.googleapis.com/maps/api/staticmap?zoom=13&size=600x300&maptype=roadmap&markers=color:red%7Clabel:C%7C<longitude>,<lat>?&key=<api key>

This will return the static map of the given co-ordinates.

Body:
For this you have to use Google Directions API

If you have two co-ordinates and you want to know about the total time taken to reach one point, you can do this by passing your co-ordinates as a parameter in this query.

https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&key=YOUR_API_KEY

The response will be a object and in this object there will be all the data that is required for this journey i.e total time, checkpoints, etc

Take a look at this example.


问:
Azure VMSS with Application gateway
Usecase:
I need to launch VM with VMSS inside application gateway depending on CPU utilization .
In VMSS I need to execute once script if anyone has done this before please share the doc for same.

Thanks.

I have created a custom template but during deployment giving error:
{
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "VMExtensionProvisioningError",
        "message": "VM has reported a failure when processing extension 'updatescriptextension'. Error message: \"Enable failed: failed to execute command: command terminated with exit status=1\"."
      }

Template: https://github.com/linuxgambler/azure/blob/master/vmss.json

答:
That error message you're seeing is due to the custom script extension for linux you are running; in your configuration you have:

"settings": {
  "commandToExecute": "sh /test.sh",
  "enableInternalDNSCheck": "false"
}

But there's no fileUris key to specify where the test.sh file is to be downloaded from (example of how to do this here: https://github.com/Azure/azure-quickstart-templates/blob/master/201-vmss-bottle-autoscale/azuredeploy.json#L229). So it could be that the test.sh file isn't on the VM (unless you got it there some other way?); it could also be something else; you could check the logs in /var/lib/waagent to see what how far the extension got; if you see files in /var/lib/waagent/custom-script/downloads/0, then you should be able to see the stdout and stderr logged there as well.

Title: Azure VMSS with Application gateway


答:
Solution (found through here):</p>

```<code>plot(XTS1, xaxt ="n")
tt <- time(XTS1)
ix <- seq(1, length(tt), by=50)
fmt <- "%b-%d"
labs <- format(tt[ix], fmt)
axis(side = 1, at = tt[ix], labels = labs,  cex.axis = 0.7)
</code>```

Title: Plot XTS object only showing Dates on x-axis

Body:
There is an XTS object, with DateTime stamps as index (multiple entries per day). I want to plot the object against DateTime on the X axis, but only showing Dates (without time). In other words, I want to edit how the x-axis labels are displayed, without affecting the plot. Any ideas?

library(xts)

#Data
XTS1 <- structure(c(0.228369333217119, 0.228289904084397, 0.228447230658951, 0.228791576808238, 0.230747528582736, 0.231930951391005, 0.23218095279688, 0.232655671733178, 0.232780332790686, 0.232737419368931, 0.232662430253128, 0.232742568778743, 0.233149068581523, 0.233801848401534, 0.233772492034511, 0.234624948258082, 0.23483556890299, 0.234796321794256, 0.23604671397228, 0.236133475815726, 0.236165665606426, 0.236028593613328, 0.23653404809854, 0.236405363926972, 0.236289501951192, 0.23595748354442, 0.235856148573546, 0.236430492268466, 0.236509873541663, 0.236320952959145, 0.236324663117125, 0.236230849130264, 0.236256142711785, 0.236443262637705, 0.236474635240435, 0.236478152698594, 0.236446010557742, 0.236433585738065, 0.236318823709326, 0.236343709733496, 0.236353484497234, 0.236293047785645, 0.236299398621113, 0.23632602130195, 0.236415592036867, 0.23644183016732, 0.236410860513062, 0.236407738860613, 0.236488620207848, 0.236521885178186, 0.236524525976254, 0.236543261190294, 0.236545852954505, 0.236554043549182, 0.236558510962661, 0.236500857781485, 0.236456811183667, 0.236429475415132, 0.23640238691203, 0.236406136067832, 0.236417470442709, 0.236338677460503, 0.236460106937516, 0.236499259900878, 0.236586474063617, 0.236543271644404, 0.236513672740977, 0.236369639034221, 0.236362697687712, 0.236797843111073, 0.237345016578261, 0.23783668813706, 0.237923216897962, 0.238248672738757, 0.23827277432708, 0.238353796658431, 0.238432929684165, 0.238426329912625, 0.238345183139418, 0.238458037645863, 0.238479196815153, 0.238658887053061, 0.238465939669501, 0.238523649852224, 0.238510811967291, 0.238618072611544, 0.238704138338676, 0.238707447338575, 0.23996516914318, 0.239424589962875, 0.239561518553478, 0.239421256904757, 0.239816852104079, 0.239445276547969, 0.239609107802299, 0.240012364436436, 0.24002458654273, 0.240130590848021, 0.239736081751086, 0.239857898122929, 0.239230991607954, 0.239805445609213, 0.240333558462471, 0.240410600760776, 0.240378078591145, 0.240399004222477, 0.239804814201628, 0.240033060931268, 0.240089397482534, 0.240197041264942, 0.239940687229403, 0.239983219836939, 0.240022917769706, 0.240337756345468, 0.240638638953238, 0.240145924499555, 0.240402820873626, 0.240634154733532, 0.240611140050359, 0.240534865617682, 0.240951950137048, 0.241127845406939, 0.241125700147753, 0.241126235785769, 0.24107570794763, 0.241088551839332, 0.241092988182315, 0.241086472173767, 0.241083390403282, 0.241091888348645, 0.241083158087253, 0.241064751836135, 0.241064210485496, 0.241091022867438, 0.240953810187424, 0.240481188224338, 0.240621074487305, 0.240541023392083, 0.240396295416436, 0.240434646218793, 0.240610526667198, 0.240808207542551, 0.240631718256586, 0.24064699063015, 0.24068954416015, 0.240711128194114, 0.240723728654195, 0.240775499747258, 0.24076580240029, 0.240772143433637, 0.240793451595961, 0.240796153528682, 0.240819395590463, 0.240807928484687, 0.241070198676456, 0.241015031342511, 0.240992277437459, 0.241067975400449, 0.241065024303712, 0.241163875314065, 0.241210015023487, 0.24111104460957, 0.241143389170502, 0.241126406233165, 0.241236385470386, 0.241216017627354, 0.241242224901225, 0.241204855537627, 0.241161113202215, 0.241188009018793, 0.241155655393916, 0.241104796660299, 0.241229168370518, 0.241187912977691, 0.241205571324508, 0.241275488693839, 0.241201890756208, 0.241062150030789, 0.241056667454678, 0.241020382598737, 0.241011174472952, 0.241075153997628, 0.240860609085096, 0.241671867834864, 0.242222875244792, 0.242105277990476, 0.242789197437053, 0.24262651942461, 0.242835209836078, 0.242065722773181, 0.242128191776504, 0.241866750527435, 0.242222755781399, 0.242405920724485, 0.242704642796114, 0.243681731065406, 0.243823985845211, 0.244075416453679, 0.244168166839201), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(
  formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000, 1413990900, 1413991800, 1413992700, 1413993600, 1413994500, 1413995400, 1413996300, 1413997200, 1413998100, 1413999000, 1413999900, 1414000800, 1414001700, 1414002600, 1414003500, 1414004400, 1414005300, 1414006200, 1414007100, 1414008000, 1414009800, 1414010700, 1414011600, 1414015200, 1414016100, 1414017000, 1414017900, 1414018800, 1414019700, 1414020600, 1414021500, 1414022400, 1414023300, 1414024200, 1414025100, 1414026000, 1414026900, 1414027800, 1414028700, 1414029600, 1414030500, 1414031400, 1414032300, 1414033200, 1414034100, 1414035000, 1414035900, 1414036800, 1414037700, 1414038600, 1414039500, 1414040400, 1414041300, 1414042200, 1414043100, 1414044000, 1414044900, 1414045800, 1414046700, 1414047600, 1414048500, 1414049400, 1414050300, 1414051200, 1414052100, 1414053000, 1414053900, 1414054800, 1414055700, 1414056600, 1414057500, 1414058400, 1414059300, 1414060200, 1414061100, 1414062000, 1414062900, 1414063800, 1414064700, 1414065600, 1414066500, 1414067400, 1414068300, 1414069200, 1414070100, 1414071000, 1414071900, 1414072800, 1414073700, 1414074600, 1414075500, 1414076400, 1414077300, 1414078200, 1414079100, 1414080000, 1414080900, 1414081800, 1414082700, 1414083600, 1414084500, 1414085400, 1414086300, 1414087200, 1414088100, 1414089000, 1414089900, 1414090800, 1414091700, 1414092600, 1414093500, 1414094400, 1414096200, 1414097100, 1414098000, 1414101600, 1414102500, 1414103400, 1414104300, 1414105200, 1414106100, 1414107000, 1414107900, 1414108800, 1414109700, 1414110600, 1414111500, 1414112400, 1414113300, 1414114200, 1414115100, 1414116000, 1414116900, 1414117800, 1414118700, 1414119600, 1414120500, 1414121400, 1414122300, 1414123200, 1414124100, 1414125000, 1414125900, 1414126800, 1414127700, 1414128600, 1414129500, 1414130400, 1414131300, 1414132200, 1414133100, 1414134000, 1414134900, 1414135800, 1414136700, 1414137600, 1414138500, 1414139400, 1414140300, 1414141200, 1414142100, 1414143000, 1414143900, 1414144800, 1414145700, 1414146600, 1414147500, 1414148400, 1414149300, 1414150200, 1414151100, 1414152000, 1414152900, 1414153800, 1414154700, 1414155600, 1414156500, 1414157400, 1414158300, 1414159200, 1414160100, 1414161000, 1414161900, 1414162800, 1414163700, 1414164600, 1414165500, 1414166400, 1414167300), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(199L, 1L))

#This plots showing DateTime on x-axis (rather than just Dates)
plot(XTS1)

#This plots showing Dates on x-axis, but plots against Dates rather than DateTime
DateTime <- index(XTS1)
Date <- as.Date(DateTime)
plot(y=XTS1, x=Date)

#Separating code for x-axis this way did not help
DateTime <- index(XTS1)
Date <- as.Date(DateTime)
plot(y=XTS1, x=Date, xaxt='n')
axis(side = 1, Date)

#Separating code for x-axis this way helped, but Dates showing in undesired format
DateTime <- index(XTS1)
plot(XTS1, xaxt='n')
axis(side = 1, at = time(XTS1))

Body:
Solution (found through here):

plot(XTS1, xaxt ="n")
tt <- time(XTS1)
ix <- seq(1, length(tt), by=50)
fmt <- "%b-%d"
labs <- format(tt[ix], fmt)
axis(side = 1, at = tt[ix], labels = labs,  cex.axis = 0.7)