问:
Vagrant ssh authentication failure
The problem with ssh authentication:

```<code>==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
</code>```

I can Ctrl+C out of the authentication loop and then successfully ssh in manually.

I performed the following steps on the guest box:

Enabled Remote Login for All Users.

Created the ~/.ssh directory with 0700 permissions.

Created the ~/.ssh/authorized_keys file with 0600 permissions.

Pasted this public key
into ~/.ssh/authorized_keys

I've also tried using a private (hostonly) network instead of the public (bridged) network, using this line in the Vagrantfile:

config.vm.network "private_network", ip: "172.16.177.7"

I get the same output (except Adapter 2: hostonly) but then cannot ssh in manually.

I also tried config.vm.network "private_network", ip: "10.0.0.100".

I also tried setting config.ssh.password in the Vagrantfile. This does output SSH auth method: password but still doesn't authenticate.

And I also tried rebuilding the box and rechecking all the above.

It looks like others have had success with this configuration, so there must be something I'm doing wrong.

I found this thread and enabled the GUI, but that doesn't help.

答:
1. Locate the private key in the host:

vagrant ssh-config
#
```

<p>Output:</p>

<pre class="lang-js prettyprint-override"><code>Host default
  ...
  Port 2222
  ...
  IdentityFile /home/me/.vagrant.d/[...]/virtualbox/vagrant_private_key
  ...
</code>```

2. Store the private key path and the port number in variables:

Use these two commands with the output from above:

pk="/home/me/.vagrant.d/.../virtualbox/vagrant_private_key"
port=2222
#
```

<h3>3. Generate a public key and upload it to the guest machine:</h3>

<p>Copy/pasta, no changes needed:</p>

<pre class="lang-shell prettyprint-override"><code>ssh-keygen -y -f $pk > authorized_keys
scp -P $port authorized_keys vagrant@localhost:~/.ssh/
vagrant ssh -c "chmod 600 ~/.ssh/authorized_keys"
rm authorized_keys
#
</code>```

Title: Vagrant ssh authentication failure

Body:
The problem with ssh authentication:

==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: bridged
==> default: Forwarding ports...
    default: 22 => 2222 (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Connection timeout. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...
    default: Error: Authentication failure. Retrying...

I can Ctrl+C out of the authentication loop and then successfully ssh in manually.

I performed the following steps on the guest box:

Enabled Remote Login for All Users.

Created the ~/.ssh directory with 0700 permissions.

Created the ~/.ssh/authorized_keys file with 0600 permissions.

Pasted this public key
into ~/.ssh/authorized_keys

I've also tried using a private (hostonly) network instead of the public (bridged) network, using this line in the Vagrantfile:

config.vm.network "private_network", ip: "172.16.177.7"

I get the same output (except Adapter 2: hostonly) but then cannot ssh in manually.

I also tried config.vm.network "private_network", ip: "10.0.0.100".

I also tried setting config.ssh.password in the Vagrantfile. This does output SSH auth method: password but still doesn't authenticate.

And I also tried rebuilding the box and rechecking all the above.

It looks like others have had success with this configuration, so there must be something I'm doing wrong.

I found this thread and enabled the GUI, but that doesn't help.

Body:
1. Locate the private key in the host:

vagrant ssh-config
#

Output:

Host default
  ...
  Port 2222
  ...
  IdentityFile /home/me/.vagrant.d/[...]/virtualbox/vagrant_private_key
  ...

2. Store the private key path and the port number in variables:

Use these two commands with the output from above:

pk="/home/me/.vagrant.d/.../virtualbox/vagrant_private_key"
port=2222
#

3. Generate a public key and upload it to the guest machine:

Copy/pasta, no changes needed:

ssh-keygen -y -f $pk > authorized_keys
scp -P $port authorized_keys vagrant@localhost:~/.ssh/
vagrant ssh -c "chmod 600 ~/.ssh/authorized_keys"
rm authorized_keys
#


来源: stackexchange

问:
Show a TextView in a FrameLayout
I'm trying to show a TextView in a FrameLayout when the marker is visible.

Like in the code below:

```
                FrameLayout frameLay = new FrameLayout(context);
                FrameLayout.LayoutParams layoutParamsFrame = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT);

                frameLay.setLayoutParams(layoutParamsFrame);

                TextView theText = new TextView(context);
                theText.setText("text_test");
                theText.setTextColor(Color.WHITE);
                theText.setTypeface(Typeface.DEFAULT_BOLD);

                LayoutParams layoutParamsText = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                theText.setLayoutParams(layoutParamsText);
                theText.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);

                first = true;

                frameLay.addView(theText);
```

This does not work for me. The marker is visible and I execute this code, but nothing happens.
How can I fix this?

答:
you can read this post it is explained how to add a TextView to a FrameLayout

```<code>    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);

((FrameLayout) findViewById(R.id.mainLayout)).addView(mEditText, params);
</code>```

So basically you have to add to addView two parameters
so becomes

frameLay.addView(theText,layoutParamsText );

ContentLicense: CC BY-SA 3.0

Title: Show a TextView in a FrameLayout

Body:
I'm trying to show a TextView in a FrameLayout when the marker is visible.

Like in the code below:

                FrameLayout frameLay = new FrameLayout(context);
                FrameLayout.LayoutParams layoutParamsFrame = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT);

                frameLay.setLayoutParams(layoutParamsFrame);

                TextView theText = new TextView(context);
                theText.setText("text_test");
                theText.setTextColor(Color.WHITE);
                theText.setTypeface(Typeface.DEFAULT_BOLD);

                LayoutParams layoutParamsText = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                theText.setLayoutParams(layoutParamsText);
                theText.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);

                first = true;

                frameLay.addView(theText);

This does not work for me. The marker is visible and I execute this code, but nothing happens.
How can I fix this?

Body:
you can read this post it is explained how to add a TextView to a FrameLayout

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);

((FrameLayout) findViewById(R.id.mainLayout)).addView(mEditText, params);

So basically you have to add to addView two parameters
so becomes

frameLay.addView(theText,layoutParamsText );


问:
Custom Elements Illegal Constructor in FireFox
I have a CustomElement with the following constructor:

```<code>export default class SomeCustomElement extends HTMLElement {
    constructor(templateId) {
        super();
        this.insertTemplateInstance(templateId);
    }
    ...
}
</code>```

I can register that Element in Chrome without any Problems.

But using Firefox with the polyfill loaded by webcomponents-loader.js from https://github.com/webcomponents/webcomponentsjs I get the ErrorMessage TypeError: Illegal constructor when calling super().

Does anybody know what is causing this?

Some more Background:

Registering of the custom Elements happens like this:

```<code>window.addEventListener("WebComponentsReady", function () {
    customElements.define(elementName, SomeCustomElement);
});
</code>```

答:
Caveat upfront: I'm not a huge fan of html imports. I stumbled across this trying to get ES 6 class-based custom elements to work in Firefox. For a conditional-polyfill-loading-no-html-import solution based on the accepted answer, read on...

To conditionally load the polyfills gets a little tricky. Per @Supersharp's answer/comments, for some reason the polyfill must be loaded synchronously (despite there being no mention of this in the official documentation). So now you have two unappealing options: include it unconditionally to get the necessary synchronous loading or...use document.write:

```<code><script>
;(function() {
  var str = '';
  // You could make this more fine-grained if desired by doing
  // more feature detection and loading the minimal polyfill file
  if (!window.customElements) str += '<script src="./node_modules/@webcomponents/webcomponentsjs/webcomponents-lite.js"></script>';
  str += '<script src="./elements.js"></script>';
  document.write(str);
})();
</script>
<foo-bar></foo-bar>
</code>```

Then in elements.js:

```<code>class FooBar extends HTMLElement {
  constructor () {
    console.log("constructing");
    super();
  }

  connectedCallback () {
    console.log("connecting");
  }

  disconnectedCallback () {
    console.log("disconnecting");
  }
};
// Note that because of the synchronous loading we don't
// need to listen for the event
customElements.define('foo-bar', FooBar);
</code>```

document.write is widely disliked for good reasons but this is IMHO a legitimate use case. Note that most of the objections here (no pre-fetch, etc.) can be ameliorated through use of service workers (for browsers that support them).

Body:
I have a CustomElement with the following constructor:

export default class SomeCustomElement extends HTMLElement {
    constructor(templateId) {
        super();
        this.insertTemplateInstance(templateId);
    }
    ...
}

I can register that Element in Chrome without any Problems.

But using Firefox with the polyfill loaded by webcomponents-loader.js from https://github.com/webcomponents/webcomponentsjs I get the ErrorMessage TypeError: Illegal constructor when calling super().

Does anybody know what is causing this?

Some more Background:

Registering of the custom Elements happens like this:

window.addEventListener("WebComponentsReady", function () {
    customElements.define(elementName, SomeCustomElement);
});

Body:
Caveat upfront: I'm not a huge fan of html imports. I stumbled across this trying to get ES 6 class-based custom elements to work in Firefox. For a conditional-polyfill-loading-no-html-import solution based on the accepted answer, read on...

To conditionally load the polyfills gets a little tricky. Per @Supersharp's answer/comments, for some reason the polyfill must be loaded synchronously (despite there being no mention of this in the official documentation). So now you have two unappealing options: include it unconditionally to get the necessary synchronous loading or...use document.write:

<script>
;(function() {
  var str = '';
  // You could make this more fine-grained if desired by doing
  // more feature detection and loading the minimal polyfill file
  if (!window.customElements) str += '<script src="./node_modules/@webcomponents/webcomponentsjs/webcomponents-lite.js"></script>';
  str += '<script src="./elements.js"></script>';
  document.write(str);
})();
</script>
<foo-bar></foo-bar>

Then in elements.js:

class FooBar extends HTMLElement {
  constructor () {
    console.log("constructing");
    super();
  }

  connectedCallback () {
    console.log("connecting");
  }

  disconnectedCallback () {
    console.log("disconnecting");
  }
};
// Note that because of the synchronous loading we don't
// need to listen for the event
customElements.define('foo-bar', FooBar);

document.write is widely disliked for good reasons but this is IMHO a legitimate use case. Note that most of the objections here (no pre-fetch, etc.) can be ameliorated through use of service workers (for browsers that support them).


问:
Binding dropdown list in a gridview edit item template
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

```<code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}
</code>```

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

答:
Its a solution for me:</p>

