问:
vue bestpractice api handling
Been reading the docs and googling around for best practice to handle api calls in bigger projects without luck (or ateast not what Im searching for).

I want to create a service / facade for the backend that I can load in every component that needs it. For exampel.

I want to fetch historical data for weather in a service so in every component I need this I can just load the weather-serivce and use a getter to fetch the wanted data. I would like to end up with something like below. But I dosent get it to work. So I wonder, what is best practice for this in vue.js?

```<code>import WeatherFacade from './data/WeatherFacade.vue'

export default {
  name: 'Chart',
  created () {
    console.log(WeatherFacade.getWeather())
  },
  components: {
    WeatherFacade
  }
}
</code>```

ps. using vue 2.1.10

答:
It could be easily done by creating some external object that will hold those data and module bundling.What I usually do in my projects is that I create services directory and group them in order I want.

Let's break it down - services/WeatherFascade.js (using VueResource)

```<code>import Vue from 'vue'

export default {
  getWeather() {
    return Vue.http.get('api/weather')
  }
}
</code>```

If you have to pass some dynamic data such as ID, pass it as just parameter

```<code>import Vue from 'vue'

export default {
  getWeather(id) {
    return Vue.http.get(`api/weather/${id}`)
  }
}
</code>```

Then in your component you can import this service, pass parameters (if you have them) and got data back.

```<code>import WeatherFascade from '../services/WeatherFascade'

export default {
  data() {
    return {
      weatherItems: []
    }
  },
  created() {
    this.getWeatherData()
  },
  methods: {
    getWeatherData() {
      WeatherFascade.getWather(// you can pass params here)
       .then(response => this.weatherItems = response.data)
       .catch(error => console.log(error))
    }
  }
}
</code>```

You can use any library for that you like, for instance axios is cool.

Title: vue bestpractice api handling

Body:
Been reading the docs and googling around for best practice to handle api calls in bigger projects without luck (or ateast not what Im searching for).

I want to create a service / facade for the backend that I can load in every component that needs it. For exampel.

I want to fetch historical data for weather in a service so in every component I need this I can just load the weather-serivce and use a getter to fetch the wanted data. I would like to end up with something like below. But I dosent get it to work. So I wonder, what is best practice for this in vue.js?

import WeatherFacade from './data/WeatherFacade.vue'

export default {
  name: 'Chart',
  created () {
    console.log(WeatherFacade.getWeather())
  },
  components: {
    WeatherFacade
  }
}

ps. using vue 2.1.10

Body:
It could be easily done by creating some external object that will hold those data and module bundling.What I usually do in my projects is that I create services directory and group them in order I want.

Let's break it down - services/WeatherFascade.js (using VueResource)

import Vue from 'vue'

export default {
  getWeather() {
    return Vue.http.get('api/weather')
  }
}

If you have to pass some dynamic data such as ID, pass it as just parameter

import Vue from 'vue'

export default {
  getWeather(id) {
    return Vue.http.get(`api/weather/${id}`)
  }
}

Then in your component you can import this service, pass parameters (if you have them) and got data back.

import WeatherFascade from '../services/WeatherFascade'

export default {
  data() {
    return {
      weatherItems: []
    }
  },
  created() {
    this.getWeatherData()
  },
  methods: {
    getWeatherData() {
      WeatherFascade.getWather(// you can pass params here)
       .then(response => this.weatherItems = response.data)
       .catch(error => console.log(error))
    }
  }
}

You can use any library for that you like, for instance axios is cool.


来源: stackexchange

问:
SSIS package fails with error "If 64-bit driver not installed, run in 32-bit mode"
I am receiving the following error when trying to run the package from the Integration Services catalog in SSMS. I changed the 64BitRuntime option to FALSE but it still does not work. The error below is followed by an error that a connection cannot be made to my Excel connection manager. Any suggestions?

Package Error: The requested OLE DB provider Microsoft.Jet.OLEDB 4.0
  is not registered. If the 64-bit driver is not installed, run the
  package in 32-bit mode. Error code: 0x00000000

答:
You have to install Microsoft Access Database Engine 2010 Redistributable and

set 64BitRuntime option to FALSE

you can get it from the following link:

https://www.microsoft.com/en-us/download/details.aspx?id=13255

More info and details can be found in the following links:

http://sqlblog.com/blogs/john_paul_cook/archive/2010/03/24/running-32-bit-ssis-in-a-64-bit-environment.aspx

http://toddmcdermid.blogspot.com/2009/10/quick-reference-ssis-in-32-and-64-bits.html?m=1

https://msdn.microsoft.com/en-us/library/ms162810.aspx

ContentLicense: CC BY-SA 3.0


问:
dropping various columns using iloc
Say I have a dataframe df1 with a bunch of columns:

```<code>Index(['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close', 'log_return',
   'close_open', 'Daily_Change', '30_Avg_Vol', '20_Avg_Vol', '15_Avg_Vol',
   '9_Avg_Vol', 'changed', 'p_changed', '5days', '7days',
   '7days_10daysAvg', '5_7days_Avg', '-2_before', '-1_before', '0_before',
   '1_before', '2_before', '3_before', '4_before', '5_before', '6_before',
   'Bullish'],
  dtype='object')
</code>```

I want to create a new dataframe that keeps some of the columns and drops others. I want to keep columns 0-13, 13-19, 19-28  (using offset notation)

I tried variations of these

```<code>x2 =df.iloc[:-5, [0:13,13:19, 19:28 ]]     # meant to edit 13:19 in this line
x2 =df.iloc[:-5, [[0:13],[13:19], [19:28 ]]
</code>```

but no luck. I get a syntaxerror

Title: dropping various columns using iloc

Body:
Say I have a dataframe df1 with a bunch of columns:

Index(['Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close', 'log_return',
   'close_open', 'Daily_Change', '30_Avg_Vol', '20_Avg_Vol', '15_Avg_Vol',
   '9_Avg_Vol', 'changed', 'p_changed', '5days', '7days',
   '7days_10daysAvg', '5_7days_Avg', '-2_before', '-1_before', '0_before',
   '1_before', '2_before', '3_before', '4_before', '5_before', '6_before',
   'Bullish'],
  dtype='object')

I want to create a new dataframe that keeps some of the columns and drops others. I want to keep columns 0-13, 13-19, 19-28  (using offset notation)

I tried variations of these

x2 =df.iloc[:-5, [0:13,13:19, 19:28 ]]     # meant to edit 13:19 in this line
x2 =df.iloc[:-5, [[0:13],[13:19], [19:28 ]]

but no luck. I get a syntaxerror

Body:
use np.r_

df.iloc[:-5, np.r_[0:13, 13:19, 19:28]]


问:
Keep only one copy of each ClickOnce dependency?
I'm publishing a ClickOnce application that has a few dependencies in the form of DLLs. When I publish the initial version 0.0.1 all the dependencies are copied into the deployment folder as I would expect.

If I make an update and publish version 0.0.2 all of the same dependencies, which are unchanged and have the same file hash, are copied into a second subfolder within the deployment folder.

The folder structure looks like this:

```<code>deployment/
    MyApplication.application
    setup.exe

    Application Files/
        MyApplication_1_0_0_1/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

        MyApplication_1_0_0_2/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222
</code>```

Is there any way to only have one copy of Dll_A.dll/Dll_B.dll when they are the same file and only have a new copy if they change?

I'm referring to the size of the directory on the developer's end. Not the size of the download and cache that clients have as I understand ClickOnce already takes care to minimize that.

答:
My issue came from a misunderstanding of how the Application Files directory works.

Yes there is a new folder with the same DLLs made each time, but for upgrades to work you do not need to keep all of the folders in it. You can erase all of them except for the most recent release and have no ill effects.

Even if someone is between versions/missed upgrades they will simply pull the latest version when their program updates. They don't need the intermediate versions they missed inbetween.

Body:
I'm publishing a ClickOnce application that has a few dependencies in the form of DLLs. When I publish the initial version 0.0.1 all the dependencies are copied into the deployment folder as I would expect.

If I make an update and publish version 0.0.2 all of the same dependencies, which are unchanged and have the same file hash, are copied into a second subfolder within the deployment folder.

The folder structure looks like this:

deployment/
    MyApplication.application
    setup.exe

    Application Files/
        MyApplication_1_0_0_1/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

        MyApplication_1_0_0_2/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

Is there any way to only have one copy of Dll_A.dll/Dll_B.dll when they are the same file and only have a new copy if they change?

I'm referring to the size of the directory on the developer's end. Not the size of the download and cache that clients have as I understand ClickOnce already takes care to minimize that.


问:
Give user an error if invalid Date entered
As part of a task for my first programming assignment we were required to create a program which tells the user how old they are in days, I've completed that however we need to use a try/catch. We've never been taught anything about them just basic concepts like classes/variables/arrays. Here is my code I need to add something in to simply tell the user if the DateTime object DateOfBirth is invalid in a text box and to start again, currently an invalid DOB just crashes the program. Here is is the code which calculates everything.</p>

```<code>private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text+" you are "+(AgeInDays.ToString())+ " Days Old");
}
</code>```

答:
If you want date of birth validation in your program, code should look soweway like that:

```<code>private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth;
    try
    {
        DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    }
    catch (Exception exception)
    {
        MessageBox.Show(exception.Message);
        return;
    }
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text + " you are " + (AgeInDays.ToString()) + " Days Old");
}
</code>```

If you want to become a qualified software developer, I suggest you:

1) get acquaintance with Exception mechanism, it's really convenient way to handle errors (exceptional situations) in your application:
https://msdn.microsoft.com/en-us/library/ms173160.aspx

2) You can use special control – DatePicker – for choosing DateTime values.