```<code>protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drpBuildServers;

        drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;

        if (drpBuildServers != null)
            // Write your code here
    }
}
</code>```

OwnerDisplayName: Renju

LastEditorDisplayName: ScarletGarden

ContentLicense: CC BY-SA 2.5

Body:
i can bind the dropdownlist in the edit item template. The drop down list is having null values.

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
  DropDownList drpBuildServers = new DropDownList();

  if (grdDevelopment.EditIndex == e.Row.RowIndex)
  {
      drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
  }
}

also getting an error

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

Body:
Its a solution for me:

protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList drpBuildServers;

        drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;

        if (drpBuildServers != null)
            // Write your code here
    }
}


问:
How to delay the removal of a class for a dropdown mega menu Bootstrap 4?
I am trying to toggle a class on a navbar toggle but when you move your mouse the the dropdown menu it quickly removes the class and hides the menu. I think what it needs is a delay on just the removal of the class but the showing of the class can still be instant. Here is a screenshot of the hover issue https://i.imgur.com/o8ccCn9.gifv

Is there a manual way to write a toggle?

Codepen: https://codepen.io/JacobLett/pen/jaaQYG?editors=0110

This is the script so far

```<code>$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready

  // when you hover a toggle show its dropdown menu
  $(".navbar .dropdown-toggle").hover(function () {
     $(this).parent().toggleClass("show");
     $(this).parent().find(".dropdown-menu").toggleClass("show");
   });

    // hide the menu when the mouse leaves the dropdown
  $( ".navbar .dropdown-menu" ).mouseleave(function() {
    $(this).removeClass("show");
  });

// document ready
});
</code>```

Update I guess .hover doesn't take into consideration the child elements. If it did my code would work. So I tried mouseenter and mouseleave but since the dropdown is position absolute it doesn't work with this either.

答:
You could use the native JavaScript setTimeout() method...

```<code>$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready

  // when you hover a toggle show its dropdown menu
  $(".navbar .dropdown-toggle").hover(function () {
     $(this).parent().toggleClass("show");
     $(this).parent().find(".dropdown-menu").toggleClass("show");
   });

    // hide the menu when the mouse leaves the dropdown
  $( ".navbar .dropdown-menu" ).mouseleave(function() {
    setTimeout(function() {
      $(this).removeClass("show");
    }, 3000); // delay the removal of the 'show' class for 3 seconds
  });

// document ready
});
</code>```

Body:
I am trying to toggle a class on a navbar toggle but when you move your mouse the the dropdown menu it quickly removes the class and hides the menu. I think what it needs is a delay on just the removal of the class but the showing of the class can still be instant. Here is a screenshot of the hover issue https://i.imgur.com/o8ccCn9.gifv

Is there a manual way to write a toggle?

Codepen: https://codepen.io/JacobLett/pen/jaaQYG?editors=0110

This is the script so far

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready

  // when you hover a toggle show its dropdown menu
  $(".navbar .dropdown-toggle").hover(function () {
     $(this).parent().toggleClass("show");
     $(this).parent().find(".dropdown-menu").toggleClass("show");
   });

    // hide the menu when the mouse leaves the dropdown
  $( ".navbar .dropdown-menu" ).mouseleave(function() {
    $(this).removeClass("show");
  });

// document ready
});

Update I guess .hover doesn't take into consideration the child elements. If it did my code would work. So I tried mouseenter and mouseleave but since the dropdown is position absolute it doesn't work with this either.

Body:
You could use the native JavaScript setTimeout() method...

$(document).ready(function() {
 // executes when HTML-Document is loaded and DOM is ready

  // when you hover a toggle show its dropdown menu
  $(".navbar .dropdown-toggle").hover(function () {
     $(this).parent().toggleClass("show");
     $(this).parent().find(".dropdown-menu").toggleClass("show");
   });

    // hide the menu when the mouse leaves the dropdown
  $( ".navbar .dropdown-menu" ).mouseleave(function() {
    setTimeout(function() {
      $(this).removeClass("show");
    }, 3000); // delay the removal of the 'show' class for 3 seconds
  });

// document ready
});


问:
How to resolve java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 2?
I am trying to execute NLTK in Hadoop environment. Following is the command which i used for execution.

```<code>bin/hadoop jar $HADOOP_HOME/contrib/streaming/hadoop-streaming-1.0.4.jar -input /user/nltk/input/ -output /user/nltk/output1/ -file /home/hduser/softwares/NLTK/unsupervised_sentiment-master.zip -mapper /home/hduser/softwares/NLTK/unsupervised_sentiment-master/sentiment.py
</code>```

unsupervised_sentiment-master.zip --- contains all the dependent files required for sentiment.py

I am getting

```<code>java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 2
    at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:362)
    at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:576)
    at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:135)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:57)
    at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:36)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:436)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
    at org.apache.hadoop.mapred.Child.main(Child.java:249)
</code>```

Any help would be greatly appreciated!!!

答:
In your sentiment.py file, add the following line to the top:

```</p>

<h1>!/usr/bin/env python</h1>

<p>```

This worked for me.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to execute NLTK in Hadoop environment. Following is the command which i used for execution.

bin/hadoop jar $HADOOP_HOME/contrib/streaming/hadoop-streaming-1.0.4.jar -input /user/nltk/input/ -output /user/nltk/output1/ -file /home/hduser/softwares/NLTK/unsupervised_sentiment-master.zip -mapper /home/hduser/softwares/NLTK/unsupervised_sentiment-master/sentiment.py

unsupervised_sentiment-master.zip --- contains all the dependent files required for sentiment.py

I am getting

java.lang.RuntimeException: PipeMapRed.waitOutputThreads(): subprocess failed with code 2
    at org.apache.hadoop.streaming.PipeMapRed.waitOutputThreads(PipeMapRed.java:362)
    at org.apache.hadoop.streaming.PipeMapRed.mapRedFinished(PipeMapRed.java:576)
    at org.apache.hadoop.streaming.PipeMapper.close(PipeMapper.java:135)
    at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:57)
    at org.apache.hadoop.streaming.PipeMapRunner.run(PipeMapRunner.java:36)
    at org.apache.hadoop.mapred.MapTask.runOldMapper(MapTask.java:436)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:372)
    at org.apache.hadoop.mapred.Child$4.run(Child.java:255)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1121)
    at org.apache.hadoop.mapred.Child.main(Child.java:249)

Any help would be greatly appreciated!!!


问:
Why can't I get Bootstrap4 to work in my Rails5 app?
I am trying to move a Rails 5 app from using the bootstrap-sass gem onto bootstrap4 through the bootstrap-rubygem gem. Despite following the instructions here and the suggestions in this post here I cannot get bootstrap styles to apply, views load and run without error, just no bootstrap styling at all.

Other than the obvious, things I have done are;

gem uninstall gem bootstrap-sass

rake assets:precompile

Here's my code, can anyone see what I'm getting wrong?

Example of a view that renders fine without error, just with zero bootstrap styling taking effect;

_navbar.html.erb:

```<code><ul class="nav navbar-nav navbar-right">
    <% if user_signed_in? %>
      <li><%= link_to_unless_current('My Quotes', quotes_path(current_user)) do %></li>
                  <% end %>
      <li><%= link_to_unless_current_or_root('New Quote', new_quote_path) %></li>
      <li><%= link_to('My Account', edit_user_registration_path) %></li>
      <li><%= link_to "Sign out", destroy_user_session_path, :method => :delete %></li>
    <% else %>
      <li><%= link_to('Sign in', new_user_session_path) %></li>
      <li><%= link_to('Sign up', new_user_registration_path) %></li>
    <% end %>
</ul>
</code>```

application.scss;

@import 'bootstrap';

application.js;

```<code>//= require jquery3
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-sprockets
//= require popper
//= require turbolinks
//= require_tree .
//= require_self
</code>```

gemfile;

```<code>source 'https://rubygems.org'

gem 'pry-rails'
gem 'watir'
gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'simple_form'
gem 'devise'
gem 'cancancan', '~> 1.10'
gem 'gon'
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: '776037c0fc799bb09da8c9ea47980bd3bf296874'
gem 'axlsx_rails'
gem 'validates_email_format_of'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
  gem 'rspec-rails', :group => [:test, :development]
  gem 'spring-commands-rspec'
  gem 'rails-controller-testing'
  gem 'factory_girl_rails'
    group :test do
        gem 'capybara'
      gem 'database_cleaner'
      gem 'shoulda-matchers', require: false
    end
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
</code>```

bundle returns this;

```<code>Using rake 12.0.0
Using concurrent-ruby 1.0.5
Using i18n 0.8.1
Using minitest 5.10.2
Using thread_safe 0.3.6
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 2.0.3
Using nio4r 2.0.0
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 7.1.4
Using public_suffix 2.0.5
Using execjs 2.7.0
Using htmlentities 4.3.4
Using mimemagic 0.3.2
Using rubyzip 1.2.1
Using bcrypt 3.1.11
Using bindex 0.5.0
Using popper_js 1.9.9
Using sass 3.4.24
Using byebug 9.0.6
Using cancancan 1.17.0
Using ffi 1.9.18
Using coderay 1.1.1
Using coffee-script-source 1.12.2
Using method_source 0.8.2
Using thor 0.19.4
Using database_cleaner 1.6.1
Using orm_adapter 0.5.0
Using diff-lcs 1.3
Using json 2.1.0
Using multi_json 1.12.1
Using request_store 1.3.2
Using rb-fsevent 0.9.8
Using pg 0.20.0
Using slop 3.6.0
Using puma 3.8.2
Using bundler 1.13.6
Using rspec-support 3.6.0
Using tilt 2.0.7
Using websocket 1.2.4
Using turbolinks-source 5.0.3
Using validates_email_format_of 1.6.3
Using tzinfo 1.2.3
Using nokogiri 1.7.2
Using rack-test 0.6.3
Using warden 1.2.7
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using addressable 2.5.1
Using autoprefixer-rails 7.1.1.2
Using uglifier 3.2.0
Using childprocess 0.7.0
Using rb-inotify 0.9.8
Using coffee-script 2.4.1
Using pry 0.10.4
Using rspec-core 3.6.0
Using rspec-expectations 3.6.0
Using rspec-mocks 3.6.0
Using turbolinks 5.0.1
Using activesupport 5.0.3
Using loofah 2.0.3
Using axlsx 2.1.0.pre from https://github.com/randym/axlsx.git (at 776037c@776037c)
Using xpath 2.1.0
Using mail 2.6.5
Using bootstrap 4.0.0.alpha6 from https://github.com/twbs/bootstrap-rubygem (at master@7cdeca9)
Using selenium-webdriver 3.4.0
Using listen 3.0.8
Using pry-rails 0.3.6
Using rails-dom-testing 2.0.3
Using globalid 0.4.0
Using activemodel 5.0.3
Using factory_girl 4.8.0
Using jbuilder 2.6.4
Using shoulda-matchers 3.1.1
Using spring 2.0.2
Using rails-html-sanitizer 1.0.3
Using capybara 2.14.0
Using watir 6.2.1
Using activejob 5.0.3
Using activerecord 5.0.3
Using spring-commands-rspec 1.0.4
Using spring-watcher-listen 2.0.1
Using actionview 5.0.3
Using actionpack 5.0.3
Using actioncable 5.0.3
Using actionmailer 5.0.3
Using axlsx_rails 0.5.1
Using railties 5.0.3
Using gon 6.1.0
Using sprockets-rails 3.2.0
Using rails-controller-testing 0.1.1
Using simple_form 3.5.0
Using coffee-rails 4.2.2
Using responders 2.4.0
Using factory_girl_rails 4.8.0
Using jquery-rails 4.3.1
Using rspec-rails 3.6.0
Using web-console 3.5.1
Using rails 5.0.3
Using sass-rails 5.0.6
Using devise 4.3.0
Bundle complete! 33 Gemfile dependencies, 105 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
</code>```