Body:
As part of a task for my first programming assignment we were required to create a program which tells the user how old they are in days, I've completed that however we need to use a try/catch. We've never been taught anything about them just basic concepts like classes/variables/arrays. Here is my code I need to add something in to simply tell the user if the DateTime object DateOfBirth is invalid in a text box and to start again, currently an invalid DOB just crashes the program. Here is is the code which calculates everything.

private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text+" you are "+(AgeInDays.ToString())+ " Days Old");
}

Body:
If you want date of birth validation in your program, code should look soweway like that:

private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth;
    try
    {
        DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    }
    catch (Exception exception)
    {
        MessageBox.Show(exception.Message);
        return;
    }
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text + " you are " + (AgeInDays.ToString()) + " Days Old");
}

If you want to become a qualified software developer, I suggest you:

1) get acquaintance with Exception mechanism, it's really convenient way to handle errors (exceptional situations) in your application:
https://msdn.microsoft.com/en-us/library/ms173160.aspx

2) You can use special control – DatePicker – for choosing DateTime values.


问:
Persistence store for state of a job in LUIGI
I started with LUIGI recently and had few questions which I was unable to answer myself using documentation

Question is regarding state of a job in LUIGI

With Luigi we can set some global configuration (record_task_history) to track history of job and it require to setup a mysql DB. This history can then be later retrieved and shown by luigi visualizer.

Are other persistence store supported for this? Can this be done in text files? (Visualizer might not work but am ok with that if I can get historical state programmatically)

When does luigi actually write state data to the persistence store? Does it keep it in memory for running job and dump data as soon as job completes?

--learner

答:
It supports any store that is supported by SQL Alchemy.
If you don't use a external store, the state is not saved (only log file). The status of a task is always checked based on the existence of its output.

You should check the source code. :D.


问:
Is there a sleep() function for Android NDK?
Under Android NDK, is there a sleep() function which sleeps for X miliseconds, but do not block the event loop?

We are writing API tests to work on Mac, Windows, and Android. So far, we have implemented some sort of sleep() for Mac and Windows, but we are all new to Android NDK and need some help there. Thank you in advance.

答:
The normal linux sleep functions (usleep, etc) will block the thread that calls them.  It's up to you which thread that is - hopefully not the UI one.

A more android style approach would be to set up an event to happen at a future time and then return from the current event.  When the new event fires you take the next step.  Think for example of a state machine with each state being entered as an event, doing something effectively instantaneous, scheduling the next state for a future time, and then returning .

ContentLicense: CC BY-SA 2.5


问:
Xamarin.Forms DisplayAlert - duplicated title in Android
I'm trying to display an alert in my Xamarin.Forms project using the following code:

```<code>DisplayAlert("¡Oops!", "Nos es imposible ubicarte, intenta ubicarte manualmente", "Ok");
</code>```

In iOS it works all OK, but in the Android emulator I see a duplicated title. Please see the below image

Is this behavior normal? Thanks in advance.

答: Clear Solution->Delete obj and bin directories in all the project folders->Rebuild Droid project->Check if it works as it should</p>

Body:
I'm trying to display an alert in my Xamarin.Forms project using the following code:

DisplayAlert("¡Oops!", "Nos es imposible ubicarte, intenta ubicarte manualmente", "Ok");

In iOS it works all OK, but in the Android emulator I see a duplicated title. Please see the below image

Is this behavior normal? Thanks in advance.


问:
SCNView snapshot image does not include the overlaySKScene
Using iOS 10.3 & Xcode 8.3

I add an overlay scene like this:

```<code>     self.scnView.overlaySKScene = someUI;  //SpriteKit SKScene
</code>```

But when I try to take a snapshot:

```<code>     UIImage *image = [self.scnView snapshot];
</code>```

The snapshot image shows only the 3D scene but not the overlay scene. But it all looks ok on-screen, meaning I can see the 3D scene and the overlay.

How do I get a snapshot that includes the overlayScene?

答:
Oops.  snapshot works fine and shows the overlay too if you set the scnView.background to any color (with alpha=1), except clearColor.

I had set the the scnView.backgroundColor to clearColor.

```<code>    self.scnView.backgroundColor = [UIColor clearColor];
</code>```

I assumed the overlay to be on top of/above the 3D Scene and background to be below/behind the 3D scene. So I didn't expect the clearColor background to apply to the overlay scene as well.  Oh well.

Body:
Using iOS 10.3 & Xcode 8.3

I add an overlay scene like this:

     self.scnView.overlaySKScene = someUI;  //SpriteKit SKScene

But when I try to take a snapshot:

     UIImage *image = [self.scnView snapshot];

The snapshot image shows only the 3D scene but not the overlay scene. But it all looks ok on-screen, meaning I can see the 3D scene and the overlay.

How do I get a snapshot that includes the overlayScene?

Body:
Oops.  snapshot works fine and shows the overlay too if you set the scnView.background to any color (with alpha=1), except clearColor.

I had set the the scnView.backgroundColor to clearColor.

    self.scnView.backgroundColor = [UIColor clearColor];

I assumed the overlay to be on top of/above the 3D Scene and background to be below/behind the 3D scene. So I didn't expect the clearColor background to apply to the overlay scene as well.  Oh well.


问:
CSS word-wrapping in div
I have a div with a width of 250px. When the innertext is wider than that i want it to break down. The div is float: left and now has an overflow. I want the scrollbar to go away by using word-wrapping. How can i achieve this?

```<code><div id="Treeview">
<div id="HandboekBox">
    <div id="HandboekTitel">
        <asp:Label ID="lblManual" runat="server"></asp:Label>
    </div>
    <div id="HandboekClose">
        <asp:ImageButton ID="btnCloseManual" runat="server"
            ImageUrl="Graphics/close.png" onclick="btnCloseManual_Click"
            BorderWidth="0" ToolTip="Sluit handboek" />
    </div>
</div>
<asp:TreeView ID="tvManual" runat="server" RootNodeStyle-CssClass="RootNode">
    <Nodes>

    </Nodes>
</asp:TreeView>
</div>
</code>```

CSS:

```<code>#Treeview
{
padding-right: 5px;
width: 250px;
height: 100%;
float: left;
border-right: solid 1px black;
overflow-x: scroll;
}
</code>```

答: try white-space:normal; This will override inheriting white-space:nowrap;

OwnerDisplayName: Martijn

Title: CSS word-wrapping in div

Body:
I have a div with a width of 250px. When the innertext is wider than that i want it to break down. The div is float: left and now has an overflow. I want the scrollbar to go away by using word-wrapping. How can i achieve this?

        <asp:Label ID="lblManual" runat="server"></asp:Label>

        <asp:ImageButton ID="btnCloseManual" runat="server"
            ImageUrl="Graphics/close.png" onclick="btnCloseManual_Click"
            BorderWidth="0" ToolTip="Sluit handboek" />

<asp:TreeView ID="tvManual" runat="server" RootNodeStyle-CssClass="RootNode">
    <Nodes>

    </Nodes>
</asp:TreeView>

CSS:

#Treeview
{
padding-right: 5px;
width: 250px;
height: 100%;
float: left;
border-right: solid 1px black;
overflow-x: scroll;
}

LastEditorDisplayName: Martijn


问:
What is the typical speed that PHP connects to MySQL?
Say I have very standard mysql connection code:

```<code>$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);
</code>```

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?

答:
One possibility is that mysql is doing a DNS lookup to find the name of the connecting server; depending on your setup, this could take a long time.  There's not really much benefit to it, aside from being able to specify the users by hostname rather than IP address (e.g. user@example.com rather than user@192.168.1.1).

This can be disabled in the configuration or when starting up MySQL with the --skip-name-resolve parameter.  More information is available on the MySQL site.

ContentLicense: CC BY-SA 4.0

Body:
Say I have very standard mysql connection code:

$dbhost = '192.168.1.99';
$dbuser = 'dbuser';
$dbpass = 'dbuserpass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'mydb';
mysql_select_db($dbname);

This would connect from the web server to the database server (say the web server is at 192.168.1.98 or something). Typically, how long would the above code run? Currently, I'm seeing about 2 seconds. Is that slow?


问:
ExtendedExecutionSession in Windows 10 UAP
I have troubles using ExtendedExecutionSession in Windows 10 UAP.

First, it seems that ExtendedExecutionSession.RequestExtensionAsync only returns Allowed if it is called from the app Suspending event handler. If it is called outside this event handler the method returns Denied.

Second, most critical problem. My app executes downloads. If any download is in progress I request ExtendedExecutionSession to allow downloads to complete. What I found at least on Windows 10 mobile though is ExtendedExecutionSession is allowed in app on suspend but downloads seem to freeze. Nothing is downloaded while app is in background and when app is resumed downloads appear frozen with no data transferred.

答:
Here is the MSDN guidance for Extended Execution: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/run-minimized-with-extended-execution

SavingData is the only type of Extended Execution Reason that can be used in the Suspending state. Note that this is specifically for saving critical user data locally that will be lost once the process is removed from memory.

It sounds like you should use the Unspecified Extended Execution if you need to accomplish something when your app is running and in the foreground. It will be revoked if the user decides to close the app before the download operation completes. Like was previously suggested, a background transfer or use of the ApplicationTrigger or MaintenanceTrigger may be better options for these downloads if you want them to continue after your app has been closed.


问:
display bootstrap navbar using react.js
I have a very simple React.js project where I am trying to add a bootstrap navbar to the project, but I can't seem to figure out how to get the navbar to display on the page.  The navbar example I am referencing can be found here, http://codepen.io/zhaozhiming/pen/LNGyvR

The project looks like the following,

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <title>My super cool title.</title>
</head>
<body>
  <div id="root"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="bundle.js" ></script>
</body>
</html>
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

App.js

```<code>import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBarTest from './common/NavBar-test';

const App = () => {
  return (
    <div id="parent">
      <div>Hello, App!</div>
      <NavBarTest {...NavBarTest} />
    </div>
  )
}

export default App;
</code>```

Navbar-test.js

```<code>import React from 'react';

// create classes
var NavBar = React.createClass({
  render: function(){
    return(
      <nav className="navbar navbar-inverse">
        <div className="container-fluid">
          <div className="navbar-header">
            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
              <span className="sr-only">Toggle navigation</span>
              <span className="icon-bar"></span>
              <span className="icon-bar"></span>
              <span className="icon-bar"></span>
            </button>
            <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />
          </div>
          <div className="collapse navbar-collapse" id="navbar-collapse">
            <NavMenu links={this.props.links} />
          </div>
        </div>
      </nav>
    );
  }
});

var NavBrand = React.createClass({
  render: function(){
    return (
      <a className="navbar-brand" href={this.props.linkTo}>{this.props.text}</a>
    );
  }
});

var NavMenu = React.createClass({
  render: function(){
    var links = this.props.links.map(function(link){
      if(link.dropdown) {
        return (
          <NavLinkDropdown links={link.links} text={link.text} active={link.active} />
        );
      }
      else {
        return (
          <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
        );
      }
    });
    return (
      <ul className="nav navbar-nav">
        {links}
      </ul>
    );
  }
});

var NavLinkDropdown = React.createClass({
  render: function(){
    var active = false;
    var links = this.props.links.map(function(link){
      if(link.active){
        active = true;
      }
      return (
        <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
      );
    });
    return (
      <li className={"dropdown " + (active ? "active" : "")}>
        <a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
          {this.props.text}
          <span className="caret"></span>
        </a>
        <ul className="dropdown-menu">
          {links}
        </ul>
      </li>
    );
  }
});

var NavLink = React.createClass({
  render: function(){
    return(
      <li className={(this.props.active ? "active" : "")}><a href={this.props.linkTo}>{this.props.text}</a></li>
    );
  }
});

// set data
var navbar = {};
navbar.brand =
  {linkTo: "#", text: "React Bootstrap Navbar"};
navbar.links = [
  {linkTo: "#", text: "Link 1"},
  {linkTo: "#", text: "Link 2"},
  {dropdown: true, text: "Dropdown", links: [
    {linkTo: "#", text: "Dropdown Link 1"},
    {linkTo: "#", text: "Dropdown Link 2", active: true}
  ]}
];

export default NavBar;
</code>```

Finally, the page appears to render, but I am seeing the following error / warning message in the browser console.  Any help on how I can get this navbar to display on the page would greatly be appreciated.

答:
According to the structure you showed, you should render NavBar in App component because you are default exporting NavBar from Navbar-test.js file. One more this in NavBar component you are accessing the values by this.props.brand so you need to define the var navbar data (data that you defined in the last of app.js file) in app.js file, Use this in app.js file, it will work:

```<code>import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBar from './common/NavBar-test';

const App = () => {
  return (
    <div id="parent">
      <div>Hello, App!</div>
      <NavBar {...navbar}/>
    </div>
  )
}

var navbar = {};
navbar.brand =  {
                    linkTo: "#",
                    text: "React Bootstrap Navbar"
                };
navbar.links = [
        {
            linkTo: "#",
            text: "Link 1"
        },
        {
            linkTo: "#",
            text: "Link 2"
        },
        {
            dropdown: true,
            text: "Dropdown",
            links: [
                {
                    linkTo: "#",
                    text: "Dropdown Link 1"
                },
                {
                    linkTo: "#",
                    text: "Dropdown Link 2",
                    active: true
                }
            ]
        }
];
</code>```

Check the working code: http://codepen.io/zhaozhiming/pen/LNGyvR?editors=0010

Title: display bootstrap navbar using react.js

Body:
I have a very simple React.js project where I am trying to add a bootstrap navbar to the project, but I can't seem to figure out how to get the navbar to display on the page.  The navbar example I am referencing can be found here, http://codepen.io/zhaozhiming/pen/LNGyvR

The project looks like the following,

index.html

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <title>My super cool title.</title>

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.js';

ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBarTest from './common/NavBar-test';

const App = () => {
  return (

Hello, App!

      <NavBarTest {...NavBarTest} />

  )
}

export default App;

Navbar-test.js

import React from 'react';

// create classes
var NavBar = React.createClass({
  render: function(){
    return(

            <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse" aria-expanded="false">
              Toggle navigation

            </button>
            <NavBrand linkTo={this.props.brand.linkTo} text={this.props.brand.text} />

            <NavMenu links={this.props.links} />

    );
  }
});

var NavBrand = React.createClass({
  render: function(){
    return (
      {this.props.text}
    );
  }
});

var NavMenu = React.createClass({
  render: function(){
    var links = this.props.links.map(function(link){
      if(link.dropdown) {
        return (
          <NavLinkDropdown links={link.links} text={link.text} active={link.active} />
        );
      }
      else {
        return (
          <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
        );
      }
    });
    return (

        {links}

    );
  }
});

var NavLinkDropdown = React.createClass({
  render: function(){
    var active = false;
    var links = this.props.links.map(function(link){
      if(link.active){
        active = true;
      }
      return (
        <NavLink linkTo={link.linkTo} text={link.text} active={link.active} />
      );
    });
    return (

          {this.props.text}

          {links}

    );
  }
});

var NavLink = React.createClass({
  render: function(){
    return(

{this.props.text}

    );
  }
});

// set data
var navbar = {};
navbar.brand =
  {linkTo: "#", text: "React Bootstrap Navbar"};
navbar.links = [
  {linkTo: "#", text: "Link 1"},
  {linkTo: "#", text: "Link 2"},
  {dropdown: true, text: "Dropdown", links: [
    {linkTo: "#", text: "Dropdown Link 1"},
    {linkTo: "#", text: "Dropdown Link 2", active: true}
  ]}
];

export default NavBar;

Finally, the page appears to render, but I am seeing the following error / warning message in the browser console.  Any help on how I can get this navbar to display on the page would greatly be appreciated.

Body:
According to the structure you showed, you should render NavBar in App component because you are default exporting NavBar from Navbar-test.js file. One more this in NavBar component you are accessing the values by this.props.brand so you need to define the var navbar data (data that you defined in the last of app.js file) in app.js file, Use this in app.js file, it will work:

import React, {PropTypes} from 'react';
import styles from './App.css';
import NavBar from './common/NavBar-test';

const App = () => {
  return (
    <div id="parent">
      <div>Hello, App!</div>
      <NavBar {...navbar}/>
    </div>
  )
}

var navbar = {};
navbar.brand =  {
                    linkTo: "#",
                    text: "React Bootstrap Navbar"
                };
navbar.links = [
        {
            linkTo: "#",
            text: "Link 1"
        },
        {
            linkTo: "#",
            text: "Link 2"
        },
        {
            dropdown: true,
            text: "Dropdown",
            links: [
                {
                    linkTo: "#",
                    text: "Dropdown Link 1"
                },
                {
                    linkTo: "#",
                    text: "Dropdown Link 2",
                    active: true
                }
            ]
        }
];

Check the working code: http://codepen.io/zhaozhiming/pen/LNGyvR?editors=0010


问:
How to make_shared count times, with different areas allocated without recur to a loop?
How to make_shared count times, with different areas allocated without recur to a loop?

I have the following code:

```<code>for( unsigned int count = 0; count < demandedSize; ++count  )
{
   m_connectionList.push_back( std::make_shared< Foo >( m_ip, m_port ));
}
</code>```

How to shorten this without a loop?

I know std::vector receaves a second argument as const T&, but in that case all shared_ptrs points to the same address (value is copied).

```<code>std::vector< std::shared_ptr<Foo> > vet( demandedSize, std::make_shared<Foo>( m_ip, m_port ) );
</code>```

How to execute make_shared count times, with different areas allocated as result without recur to a loop

答:
This should do the trick:

```<code>std::generate_n( back_inserter( m_connectionList ), demandedSize, [this]{
    return std::make_shared< Foo >( m_ip, m_port ) );
});
</code>```