rails -v returns;

```<code>Rails 5.0.3
</code>```

ruby -v returns;

```<code>ruby 2.3.0p0
</code>```

gem list returns;

```<code>    *** LOCAL GEMS ***

actioncable (5.0.3, 5.0.0.1)
actionmailer (5.0.3, 5.0.0.1)
actionpack (5.0.3, 5.0.0.1)
actionview (5.0.3, 5.0.0.1)
activejob (5.0.3, 5.0.0.1)
activemodel (5.0.3, 5.0.0.1)
activerecord (5.0.3, 5.0.0.1)
activesupport (5.0.3, 5.0.0.1)
addressable (2.5.1)
ansi (1.5.0)
arel (7.1.4, 7.1.1)
autoprefixer-rails (7.1.1.2, 6.4.1)
axlsx_rails (0.5.1)
bcrypt (3.1.11)
bigdecimal (default: 1.2.8)
bindex (0.5.0)
bootstrap-will_paginate (0.0.10)
builder (3.2.3, 3.2.2)
bundler (1.13.6)
bundler-unload (1.0.2)
byebug (9.0.6, 9.0.0)
cancancan (1.17.0)
capybara (2.14.0)
carrierwave (0.11.2)
CFPropertyList (2.3.2)
childprocess (0.7.0)
coderay (1.1.1)
coffee-rails (4.2.2, 4.2.1)
coffee-script (2.4.1)
coffee-script-source (1.12.2, 1.10.0)
concurrent-ruby (1.0.5, 1.0.2)
database_cleaner (1.6.1)
debug_inspector (0.0.2)
devise (4.3.0)
did_you_mean (1.0.2, 1.0.0)
diff-lcs (1.3)
erubis (2.7.0)
excon (0.52.0)
execjs (2.7.0)
executable-hooks (1.3.2)
factory_girl (4.8.0)
factory_girl_rails (4.8.0)
faker (1.6.6, 1.6.3)
ffi (1.9.18, 1.9.14)
fission (0.5.0)
fog (1.38.0)
fog-aliyun (0.1.0)
fog-atmos (0.1.0)
fog-aws (0.11.0)
fog-brightbox (0.11.0)
fog-cloudatcost (0.1.2)
fog-core (1.42.0)
fog-dynect (0.0.3)
fog-ecloud (0.3.0)
fog-google (0.1.0)
fog-json (1.0.2)
fog-local (0.3.0)
fog-openstack (0.1.12)
fog-powerdns (0.1.1)
fog-profitbricks (0.0.5)
fog-rackspace (0.1.1)
fog-radosgw (0.0.5)
fog-riakcs (0.1.0)
fog-sakuracloud (1.7.5)
fog-serverlove (0.1.2)
fog-softlayer (1.1.4)
fog-storm_on_demand (0.1.1)
fog-terremark (0.1.0)
fog-vmfusion (0.1.0)
fog-voxel (0.1.0)
fog-vsphere (1.0.1)
fog-xenserver (0.2.3)
fog-xml (0.1.2)
formatador (0.2.5)
gem-wrappers (1.2.7)
globalid (0.4.0, 0.3.7)
gon (6.1.0)
guard (2.13.0)
guard-compat (1.2.1)
guard-minitest (2.4.4)
htmlentities (4.3.4)
i18n (0.8.1, 0.7.0)
inflecto (0.0.2)
io-console (0.4.6, default: 0.4.5)
ipaddress (0.8.3)
jbuilder (2.6.4, 2.4.1)
jquery-rails (4.3.1, 4.1.1)
json (2.1.0, 2.0.2, default: 1.8.3)
listen (3.0.8)
loofah (2.0.3)
lumberjack (1.0.10)
mail (2.6.5, 2.6.4)
method_source (0.8.2)
mime-types (3.1)
mime-types-data (3.2016.0521)
mimemagic (0.3.2)
mini_magick (4.5.1)
mini_portile2 (2.1.0)
minitest (5.10.2, 5.9.1, 5.9.0, 5.8.3)
minitest-reporters (1.1.9)
multi_json (1.12.1)
nenv (0.3.0)
net-telnet (0.1.1)
nio4r (2.0.0, 1.2.1)
nokogiri (1.7.2, 1.6.8.1, 1.6.8)
notiffany (0.1.1)
orm_adapter (0.5.0)
pg (0.20.0, 0.18.4)
pkg-config (1.1.7)
popper_js (1.9.9)
power_assert (0.3.1, 0.2.6)
pry (0.10.4)
pry-rails (0.3.6)
psych (2.2.0, default: 2.0.17)
public_suffix (2.0.5)
puma (3.8.2, 3.4.0)
rack (2.0.3, 2.0.1)
rack-test (0.6.3)
rails (5.0.3, 5.0.0.1)
rails-controller-testing (0.1.1)
rails-dom-testing (2.0.3, 2.0.1)
rails-html-sanitizer (1.0.3)
railties (5.0.3, 5.0.0.1)
rake (12.0.0, 11.3.0, 11.2.2, 10.4.2)
rb-fsevent (0.9.8, 0.9.7)
rb-inotify (0.9.8, 0.9.7)
rbvmomi (1.8.2)
rdoc (5.0.0, default: 4.2.1)
request_store (1.3.2)
responders (2.4.0)
rspec-core (3.6.0)
rspec-expectations (3.6.0)
rspec-mocks (3.6.0)
rspec-rails (3.6.0)
rspec-support (3.6.0)
ruby-progressbar (1.8.1)
rubygems-bundler (1.4.4)
rubygems-update (2.6.12, 2.6.8)
rubyzip (1.2.1)
rvm (1.11.3.9)
sass (3.4.24, 3.4.22)
sass-rails (5.0.6)
selenium-webdriver (3.4.0)
shellany (0.0.1)
shoulda-matchers (3.1.1)
simple_form (3.5.0)
slop (3.6.0)
spring (2.0.2, 1.7.2)
spring-commands-rspec (1.0.4)
spring-watcher-listen (2.0.1, 2.0.0)
sprockets (3.7.1, 3.7.0)
sprockets-rails (3.2.0)
sqlite3 (1.3.11)
test-unit (3.2.2, 3.1.5)
thor (0.19.4, 0.19.1)
thread_safe (0.3.6, 0.3.5)
tilt (2.0.7, 2.0.5)
trollop (2.1.2)
turbolinks (5.0.1)
turbolinks-source (5.0.3, 5.0.0)
tzinfo (1.2.3, 1.2.2)
uglifier (3.2.0, 3.0.0)
validates_email_format_of (1.6.3)
warden (1.2.7)
watir (6.2.1)
web-console (3.5.1, 3.1.1)
websocket (1.2.4)
websocket-driver (0.6.5, 0.6.4)
websocket-extensions (0.1.2)
will_paginate (3.1.0)
xml-simple (1.1.5)
xpath (2.1.0)
</code>```

答: Try putting //= require popper before //= require bootstrap & //= require bootstrap-sprockets

Body:
I am trying to move a Rails 5 app from using the bootstrap-sass gem onto bootstrap4 through the bootstrap-rubygem gem. Despite following the instructions here and the suggestions in this post here I cannot get bootstrap styles to apply, views load and run without error, just no bootstrap styling at all.

Other than the obvious, things I have done are;

gem uninstall gem bootstrap-sass

rake assets:precompile

Here's my code, can anyone see what I'm getting wrong?

Example of a view that renders fine without error, just with zero bootstrap styling taking effect;

_navbar.html.erb:

    <% if user_signed_in? %>

<%= link_to_unless_current('My Quotes', quotes_path(current_user)) do %>

                  <% end %>

<%= link_to_unless_current_or_root('New Quote', new_quote_path) %>

<%= link_to('My Account', edit_user_registration_path) %>

<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>

    <% else %>

<%= link_to('Sign in', new_user_session_path) %>

<%= link_to('Sign up', new_user_registration_path) %>

    <% end %>

application.scss;

@import 'bootstrap';

application.js;

//= require jquery3
//= require jquery_ujs
//= require bootstrap
//= require bootstrap-sprockets
//= require popper
//= require turbolinks
//= require_tree .
//= require_self

gemfile;

source 'https://rubygems.org'

gem 'pry-rails'
gem 'watir'
gem 'bootstrap', git: 'https://github.com/twbs/bootstrap-rubygem'
gem 'simple_form'
gem 'devise'
gem 'cancancan', '~> 1.10'
gem 'gon'
gem 'rubyzip', '>= 1.2.1'
gem 'axlsx', git: 'https://github.com/randym/axlsx.git', ref: '776037c0fc799bb09da8c9ea47980bd3bf296874'
gem 'axlsx_rails'
gem 'validates_email_format_of'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use postgresql as the database for Active Record
gem 'pg', '~> 0.18'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
  gem 'rspec-rails', :group => [:test, :development]
  gem 'spring-commands-rspec'
  gem 'rails-controller-testing'
  gem 'factory_girl_rails'
    group :test do
        gem 'capybara'
      gem 'database_cleaner'
      gem 'shoulda-matchers', require: false
    end
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