Live Example on Coliru.

Body:
How to make_shared count times, with different areas allocated without recur to a loop?

I have the following code:

for( unsigned int count = 0; count < demandedSize; ++count  )
{
   m_connectionList.push_back( std::make_shared< Foo >( m_ip, m_port ));
}

How to shorten this without a loop?

I know std::vector receaves a second argument as const T&, but in that case all shared_ptrs points to the same address (value is copied).

std::vector< std::shared_ptr<Foo> > vet( demandedSize, std::make_shared<Foo>( m_ip, m_port ) );

How to execute make_shared count times, with different areas allocated as result without recur to a loop

Body:
This should do the trick:

std::generate_n( back_inserter( m_connectionList ), demandedSize, [this]{
    return std::make_shared< Foo >( m_ip, m_port ) );
});

Live Example on Coliru.


答:
Just using noquote() not to draw the quotes around a string doesn't turn a character value into an executable piece of code. There is a big different in R between a character value an a symbol or function call. You can't really just replace one with the other.

So let's say you have extracted the character value from the rownames

```<code>x <- "W2.4"
</code>```

This is basically the string version of the function you want. You can get the value of a symbol (in this case the function W2.4 from the drc:package) from its string name with get(). So you can call

```<code>drm(y~x, logDose = 10, fct = get(x)())
</code>```

Note the extra parenthesis. The get(x)-call returns the W2.4 function, and the second set of parenthesis calls that function returned by get().

Using the ryegrass dataset that comes with the drc package, we can see that these two lines return the same thing

```<code>drm(rootl ~ conc, data = ryegrass, fct = W2.4())
drm(rootl ~ conc, data = ryegrass, fct = get(x)())
</code>```

Title: Resolving a variable value within a function call R

Body:
I have a data frame defined as follows:

model_comp
         logLik       IC  Lack of fit  Res var
W2.4  -353.2939 716.5878 1.361885e-01 26.80232
baro5 -353.2936 718.5871          NaN 27.04363
LL.5  -353.2940 718.5880          NaN 27.04384
LL.3  -360.3435 728.6871 3.854799e-04 29.99842
W1.3  -360.3842 728.7684 3.707592e-04 30.01948
W1.4  -360.3129 730.6258 7.850947e-05 30.25028
LL.4  -360.3170 730.6340 7.818416e-05 30.25243

The best model fit is the one with the lowest IC (information criteria). I want to use the best fit to do some plotting etc...  So I created:

> bestmodel <- noquote(paste0(as.name(rownames(model_comp[which.min(model_comp$IC),])),"()"))
> bestmodel
[1] W2.4()

I want to use the W2.4() as a function call to a the DRC package.

For example this call works when manually specified:

drm(y~x,logDose = 10, fct=W2.4())

I'm trying to use the value in bestmodel instead to do something like:

drm(y~x,logDose = 10,fct = as.formula(paste(bestmodel)))

I've tried all the options given here with no success.  I've messed with as.formula(), noquote(), as.name() with no success.

I also tried as.name(paste0(as.name(bestmodel),"()")) where I didn't add on the "()" in the bestmodel definition above. Still no dice.

model_comp <- structure(list(logLik = c(-353.293902612472, -353.293568997018,
-353.294024776211, -360.343530770823, -360.384220907907, -360.312897918459,
-360.317018443052), IC = c(716.587805224944, 718.587137994035,
718.588049552421, 728.687061541646, 728.768441815814, 730.625795836919,
730.634036886105), `Lack of fit` = c(0.136188459104035, NaN,
NaN, 0.000385479884900107, 0.000370759187117765, 7.85094742623572e-05,
7.81841606352332e-05), `Res var` = c(26.8023196097934, 27.0436263934882,
27.0438389102235, 29.9984226526044, 30.0194755526501, 30.2502847248304,
30.2524338881051)), .Names = c("logLik", "IC", "Lack of fit",
"Res var"), row.names = c("W2.4", "baro5", "LL.5", "LL.3", "W1.3",
"W1.4", "LL.4"), class = "data.frame")

Body:
Just using noquote() not to draw the quotes around a string doesn't turn a character value into an executable piece of code. There is a big different in R between a character value an a symbol or function call. You can't really just replace one with the other.

So let's say you have extracted the character value from the rownames

x <- "W2.4"

This is basically the string version of the function you want. You can get the value of a symbol (in this case the function W2.4 from the drc:package) from its string name with get(). So you can call

drm(y~x, logDose = 10, fct = get(x)())

Note the extra parenthesis. The get(x)-call returns the W2.4 function, and the second set of parenthesis calls that function returned by get().

Using the ryegrass dataset that comes with the drc package, we can see that these two lines return the same thing

drm(rootl ~ conc, data = ryegrass, fct = W2.4())
drm(rootl ~ conc, data = ryegrass, fct = get(x)())


问:
How to select rows with only one relation?
I have three tables which store a simple onet-to-many relationship.

```<code>Table1  idT1  Name
          1    A
          2    B
          3    B

Table2  idT2  Value
          1     AA
          2     BB
          3     CC
          4     DD

Table3   idT1  idT2
           1     4
           1     2
           2     1
           2     4
           2     3
           3     4
</code>```

I need to return those rows in Table3 which only have one relationship between Table1 and and some rows from Table2.

Something like this:

If I look for rows that have a relation idT2 = 4,  the query should return only this row:

```<code>Table3   idT1  idT2
           3     4
</code>```

I figured out this query but I think there must be something easier:

```<code>    ;WITH tb AS(SELECT idT1 FROM Table3 WHERE idT2 IN(4))
    SELECT t.idT1 FROM T3 t INNER JOIN tb ON t.idT1 = tb.idT1
    GROUP BY idT1 HAVING COUNT(t.idT2) = 1
</code>```

Any help will be appreciated, what do you think?

答:
One method is to use aggregation and just look for the values that appear once for a given idT2:

```<code>select idT1, max(idT2) as idT2
from t3
group by idT1
having min(idT2) = 4 and max(idT2) = 4;
</code>```

You could also do this using not exists:

```<code>select t3.*
from t3
where t3.idT2 = 4 and
      not exists (select 1 from t3 tt3 where tt3.idT1 = t3.idT1 and tt3.idT2 <> 4);
</code>```

Body:
I have three tables which store a simple onet-to-many relationship.

Table1  idT1  Name
          1    A
          2    B
          3    B

Table2  idT2  Value
          1     AA
          2     BB
          3     CC
          4     DD

Table3   idT1  idT2
           1     4
           1     2
           2     1
           2     4
           2     3
           3     4

I need to return those rows in Table3 which only have one relationship between Table1 and and some rows from Table2.

Something like this:

If I look for rows that have a relation idT2 = 4,  the query should return only this row:

Table3   idT1  idT2
           3     4

I figured out this query but I think there must be something easier:

    ;WITH tb AS(SELECT idT1 FROM Table3 WHERE idT2 IN(4))
    SELECT t.idT1 FROM T3 t INNER JOIN tb ON t.idT1 = tb.idT1
    GROUP BY idT1 HAVING COUNT(t.idT2) = 1

Any help will be appreciated, what do you think?

Body:
One method is to use aggregation and just look for the values that appear once for a given idT2:

select idT1, max(idT2) as idT2
from t3
group by idT1
having min(idT2) = 4 and max(idT2) = 4;

You could also do this using not exists:

select t3.*
from t3
where t3.idT2 = 4 and
      not exists (select 1 from t3 tt3 where tt3.idT1 = t3.idT1 and tt3.idT2 <> 4);


问:
How do I make builds public in buildbot
I have a buildbot working and have added basic authentication following "Setting Authorized Web Users" from the manual http://docs.buildbot.net/current/tutorial/tour.html. I was hoping to restrict people who could trigger a new build.

But now the web interface shows no builds at all without login. How can I make the builds public?

My current config looks like this, minus the line giving the password details.

```<code>c['www']['authz'] = util.Authz(
        allowRules = [
                        util.AnyControlEndpointMatcher(role="admins")
                    ],
        roleMatchers = [
                        util.RolesFromUsername(roles=['admins'], usernames=['xxx'])
                    ]
)
</code>```

答:
I have crated a solution based on this message to the mailing list.

https://lists.buildbot.net/pipermail/users/2017-February/001066.html

```<code>##util.AnyControlEndpointMatcher(role="admins")

util.StopBuildEndpointMatcher(role="admins"),
util.ForceBuildEndpointMatcher(role="admins"),
util.RebuildBuildEndpointMatcher(role="admins")
</code>```

This seems to run counter to the documentation which says a call to AnyControlEndpointMatcher should be added and the simple example. So still confused.

Title: How do I make builds public in buildbot

Body:
I have a buildbot working and have added basic authentication following "Setting Authorized Web Users" from the manual http://docs.buildbot.net/current/tutorial/tour.html. I was hoping to restrict people who could trigger a new build.

But now the web interface shows no builds at all without login. How can I make the builds public?

My current config looks like this, minus the line giving the password details.

c['www']['authz'] = util.Authz(
        allowRules = [
                        util.AnyControlEndpointMatcher(role="admins")
                    ],
        roleMatchers = [
                        util.RolesFromUsername(roles=['admins'], usernames=['xxx'])
                    ]
)

Body:
I have crated a solution based on this message to the mailing list.

https://lists.buildbot.net/pipermail/users/2017-February/001066.html

##util.AnyControlEndpointMatcher(role="admins")

util.StopBuildEndpointMatcher(role="admins"),
util.ForceBuildEndpointMatcher(role="admins"),
util.RebuildBuildEndpointMatcher(role="admins")

This seems to run counter to the documentation which says a call to AnyControlEndpointMatcher should be added and the simple example. So still confused.


问:
Mongoose: Updating many entries starves connection pool
So I receive on my node server 80,000+ records at a time that need to be put into Mongo as updates.  I am aware that mongoose doesn't support this functionality, so each one has be be updated individually.

When I do this however, even when a connection pool is set up to be say 100, it still overwhelms the connection pool and the result is that any other web or system traffic needing to do a database call cannot complete.  Is there any way to have a model limit the amount of connection it uses, or any other good way to work around this?  For now we are resource limited to having only a single db or node instance to handle front and back end items.

Any comments or suggestions to try welcome.

Thanks

答:
You can perform bulk updates with Mongoose, using Model.bulkWrite().

The documentation doesn't specify how many documents you can update per batch, but the MongoDB documentation documenting the underlying mechanism seems to suggest that you might be able to send all 80K updates at once.


问:
Linq to SQL: Is it better to have a small DataContext for each page or a global one?
I am trying out Linq to SQL in an ASP.NET application that uses a large database with lots of foreign keys (100+ tables).  I am impressed with how Linq permits you to create a datacontext with all of your relationships intact and to then create Linq statements that automatically join tables.  However, this leads to a question: if I am submitting a Linq statement that just works with one or two tables, is it better to have a datacontext that just has the necessary table/tables? It seems to me that if I build a datacontext with all of the tables in the database, it would be quite massive and loading it for every use of Linq would have a negative impact on performance.  Am I right?

Comment: I know to create the datacontext only as needed (but thank you nonetheless for mentioning it).  The question is really about whether I should have lots of little datacontexts or whether it would be Ok to build one big one.

答:
I believe that data context are pretty lightweight, mostly just containers.   The data isn't actually loaded into the context until you query it.  I don't think it would be wrong to have a single data context, but only instantiate it as needed (as a unit of work) rather than keeping it around all the time.  That way, you don't have a long-lived object that may continue to grow bigger and bigger.

If your tables can be separated into related groups of tables, you may want to consider having a separate data context for each of these groups.  I'm not sure how LINQ would handle a query using data from multiple contexts, but it seems like it ought to work as long as the tables are on the same server.  You'd have to check this if you did break things down into multiple contexts and had queries that needed tables from more than one.

Typically I use a single context and instantiate it as needed, but I don't have any databases that are quite as big as yours.

OwnerDisplayName: tvanfosson

LastEditorDisplayName: tvanfosson


问:
Strip comments in CSS using VIM
I think vim can really do this. I just don't know my way arround search and replace using regex. Can anyone help me around this one.

Update

Thanks to Chris below for helping me around this one. Here is the map.

```<code>map <leader>rc :%s@\v/\*([^*]\|[\r\n]\|(\*+([^*/]\|[\r\n])))*\*+/@@g<cr>
</code>```

答:
:%s@/\*\([^*]\|[\r\n]\|\(\*\+\([^*/]\|[\r\n]\)\)\)*\*\+/@@g will get rid of all CSS comments (note that's using @ rather than / as the delimiter to avoid escaping the \

You can also use \v, the "very magic" flag (read :help \v), and not need to make the ()|+ characters magic: :%s@\v/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/@@g.

(This answer is just extending jball's answer by putting in the Vim syntax for it.)

Title: Strip comments in CSS using VIM

Body:
I think vim can really do this. I just don't know my way arround search and replace using regex. Can anyone help me around this one.

Update

Thanks to Chris below for helping me around this one. Here is the map.

map <leader>rc :%s@\v/\*([^*]\|[\r\n]\|(\*+([^*/]\|[\r\n])))*\*+/@@g<cr>


问:
Javascript parseFloat() sometimes returns NaN - Possibly just on older versions of Firefox
I have tested this application on all current major browsers and it works reliably and correctly. The app is now deployed and I am getting reports that sometimes the result is NaN.

The function below uses parsefloat() to find the total of a column of prices in a table. Sometimes that total is displayed as NaN. I have been unable to reproduce it and the customers who report the issue thus far have not been sufficiently technically competent to tell me what browser they are using. One person sent a screen shot of Firefox on a Mac and another knew it was Firefox on Windows.

In the below code, this line:

```<code>var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);
</code>```

properly sets linePrice to 6.50 and the value of innerHTML is "$6.50". The next line calls parseFloat(linePrice);

Finally, this line:

```<code>document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });
</code>```

Causes NaN to be displayed instead of the column total.

Any help would be greatly appreciated!

Here is the code:

```<code>  function totalTbl()
  {
    var table = document.getElementById('myTbl');
    var rows = table.getElementsByTagName('tr');

    var tableTotal = 0;

    // Skip the first (header) row and the last (add row) row
    len = rows.length - 2;
    numRows = len - 1;

    for (var i = 1; i < len; i++)
    {
      var cell = rows[i].cells[5];
      if (cell.firstChild != null)
      {
        var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);

        tableTotal += parseFloat(linePrice);
      }
    }

    document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });

  }
</code>```

答:
I feel it'll be difficult to find one point in your code where this is being caused without more code to examine, so I'll attempt to address a few issues and hopefully we'll hit on the issue.

So firstly, never use != or ==, this performs type coercion, the rules of which are unintuitive and unmemorable and are best simply avoided. Instead always use === or !==, which will not perform type coercion. If do want to perform type coercion I would do so explicitly.

Secondly, if these values are being provided by user input I'd argue against using a naive solution such as .substr, and in its place use a regex such as /\d+(.\d*)?/. If it's not from user input you're probably safe.

Thirdly, and what I most suspect is the issue, is toLocaleString. It was my understanding that toLocaleString was fairly untrustworthy as a function due to the different implementations provided by different browsers. I'm on a Mac, and Chrome produces $7.50, and Firefox produces US$7.50. These seem fine as they are, but hint at possible issues for older versions of these browsers, and also if you were to attempt naive string manipulation on them you'd quickly encounter problems. It's fairly easy to replace toLocaleString with a safe and concise solution.

document.getElementById('totalPrice').innerHTML = '$' + tableTotal.toFixed(2)

This assumes typeof tableTotal === 'number', otherwise you must simply do (+tableTotal).toFixed(2) to perform type coercion.

Good luck, and let me know if I've solved your problem.

Body:
I have tested this application on all current major browsers and it works reliably and correctly. The app is now deployed and I am getting reports that sometimes the result is NaN.

The function below uses parsefloat() to find the total of a column of prices in a table. Sometimes that total is displayed as NaN. I have been unable to reproduce it and the customers who report the issue thus far have not been sufficiently technically competent to tell me what browser they are using. One person sent a screen shot of Firefox on a Mac and another knew it was Firefox on Windows.

In the below code, this line:

var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);

properly sets linePrice to 6.50 and the value of innerHTML is "$6.50". The next line calls parseFloat(linePrice);

Finally, this line:

document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });

Causes NaN to be displayed instead of the column total.

Any help would be greatly appreciated!

Here is the code:

  function totalTbl()
  {
    var table = document.getElementById('myTbl');
    var rows = table.getElementsByTagName('tr');

    var tableTotal = 0;

    // Skip the first (header) row and the last (add row) row
    len = rows.length - 2;
    numRows = len - 1;

    for (var i = 1; i < len; i++)
    {
      var cell = rows[i].cells[5];
      if (cell.firstChild != null)
      {
        var linePrice = rows[i].cells[gTblLinePriceCol].innerHTML.substr(1);

        tableTotal += parseFloat(linePrice);
      }
    }

    document.getElementById('totalPrice').innerHTML = tableTotal.toLocaleString('us-US', { style: 'currency', currency: 'USD' });

  }


问:
rails - application.css asset not found in production mode
I'm upgrading an application to use the asset pipeline.

I've got the css assets compiling into an application css file but they not being found when I run the application in production mode with

```<code>RAILS_ENV=production bundle exec rails s
</code>```

and I visit any page I get the correct output from the database but no styling and the log shows:

```<code>ActionController::RoutingError (No route matches [GET]
"/assets/default.scss-1a27c...f07c.css"):
</code>```

Even though that file exists in public/assets

```<code>$ ls public/assets/def*
public/assets/default.scss-1a27c...f07c.css     public/assets/default.scss.css
public/assets/default.scss-1a27c...f07c.css.gz  public/assets/default.scss.css.gz
</code>```

What do I need to change to get the server to find the asset file?

Same is happening for my other .css files.  They get compiled into public/assets with finger prints but then are not found.

Page source is showing:

```<code><link href="/assets/default.scss-1a27c...f07c.css"
media="screen" rel="stylesheet" type="text/css" />
</code>```

The rails (haml) source is = stylesheet_link_tag 'default.scss.css'