bundle returns this;

Using rake 12.0.0
Using concurrent-ruby 1.0.5
Using i18n 0.8.1
Using minitest 5.10.2
Using thread_safe 0.3.6
Using builder 3.2.3
Using erubis 2.7.0
Using mini_portile2 2.1.0
Using rack 2.0.3
Using nio4r 2.0.0
Using websocket-extensions 0.1.2
Using mime-types-data 3.2016.0521
Using arel 7.1.4
Using public_suffix 2.0.5
Using execjs 2.7.0
Using htmlentities 4.3.4
Using mimemagic 0.3.2
Using rubyzip 1.2.1
Using bcrypt 3.1.11
Using bindex 0.5.0
Using popper_js 1.9.9
Using sass 3.4.24
Using byebug 9.0.6
Using cancancan 1.17.0
Using ffi 1.9.18
Using coderay 1.1.1
Using coffee-script-source 1.12.2
Using method_source 0.8.2
Using thor 0.19.4
Using database_cleaner 1.6.1
Using orm_adapter 0.5.0
Using diff-lcs 1.3
Using json 2.1.0
Using multi_json 1.12.1
Using request_store 1.3.2
Using rb-fsevent 0.9.8
Using pg 0.20.0
Using slop 3.6.0
Using puma 3.8.2
Using bundler 1.13.6
Using rspec-support 3.6.0
Using tilt 2.0.7
Using websocket 1.2.4
Using turbolinks-source 5.0.3
Using validates_email_format_of 1.6.3
Using tzinfo 1.2.3
Using nokogiri 1.7.2
Using rack-test 0.6.3
Using warden 1.2.7
Using sprockets 3.7.1
Using websocket-driver 0.6.5
Using mime-types 3.1
Using addressable 2.5.1
Using autoprefixer-rails 7.1.1.2
Using uglifier 3.2.0
Using childprocess 0.7.0
Using rb-inotify 0.9.8
Using coffee-script 2.4.1
Using pry 0.10.4
Using rspec-core 3.6.0
Using rspec-expectations 3.6.0
Using rspec-mocks 3.6.0
Using turbolinks 5.0.1
Using activesupport 5.0.3
Using loofah 2.0.3
Using axlsx 2.1.0.pre from https://github.com/randym/axlsx.git (at 776037c@776037c)
Using xpath 2.1.0
Using mail 2.6.5
Using bootstrap 4.0.0.alpha6 from https://github.com/twbs/bootstrap-rubygem (at master@7cdeca9)
Using selenium-webdriver 3.4.0
Using listen 3.0.8
Using pry-rails 0.3.6
Using rails-dom-testing 2.0.3
Using globalid 0.4.0
Using activemodel 5.0.3
Using factory_girl 4.8.0
Using jbuilder 2.6.4
Using shoulda-matchers 3.1.1
Using spring 2.0.2
Using rails-html-sanitizer 1.0.3
Using capybara 2.14.0
Using watir 6.2.1
Using activejob 5.0.3
Using activerecord 5.0.3
Using spring-commands-rspec 1.0.4
Using spring-watcher-listen 2.0.1
Using actionview 5.0.3
Using actionpack 5.0.3
Using actioncable 5.0.3
Using actionmailer 5.0.3
Using axlsx_rails 0.5.1
Using railties 5.0.3
Using gon 6.1.0
Using sprockets-rails 3.2.0
Using rails-controller-testing 0.1.1
Using simple_form 3.5.0
Using coffee-rails 4.2.2
Using responders 2.4.0
Using factory_girl_rails 4.8.0
Using jquery-rails 4.3.1
Using rspec-rails 3.6.0
Using web-console 3.5.1
Using rails 5.0.3
Using sass-rails 5.0.6
Using devise 4.3.0
Bundle complete! 33 Gemfile dependencies, 105 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.

rails -v returns;

Rails 5.0.3

ruby -v returns;

ruby 2.3.0p0

gem list returns;

    *** LOCAL GEMS ***

actioncable (5.0.3, 5.0.0.1)
actionmailer (5.0.3, 5.0.0.1)
actionpack (5.0.3, 5.0.0.1)
actionview (5.0.3, 5.0.0.1)
activejob (5.0.3, 5.0.0.1)
activemodel (5.0.3, 5.0.0.1)
activerecord (5.0.3, 5.0.0.1)
activesupport (5.0.3, 5.0.0.1)
addressable (2.5.1)
ansi (1.5.0)
arel (7.1.4, 7.1.1)
autoprefixer-rails (7.1.1.2, 6.4.1)
axlsx_rails (0.5.1)
bcrypt (3.1.11)
bigdecimal (default: 1.2.8)
bindex (0.5.0)
bootstrap-will_paginate (0.0.10)
builder (3.2.3, 3.2.2)
bundler (1.13.6)
bundler-unload (1.0.2)
byebug (9.0.6, 9.0.0)
cancancan (1.17.0)
capybara (2.14.0)
carrierwave (0.11.2)
CFPropertyList (2.3.2)
childprocess (0.7.0)
coderay (1.1.1)
coffee-rails (4.2.2, 4.2.1)
coffee-script (2.4.1)
coffee-script-source (1.12.2, 1.10.0)
concurrent-ruby (1.0.5, 1.0.2)
database_cleaner (1.6.1)
debug_inspector (0.0.2)
devise (4.3.0)
did_you_mean (1.0.2, 1.0.0)
diff-lcs (1.3)
erubis (2.7.0)
excon (0.52.0)
execjs (2.7.0)
executable-hooks (1.3.2)
factory_girl (4.8.0)
factory_girl_rails (4.8.0)
faker (1.6.6, 1.6.3)
ffi (1.9.18, 1.9.14)
fission (0.5.0)
fog (1.38.0)
fog-aliyun (0.1.0)
fog-atmos (0.1.0)
fog-aws (0.11.0)
fog-brightbox (0.11.0)
fog-cloudatcost (0.1.2)
fog-core (1.42.0)
fog-dynect (0.0.3)
fog-ecloud (0.3.0)
fog-google (0.1.0)
fog-json (1.0.2)
fog-local (0.3.0)
fog-openstack (0.1.12)
fog-powerdns (0.1.1)
fog-profitbricks (0.0.5)
fog-rackspace (0.1.1)
fog-radosgw (0.0.5)
fog-riakcs (0.1.0)
fog-sakuracloud (1.7.5)
fog-serverlove (0.1.2)
fog-softlayer (1.1.4)
fog-storm_on_demand (0.1.1)
fog-terremark (0.1.0)
fog-vmfusion (0.1.0)
fog-voxel (0.1.0)
fog-vsphere (1.0.1)
fog-xenserver (0.2.3)
fog-xml (0.1.2)
formatador (0.2.5)
gem-wrappers (1.2.7)
globalid (0.4.0, 0.3.7)
gon (6.1.0)
guard (2.13.0)
guard-compat (1.2.1)
guard-minitest (2.4.4)
htmlentities (4.3.4)
i18n (0.8.1, 0.7.0)
inflecto (0.0.2)
io-console (0.4.6, default: 0.4.5)
ipaddress (0.8.3)
jbuilder (2.6.4, 2.4.1)
jquery-rails (4.3.1, 4.1.1)
json (2.1.0, 2.0.2, default: 1.8.3)
listen (3.0.8)
loofah (2.0.3)
lumberjack (1.0.10)
mail (2.6.5, 2.6.4)
method_source (0.8.2)
mime-types (3.1)
mime-types-data (3.2016.0521)
mimemagic (0.3.2)
mini_magick (4.5.1)
mini_portile2 (2.1.0)
minitest (5.10.2, 5.9.1, 5.9.0, 5.8.3)
minitest-reporters (1.1.9)
multi_json (1.12.1)
nenv (0.3.0)
net-telnet (0.1.1)
nio4r (2.0.0, 1.2.1)
nokogiri (1.7.2, 1.6.8.1, 1.6.8)
notiffany (0.1.1)
orm_adapter (0.5.0)
pg (0.20.0, 0.18.4)
pkg-config (1.1.7)
popper_js (1.9.9)
power_assert (0.3.1, 0.2.6)
pry (0.10.4)
pry-rails (0.3.6)
psych (2.2.0, default: 2.0.17)
public_suffix (2.0.5)
puma (3.8.2, 3.4.0)
rack (2.0.3, 2.0.1)
rack-test (0.6.3)
rails (5.0.3, 5.0.0.1)
rails-controller-testing (0.1.1)
rails-dom-testing (2.0.3, 2.0.1)
rails-html-sanitizer (1.0.3)
railties (5.0.3, 5.0.0.1)
rake (12.0.0, 11.3.0, 11.2.2, 10.4.2)
rb-fsevent (0.9.8, 0.9.7)
rb-inotify (0.9.8, 0.9.7)
rbvmomi (1.8.2)
rdoc (5.0.0, default: 4.2.1)
request_store (1.3.2)
responders (2.4.0)
rspec-core (3.6.0)
rspec-expectations (3.6.0)
rspec-mocks (3.6.0)
rspec-rails (3.6.0)
rspec-support (3.6.0)
ruby-progressbar (1.8.1)
rubygems-bundler (1.4.4)
rubygems-update (2.6.12, 2.6.8)
rubyzip (1.2.1)
rvm (1.11.3.9)
sass (3.4.24, 3.4.22)
sass-rails (5.0.6)
selenium-webdriver (3.4.0)
shellany (0.0.1)
shoulda-matchers (3.1.1)
simple_form (3.5.0)
slop (3.6.0)
spring (2.0.2, 1.7.2)
spring-commands-rspec (1.0.4)
spring-watcher-listen (2.0.1, 2.0.0)
sprockets (3.7.1, 3.7.0)
sprockets-rails (3.2.0)
sqlite3 (1.3.11)
test-unit (3.2.2, 3.1.5)
thor (0.19.4, 0.19.1)
thread_safe (0.3.6, 0.3.5)
tilt (2.0.7, 2.0.5)
trollop (2.1.2)
turbolinks (5.0.1)
turbolinks-source (5.0.3, 5.0.0)
tzinfo (1.2.3, 1.2.2)
uglifier (3.2.0, 3.0.0)
validates_email_format_of (1.6.3)
warden (1.2.7)
watir (6.2.1)
web-console (3.5.1, 3.1.1)
websocket (1.2.4)
websocket-driver (0.6.5, 0.6.4)
websocket-extensions (0.1.2)
will_paginate (3.1.0)
xml-simple (1.1.5)
xpath (2.1.0)