public.assets curently includes has the following files.

```<code>$ ls public/assets/def*
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css.gz
public/assets/default.scss.css
public/assets/default.scss.css.gz
</code>```

application.rb has

```<code>$ cat config/application.rb
require File.expand_path('../boot', __FILE__)

# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

if defined?(Bundler)
  # If you precompile assets before deploying to production, use this line
  Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  # Bundler.require(:default, :assets, Rails.env)
end

module Linker
  class Application < Rails::Application
    config.encoding = "utf-8"
    config.filter_parameters += [:password]
    config.assets.enabled = true
    config.assets.initialize_on_precompile = false # For Heroku
    config.assets.version = '1.0'
  end
end
</code>```

config/environments/production has:

```<code>$ cat config/environments/production.rb
Linker::Application.configure do
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.assets.precompile += ['default.scss.css','main.css', 'jquery-ui-1.8.22.custom.css']
  config.serve_static_assets = false
  config.assets.compress = true
  config.assets.compile = false
  config.assets.digest = true
  config.log_level = :debug
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
end
</code>```

This seems to be happening for all assets, e.g.

```<code>Started GET "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css"):
Started GET "/assets/main-6864687b4114a1c316e444bd90f233ff.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/main-6864687b4114a1c316e444bd90f233ff.css"):
Started GET "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css"):
Started GET "/assets/application-fc1d492d730f2a45581a40eac4607db8.js" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/application-fc1d492d730f2a45581a40eac4607db8.js"):
Started GET "/images/link.ico" for 127.0.0.1 at 2014-02-23 10:24:48 -0500
ActionController::RoutingError (No route matches [GET] "/images/link.ico"):
</code>```

答:
The Rails 5 solution is similar to the Rails 4 solution given by Jules Copeland above.

In your pre-generated config/environments/production.rb file, there should be an entry that looks something like this:

```<code># Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
</code>```

I found a decent explanation for this setting in the Configuring Rails Applications guide at http://guides.rubyonrails.org:

config.public_file_server.enabled configures Rails to serve static
  files from the public directory. This option defaults to true, but in
  the production environment it is set to false because the server
  software (e.g. NGINX or Apache) used to run the application should
  serve static files instead. If you are running or testing your app in
  production mode using WEBrick (it is not recommended to use WEBrick in
  production) set the option to true. Otherwise, you won't be able to
  use page caching and request for files that exist under the public
  directory.

Conclusion: In production, starting your rails server with RAILS_SERVE_STATIC_FILES=1 will allow Rails to serve any files in the public/assets directory just as a web server would. Keep in mind, Rails is an app server and will not do this as efficiently as a web server (e.g. NGINX, Apache, etc.). For real-world applications, you should have a dedicated web server sitting in front of Rails which will serve static assets by itself and only bother Rails for dynamic content as needed. For more details, see this article by Justin Weiss on the differences between web servers and app servers.

Body:
I'm upgrading an application to use the asset pipeline.

I've got the css assets compiling into an application css file but they not being found when I run the application in production mode with

RAILS_ENV=production bundle exec rails s

and I visit any page I get the correct output from the database but no styling and the log shows:

ActionController::RoutingError (No route matches [GET]
"/assets/default.scss-1a27c...f07c.css"):

Even though that file exists in public/assets

$ ls public/assets/def*
public/assets/default.scss-1a27c...f07c.css     public/assets/default.scss.css
public/assets/default.scss-1a27c...f07c.css.gz  public/assets/default.scss.css.gz

What do I need to change to get the server to find the asset file?

Same is happening for my other .css files.  They get compiled into public/assets with finger prints but then are not found.

Page source is showing:

<link href="/assets/default.scss-1a27c...f07c.css"
media="screen" rel="stylesheet" type="text/css" />

The rails (haml) source is = stylesheet_link_tag 'default.scss.css'

public.assets curently includes has the following files.

$ ls public/assets/def*
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css
public/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css.gz
public/assets/default.scss.css
public/assets/default.scss.css.gz

application.rb has

$ cat config/application.rb
require File.expand_path('../boot', __FILE__)

# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

if defined?(Bundler)
  # If you precompile assets before deploying to production, use this line
  Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  # Bundler.require(:default, :assets, Rails.env)
end

module Linker
  class Application < Rails::Application
    config.encoding = "utf-8"
    config.filter_parameters += [:password]
    config.assets.enabled = true
    config.assets.initialize_on_precompile = false # For Heroku
    config.assets.version = '1.0'
  end
end

config/environments/production has:

$ cat config/environments/production.rb
Linker::Application.configure do
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.assets.precompile += ['default.scss.css','main.css', 'jquery-ui-1.8.22.custom.css']
  config.serve_static_assets = false
  config.assets.compress = true
  config.assets.compile = false
  config.assets.digest = true
  config.log_level = :debug
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
end

This seems to be happening for all assets, e.g.

Started GET "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/default.scss-1a27c22229b7b522066181f27af4f07c.css"):
Started GET "/assets/main-6864687b4114a1c316e444bd90f233ff.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/main-6864687b4114a1c316e444bd90f233ff.css"):
Started GET "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/jquery-ui-1.8.22.custom-24319b4b1218846a3fe22a0479ae98b4.css"):
Started GET "/assets/application-fc1d492d730f2a45581a40eac4607db8.js" for 127.0.0.1 at 2014-02-23 10:24:47 -0500
ActionController::RoutingError (No route matches [GET] "/assets/application-fc1d492d730f2a45581a40eac4607db8.js"):
Started GET "/images/link.ico" for 127.0.0.1 at 2014-02-23 10:24:48 -0500
ActionController::RoutingError (No route matches [GET] "/images/link.ico"):

Body:
The Rails 5 solution is similar to the Rails 4 solution given by Jules Copeland above.

In your pre-generated config/environments/production.rb file, there should be an entry that looks something like this:

# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

I found a decent explanation for this setting in the Configuring Rails Applications guide at http://guides.rubyonrails.org:

config.public_file_server.enabled configures Rails to serve static
  files from the public directory. This option defaults to true, but in
  the production environment it is set to false because the server
  software (e.g. NGINX or Apache) used to run the application should
  serve static files instead. If you are running or testing your app in
  production mode using WEBrick (it is not recommended to use WEBrick in
  production) set the option to true. Otherwise, you won't be able to
  use page caching and request for files that exist under the public
  directory.

Conclusion: In production, starting your rails server with RAILS_SERVE_STATIC_FILES=1 will allow Rails to serve any files in the public/assets directory just as a web server would. Keep in mind, Rails is an app server and will not do this as efficiently as a web server (e.g. NGINX, Apache, etc.). For real-world applications, you should have a dedicated web server sitting in front of Rails which will serve static assets by itself and only bother Rails for dynamic content as needed. For more details, see this article by Justin Weiss on the differences between web servers and app servers.


问:
Showing a dynamic number of views in RecyclerView item?
I am trying to re-create this:

I have a list of data:

```<code>List<Block> blocks;
</code>```

And the Block.java class has a method getNumBlocks() which returns the number of blocks that item should show. The number of blocks can range from something as small as 1 block to something as large as 20 blocks.

I created a normal RecyclerView adapter, along with the ImageView layout for the block:

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

    private Context context;

    private List<Block> blocks;

    public BlockAdapter(Context context, List<Block> blocks) {
        this.context = context;
        this.blocks = blocks;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView block;

        public ViewHolder(View v) {
            super(v);

            block = (ImageView) v.findViewById(R.id.block);
        }
    }

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.block_layout, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Block block = blocks.get(position);

        // How to use block.getNumBlocks() to show the correct number of blocks?
    }

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

}
</code>```

Here is block_layout.xml (it's just an empty LinearLayout, the blocks should be added inside of this LinearLayout):

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_bg"
    android:padding="16dp">

</LinearLayout>
</code>```

And here is the block.xml layout:

```<code><ImageView
    android:id="@+id/block"
    android:layout_width="18dp"
    android:layout_height="18dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp" />
</code>```

So my question is, how can I implement this so that it shows the correct number of blocks for each RecyclerView item?

What is the best way to do this performance wise?

答:
It's good that you care about performance. Creating new ImageViews every time you want to display a row is against the idea of recycling views. Basically when scrolling you would re-use only the top level views, but still creating new ImageViews for any item every time it appears on screen.