问:
How do I create a dynamic variable name in React?
In React, I am trying to dynamically create my state variable name using a variable and static text. 'level2' will be created by 'level' text plus a variable indicating what level (selectedItem.Level+1).

```<code>this.state={
  level1:[""], // city
  level2:[""]  // township
  level3:[""]  // neighborhood
  level4:[""]  // street
}
</code>```

When a user clicks on a city, I populate an array of all townships within the city and so on. Through props I know what level was clicked. I would like to dynamically create what state variable to update.

'FilteredListFromClick' is a array of children based on what parent was clicked.

```<code>this.setState({level2: FilteredListFromClick}) // hard coding name works, level2 is populated with a list of townships in clicked city.

var levelName = "level" + selectedItem.Level+1; // column1, column2, etc
this.setState({levelName: FilteredListFromClick}) // does not work, state is not updated, results are an empty list

this.setState({"level"{selectedItem.Level+1}: FilteredListFromClick}) // syntax errors - I've tried playing around with different combos of (), {}, "", and so on. Ideally I would like to set my state in one line like this.
</code>```

答:
Prakash's solution works given an advanced enough EcmaScript version.

An older-style and (IMHO) slightly more readable solution is to build the map outside and pass it in.

```<code>const newState = {}
newState["level" + selectedItem.Level+1] = FilteredListFromClick
this.setState(newState)
</code>```

Body:
In React, I am trying to dynamically create my state variable name using a variable and static text. 'level2' will be created by 'level' text plus a variable indicating what level (selectedItem.Level+1).

this.state={
  level1:[""], // city
  level2:[""]  // township
  level3:[""]  // neighborhood
  level4:[""]  // street
}

When a user clicks on a city, I populate an array of all townships within the city and so on. Through props I know what level was clicked. I would like to dynamically create what state variable to update.

'FilteredListFromClick' is a array of children based on what parent was clicked.

this.setState({level2: FilteredListFromClick}) // hard coding name works, level2 is populated with a list of townships in clicked city.

var levelName = "level" + selectedItem.Level+1; // column1, column2, etc
this.setState({levelName: FilteredListFromClick}) // does not work, state is not updated, results are an empty list

this.setState({"level"{selectedItem.Level+1}: FilteredListFromClick}) // syntax errors - I've tried playing around with different combos of (), {}, "", and so on. Ideally I would like to set my state in one line like this.

Body:
Prakash's solution works given an advanced enough EcmaScript version.

An older-style and (IMHO) slightly more readable solution is to build the map outside and pass it in.

const newState = {}
newState["level" + selectedItem.Level+1] = FilteredListFromClick
this.setState(newState)


问:
Deleting elements that appeare more than once in the list and leaving only one element
I have a small question.
how can i check if a list has identical elements and if the list has identical elements, how can leave only one of those elements in the list?

For example, i wrote this code:

```<code>def courses_per_student(tuple_lst):
    courses={}
    new_tuple_lst=[]
    for i in range(len(tuple_lst)):
            new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
    for m in new_tuple_lst:
       if not courses.has_key(m[0]):
            courses[m[0]]=[m[1]]
       else:
           courses[m[0]]=courses[m[0]]+[m[1]]
    return courses
</code>```

which for:   courses_per_student([("Rina", "Math"), ("Yossi", "Chemistry"), ("Riki", "python"), ("Rina", "math"), ("Yossi", "biology")])
returns:
{'rina': ['math', 'math'], 'yossi': ['chemistry', 'biology'], 'riki': ['python']}

I want that 'math' will appere only once in the list.
thankyou

答:
...

```<code>        for m in new_tuple_lst:
           if not courses.has_key(m[0]):
                courses[m[0]]=[m[1]]
           elif m[1] not in courses[m[0]]:
               courses[m[0]]=courses[m[0]]+[m[1]]
</code>```

Use set instead of list should also do it if the order does not matter.

Body:
I have a small question.
how can i check if a list has identical elements and if the list has identical elements, how can leave only one of those elements in the list?

For example, i wrote this code:

def courses_per_student(tuple_lst):
    courses={}
    new_tuple_lst=[]
    for i in range(len(tuple_lst)):
            new_tuple_lst.append((str(tuple_lst[i][0]).lower(),(str(tuple_lst[i][1]).lower())))
    for m in new_tuple_lst:
       if not courses.has_key(m[0]):
            courses[m[0]]=[m[1]]
       else:
           courses[m[0]]=courses[m[0]]+[m[1]]
    return courses

which for:   courses_per_student([("Rina", "Math"), ("Yossi", "Chemistry"), ("Riki", "python"), ("Rina", "math"), ("Yossi", "biology")])
returns:
{'rina': ['math', 'math'], 'yossi': ['chemistry', 'biology'], 'riki': ['python']}

I want that 'math' will appere only once in the list.
thankyou

Body:
...

        for m in new_tuple_lst:
           if not courses.has_key(m[0]):
                courses[m[0]]=[m[1]]
           elif m[1] not in courses[m[0]]:
               courses[m[0]]=courses[m[0]]+[m[1]]

Use set instead of list should also do it if the order does not matter.


问:
DROP...CREATE vs ALTER
When it comes to creating stored procedures, views, functions, etc., is it better to do a DROP...CREATE or an ALTER on the object?

I've seen numerous "standards" documents stating to do a DROP...CREATE, but I've seen numerous comments and arguments advocating for the ALTER method.

The ALTER method preserves security, while I've heard that the DROP...CREATE method forces a recompile on the entire SP the first time it's executed instead of just a a statement level recompile.

Can someone please tell me if there are other advantages / disadvantages to using one over the other?

答:
Starting with SQL Server 2016 SP1, you now have the option to use CREATE OR ALTER syntax for stored procedures, functions, triggers, and views.  See CREATE OR ALTER – another great language enhancement in SQL Server 2016 SP1 on the SQL Server Database Engine Blog.  For example:

```<code>CREATE OR ALTER PROCEDURE dbo.MyProc
AS
BEGIN
    SELECT * FROM dbo.MyTable
END;
</code>```

Title: DROP...CREATE vs ALTER

Body:
Starting with SQL Server 2016 SP1, you now have the option to use CREATE OR ALTER syntax for stored procedures, functions, triggers, and views.  See CREATE OR ALTER – another great language enhancement in SQL Server 2016 SP1 on the SQL Server Database Engine Blog.  For example:

CREATE OR ALTER PROCEDURE dbo.MyProc
AS
BEGIN
    SELECT * FROM dbo.MyTable
END;


问:
Chromecast & Air for Android Apps (AS3)
Anyone one know a simple way to use / intergrate a chromecast sender for my Air for Android Apps so they can cast directly to a TV.

I've done a few successful tests on webpages.

but as for intergrating the code into an entirely AS3 project, I don't know were to begin?  and I can't seem to find any docs on how to do this.

Thank you in advance for your help.

答:
The ANE on Github is not a solution (line 19 of AirCast.as specifically excludes Android).

More fundamentally, even after re-engineering the ANE to get around the original block, it is currently not possible to get a reference to android.os.Bundle (which is required) as the class is not reachable, no matter how many SDK jars you build into the ANE.

Until there is a means to get the bundle, then this call will always fail:

```<code>CastDevice mSelectedDevice = CastDevice.getFromBundle(route.getExtras());
</code>```

With:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/cast/CastDevice;
</code>```

But if anybody can get around this, please let me know as I would dearly like to get there...

Title: Chromecast & Air for Android Apps (AS3)

Body:
The ANE on Github is not a solution (line 19 of AirCast.as specifically excludes Android).

More fundamentally, even after re-engineering the ANE to get around the original block, it is currently not possible to get a reference to android.os.Bundle (which is required) as the class is not reachable, no matter how many SDK jars you build into the ANE.

Until there is a means to get the bundle, then this call will always fail:

CastDevice mSelectedDevice = CastDevice.getFromBundle(route.getExtras());

With:

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/cast/CastDevice;

But if anybody can get around this, please let me know as I would dearly like to get there...


问:
Concatenate ByteArrayOutputStream
```<code>public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

```<code>public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
</code>```

答: The method writeTo() will let you append the contents of a ByteArrayOutputStream to any other OutputStream.

Title: Concatenate ByteArrayOutputStream

Body:
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(objectStream);
        dout.writeUTF(recordid);

        dout.close();
        objectStream.close();
        return objectStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

There is a problem with the code above. I first create an objectStream (in another class). And then I manually add the recordid to the ByteArrayOutputStream. But is there a way to first add the recordId & then append the ByteArrayOutputStream to it? Basically I have 2 ByteArrayoutputStreams which need to be concatenated (and remain a ByteArrayOutputStream).

edit:
My new version should work but it does not. When I print out the hashcode of dout, it is the same before and after the flush. It's like it stays empty? Is that possible?