To deal with that you can create your own pool of views like that:

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

    private final List<Block> blocks;
    private final List<ImageView> imageViewPool = new LinkedList<>();

    public BlockAdapter(List<Block> blocks) {
        this.blocks = blocks;
    }

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

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.block_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.bind(blocks.get(position));
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private final List<ImageView> imageViews = new ArrayList<>();
        private final ViewGroup container;

        public ViewHolder(View v) {
            super(v);
            container = (ViewGroup) itemView;
        }

        public void bind(Block block) {
            recycleImageViews();
            for (int i = 0; i < block.getNumBlocks(); ++i) {
                final ImageView imageView = getRecycledImageViewOrCreate();
                imageViews.add(imageView);
                container.addView(imageView);
            }
        }

        private ImageView getRecycledImageViewOrCreate() {
            if (imageViewPool.isEmpty()) {
                return (ImageView)LayoutInflater.from(container.getContext()).inflate(R.layout.block, container, false);
            }
            return imageViewPool.remove(0);
        }

        public void recycleImageViews() {
            imageViewPool.addAll(imageViews);
            imageViews.clear();
            container.removeAllViews();
        }
    }

    @Override
    public void onViewRecycled(ViewHolder holder) {
        super.onViewRecycled(holder);
        holder.recycleImageViews();
    }
}
</code>```

The idea behind this solution is very similar to what RecyclerView does.

Every time ViewHolder wants to present sub items it will:

Take ImageView from the imageViewPool. If there is no spare one in the pool, a new one will be inflated.

Attach this ImageView to itself.

Later, when particular ViewHolder is re-used or recycled it will:

Detach all ImageViews from itself.

Return those ImageViews to re-usable pool so next item that will appear on the screen can take those.

Body:
I am trying to re-create this:

I have a list of data:

List<Block> blocks;

And the Block.java class has a method getNumBlocks() which returns the number of blocks that item should show. The number of blocks can range from something as small as 1 block to something as large as 20 blocks.

I created a normal RecyclerView adapter, along with the ImageView layout for the block:

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

    private Context context;

    private List<Block> blocks;

    public BlockAdapter(Context context, List<Block> blocks) {
        this.context = context;
        this.blocks = blocks;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView block;

        public ViewHolder(View v) {
            super(v);

            block = (ImageView) v.findViewById(R.id.block);
        }
    }

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.block_layout, parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        Block block = blocks.get(position);

        // How to use block.getNumBlocks() to show the correct number of blocks?
    }

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

}

Here is block_layout.xml (it's just an empty LinearLayout, the blocks should be added inside of this LinearLayout):

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_bg"
    android:padding="16dp">

</LinearLayout>

And here is the block.xml layout:

<ImageView
    android:id="@+id/block"
    android:layout_width="18dp"
    android:layout_height="18dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp" />

So my question is, how can I implement this so that it shows the correct number of blocks for each RecyclerView item?

What is the best way to do this performance wise?

Body:
It's good that you care about performance. Creating new ImageViews every time you want to display a row is against the idea of recycling views. Basically when scrolling you would re-use only the top level views, but still creating new ImageViews for any item every time it appears on screen.

To deal with that you can create your own pool of views like that:

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

    private final List<Block> blocks;
    private final List<ImageView> imageViewPool = new LinkedList<>();

    public BlockAdapter(List<Block> blocks) {
        this.blocks = blocks;
    }

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

    @Override
    public BlockAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.block_layout, parent, false));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.bind(blocks.get(position));
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private final List<ImageView> imageViews = new ArrayList<>();
        private final ViewGroup container;

        public ViewHolder(View v) {
            super(v);
            container = (ViewGroup) itemView;
        }

        public void bind(Block block) {
            recycleImageViews();
            for (int i = 0; i < block.getNumBlocks(); ++i) {
                final ImageView imageView = getRecycledImageViewOrCreate();
                imageViews.add(imageView);
                container.addView(imageView);
            }
        }

        private ImageView getRecycledImageViewOrCreate() {
            if (imageViewPool.isEmpty()) {
                return (ImageView)LayoutInflater.from(container.getContext()).inflate(R.layout.block, container, false);
            }
            return imageViewPool.remove(0);
        }

        public void recycleImageViews() {
            imageViewPool.addAll(imageViews);
            imageViews.clear();
            container.removeAllViews();
        }
    }

    @Override
    public void onViewRecycled(ViewHolder holder) {
        super.onViewRecycled(holder);
        holder.recycleImageViews();
    }
}

The idea behind this solution is very similar to what RecyclerView does.

Every time ViewHolder wants to present sub items it will:

Take ImageView from the imageViewPool. If there is no spare one in the pool, a new one will be inflated.

Attach this ImageView to itself.

Later, when particular ViewHolder is re-used or recycled it will:

Detach all ImageViews from itself.

Return those ImageViews to re-usable pool so next item that will appear on the screen can take those.


问:
Adding a reference to an object to a map in C++
I'm having trouble inserting a reference to an object into a map in C++.

Here is some sample code to show what I want to do:

```<code>#include <iostream>
#include <map>

class Foo {
public:
    // ...

    void addToMap();
};

std::map<std::string, Foo&> myMap;

void Foo::addToMap() {
    myMap.insert(std::make_pair(std::string("hello"), *this));
}

int main() {
    Foo foo;
    foo.addToMap();
}
</code>```

When I compile, I get a very cryptic error message of

```<code>main.cpp: In member function ‘void Foo::addToMap()’:
main.cpp:12:48: error: no matching function for call to ‘std::map<std::__cxx11::basic_string<char>, Foo&>::insert(std::pair<const char*, Foo>)’
     myMap.insert(std::make_pair("hello", *this));
                                                ^
In file included from /usr/include/c++/6.3.1/map:61:0,
                 from main.cpp:2:
/usr/include/c++/6.3.1/bits/stl_map.h:731:7: note: candidate: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, Foo&>]
       insert(const value_type& __x)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:731:7: note:   no known conversion for argument 1 from ‘std::pair<const char*, Foo>’ to ‘const value_type& {aka const std::pair<const std::__cxx11::basic_string<char>, Foo&>&}’
/usr/include/c++/6.3.1/bits/stl_map.h:739:9: note: candidate: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(_Pair&& __x)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:739:9: note:   template argument deduction/substitution failed:
/usr/include/c++/6.3.1/bits/stl_map.h:735:32: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
       template<typename _Pair, typename = typename
                                ^~~~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:752:7: note: candidate: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
       insert(std::initializer_list<value_type> __list)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:752:7: note:   no known conversion for argument 1 from ‘std::pair<const char*, Foo>’ to ‘std::initializer_list<std::pair<const std::__cxx11::basic_string<char>, Foo&> >’
/usr/include/c++/6.3.1/bits/stl_map.h:781:7: note: candidate: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, Foo&>]
       insert(const_iterator __position, const value_type& __x)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:781:7: note:   candidate expects 2 arguments, 1 provided
/usr/include/c++/6.3.1/bits/stl_map.h:792:9: note: candidate: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(const_iterator __position, _Pair&& __x)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:792:9: note:   template argument deduction/substitution failed:
main.cpp:12:48: note:   candidate expects 2 arguments, 1 provided
     myMap.insert(std::make_pair("hello", *this));
                                                ^
In file included from /usr/include/c++/6.3.1/map:61:0,
                 from main.cpp:2:
/usr/include/c++/6.3.1/bits/stl_map.h:807:9: note: candidate: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(_InputIterator __first, _InputIterator __last)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:807:9: note:   template argument deduction/substitution failed:
main.cpp:12:48: note:   candidate expects 2 arguments, 1 provided
     myMap.insert(std::make_pair("hello", *this));
</code>```

I have no idea how to make the pointer this into a reference, which I can then insert into the map. How would I go about fixing the code?

答:
The standard library containers can't contain references. Use pointers instead, or wrap your references to T in std::reference_wrapper<T> instead, e.g.

```<code>#include <functional>
#include <map>
#include <string>