public byte[] toByteArray() {
        try {

            ByteArrayOutputStream realOutputStream = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(realOutputStream);
            dout.writeUTF(dataObject.getClass().toString());
            dout.writeUTF(recordid);
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());
            dout.flush();
            System.out.println("Recordid: " + recordid + "|" +  dout.hashCode());

            ByteArrayOutputStream objectStream = dataObject.toByteArrayOutputStream();
            dout.write(objectStream.toByteArray());

            dout.close();
            objectStream.close();
            return objectStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


问:
Laravel 5.5 Shared hosting changing from /public to /public_html - partially working
I have read through a thread on [Laracasts thread] (https://laracasts.com/discuss/channels/general-discussion/where-do-you-set-public-directory-laravel-5?page=2) but not sure of the current right solution especially for Laravel 5.5 ? (note: i do not have access to change any config server side apart from selecting which Php version to use - and a handful ssh commands [with limited directories i can access] ).

My case: using shared hosting, so my public directory is

/home/{mycomputer generated user}/public_html/

Initially I uploaded Laravel directory into public_html folder . The system worked with the quirks of having the URL www.mydomain.xyz/public/ as the URL to root.

Then I tried this approach of modifying the path:

Moved all files out of the public_html folder to have the same level as public_html folder.

So the folders (in my previously laravel folder) reside here:

/home/{mycomputer generated user}/

Copied the content of /public into /public_html

Edited the index.php content of /public_html

FROM:
require __DIR__.'/../vendor/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';

TO:
require '/home/{my user}/vendor/autoload.php';
$app = require_once '/home/{my user}/bootstrap/app.php';

And now my main page loaded fine (welcome view)  as stated in my web.php route file

Route::get('/', function () {
    return view('welcome');
});

===================================================================

MY ISSUE:

However, any other routes would fail

"Not Found

The requested URL /{legitimate route} was not found on this server"

Any other steps that i needed to do?

I tried:
1. loading a simple jpg file stored in public_html folder, and that worked fine (mydomain.xyz/test.jpg )

changed the route for root to return invalid view, that threw a Laravel error

Route::get('/', function () {
        return view('test');
    });

"InvalidArgumentException
View [test] not found."

Tried using closures (instead of using controllers) to return a legit view - did not work

Route::get('/main', function () {
    return view('tempview.main');
});

What did i miss? .htaccess changes? another place where i need to change the public path?

答:
I am answering depend on your trying:

Step 1. copy index.php and .htaccess from public to public_html that means into root folder.

Step 2. modify the index.php into public_html folder

```<code>From: require __DIR__.'/../vendor/autoload.php';

To: require __DIR__.'/vendor/autoload.php';
</code>```

And

```<code>From: $app = require_once __DIR__.'/../bootstrap/app.php';

To: $app = require_once __DIR__.'/bootstrap/app.php';
</code>```

Body:
I am answering depend on your trying:

Step 1. copy index.php and .htaccess from public to public_html that means into root folder.

Step 2. modify the index.php into public_html folder

From: require __DIR__.'/../vendor/autoload.php';

To: require __DIR__.'/vendor/autoload.php';

And

From: $app = require_once __DIR__.'/../bootstrap/app.php';

To: $app = require_once __DIR__.'/bootstrap/app.php';


问:
Creating a user in Meteor and in a 3rd party service via http at the same time
I've got quite a complicated interaction that I'm just overwhelmed with.

My application allows users to register an account. When they register, I call a Meteor Method that also uses their registration details to register them an account on an external application using the API. (single sign on).

My problem is, the external API returns an ID which I need to associate with the user in my database.

I'm not sure how to do this.

Here's my code

Client side registration code:

```<code>Template.register.events({
'submit #signUpForm': function(e, t) {
e.preventDefault();

var signUpForm = $(e.currentTarget),
    forename = trimInput(signUpForm.find('#forename').val()),
    surname = trimInput(signUpForm.find('#surname').val()),
    email = trimInput(signUpForm.find('#signUpEmail').val().toLowerCase()),
    password = signUpForm.find('#signUpPassword').val(),
    passwordConfirm = signUpForm.find('#signUpPasswordConfirm').val();
    profile = {forename: forename, surname: surname};

if (isNotEmpty(email) && isNotEmpty(password) && isEmail(email) && areValidPasswords(password, passwordConfirm)) {

  Accounts.createUser({email: email, password: password, profile: profile}, function(err) {
    if (err) {
      if (err.message === 'Email already exists. [403]') {
        console.log('We are sorry but this email is already used.');
      } else {
        console.log('We are sorry but something went wrong.');
      }
    } else {
      console.log('Congrats new Meteorite, you\'re in!');
      Meteor.call('createUser', email, forename, surname); //registers user on external app using API
      Router.go('/');
    }
  });

}
return false;
},

});
</code>```

and here's the method I'm using

```<code>Meteor.methods({
'createUser': function(email, forename, surname) {

  var endPoint = "/user"

  HTTP.call( verb, 'http://sandbox.wceaapi.org/v1.1'+ endPoint, {
    headers: {
      "Request-Time": timeStamp,
      "Api-Key": key,
      "Signature": hash
    },
    data: {
      "email": email,
      "name": forename,
      "surname": surname
    }
  }, function( error, response ) {
      if ( error ) {
        console.log( error );
      } else {
        console.log( response );
        var result = JSON.parse(response.content);

        var id = result.records.id;
        console.log(id); //this ID is what I want to then pass back to client and attach to the new user in the database.
      }
    });//end function error response
}// end createUser
});//end method
</code>```

The ID variable that I'm retrieving from the API is what I want to then attach to the new user's account. I don't know how to do this.

Bonus points Right now, the user account is being registered on my site even if it fails on the remote server. How can I make it so the user account isn't registered on either if there is a problem? This is quite a complex interaction for a newbie like me so your help is much appreciated.

Thank you

EDIT

Following Michael's advice below - I've added a callback that if the external API registration fails, I log the user out then delete them from my database. This isn't working though. Also, the external API allows me to delete a user, and I've created a method to do so, but I just don't know how to call that method on the client side and then proceed with user registration based on whether it's successful or not - so I decided to do it in the order Michael suggested.

Here's the updated code (ignore the console.log they are for testing)

```<code>Meteor.methods({
'createWceaUser': function(email, forename, surname) {

  var endPoint = "/user";

  HTTP.call( verb, 'http://sandbox.wceaapi.org/v1.1'+ endPoint, {
    headers: {
      "Request-Time": timeStamp,
      "Api-Key": key,
      "Signature": hash
    },
    data: {
      "email": email,
      "name": forename,
      "surname": surname
    }
  }, function( error, response ) {
      if ( error ) {
        console.log(error);
        Meteor.logout();
        Meteor.users.remove({ _id: Meteor.userId() });
      } else {
        console.log( response );
        var result = JSON.parse(response.content);
        var id = result.records.id;
        console.log(id);
        Meteor.users.update({ _id: Meteor.userId() }, { $set: { 'profile.wceaId': id }});
      }
    });//end function error response
}// end createWceaUser
});//end method
</code>```

The error I get is "Exception in callback of async function: TypeError: Object # has no method 'logout'"

答:
1) webhooks- some api's offer to call you back if you register a webhook url for them, which you can easily do with your router in meteor.

2) hit them again after some time, or resolve a promise with a callback

Body:
I've got quite a complicated interaction that I'm just overwhelmed with.

My application allows users to register an account. When they register, I call a Meteor Method that also uses their registration details to register them an account on an external application using the API. (single sign on).

My problem is, the external API returns an ID which I need to associate with the user in my database.

I'm not sure how to do this.

Here's my code

Client side registration code:

Template.register.events({
'submit #signUpForm': function(e, t) {
e.preventDefault();

var signUpForm = $(e.currentTarget),
    forename = trimInput(signUpForm.find('#forename').val()),
    surname = trimInput(signUpForm.find('#surname').val()),
    email = trimInput(signUpForm.find('#signUpEmail').val().toLowerCase()),
    password = signUpForm.find('#signUpPassword').val(),
    passwordConfirm = signUpForm.find('#signUpPasswordConfirm').val();
    profile = {forename: forename, surname: surname};

if (isNotEmpty(email) && isNotEmpty(password) && isEmail(email) && areValidPasswords(password, passwordConfirm)) {

  Accounts.createUser({email: email, password: password, profile: profile}, function(err) {
    if (err) {
      if (err.message === 'Email already exists. [403]') {
        console.log('We are sorry but this email is already used.');
      } else {
        console.log('We are sorry but something went wrong.');
      }
    } else {
      console.log('Congrats new Meteorite, you\'re in!');
      Meteor.call('createUser', email, forename, surname); //registers user on external app using API
      Router.go('/');
    }
  });

}
return false;
},

});

and here's the method I'm using

Meteor.methods({
'createUser': function(email, forename, surname) {

  var endPoint = "/user"

  HTTP.call( verb, 'http://sandbox.wceaapi.org/v1.1'+ endPoint, {
    headers: {
      "Request-Time": timeStamp,
      "Api-Key": key,
      "Signature": hash
    },
    data: {
      "email": email,
      "name": forename,
      "surname": surname
    }
  }, function( error, response ) {
      if ( error ) {
        console.log( error );
      } else {
        console.log( response );
        var result = JSON.parse(response.content);

        var id = result.records.id;
        console.log(id); //this ID is what I want to then pass back to client and attach to the new user in the database.
      }
    });//end function error response
}// end createUser
});//end method

The ID variable that I'm retrieving from the API is what I want to then attach to the new user's account. I don't know how to do this.

Bonus points Right now, the user account is being registered on my site even if it fails on the remote server. How can I make it so the user account isn't registered on either if there is a problem? This is quite a complex interaction for a newbie like me so your help is much appreciated.

Thank you

EDIT

Following Michael's advice below - I've added a callback that if the external API registration fails, I log the user out then delete them from my database. This isn't working though. Also, the external API allows me to delete a user, and I've created a method to do so, but I just don't know how to call that method on the client side and then proceed with user registration based on whether it's successful or not - so I decided to do it in the order Michael suggested.

Here's the updated code (ignore the console.log they are for testing)

Meteor.methods({
'createWceaUser': function(email, forename, surname) {

  var endPoint = "/user";

  HTTP.call( verb, 'http://sandbox.wceaapi.org/v1.1'+ endPoint, {
    headers: {
      "Request-Time": timeStamp,
      "Api-Key": key,
      "Signature": hash
    },
    data: {
      "email": email,
      "name": forename,
      "surname": surname
    }
  }, function( error, response ) {
      if ( error ) {
        console.log(error);
        Meteor.logout();
        Meteor.users.remove({ _id: Meteor.userId() });
      } else {
        console.log( response );
        var result = JSON.parse(response.content);
        var id = result.records.id;
        console.log(id);
        Meteor.users.update({ _id: Meteor.userId() }, { $set: { 'profile.wceaId': id }});
      }
    });//end function error response
}// end createWceaUser
});//end method

The error I get is "Exception in callback of async function: TypeError: Object # has no method 'logout'"


问:
Qt is not detecting android kits automaticallly
I am an absolute beginner. I want to install Qt for android development.

I followed the instructions for installing Qt as specified on Qt's website. I installed android manager and set up SDK, NDK, ant and JDK. After this I specified there locations in Qt but Qt is not detecting any kits at all. Why? Is there something that i am missing?

It might help to know that I an running Qt on ubuntu 16.04.3 and my Qt's version is Qt Creator (community) open source free

If I manually add a kit what should I do about sysroot and other empty fields.

What do i do about the empty fields

答:
I had to configure manually as well  for embedded linux.. To configure manually, in case you did all the configuration to  a new qt, i just gotta select your compiler and change the qt version to the one you configured for the cross compiler. All the other option, let by default. Make sure your cross compiler command is set in your PATH.

This qt version is the path to your qmake.


问:
How to change the PDF file
I have created PDF file by using php script and FPDF lib. It works fine, i have created two files named index.php and create_result.php in the file create_result.php i have written the php script for pdf file. what i want is that if i changed any program in this file there is no change in pdf file. my confusion is how to change the pdf file ,

```<code>ex:(result.pdf).
</code>```

In the result.pdf file i have made a registraion form , if i want to change any thing in this result.pdf in the sense what should i do for a change?

答:
Two things:

Does the Server have the permission to overwrite the PDF

Do you write Data from you login-Script into the PDF? If so, you have serious problems with multithreading, becaus one user can change the PDF for another user. You have to write a temporal PDF-File per user, with a unique filename.

Title: How to change the PDF file

Body:
I have created PDF file by using php script and FPDF lib. It works fine, i have created two files named index.php and create_result.php in the file create_result.php i have written the php script for pdf file. what i want is that if i changed any program in this file there is no change in pdf file. my confusion is how to change the pdf file ,

ex:(result.pdf).

In the result.pdf file i have made a registraion form , if i want to change any thing in this result.pdf in the sense what should i do for a change?


问:
How to 'grep' a continuous log file stream with 'tailf' and when the needed string is obtained, close/break the 'tailf' automatically?
into a bash script, I need to grep a contiuous log streaming and when the proper string is filtered, I need to stop the 'tailf' command to move ond with other implementations.

The common command that works is:

```<code>tailf /dir/dir/dir/server.log | grep --line-buffered "Started in"
</code>```

after the "Started in" line is gathered, I need to break down the "tailf" command.

All this stuff into a bash script.

答:
use grep -m1, it means return the first match then stop:

-m num, --max-count=num

         Stop reading the file after num matches.

```<code>tailf /dir/dir/dir/server.log | grep -m1 "Started in"
</code>```

Body:
into a bash script, I need to grep a contiuous log streaming and when the proper string is filtered, I need to stop the 'tailf' command to move ond with other implementations.

The common command that works is:

tailf /dir/dir/dir/server.log | grep --line-buffered "Started in"

after the "Started in" line is gathered, I need to break down the "tailf" command.

All this stuff into a bash script.

Body:
use grep -m1, it means return the first match then stop:

-m num, --max-count=num

         Stop reading the file after num matches.

tailf /dir/dir/dir/server.log | grep -m1 "Started in"


问:
Django Rest Framework pagination extremely slow count
I turned pagination on in Django Rest framework and it appears to be incredibly slow. Count looks like the culprit, and is taking hundreds of milliseconds to return each time due to the millions of rows in the tables.

I am using postgresql as the database. Is there any way to not count the rows and still use pagination? The performance was fine before this was enabled if I manually filtered the queryset.

答:
The issue is, that the query used to count is the same potentially complex one as used to fetch the data. That's rather wasteful. PageNumberPagination uses Django's own Paginator internally.

To make the query for the count simpler override the paginator class DRF uses:

```<code>from django.core.paginator import Paginator
from django.utils.functional import cached_property
from rest_framework.pagination import PageNumberPagination

class FasterDjangoPaginator(Paginator):
    @cached_property
    def count(self):
        # only select 'id' for counting, much cheaper
        return self.object_list.values('id').count()

class FasterPageNumberPagination(PageNumberPagination):
    django_paginator_class = FasterDjangoPaginator
</code>```

Body:
The issue is, that the query used to count is the same potentially complex one as used to fetch the data. That's rather wasteful. PageNumberPagination uses Django's own Paginator internally.

To make the query for the count simpler override the paginator class DRF uses:

from django.core.paginator import Paginator
from django.utils.functional import cached_property
from rest_framework.pagination import PageNumberPagination

class FasterDjangoPaginator(Paginator):
    @cached_property
    def count(self):
        # only select 'id' for counting, much cheaper
        return self.object_list.values('id').count()

class FasterPageNumberPagination(PageNumberPagination):
    django_paginator_class = FasterDjangoPaginator


问:
Clip text overrun from beginning Javafx
Similar to OverrunStyle.LEADING_ELLIPSIS I would like to shorten my word from the words start, but without the ellipses, similar to ovverun style clip. Is this possible?

答:
You can use Label.setEllipsisString():

```<code>Label myLabel = new Label("SomeLongText");
myLabel.setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);
myLabel.setEllipsisString("");
</code>```

This should only truncate the text as needed, without appending extra characters (...).

Title: Clip text overrun from beginning Javafx

Body:
You can use Label.setEllipsisString():

Label myLabel = new Label("SomeLongText");
myLabel.setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);
myLabel.setEllipsisString("");

This should only truncate the text as needed, without appending extra characters (...).


问:
Adding a statement to correctly hide/unhide rows
I have some code that will hide rows when a topic is "closed" It works flawlessly until the point where I close a new topic.

The issue is that typical use of the sheet will have all closed topics hidden. So when I change an open topic to closed, and run this macro, it will un-hide all hidden topics, but hide the newest one (essentially because this code is just reversing itself back and forth).

I need to add a statement so that it will un-hide all hidden topics, and NOT hide the newest "closed" topic. Hard for me to explain, so I am sorry for that.

```<code>Set Rng = Range("A11:A1000")
For Each MyCell In Rng
    If MyCell.Value = "Closed" Then
        If MyCell.EntireRow.Hidden = True Then
            MyCell.EntireRow.Hidden = False
        Else
            MyCell.EntireRow.Hidden = True
        End If
        End If
Next MyCell

With ActiveSheet.Buttons("Button 1")
        If .Caption = "Hide" Then
            .Caption = "Show"
        Else
            .Caption = "Hide"
        End If
    End With
End Sub
</code>```

Okay, so in the first image is an example of me "closing" a topic. I simply change "open" to "close" and it flags green. NOTE: All previously closed topics are currently HIDDEN.

When I run this macro to "Show" it will un-hide all hidden rows, however it will now HIDE the row that I just changed to "Closed" due to the fact that it was not previously hidden. You can see that when all are shown, Row 33 is hidden.

答:
A couple of things:

1) The statement MyCell.Value = "Closed" returns a boolean value (true or false). So you can just do (As an example):

```<code>  MyCell.EntireRow.Hidden = (MyCell.Value = "Closed")
</code>```

The parentheses are superfluous, but it makes it clearer what is happening so I include them. This just sets the row to hidden when the value is "closed". Nice and simple. If the value isn't "Closed" then the row is unhidden. You can multiply (or AND) two boolean statements together to get more complex results. True*False = False, True*True=True

2) To work with your button maybe consider changing the caption FIRST and then reacting to the new value.

Combining those two changes together you can do something like:

```<code>With ActiveSheet.Buttons("Button 1")
    If .Caption = "Hide" Then
        .Caption = "Show"
    Else
        .Caption = "Hide"
    End If
End With

Set Rng = Range("A11:A1000")
For Each MyCell In Rng
    MyCell.EntireRow.Hidden = (ActiveSheet.Buttons("Button 1").Caption <> "Hide" And MyCell.Value2 = "Closed")
Next MyCell
</code>```

All the confusing boolean stuff aside, you could switch over to using an autofilter to attack your hide/show so you don't have to iterate your huge range:

```<code>Sub button_click()
    If ActiveSheet.Buttons("Button 1").caption = "Show" Then
        ActiveSheet.Buttons("Button 1").caption = "Hide"
        Range("A10:A1000").AutoFilter Field:=1, Criteria1:="<>Closed", VisibleDropDown:=False
    Else
        ActiveSheet.Buttons("Button 1").caption = "Show"
        ActiveSheet.AutoFilterMode = False
    End If
End Sub
</code>```

Body:
I have some code that will hide rows when a topic is "closed" It works flawlessly until the point where I close a new topic.

The issue is that typical use of the sheet will have all closed topics hidden. So when I change an open topic to closed, and run this macro, it will un-hide all hidden topics, but hide the newest one (essentially because this code is just reversing itself back and forth).

I need to add a statement so that it will un-hide all hidden topics, and NOT hide the newest "closed" topic. Hard for me to explain, so I am sorry for that.

Set Rng = Range("A11:A1000")
For Each MyCell In Rng
    If MyCell.Value = "Closed" Then
        If MyCell.EntireRow.Hidden = True Then
            MyCell.EntireRow.Hidden = False
        Else
            MyCell.EntireRow.Hidden = True
        End If
        End If
Next MyCell

With ActiveSheet.Buttons("Button 1")
        If .Caption = "Hide" Then
            .Caption = "Show"
        Else
            .Caption = "Hide"
        End If
    End With
End Sub

Okay, so in the first image is an example of me "closing" a topic. I simply change "open" to "close" and it flags green. NOTE: All previously closed topics are currently HIDDEN.

When I run this macro to "Show" it will un-hide all hidden rows, however it will now HIDE the row that I just changed to "Closed" due to the fact that it was not previously hidden. You can see that when all are shown, Row 33 is hidden.

Body:
A couple of things:

1) The statement MyCell.Value = "Closed" returns a boolean value (true or false). So you can just do (As an example):

  MyCell.EntireRow.Hidden = (MyCell.Value = "Closed")

The parentheses are superfluous, but it makes it clearer what is happening so I include them. This just sets the row to hidden when the value is "closed". Nice and simple. If the value isn't "Closed" then the row is unhidden. You can multiply (or AND) two boolean statements together to get more complex results. True*False = False, True*True=True

2) To work with your button maybe consider changing the caption FIRST and then reacting to the new value.

Combining those two changes together you can do something like:

With ActiveSheet.Buttons("Button 1")
    If .Caption = "Hide" Then
        .Caption = "Show"
    Else
        .Caption = "Hide"
    End If
End With

Set Rng = Range("A11:A1000")
For Each MyCell In Rng
    MyCell.EntireRow.Hidden = (ActiveSheet.Buttons("Button 1").Caption <> "Hide" And MyCell.Value2 = "Closed")
Next MyCell