std::map<std::string, std::reference_wrapper<Foo> > myMap;
</code>```

Body:
I'm having trouble inserting a reference to an object into a map in C++.

Here is some sample code to show what I want to do:

#include <iostream>
#include <map>

class Foo {
public:
    // ...

    void addToMap();
};

std::map<std::string, Foo&> myMap;

void Foo::addToMap() {
    myMap.insert(std::make_pair(std::string("hello"), *this));
}

int main() {
    Foo foo;
    foo.addToMap();
}

When I compile, I get a very cryptic error message of

main.cpp: In member function ‘void Foo::addToMap()’:
main.cpp:12:48: error: no matching function for call to ‘std::map<std::__cxx11::basic_string<char>, Foo&>::insert(std::pair<const char*, Foo>)’
     myMap.insert(std::make_pair("hello", *this));
                                                ^
In file included from /usr/include/c++/6.3.1/map:61:0,
                 from main.cpp:2:
/usr/include/c++/6.3.1/bits/stl_map.h:731:7: note: candidate: std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(const value_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, Foo&>]
       insert(const value_type& __x)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:731:7: note:   no known conversion for argument 1 from ‘std::pair<const char*, Foo>’ to ‘const value_type& {aka const std::pair<const std::__cxx11::basic_string<char>, Foo&>&}’
/usr/include/c++/6.3.1/bits/stl_map.h:739:9: note: candidate: template<class _Pair, class> std::pair<typename std::_Rb_tree<_Key, std::pair<const _Key, _Tp>, std::_Select1st<std::pair<const _Key, _Tp> >, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<std::pair<const _Key, _Tp> >::other>::iterator, bool> std::map<_Key, _Tp, _Compare, _Alloc>::insert(_Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(_Pair&& __x)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:739:9: note:   template argument deduction/substitution failed:
/usr/include/c++/6.3.1/bits/stl_map.h:735:32: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
       template<typename _Pair, typename = typename
                                ^~~~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:752:7: note: candidate: void std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::initializer_list<std::pair<const _Key, _Tp> >) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
       insert(std::initializer_list<value_type> __list)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:752:7: note:   no known conversion for argument 1 from ‘std::pair<const char*, Foo>’ to ‘std::initializer_list<std::pair<const std::__cxx11::basic_string<char>, Foo&> >’
/usr/include/c++/6.3.1/bits/stl_map.h:781:7: note: candidate: std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, const value_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >; std::map<_Key, _Tp, _Compare, _Alloc>::value_type = std::pair<const std::__cxx11::basic_string<char>, Foo&>]
       insert(const_iterator __position, const value_type& __x)
       ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:781:7: note:   candidate expects 2 arguments, 1 provided
/usr/include/c++/6.3.1/bits/stl_map.h:792:9: note: candidate: template<class _Pair, class> std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::insert(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator, _Pair&&) [with _Pair = _Pair; <template-parameter-2-2> = <template-parameter-1-2>; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(const_iterator __position, _Pair&& __x)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:792:9: note:   template argument deduction/substitution failed:
main.cpp:12:48: note:   candidate expects 2 arguments, 1 provided
     myMap.insert(std::make_pair("hello", *this));
                                                ^
In file included from /usr/include/c++/6.3.1/map:61:0,
                 from main.cpp:2:
/usr/include/c++/6.3.1/bits/stl_map.h:807:9: note: candidate: template<class _InputIterator> void std::map<_Key, _Tp, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = _InputIterator; _Key = std::__cxx11::basic_string<char>; _Tp = Foo&; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, Foo&> >]
         insert(_InputIterator __first, _InputIterator __last)
         ^~~~~~
/usr/include/c++/6.3.1/bits/stl_map.h:807:9: note:   template argument deduction/substitution failed:
main.cpp:12:48: note:   candidate expects 2 arguments, 1 provided
     myMap.insert(std::make_pair("hello", *this));

I have no idea how to make the pointer this into a reference, which I can then insert into the map. How would I go about fixing the code?

Body:
The standard library containers can't contain references. Use pointers instead, or wrap your references to T in std::reference_wrapper<T> instead, e.g.

#include <functional>
#include <map>
#include <string>

std::map<std::string, std::reference_wrapper<Foo> > myMap;


问:
What is the --release flag in the Java 9 compiler?
Java 9's javac has a new flag --release:

```<code>> javac --help
...

--release <release>
    Compile for a specific VM version. Supported targets: 6, 7, 8, 9
</code>```

How is it different from -source and -target flags? Is it just a shortcut for -source X -target X?

答:
--release X is more than just a shortcut to -source X -target X because -source and -target are not sufficient to safely compile to an older release. You also need to set a -bootclasspath flag which must correspond to the older release (and this flag is often forgotten). So, in Java 9 they made a single --release flag which is a replacement for three flags: -source, -target and -bootclasspath.

So, this is an example of compiling to Java 1.7:

```<code>javac --release 7 <source files>
</code>```

Note that you don't even need to have JDK 7 installed on your computer. JDK 9 already contains the needed information to prevent you from accidental linking to symbols that did not exist in JDK 7.

Another important difference is that you can only use public APIs when compiling with --release:

```<code>> javac --add-exports java.base/sun.invoke=ALL-UNNAMED --release 11 Main.java
error: exporting a package from system module java.base is not allowed with --release
1 error
</code>```

If you want to use internal APIs, you have to remove the option --release:

```<code>> javac --add-exports java.base/sun.invoke=ALL-UNNAMED Main.java
</code>```

or

```<code>> javac --add-exports java.base/sun.invoke=ALL-UNNAMED -source 11 -target 11  Main.java
</code>```

Body:
Java 9's javac has a new flag --release:

> javac --help
...

--release <release>
    Compile for a specific VM version. Supported targets: 6, 7, 8, 9

How is it different from -source and -target flags? Is it just a shortcut for -source X -target X?

Body:
--release X is more than just a shortcut to -source X -target X because -source and -target are not sufficient to safely compile to an older release. You also need to set a -bootclasspath flag which must correspond to the older release (and this flag is often forgotten). So, in Java 9 they made a single --release flag which is a replacement for three flags: -source, -target and -bootclasspath.

So, this is an example of compiling to Java 1.7:

javac --release 7 <source files>

Note that you don't even need to have JDK 7 installed on your computer. JDK 9 already contains the needed information to prevent you from accidental linking to symbols that did not exist in JDK 7.

Another important difference is that you can only use public APIs when compiling with --release:

> javac --add-exports java.base/sun.invoke=ALL-UNNAMED --release 11 Main.java
error: exporting a package from system module java.base is not allowed with --release
1 error

If you want to use internal APIs, you have to remove the option --release:

> javac --add-exports java.base/sun.invoke=ALL-UNNAMED Main.java

or

> javac --add-exports java.base/sun.invoke=ALL-UNNAMED -source 11 -target 11  Main.java


问:
Interlinking two option groups in MS Access form
I have two option groups with frames on a form: Packing and Pallet. Packing contains 3 values: Box, Rack and Pallet. I wish to connect the frames such that if a person clicks on Pallet option in Packing Frame, the Pallet frame activates and remains deactivated for the remaining two options.

```<code>Private Sub Frame_Packing_BeforeUpdate(Cancel As Integer)
   If Frame_Packing.Value = 3 Then
      Frame_Palet.Locked = False
   End If
End Sub
</code>```

I tried this code, but it only works once. So, if I click on Pallet the Pallet frame gets unlocked but if I change the value to Box, it doesn't deactivate. I want the Pallet frame to be active only when the pallet option is active under the Packing frame.

By frame I mean Option Group, which has option boxes underneath it. For example, Gender, you can either Select MALE or FEMALE.

答:
Simply add an Else condition to deactivate the lock:

```<code>Private Sub Frame_Packing_AfterUpdate()
   If Frame_Packing.Value = 3 Then
      Me.Dirty = False
      Frame_Palet.Locked = False
   Else
      Frame_Palet.Locked = True
   End If
End Sub
</code>```

Body:
I have two option groups with frames on a form: Packing and Pallet. Packing contains 3 values: Box, Rack and Pallet. I wish to connect the frames such that if a person clicks on Pallet option in Packing Frame, the Pallet frame activates and remains deactivated for the remaining two options.

Private Sub Frame_Packing_BeforeUpdate(Cancel As Integer)
   If Frame_Packing.Value = 3 Then
      Frame_Palet.Locked = False
   End If
End Sub

I tried this code, but it only works once. So, if I click on Pallet the Pallet frame gets unlocked but if I change the value to Box, it doesn't deactivate. I want the Pallet frame to be active only when the pallet option is active under the Packing frame.

By frame I mean Option Group, which has option boxes underneath it. For example, Gender, you can either Select MALE or FEMALE.

Body:
Simply add an Else condition to deactivate the lock:

Private Sub Frame_Packing_AfterUpdate()
   If Frame_Packing.Value = 3 Then
      Me.Dirty = False
      Frame_Palet.Locked = False
   Else
      Frame_Palet.Locked = True
   End If
End Sub


问:
Run code before all Airflow DAGs
I'm using the relatively new airflow project. I have a bunch of DAGs written and running. Now I want to integrate a bug reporting service, so that if any code in any of the DAGs raises an exception, the information will be sent to a certain API. I can put the API call in the on_failure_callback of each DAG, but I need to execute an initializing line like bug_reporter.init(bug_reporter_token) that just needs to run once.

Is there a place in Airflow for initializing code? Right now I'm initializing the bug tracker at the beginning of every DAG definition file. This seems to be redundant, but I can't find a place to write a file that runs before the DAGs are defined. I've tried reading about plugins, but it doesn't seem to be there.

答:
In your DAG definition file, instead of a DAG use your own subclass:

from airflow.utils.decorators import apply_defaults
import bug_reporter

class DAGWithBugReporter(DAG):
    @apply_defaults
    def __init__(
        self,
        bug_reporter_token,
        *args, **kwargs):

        super(DAGWithBugReporter, self).__init__(*args, **kwargs)
        bug_reporter.init(bug_reporter_token)
```

<p>Then in your dag definition:</p>

<pre class="lang-py prettyprint-override"><code>dag = DAGWithBugReporter(
    dag_id='my_dag',
    schedule_interval=None,
    start_date=datetime(2017, 2, 26),
    bug_reporter_token=my_token_from_somewhere
)

t1 = PythonOperator(
    task_id='t1',
    provide_context=True,
    python_callable=my_callable,
    xcom_push=True,
    dag=dag)
</code>```

Title: Run code before all Airflow DAGs

Body:
In your DAG definition file, instead of a DAG use your own subclass:

from airflow.utils.decorators import apply_defaults
import bug_reporter

class DAGWithBugReporter(DAG):
    @apply_defaults
    def __init__(
        self,
        bug_reporter_token,
        *args, **kwargs):

        super(DAGWithBugReporter, self).__init__(*args, **kwargs)
        bug_reporter.init(bug_reporter_token)

Then in your dag definition:

dag = DAGWithBugReporter(
    dag_id='my_dag',
    schedule_interval=None,
    start_date=datetime(2017, 2, 26),
    bug_reporter_token=my_token_from_somewhere
)

t1 = PythonOperator(
    task_id='t1',
    provide_context=True,
    python_callable=my_callable,
    xcom_push=True,
    dag=dag)