All the confusing boolean stuff aside, you could switch over to using an autofilter to attack your hide/show so you don't have to iterate your huge range:

Sub button_click()
    If ActiveSheet.Buttons("Button 1").caption = "Show" Then
        ActiveSheet.Buttons("Button 1").caption = "Hide"
        Range("A10:A1000").AutoFilter Field:=1, Criteria1:="<>Closed", VisibleDropDown:=False
    Else
        ActiveSheet.Buttons("Button 1").caption = "Show"
        ActiveSheet.AutoFilterMode = False
    End If
End Sub


问:
Spring JPARepository querying many to many intersection table
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

```<code>@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Publisher class

```<code>@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Intersection Table

```<code>@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}
</code>```

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes

答:
In BookRepository

Get publisher's books

findBooksByBookPublishersPublisherId(Long publisherId)

Get books not published by publisher

findBooksByBookPublishersPublisherIdNot(Long publisherId)

IMHO Publication is much more apropriate name then BookPublisher in your case as Publisher by itself could be BookPublisher (a published that publishing books)

Body:
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Publisher class

@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Intersection Table

@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes


问:
How do you change headers in a CSV File with FasterCSV then save the new headers?
I'm having trouble understanding the :header_converters and :converters in FasterCSV. Basically, all I want to do is change column headers to their appropriate column names.

something like:

```<code>FasterCSV.foreach(csv_file, {:headers => true, :return_headers => false, :header_converters => :symbol, :converters => :all} ) do |row|
    puts row[:some_column_header] # Would be "Some Column Header" in the csv file.
</code>```

execpt I don't umderstand :symbol and :all in the converter parameters.

答:
Rewriting CSV file headers is a common requirement for anyone converting exported CSV files into imports.

I found the following approach gave me what I needed:

```<code>lookup_headers = { "old": "new", "cat": "dog" } # The desired header swaps

CSV($>, headers: true, write_headers: true) do |csv_out|
  CSV.foreach( ARGV[0],
               headers: true,
               # the following lambda replaces the header if it is found, leaving it if not...
               header_converters: lambda{ |h| lookup_headers[h] || h},
               return_headers: true) do |master_row|

    if master_row.header_row?
      # The headers are now correctly replaced by calling the updated headers
      csv_out << master_row.headers
    else
      csv_out << master_row
    end
  end
end
</code>```

Hope this helps!

Body:
I'm having trouble understanding the :header_converters and :converters in FasterCSV. Basically, all I want to do is change column headers to their appropriate column names.

something like:

FasterCSV.foreach(csv_file, {:headers => true, :return_headers => false, :header_converters => :symbol, :converters => :all} ) do |row|
    puts row[:some_column_header] # Would be "Some Column Header" in the csv file.

execpt I don't umderstand :symbol and :all in the converter parameters.

Body:
Rewriting CSV file headers is a common requirement for anyone converting exported CSV files into imports.

I found the following approach gave me what I needed:

lookup_headers = { "old": "new", "cat": "dog" } # The desired header swaps

CSV($>, headers: true, write_headers: true) do |csv_out|
  CSV.foreach( ARGV[0],
               headers: true,
               # the following lambda replaces the header if it is found, leaving it if not...
               header_converters: lambda{ |h| lookup_headers[h] || h},
               return_headers: true) do |master_row|

    if master_row.header_row?
      # The headers are now correctly replaced by calling the updated headers
      csv_out << master_row.headers
    else
      csv_out << master_row
    end
  end
end

Hope this helps!


问:
Xcode automatically perform build opertaion
I am facing unexpected issue with Xcode 9.0. Even if I am writing code in the app, Xcode automatically performs build operation. See below image

Even I deleted derived data, restarts Xcode and System but issue is the same. Because of this my system in getting slow down.

Can anyone suggest how should I stop this build operation.

Please let me know if I have explain my question more.

答: Its happen because of automatic refresh of IBDesignable. For this goto Storyboard -> Menu Editor -> Automatically Refresh View just uncheck it . It will work fine.


问:
Executing query from SSDT
I'm using Visual Studio 2015, SSIS to run set of sql tasks in Execute Sql task and then do a data transfer between tables which are in SSMS by executing package in SSIS. When we run a series of sql statements on SSMS, we get results like rows effected for every sql successful activity. However, now I want to automate the process using SSIS to reduce the turn around time. I would like to get the rows effected for every sql query like select, insert, delete which are in execute sql task. How can it be done in SSIS? I don't have dbo_owner permission to stored procedures in SSMS. I'm thinking SSIS would be a quick way. But it is very important for me to make a log of rows effected to validate the data, as it is financial data. I have nearly 10 sql statements in each sql task like select and delete. But the output is only one table.

                                                                               For example my sql task is like below

```<code>select * from dbo.table1;
select * from dbo.table2 where city = 'Chicago';
create dbo.table3(id int, name varchar(50);
insert into dbo.table3(1,'a');
select * from dbo.table3;
</code>```

If I execute this in SSMS I get rows effected for each select statement and also table is created. If I execute the same through package in SSIS, how will get messages for each of them?

答:
You can use the Row Count transaformation after the Data source and save it the variable. Can refer to this get the number of rows returned from the Source that SHOULD be processed.

Hope this help.

Title: Executing query from SSDT

Body:
I'm using Visual Studio 2015, SSIS to run set of sql tasks in Execute Sql task and then do a data transfer between tables which are in SSMS by executing package in SSIS. When we run a series of sql statements on SSMS, we get results like rows effected for every sql successful activity. However, now I want to automate the process using SSIS to reduce the turn around time. I would like to get the rows effected for every sql query like select, insert, delete which are in execute sql task. How can it be done in SSIS? I don't have dbo_owner permission to stored procedures in SSMS. I'm thinking SSIS would be a quick way. But it is very important for me to make a log of rows effected to validate the data, as it is financial data. I have nearly 10 sql statements in each sql task like select and delete. But the output is only one table.

                                                                               For example my sql task is like below

select * from dbo.table1;
select * from dbo.table2 where city = 'Chicago';
create dbo.table3(id int, name varchar(50);
insert into dbo.table3(1,'a');
select * from dbo.table3;

If I execute this in SSMS I get rows effected for each select statement and also table is created. If I execute the same through package in SSIS, how will get messages for each of them?


问:
How to extract date and time using XSLT?
This is request I have

```<code><test>
    <conversationId>495</conversationId>
    <conversation>
        <origination>DB</origination>
        <Content>
            <transactions>
                <merchantCountry>840</merchantCountry>
                <timestamp>2017-06-12T13:49:03.343Z</timestamp>

</test>
</code>```

I need the timestamp value

```<code>Date=2017-06-12
time=13:49:03
</code>```

I only need the HH:MM:SS doesn't need anything after.

Expected output

```<code>time=13:49:03
</code>```

I have a solution however I am doing that using two variables

```<code><xsl:variable name="time" select="/test/conversation/Content/transactions/timestamp"/>
    <xsl:variable name="timechange">
                <xsl:value-of select="substring-after($time, 'T')"/>
            </xsl:variable>
            <xsl:variable name="timechange1">
                <xsl:value-of select="substring-before($timechange, '.')"/>
            </xsl:variable>
</code>```

I was wondering if same can be done in single statement.

```<code><xsl:value-of select="substring-after(substring-before($time, 'T'), '.')" /> but nothing came.
</code>```

Updating:

```<code>"timestamp": "2017-07-12T13:49:03.343Z",
                "timestamp": "2017-07-12T13:49:03Z",
                "timestamp": "2017-07-12T13:49:03.343-00:05",
                "timestamp": "2017-07-12T13:49:03.343+00:15",
                "timestamp": "2017-07-12T13:49:03+01:05",
                "timestamp": "2017-07-12T13:49:03-01:05",
</code>```

答:
Your substring-after should be substring-before and your substring-before should be substring-after.

Instead of:

```<code><xsl:value-of select="substring-after(substring-before($time, 'T'), '.')" />
</code>```

try:

```<code><xsl:value-of select="substring-before(substring-after($time, 'T'), '.')" />
</code>```

To handle dateTime's that don't contain ., add an additional concat...

```<code><xsl:value-of select="substring-before(concat(substring-after($time, 'T'),'.'), '.')" />
</code>```

or use substring()...

```<code><xsl:value-of select="substring($time,12,8)" />
</code>```

This will work with both 2017-06-12T13:49:03.343Z and 2017-06-12T13:49:03.

Body:
This is request I have

<test>
    <conversationId>495</conversationId>
    <conversation>
        <origination>DB</origination>
        <Content>
            <transactions>
                <merchantCountry>840</merchantCountry>
                <timestamp>2017-06-12T13:49:03.343Z</timestamp>

</test>

I need the timestamp value

Date=2017-06-12
time=13:49:03

I only need the HH:MM:SS doesn't need anything after.

Expected output

time=13:49:03

I have a solution however I am doing that using two variables

<xsl:variable name="time" select="/test/conversation/Content/transactions/timestamp"/>
    <xsl:variable name="timechange">
                <xsl:value-of select="substring-after($time, 'T')"/>
            </xsl:variable>
            <xsl:variable name="timechange1">
                <xsl:value-of select="substring-before($timechange, '.')"/>
            </xsl:variable>

I was wondering if same can be done in single statement.

<xsl:value-of select="substring-after(substring-before($time, 'T'), '.')" /> but nothing came.

Updating:

"timestamp": "2017-07-12T13:49:03.343Z",
                "timestamp": "2017-07-12T13:49:03Z",
                "timestamp": "2017-07-12T13:49:03.343-00:05",
                "timestamp": "2017-07-12T13:49:03.343+00:15",
                "timestamp": "2017-07-12T13:49:03+01:05",
                "timestamp": "2017-07-12T13:49:03-01:05",

Body:
Your substring-after should be substring-before and your substring-before should be substring-after.

Instead of:

<xsl:value-of select="substring-after(substring-before($time, 'T'), '.')" />

try:

<xsl:value-of select="substring-before(substring-after($time, 'T'), '.')" />

To handle dateTime's that don't contain ., add an additional concat...

<xsl:value-of select="substring-before(concat(substring-after($time, 'T'),'.'), '.')" />

or use substring()...

<xsl:value-of select="substring($time,12,8)" />

This will work with both 2017-06-12T13:49:03.343Z and 2017-06-12T13:49:03.