问:
Stop accordion expanding on page load
I am useless with JS as I have no idea what Im doing but I've hit a wall that CSS wont get me past.

I have a page on a website where there are some accordion text sections. The problem I am having is that I want to make it so that none of these are expanded on page load, I want them to all be hidden. Currently the page opens with the top option expanded.

Below is what I believe to be the responsible script, can anyone shed any light for me?

Thanks in advance.

```<code>/**
* Accordion-folding functionality.
*
* Markup with the appropriate classes will be automatically hidden,
* with one section opening at a time when its title is clicked.
* Use the following markup structure for accordion behavior:
*
* <div class="accordion-container">
*   <div class="accordion-section open">
*       <h3 class="accordion-section-title"></h3>
*       <div class="accordion-section-content">
*       </div>
*   </div>
*   <div class="accordion-section">
*       <h3 class="accordion-section-title"></h3>
*       <div class="accordion-section-content">
*       </div>
*   </div>
*   <div class="accordion-section">
*       <h3 class="accordion-section-title"></h3>
*       <div class="accordion-section-content">
*       </div>
*   </div>
* </div>
*
* Note that any appropriate tags may be used, as long as the above classes are present.
*
* @since 3.6.0.
*/

( function( $ ){

$( document ).ready( function () {

    // Expand/Collapse accordion sections on click.
    $( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) {
        if ( e.type === 'keydown' && 13 !== e.which ) { // "return" key
            return;
        }

        e.preventDefault(); // Keep this AFTER the key filter above

        accordionSwitch( $( this ) );
    });

});

/**
 * Close the current accordion section and open a new one.
 *
 * @param {Object} el Title element of the accordion section to toggle.
 * @since 3.6.0
 */
function accordionSwitch ( el ) {

    var section = el.closest( '.accordion-section' ),
        sectionToggleControl = section.find( '[aria-expanded]' ).first(),
        container = section.closest( '.accordion-container' ),
        siblings = container.find( '.open' ),
        siblingsToggleControl = siblings.find( '[aria-expanded]' ).first(),
        content = section.find( '.accordion-section-content' );

    // This section has no content and cannot be expanded.
    if ( section.hasClass( 'cannot-expand' ) ) {
        return;
    }

    // Add a class to the container to let us know something is happening inside.
    // This helps in cases such as hiding a scrollbar while animations are executing.
    container.addClass( 'opening' );

    if ( section.hasClass( 'open' ) ) {
        section.toggleClass( 'open' );
        content.toggle( true ).slideToggle( 150 );
    } else {
        siblingsToggleControl.attr( 'aria-expanded', 'false' );
        siblings.removeClass( 'open' );
        siblings.find( '.accordion-section-content' ).show().slideUp( 150 );
        content.toggle( false ).slideToggle( 150 );
        section.toggleClass( 'open' );
    }

    // We have to wait for the animations to finish
    setTimeout(function(){
        container.removeClass( 'opening' );
    }, 150);

    // If there's an element with an aria-expanded attribute, assume it's a toggle control and toggle the aria-expanded value.
    if ( sectionToggleControl ) {
        sectionToggleControl.attr( 'aria-expanded', String( sectionToggleControl.attr( 'aria-expanded' ) === 'false' ) );
    }
}
</code>```

})(jQuery);

答:
If you have the exact same HTML as in the top of the file, remove the open class from the first accordion:

```<code><div class="accordion-container">
    <!-- The next accordion-section also had the open class -->
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
</div>
</code>```

Title: Stop accordion expanding on page load

Body:
I am useless with JS as I have no idea what Im doing but I've hit a wall that CSS wont get me past.

I have a page on a website where there are some accordion text sections. The problem I am having is that I want to make it so that none of these are expanded on page load, I want them to all be hidden. Currently the page opens with the top option expanded.

Below is what I believe to be the responsible script, can anyone shed any light for me?

Thanks in advance.

/**
* Accordion-folding functionality.
*
* Markup with the appropriate classes will be automatically hidden,
* with one section opening at a time when its title is clicked.
* Use the following markup structure for accordion behavior:
*
*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*

*
* Note that any appropriate tags may be used, as long as the above classes are present.
*
* @since 3.6.0.
*/

( function( $ ){

$( document ).ready( function () {

    // Expand/Collapse accordion sections on click.
    $( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) {
        if ( e.type === 'keydown' && 13 !== e.which ) { // "return" key
            return;
        }

        e.preventDefault(); // Keep this AFTER the key filter above

        accordionSwitch( $( this ) );
    });

});

/**
 * Close the current accordion section and open a new one.
 *
 * @param {Object} el Title element of the accordion section to toggle.
 * @since 3.6.0
 */
function accordionSwitch ( el ) {

    var section = el.closest( '.accordion-section' ),
        sectionToggleControl = section.find( '[aria-expanded]' ).first(),
        container = section.closest( '.accordion-container' ),
        siblings = container.find( '.open' ),
        siblingsToggleControl = siblings.find( '[aria-expanded]' ).first(),
        content = section.find( '.accordion-section-content' );

    // This section has no content and cannot be expanded.
    if ( section.hasClass( 'cannot-expand' ) ) {
        return;
    }

    // Add a class to the container to let us know something is happening inside.
    // This helps in cases such as hiding a scrollbar while animations are executing.
    container.addClass( 'opening' );

    if ( section.hasClass( 'open' ) ) {
        section.toggleClass( 'open' );
        content.toggle( true ).slideToggle( 150 );
    } else {
        siblingsToggleControl.attr( 'aria-expanded', 'false' );
        siblings.removeClass( 'open' );
        siblings.find( '.accordion-section-content' ).show().slideUp( 150 );
        content.toggle( false ).slideToggle( 150 );
        section.toggleClass( 'open' );
    }

    // We have to wait for the animations to finish
    setTimeout(function(){
        container.removeClass( 'opening' );
    }, 150);

    // If there's an element with an aria-expanded attribute, assume it's a toggle control and toggle the aria-expanded value.
    if ( sectionToggleControl ) {
        sectionToggleControl.attr( 'aria-expanded', String( sectionToggleControl.attr( 'aria-expanded' ) === 'false' ) );
    }
}

})(jQuery);

Body:
If you have the exact same HTML as in the top of the file, remove the open class from the first accordion:

<div class="accordion-container">
    <!-- The next accordion-section also had the open class -->
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
    <div class="accordion-section">
        <h3 class="accordion-section-title"></h3>
        <div class="accordion-section-content">
        </div>
    </div>
</div>


来源: stackexchange

问:
replacing a unicode character
I can't figure out how to remove a Unicode character using .replace(...) here's what I've tried

```<code> $(elem).click(function () {
   var display = $("." + target).css('display');
   var lastChar = display == 'none' ? 'a' : '8';
   $("." + target).slideToggle(500);
   alert('index: ' + $(this).text().indexOf('⇈'));
   $(this).html($(this).html().replace('⇈','').replace('⇊','') + ' &#x21c' + lastChar + ';');
 });
</code>```

It is adding my double arrow up and down, but indexOf is always -1, and my replace calls are not removing the Unicode character. I'm looking at this now and thinking that if I start off with one of these Unicode chars I could just replace it with the other one... If I could get replace to work at all ;-)

What am I doing wrong? Thanks!

答:
Try using String.fromCharCode()

The static String.fromCharCode() method returns a string created by
  using the specified sequence of Unicode values.

Syntax

String.fromCharCode(num1[, ...[, numN]]);

Examples

myString.replace(String.fromCharCode(8648),''); for ⇈
myString.replace(String.fromCharCode(8650),''); for ⇊
myString.indexOf(String.fromCharCode(84,69,83,84);

ContentLicense: CC BY-SA 3.0

Title: replacing a unicode character

Body:
I can't figure out how to remove a Unicode character using .replace(...) here's what I've tried

 $(elem).click(function () {
   var display = $("." + target).css('display');
   var lastChar = display == 'none' ? 'a' : '8';
   $("." + target).slideToggle(500);
   alert('index: ' + $(this).text().indexOf('⇈'));
   $(this).html($(this).html().replace('⇈','').replace('⇊','') + ' &#x21c' + lastChar + ';');
 });

It is adding my double arrow up and down, but indexOf is always -1, and my replace calls are not removing the Unicode character. I'm looking at this now and thinking that if I start off with one of these Unicode chars I could just replace it with the other one... If I could get replace to work at all ;-)

What am I doing wrong? Thanks!


问:
how to force a Polymer.Element extended class to execute its lifecycle without attaching it to the dom?
Consider this element (minimal for the purpose of the question) :

```<code>class MyCountDown extends Polymer.Element
{
  static get is () { return 'my-count-down'; }

  static get properties ()
  {
    return {

      time: { /* time in seconds */
        type: Number,
        observer: '_startCountDown'
      },

      remains: Number
    }
  }

  _startCountDown ()
  {

    this.remains = this.time;

    this.tickInterval = window.setInterval(() => {
      this.remains--;
      if (this.remains == 0) {
        console.log('countdown!');
        this._stopCountDown();
      }
    }, 1000);
  }

  _stopCountDown () {
    if (this.tickInterval) {
      window.clearInterval(this.tickInterval);
    }
  }
}

customElements.define(MyCountDown.is, MyCountDown);
</code>```

If I get one instance and set the property time,

```<code>let MyCountDown = customElements.get('my-count-down');
let cd = new MyCountDown();
cd.time = 5;
</code>```

the property time changes but the observer and the _startCountDown() function is not called. I believe Polymer is waiting for the Instance to be attached to the DOM because in fact when I appendChild() this element to the document the count down starts and after 5 seconds the console logs 'countdown!' as expected.

My goal is to execute this lifecycle without attaching anything to the document because the instances of MyCountDown are not always attached to the view but/and they need to be live-code between the different components of my web application.

One solution is to attach the new MyCountDown instances to an hidden element of the dom to force the Polymer lifecycle but I think this is not so intuitive.

答:
I don't know the exact place to call, but the problem you have is that the property assessors are not in place.

I think you might get a clue from this talk https://www.youtube.com/watch?v=assSM3rlvZ8 at google i/o

call this._enableProperties() in a constructor callback?

Body:
Consider this element (minimal for the purpose of the question) :

class MyCountDown extends Polymer.Element
{
  static get is () { return 'my-count-down'; }

  static get properties ()
  {
    return {

      time: { /* time in seconds */
        type: Number,
        observer: '_startCountDown'
      },

      remains: Number
    }
  }

  _startCountDown ()
  {

    this.remains = this.time;

    this.tickInterval = window.setInterval(() => {
      this.remains--;
      if (this.remains == 0) {
        console.log('countdown!');
        this._stopCountDown();
      }
    }, 1000);
  }

  _stopCountDown () {
    if (this.tickInterval) {
      window.clearInterval(this.tickInterval);
    }
  }
}

customElements.define(MyCountDown.is, MyCountDown);

If I get one instance and set the property time,

let MyCountDown = customElements.get('my-count-down');
let cd = new MyCountDown();
cd.time = 5;

the property time changes but the observer and the _startCountDown() function is not called. I believe Polymer is waiting for the Instance to be attached to the DOM because in fact when I appendChild() this element to the document the count down starts and after 5 seconds the console logs 'countdown!' as expected.

My goal is to execute this lifecycle without attaching anything to the document because the instances of MyCountDown are not always attached to the view but/and they need to be live-code between the different components of my web application.

One solution is to attach the new MyCountDown instances to an hidden element of the dom to force the Polymer lifecycle but I think this is not so intuitive.


问:
Does not open more than 2 emulators simultaneously
The IDE does not let me open more than 2 AVD simultaneously. After 2 are already running and attempting to start 3rd AVD - Android Studio displays the message "Starting AVD", but when loading ends nothing happens. No logs, no errors.

If, for example, you choose to close one of already running AVD, and start another - it starts properly, i.e. all AVDs behave well individually.

If matters, I use:

Nexus 6 API 23 (Android 6.0 Google APIs), x86;

Nexus S API 22 (Android 5.1 Google APIs), x86;

Pixel API 25 (Android 7.1.1 Google APIs), x86;

Android Studio 2.3.1

答:
Have same problem today and found it related to RAM usage limit for HAXM

Found answer at here

Why launching more than 2 AVDs works only under specific conditions

Reinstall HAXM and set more ram to fit your need

https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager


问:
laravel display data on a page based on id
I have a page that shows links with name of businesses that are retrieved in database like this:

Controller:

```<code>public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}
</code>```

View:

```<code>@extends('master') @section('title', 'Live Oldham') @section('content')
@section('content')
            @foreach ($business as $businesses)
        <a target="_blank" href="{{ url('business/' . $businesses->name) }}"> {{($businesses->name) }}
        </a> @endforeach
@endsection
</code>```

Route:

```<code>Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
</code>```

I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.

Controller:

```<code>function displayBusiness() {
    $business = Business::all();
    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
</code>```

View:

```<code>@foreach ($business as $businesses)
    <p>{{$businesses->name}}</p>
    <p>{{$businesses->email}}</p>
@endforeach
@foreach ($address as $addresses)
    <p>{{$addresses->firstline_address}}</p>
    <p>{{$addresses->secondline_address}}</p>
    <p>{{$addresses->town}}</p>
    <p>{{$addresses->city}}</p>
    <p>{{$addresses->postcode}}</p>
    <p>{{$addresses->telephone}}</p>
@endforeach
</code>```

Route:

```<code>Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');
</code>```

Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.

Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.

Thanks!

答:
Route parameters are available in the controller function as parameters. Now you can build a query with this function. If your query does not return any results, you can send the user back to the business overview.</p>

```<code>function displayBusiness($name) {
    $business = Business::where('name', $name)->orWhere('id', $name)->first();
    if ($business === null)
    {
        // No business with this name or id found.
        // Redirect to businesses list page.
    }

    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
</code>```

Body:
I have a page that shows links with name of businesses that are retrieved in database like this:

Controller:

public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}

View:

@extends('master') @section('title', 'Live Oldham') @section('content')
@section('content')
            @foreach ($business as $businesses)
        name) }}"> {{($businesses->name) }}
         @endforeach
@endsection

Route:

Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');

I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.

Controller:

function displayBusiness() {
    $business = Business::all();
    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}

View:

@foreach ($business as $businesses)

{{$businesses->name}}

{{$businesses->email}}

@endforeach
@foreach ($address as $addresses)

{{$addresses->firstline_address}}

{{$addresses->secondline_address}}

{{$addresses->town}}

{{$addresses->city}}

{{$addresses->postcode}}

{{$addresses->telephone}}

@endforeach

Route:

Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');

Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.

Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.

Thanks!

Body:
Route parameters are available in the controller function as parameters. Now you can build a query with this function. If your query does not return any results, you can send the user back to the business overview.

function displayBusiness($name) {
    $business = Business::where('name', $name)->orWhere('id', $name)->first();
    if ($business === null)
    {
        // No business with this name or id found.
        // Redirect to businesses list page.
    }

    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}


问:
Angular Material - md-tabs inside md-toolbar. md-tabs next to other elements inside md-toolbar
I want to have mf-tabs within md-toolbar and i use solution provided by Sithdown in https://github.com/angular/material/issues/1076

It works fine for me, but my problem is that i need to have md-tabs next to other elements inside md-toolbar, but for now, md-tabs is always underneath of other elements, just like that:

Image example:
http://imgur.com/SSVaet9

My code:

```<code><md-toolbar>
     <span>saddsa</span>
     <md-tabs md-selected="selectedIndex" style="padding-top: 16px;">
        <md-tab ng-repeat="tab in tabs track by $index" id="tab{$index + 1}" aria-controls="tab{$index + 1}-content">
            {{tab.title}}
        </md-tab>
    </md-tabs>
</md-toolbar>

<md-tabs md-dynamic-height md-selected="selectedIndex" style="display: none">
    <md-tab ng-repeat="tab in tabs track by $index" label="tab.title">
        {{tab.content}}
    </md-tab>
</md-tabs>
</code>```

My code on Plunker:
http://plnkr.co/edit/guKrRzB9F34mlFDqj4AS?p=preview

答:
Check this out, the angular-material2 github has some demo-app example.  This will create tabs in the toolbar.
https://github.com/angular/components/blob/master/src/components-examples/material/tabs/tab-nav-bar-basic/tab-nav-bar-basic-example.html

Basically, we need to use md-tab-nav-bar property in a
. I have a similar situation and was looking for answers. I have updated their code to include md-toolbar. Here is my example:

```<code>`<div class="demo-nav-bar">
  <md-toolbar color="accent">
      <nav md-tab-nav-bar aria-label="weather navigation links">
    <a md-tab-link>
      tab1
    </a>
    <a md-tab-link>
      tab2
    </a>
  </nav>
  </md-toolbar>
</div>
`
</code>```

css:

```<code>`.demo-nav-bar {
  border: 1px solid #e0e0e0;
  margin-bottom: 40px;

}
`
</code>```

Body:
I want to have mf-tabs within md-toolbar and i use solution provided by Sithdown in https://github.com/angular/material/issues/1076

It works fine for me, but my problem is that i need to have md-tabs next to other elements inside md-toolbar, but for now, md-tabs is always underneath of other elements, just like that:

Image example:
http://imgur.com/SSVaet9

My code:

<md-toolbar>
     saddsa
     <md-tabs md-selected="selectedIndex" style="padding-top: 16px;">
        <md-tab ng-repeat="tab in tabs track by $index" id="tab{$index + 1}" aria-controls="tab{$index + 1}-content">
            {{tab.title}}
        </md-tab>
    </md-tabs>
</md-toolbar>

<md-tabs md-dynamic-height md-selected="selectedIndex" style="display: none">
    <md-tab ng-repeat="tab in tabs track by $index" label="tab.title">
        {{tab.content}}
    </md-tab>
</md-tabs>

My code on Plunker:
http://plnkr.co/edit/guKrRzB9F34mlFDqj4AS?p=preview

Body:
Check this out, the angular-material2 github has some demo-app example.  This will create tabs in the toolbar.
https://github.com/angular/components/blob/master/src/components-examples/material/tabs/tab-nav-bar-basic/tab-nav-bar-basic-example.html

Basically, we need to use md-tab-nav-bar property in a <div>. I have a similar situation and was looking for answers. I have updated their code to include md-toolbar. Here is my example:

`<div class="demo-nav-bar">
  <md-toolbar color="accent">
      <nav md-tab-nav-bar aria-label="weather navigation links">
    <a md-tab-link>
      tab1
    </a>
    <a md-tab-link>
      tab2
    </a>
  </nav>
  </md-toolbar>
</div>
`

css:

`.demo-nav-bar {
  border: 1px solid #e0e0e0;
  margin-bottom: 40px;

}
`

ContentLicense: CC BY-SA 4.0


问:
Component Services application not running properly on Windows Server 2012
I'm new to this old stuff... I've set up my COM+ application (Classic ASP) on Windows Server 2012, but could only get it to run by unchecking "Enforce access checks for this application" in the application properties. It now runs okay, but any time the application tries to hit the database in any way, I get nothing.  I've checked access to the necessary folders (as far as I know) and the user (local user, in the identity tab) has read/write access.  Any ideas?  And is more information needed?</p>

答:
As you probably already know, Windows Server releases are an ever-changing minefield of permission issues (aka user identity issues). What worked under 2008 may no longer under 2012.

The components in a classic ASP solution pretty much all have the potential to be running as different identities in the context of Windows.

Typical examples of unexpected identities are System, Network Service, and IUSR.

Where these options bite are, for example:

In IIS your web site has an assigned app pool in which it runs. The app pool has a user identity assignment;

In IIS, your virtual folders map to physical folders under Windows and there is access security there;

With COM you get a further identity option to set - this is the 'run-as' identity, which is the effective user that executes the COM components for you.

With a database such as MS SQL Server, you get the concept of user connection security which can be set to use Windows user authentication (trust the windows user) or userid/pwd required. So if you use, for example ADODB, in your code you must supply a connection string that you have to match to the connection settings the DB expects and will allow.

From your description I assume that you have the IIS site up and running, and your issue is confined to DB access from the COM components. You need to establish how the COM components connect to the DB and check that the DB will accept the credentials in use. If you are using Windows Authentication for the DB then you need to confirm for sure the run-as identity that is in use. In my setup we create a dedicated Windows user that we set aside specifically to use for COM so that we can be absolutely sure of the identity, and in our most verbose logging from the COM components we capture the run-as identity just to confirm it is all wired up correctly.

We do the same with dedicated Windows users for the IIS app pool user too. In general you are better off being sure which identity is in use by assigning it yourself rather than taking the default. Additionally, the defaults such as Network Service seem to have a diminishing amount of privs in Windows overall.

Word of caution - on the other hand do not give your dedicated users more access than they need, for example making them members of the Administrator group when you are frustrated or feeling your way through permission issues. Sure, assign these on a very temporary basis to confirm that access privs are the issue, but be sure to remove such assignments as soon as you possible can.

EDIT: I had this half written when your comment came in. You say that there was a missing component - I had not considered that potential as you seemed to be saying that the config worked but COM did not. Well done for solving your issue. I will leave this answer in place as some of what I have written could be useful for future folks walking the same or similar path.


问:
Lifting shared State up the tree
I'm trying to build a little React app that when a user selects a meat product the ui will show that category of meat from the json data file. I have a Products class as the parent to a class ProductCategoryRow and a SelectProduct function. I'm a little confused as to how to set the state in the Products class and pass the props on to ProductCategoryRow and SelectProduct.

```<code>function SelectProduct (props) {
const products = ['All', 'Beef', 'Lamb', 'Poultry'];
return (
<ul className='products'>
{products.map(function (prod) {
   return (
       <li
        style={prod === props.selectedProduct ? { color: '#d0021b' }:null}
                onClick={props.onSelect.bind(null, prod)}
                key={prod}>
                {prod}
            </li>
        )
    })}
</ul>
)};

class ProductCategoryRow extends React.Component {
constructor(props) {
super(props);

this.state = {
    list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
   const isNotId = item => item.objectID !== id;
   const updatedList = this.state.list.filter(isNotId);
   this.setState({ list: updatedList });
}

render() {
    return (
        <div className="container">
            { this.state.list.map(item =>
             <div key={item.objectID} className="product-category-row">
                        <div>{item.category}</div>
                        <div>{item.meatCut}</div>
                        <div>{item.cooking}</div>
                        <div>{item.price}</div>
                        <div>
                            <button
                            onClick={() => this.onDismiss(item.objectID)}
                            type="button"
                            >
                            Dismiss
                            </button>
                        </div>
                </div>
            )}
        </div>
    )
}
}

SelectProduct.propTypes = {
selectedProduct: PropTypes.string.isRequired,
onSelect: PropTypes.func.isRequired,
}

class Products extends React.Component {
constructor (props) {
    super(props);
    this.state = {
        selectedProduct: 'All',
        lists: null
    };
    this.updateProduct = this.updateProduct.bind(this);
}

componentDidMount () {
  this.updateProduct(this.state.selectedProduct);
}

updateProduct(prod) {
    this.setState(function () {
        return {
            selectedProduct: prod,
            lists: null
        }
    })
}

render() {
    return (
        <div>
            <SelectProduct
            selectedProduct={this.state.selectedProduct}
            onSelect={this.updateProduct}
            />
            <ProductCategoryRow />
        </div>
    )
}
}

export default Products;
</code>```

Thanks in advance

答:
You are already updating your parent component state when a product is selected, so that is good! Now, you need to pass in this.state.selectedProduct to the ProductCategoryRow component as a selectedProduct prop in your render method:

```<code>function SelectProduct (props) {
const products = ['All', 'Beef', 'Lamb', 'Poultry'];
return (
<ul className='products'>
{products.map(function (prod) {
   return (
       <li
        style={prod === props.selectedProduct ? { color: '#d0021b' }:null}
                onClick={props.onSelect.bind(null, prod)}
                key={prod}>
                {prod}
            </li>
        )
    })}
</ul>
)};

class ProductCategoryRow extends React.Component {
constructor(props) {
super(props);

this.state = {
    list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
   const isNotId = item => item.objectID !== id;
   const updatedList = this.state.list.filter(isNotId);
   this.setState({ list: updatedList });
}

render() {
    return (
        <div className="container">
            { this.state.list.map(item =>
             <div key={item.objectID} className="product-category-row">
                        <div>{item.category}</div>
                        <div>{item.meatCut}</div>
                        <div>{item.cooking}</div>
                        <div>{item.price}</div>
                        <div>
                            <button
                            onClick={() => this.onDismiss(item.objectID)}
                            type="button"
                            >
                            Dismiss
                            </button>
                        </div>
                </div>
            )}
        </div>
    )
}
}

SelectProduct.propTypes = {
selectedProduct: PropTypes.string.isRequired,
onSelect: PropTypes.func.isRequired,
}

class Products extends React.Component {
constructor (props) {
    super(props);
    this.state = {
        selectedProduct: 'All',
        lists: null
    };
    this.updateProduct = this.updateProduct.bind(this);
}

componentDidMount () {
  this.updateProduct(this.state.selectedProduct);
}

updateProduct(prod) {
    this.setState(function () {
        return {
            selectedProduct: prod,
            lists: null
        }
    })
}

render() {
    return (
        <div>
            <SelectProduct
            selectedProduct={this.state.selectedProduct}
            onSelect={this.updateProduct}
            />
            <ProductCategoryRow selectedProduct={this.state.selectedProduct} />
        </div>
    )
}
}

export default Products;
</code>```

Title: Lifting shared State up the tree

Body:
I'm trying to build a little React app that when a user selects a meat product the ui will show that category of meat from the json data file. I have a Products class as the parent to a class ProductCategoryRow and a SelectProduct function. I'm a little confused as to how to set the state in the Products class and pass the props on to ProductCategoryRow and SelectProduct.

function SelectProduct (props) {
const products = ['All', 'Beef', 'Lamb', 'Poultry'];
return (

{products.map(function (prod) {
   return (

                {prod}

        )
    })}

)};

class ProductCategoryRow extends React.Component {
constructor(props) {
super(props);

this.state = {
    list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
   const isNotId = item => item.objectID !== id;
   const updatedList = this.state.list.filter(isNotId);
   this.setState({ list: updatedList });
}

render() {
    return (

            { this.state.list.map(item =>

{item.category}

{item.meatCut}

{item.cooking}

{item.price}

                            <button
                            onClick={() => this.onDismiss(item.objectID)}
                            type="button"
                            >
                            Dismiss
                            </button>

            )}

    )
}
}

SelectProduct.propTypes = {
selectedProduct: PropTypes.string.isRequired,
onSelect: PropTypes.func.isRequired,
}

class Products extends React.Component {
constructor (props) {
    super(props);
    this.state = {
        selectedProduct: 'All',
        lists: null
    };
    this.updateProduct = this.updateProduct.bind(this);
}

componentDidMount () {
  this.updateProduct(this.state.selectedProduct);
}

updateProduct(prod) {
    this.setState(function () {
        return {
            selectedProduct: prod,
            lists: null
        }
    })
}

render() {
    return (

            <SelectProduct
            selectedProduct={this.state.selectedProduct}
            onSelect={this.updateProduct}
            />
            <ProductCategoryRow />

    )
}
}

export default Products;

Thanks in advance

Body:
You are already updating your parent component state when a product is selected, so that is good! Now, you need to pass in this.state.selectedProduct to the ProductCategoryRow component as a selectedProduct prop in your render method:

function SelectProduct (props) {
const products = ['All', 'Beef', 'Lamb', 'Poultry'];
return (
<ul className='products'>
{products.map(function (prod) {
   return (
       <li
        style={prod === props.selectedProduct ? { color: '#d0021b' }:null}
                onClick={props.onSelect.bind(null, prod)}
                key={prod}>
                {prod}
            </li>
        )
    })}
</ul>
)};

class ProductCategoryRow extends React.Component {
constructor(props) {
super(props);

this.state = {
    list: list,
};
this.onDismiss = this.onDismiss.bind(this);
}

onDismiss(id) {
   const isNotId = item => item.objectID !== id;
   const updatedList = this.state.list.filter(isNotId);
   this.setState({ list: updatedList });
}

render() {
    return (
        <div className="container">
            { this.state.list.map(item =>
             <div key={item.objectID} className="product-category-row">
                        <div>{item.category}</div>
                        <div>{item.meatCut}</div>
                        <div>{item.cooking}</div>
                        <div>{item.price}</div>
                        <div>
                            <button
                            onClick={() => this.onDismiss(item.objectID)}
                            type="button"
                            >
                            Dismiss
                            </button>
                        </div>
                </div>
            )}
        </div>
    )
}
}

SelectProduct.propTypes = {
selectedProduct: PropTypes.string.isRequired,
onSelect: PropTypes.func.isRequired,
}

class Products extends React.Component {
constructor (props) {
    super(props);
    this.state = {
        selectedProduct: 'All',
        lists: null
    };
    this.updateProduct = this.updateProduct.bind(this);
}

componentDidMount () {
  this.updateProduct(this.state.selectedProduct);
}

updateProduct(prod) {
    this.setState(function () {
        return {
            selectedProduct: prod,
            lists: null
        }
    })
}

render() {
    return (
        <div>
            <SelectProduct
            selectedProduct={this.state.selectedProduct}
            onSelect={this.updateProduct}
            />
            <ProductCategoryRow selectedProduct={this.state.selectedProduct} />
        </div>
    )
}
}

export default Products;


问:
Numpy compare 2 array shape, if different, append 0 to match shape
I am comparing 2 numpy arrays, and want to add them together. but, before doing so, i need to make sure they are the same size. If the size are not same, then take the smaller sized one and fill the last rows with zero to match the shape.
Both array have 16 columns and N rows. I am assuming it should be pretty straight forward, but I can't get my head around it. So far I am able to compare the 2 array shape.

```<code>import csv
import numpy as np
import sys
data = np.genfromtxt('./test1.csv', dtype=float, delimiter=',')
data_sys = np.genfromtxt('./test2.csv', dtype=float, delimiter=',')
print data.shape
print data_sys.shape
if data.shape != data_sys.shape:
        print "we have an error"
</code>```

This is the output I got:

```<code>=============New file.csv============
(603, 16)
(604, 16)
we have an error
</code>```

I want the fill the last row of "data" array with 0 so that I can add the 2 arrays.
Thanks for your help.

答:
I had a similar situation. Two arrays of sizes mask_in:(n1,m1) and mask_ot:(n2,m2)that were generated through a mask of a 2D image of size (N,M) where A2 is larger than A1 and both share a common center (X0,Y0). I followed the approach suggested by @AniaG using vstack and hstack. I simply obtained the shapes of both arrays, size difference and finally account the number of missing elements at both ends.
Here is what I got:</p>

```<code>mask_in = np.random.randint(2, size = (2, 8))
mask_ot = np.random.randint(2, size = (6, 16))
mask_in_amp = mask_in

dif_row = mask_ot.shape[0]-mask_in_amp.shape[0]
dif_col = mask_ot.shape[1]-mask_in_amp.shape[1]

complete_row = dif_row / 2
complete_col = dif_col / 2

mask_in_amp = np.vstack((mask_in_amp, np.zeros((complete_row, mask_in_amp.shape[1]))))
mask_in_amp = np.vstack((np.zeros((complete_row, mask_in_amp.data.shape[1])), mask_in_amp))

mask_in_amp = np.hstack((mask_in_amp, np.zeros((mask_in_amp.shape[0],complete_col))))
mask_in_amp = np.hstack((np.zeros((mask_in_amp.shape[0],complete_col)), mask_in_amp))
</code>```

Body:
I am comparing 2 numpy arrays, and want to add them together. but, before doing so, i need to make sure they are the same size. If the size are not same, then take the smaller sized one and fill the last rows with zero to match the shape.
Both array have 16 columns and N rows. I am assuming it should be pretty straight forward, but I can't get my head around it. So far I am able to compare the 2 array shape.

import csv
import numpy as np
import sys
data = np.genfromtxt('./test1.csv', dtype=float, delimiter=',')
data_sys = np.genfromtxt('./test2.csv', dtype=float, delimiter=',')
print data.shape
print data_sys.shape
if data.shape != data_sys.shape:
        print "we have an error"

This is the output I got:

=============New file.csv============
(603, 16)
(604, 16)
we have an error

I want the fill the last row of "data" array with 0 so that I can add the 2 arrays.
Thanks for your help.

Body:
I had a similar situation. Two arrays of sizes mask_in:(n1,m1) and mask_ot:(n2,m2)that were generated through a mask of a 2D image of size (N,M) where A2 is larger than A1 and both share a common center (X0,Y0). I followed the approach suggested by @AniaG using vstack and hstack. I simply obtained the shapes of both arrays, size difference and finally account the number of missing elements at both ends.
Here is what I got:

mask_in = np.random.randint(2, size = (2, 8))
mask_ot = np.random.randint(2, size = (6, 16))
mask_in_amp = mask_in

dif_row = mask_ot.shape[0]-mask_in_amp.shape[0]
dif_col = mask_ot.shape[1]-mask_in_amp.shape[1]

complete_row = dif_row / 2
complete_col = dif_col / 2

mask_in_amp = np.vstack((mask_in_amp, np.zeros((complete_row, mask_in_amp.shape[1]))))
mask_in_amp = np.vstack((np.zeros((complete_row, mask_in_amp.data.shape[1])), mask_in_amp))

mask_in_amp = np.hstack((mask_in_amp, np.zeros((mask_in_amp.shape[0],complete_col))))
mask_in_amp = np.hstack((np.zeros((mask_in_amp.shape[0],complete_col)), mask_in_amp))


问:
jQuery: Convert every four LI into one
I'm working on a slider, where I want to convert every four LI into one LI.

The slider shows a LI with four elements at the time. I want the content to be SPANs contained in a LI.

From: (one SPAN per LI)

```<code><li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
<li><span>#Content</span></li>
</code>```

...into:  (four SPAN per LI)

```<code><li><span>#Content</span><span>#Content</span><span>#Content</span><span>#Content</span></li>
<li><span>#Content</span><span>#Content</span></li>
</code>```

I can't seem to find any information on the Internet, about this technique. What should I do?

Does it make any sense? Sorry about my poor English...

答: Fetch content of 4 li and concatinate content into single li Try to use create_html.js (plugin) to create li efficiently</p>

ContentLicense: CC BY-SA 2.5

Title: jQuery: Convert every four LI into one

Body:
I'm working on a slider, where I want to convert every four LI into one LI.

The slider shows a LI with four elements at the time. I want the content to be SPANs contained in a LI.

From: (one SPAN per LI)

#Content

#Content

#Content

#Content

#Content

#Content

...into:  (four SPAN per LI)

#Content#Content#Content#Content

#Content#Content

I can't seem to find any information on the Internet, about this technique. What should I do?

Does it make any sense? Sorry about my poor English...


问:
Parse pnputil output to published name for specific class
In PowerShell, after I type "pnputil.exe -e", I get a list of driver info as below. I need to get class monitor's published name from the list and store "oem8.inf" into $monitor_name. Which command can I use to search for class = monitor and extract it's published name to a variable. Because the attribute "published name" has space, so I have no idea how to make this work.

```<code>Published name :            oem8.inf
Driver package provider :   HP
Class :                     Monitors
Driver date and version :   07/25/2013 2.2.0.0
Signer name :               Microsoft Windows Hardware Compatibility Publisher

Published name :            oem6.inf
Driver package provider :   Canon
Class :                     Printers
Driver date and version :   06/21/2006 6.1.7600.16385
Signer name :               Microsoft Windows

Published name :            oem1.inf
Driver package provider :   Microsoft
Class :                     Printers
Driver date and version :   06/21/2006 10.0.14393.0
Signer name :               Microsoft Windows
</code>```

答:
colsw's helpful answer is the way to go and his approach illustrates an important point:

If you perform your task via PowerShell cmdlets such as Get-CimInstance (which supersedes the obsolete Get-WmiObject), there is no need for string manipulation in order to extract information - PowerShell's object-oriented nature allows for solutions that are both more robust and more convenient compared to traditional output-text-parsing techniques.

That said, if needed, PowerShell has powerful string parsing features too:

```<code>$monitor_name = pnputil.exe -e |
                Select-String -Context 2 'Class :\s+ Monitors' |
                ForEach-Object { ($_.Context.PreContext[0] -split ' : +')[1] }
</code>```

With your sample input, this yields:

oem8.inf
```

Body:
In PowerShell, after I type "pnputil.exe -e", I get a list of driver info as below. I need to get class monitor's published name from the list and store "oem8.inf" into $monitor_name. Which command can I use to search for class = monitor and extract it's published name to a variable. Because the attribute "published name" has space, so I have no idea how to make this work.

Published name :            oem8.inf
Driver package provider :   HP
Class :                     Monitors
Driver date and version :   07/25/2013 2.2.0.0
Signer name :               Microsoft Windows Hardware Compatibility Publisher

Published name :            oem6.inf
Driver package provider :   Canon
Class :                     Printers
Driver date and version :   06/21/2006 6.1.7600.16385
Signer name :               Microsoft Windows

Published name :            oem1.inf
Driver package provider :   Microsoft
Class :                     Printers
Driver date and version :   06/21/2006 10.0.14393.0
Signer name :               Microsoft Windows

Body:
colsw's helpful answer is the way to go and his approach illustrates an important point:

If you perform your task via PowerShell cmdlets such as Get-CimInstance (which supersedes the obsolete Get-WmiObject), there is no need for string manipulation in order to extract information - PowerShell's object-oriented nature allows for solutions that are both more robust and more convenient compared to traditional output-text-parsing techniques.

That said, if needed, PowerShell has powerful string parsing features too:

$monitor_name = pnputil.exe -e |
                Select-String -Context 2 'Class :\s+ Monitors' |
                ForEach-Object { ($_.Context.PreContext[0] -split ' : +')[1] }

With your sample input, this yields:

oem8.inf


问:
Extract Data from ROSbag
I'm pretty new to python and just need to be able to extract raw data messages from a rosbag so that I can manipulate it with algorithms to look for patterns in LiDAR data.

I found  a script on github to extract data from a rosbag but get this error (running from terminal in Ubuntu 16.04):

```<code>adam@manatee:~/workspace/TORC/LiDAR$ python ExtractDataROSbag.py 2017-02-27-09-35-59_0.bag
[OK] Found bag: 2017-02-27-09-35-59_0.bag
Traceback (most recent call last):
  File "ExtractDataROSbag.py", line 130, in <module>
    run()
  File "ExtractDataROSbag.py", line 40, in run
    bag = rosbag.Bag(inputFileName)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 173, in __init__
    self._open(f, mode, allow_unindexed)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 1096, in _open
    if   mode == 'r': self._open_read(f, allow_unindexed)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 1118, in _open_read
    self._file     = open(f, 'rb')
IOError: [Errno 2] No such file or directory: '2017-02-27-09-35-59_0.bag'
</code>```

It seem to iterate through the beginning of the code and recognizes the bag file, printing "Found Bag" and even setting the variables after that, but then the error begins.

The full code of the script I am running is as follows:

```<code>#!/usr/bin/python

# Copyright 2010 Ankur Sinha
# Author: Ankur Sinha
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# File : extractRawInfo.py
#

import rosbag
import sys
import os
import pickle

# Global variable for input file name

def run():
    """
    Main run method. Calls other helper methods to get work done
    """

    if len(sys.argv) != 2:
        sys.stderr.write('[ERROR] This script only takes input bag file as argument.n')
    else:
        inputFileName = sys.argv[1]
        print "[OK] Found bag: %s" % inputFileName

        bag = rosbag.Bag(inputFileName)
        topicList = readBagTopicList(bag)

        while True:
            if len(topicList) == 0:
                print "No topics in list. Exiting"
                break
            selection  = menu(topicList)

            if selection == -92:
                print "[OK] Printing them all"
                for topic in topicList:
                    extract_data(bag, topic, inputFileName)
                break
            elif selection == -45:
                break
            else:
                topic = topicList[selection]
                extract_data(bag, topic, inputFileName)
                topicList.remove(topicList[selection])

        bag.close()

def extract_data (bag, topic, inputFileName):
    """
    Spew messages to a file

    args:
        topic -> topic to extract and print to txt file
    """

    outputFileName = os.path.splitext(os.path.split(inputFileName)[1])[0] + topic.replace("/","-") + ".txt"
    print "[OK] Printing %s" % topic
    print "[OK] Output file will be called %s." % outputFileName

    outputFh = open(outputFileName, "w")

    for topic, msg, t in bag.read_messages(topics=topic):
        pickle.dump(msg,outputFh)

    outputFh.close()
    print "[OK] DONE"

def menu (topicList):
    """
    Print the user menu and take input

    args:
        topicList: tuple containing list of topics

    returns:
        selection: user selection as integer
    """

    i = 0
    for topic in topicList:
        print '[{0}] {1}'.format(i, topic)
        i = i+1
    if len(topicList) > 1:
        print '[{0}] Extract all'.format(len(topicList))
        print '[{0}] Exit'.format(len(topicList) + 1)
    else:
        print '[{0}] Exit'.format(len(topicList))

    while True:
        print 'Enter a topic number to extract raw data from:'
        selection = raw_input('>>>')
        if int(selection) == len(topicList):
            return -92 # print all
        elif int(selection) == (len(topicList) +1):
            return -45 # exit
        elif (int(selection) < len(topicList)) and (int(selection) >= 0):
            return int(selection)
        else:
            print "[ERROR] Invalid input"

def readBagTopicList(bag):
    """
    Read and save the initial topic list from bag
    """
    print "[OK] Reading topics in this bag. Can take a while.."
    topicList = []
    for topic, msg, t in bag.read_messages():
        if topicList.count(topic) == 0:
            topicList.append (topic)

    print '{0} topics found:'.format(len(topicList))
    return topicList

if __name__ == "__main__":
    run()
</code>```

答:
Ensure that the named file really does exist. Copy the filename out of the error message and ask your system to find it. Don't retype the name, because if you introduced an error the first time, you may do it again.

If the file really is there, try providing the full path to the .bag file on the command line.

Title: Extract Data from ROSbag

Body:
I'm pretty new to python and just need to be able to extract raw data messages from a rosbag so that I can manipulate it with algorithms to look for patterns in LiDAR data.

I found  a script on github to extract data from a rosbag but get this error (running from terminal in Ubuntu 16.04):

adam@manatee:~/workspace/TORC/LiDAR$ python ExtractDataROSbag.py 2017-02-27-09-35-59_0.bag
[OK] Found bag: 2017-02-27-09-35-59_0.bag
Traceback (most recent call last):
  File "ExtractDataROSbag.py", line 130, in <module>
    run()
  File "ExtractDataROSbag.py", line 40, in run
    bag = rosbag.Bag(inputFileName)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 173, in __init__
    self._open(f, mode, allow_unindexed)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 1096, in _open
    if   mode == 'r': self._open_read(f, allow_unindexed)
  File "/opt/ros/kinetic/lib/python2.7/dist-packages/rosbag/bag.py", line 1118, in _open_read
    self._file     = open(f, 'rb')
IOError: [Errno 2] No such file or directory: '2017-02-27-09-35-59_0.bag'

It seem to iterate through the beginning of the code and recognizes the bag file, printing "Found Bag" and even setting the variables after that, but then the error begins.

The full code of the script I am running is as follows:

#!/usr/bin/python

# Copyright 2010 Ankur Sinha
# Author: Ankur Sinha
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# File : extractRawInfo.py
#

import rosbag
import sys
import os
import pickle

# Global variable for input file name

def run():
    """
    Main run method. Calls other helper methods to get work done
    """

    if len(sys.argv) != 2:
        sys.stderr.write('[ERROR] This script only takes input bag file as argument.n')
    else:
        inputFileName = sys.argv[1]
        print "[OK] Found bag: %s" % inputFileName

        bag = rosbag.Bag(inputFileName)
        topicList = readBagTopicList(bag)

        while True:
            if len(topicList) == 0:
                print "No topics in list. Exiting"
                break
            selection  = menu(topicList)

            if selection == -92:
                print "[OK] Printing them all"
                for topic in topicList:
                    extract_data(bag, topic, inputFileName)
                break
            elif selection == -45:
                break
            else:
                topic = topicList[selection]
                extract_data(bag, topic, inputFileName)
                topicList.remove(topicList[selection])

        bag.close()

def extract_data (bag, topic, inputFileName):
    """
    Spew messages to a file

    args:
        topic -> topic to extract and print to txt file
    """

    outputFileName = os.path.splitext(os.path.split(inputFileName)[1])[0] + topic.replace("/","-") + ".txt"
    print "[OK] Printing %s" % topic
    print "[OK] Output file will be called %s." % outputFileName

    outputFh = open(outputFileName, "w")

    for topic, msg, t in bag.read_messages(topics=topic):
        pickle.dump(msg,outputFh)

    outputFh.close()
    print "[OK] DONE"

def menu (topicList):
    """
    Print the user menu and take input

    args:
        topicList: tuple containing list of topics

    returns:
        selection: user selection as integer
    """

    i = 0
    for topic in topicList:
        print '[{0}] {1}'.format(i, topic)
        i = i+1
    if len(topicList) > 1:
        print '[{0}] Extract all'.format(len(topicList))
        print '[{0}] Exit'.format(len(topicList) + 1)
    else:
        print '[{0}] Exit'.format(len(topicList))

    while True:
        print 'Enter a topic number to extract raw data from:'
        selection = raw_input('>>>')
        if int(selection) == len(topicList):
            return -92 # print all
        elif int(selection) == (len(topicList) +1):
            return -45 # exit
        elif (int(selection) < len(topicList)) and (int(selection) >= 0):
            return int(selection)
        else:
            print "[ERROR] Invalid input"

def readBagTopicList(bag):
    """
    Read and save the initial topic list from bag
    """
    print "[OK] Reading topics in this bag. Can take a while.."
    topicList = []
    for topic, msg, t in bag.read_messages():
        if topicList.count(topic) == 0:
            topicList.append (topic)

    print '{0} topics found:'.format(len(topicList))
    return topicList

if __name__ == "__main__":
    run()


问:
Angular2: Routing restrict child not working
My application has two main areas - one free and one private. Each one needs to have its own navbar and content. Because of that, I have a router outlet where I want both areas be rendered, one at a time - free area for any user and private area for logged in users.

app.component.html

```<code><router-outlet></router-outlet>
</code>```

The FreeAreaComponent and RestrictAreaComponent, as said before, has its own navbar and content. Thinking on reusability of code, I keep the navbar and routes only the content as a child router outlet, like bellow:

FreeAreaComponent

```<code><app-free-navbar></app-free-navbar>
<router-outlet></router-outlet>
</code>```

RestrictAreaComponent

```<code><app-restrict-navbar></app-restrict-navbar>
<router-outlet></router-outlet>
</code>```

On the free area, the default component that needs to be called is LandingComponent, that is my landing "page" (quotation because we know it is a SPA).

On the restrict area, the default one is WelcomeComponent, that is just a welcome "page" (quotation because we know it is a SPA).

Because of the behavior described above, the routing rules are like bellow:

app-routing.module.ts

```<code>const appRoutes: Routes =[
{ path: '', component: FreeAreaComponent, children: [
  { path: '', component: LandingComponent, pathMatch: 'full' },
  { path: 'signup', component: SignupComponent },
  { path: 'signin', component: SigninComponent }
]},
{ path: 'restrict', canActivateChild: [AuthGuard], component: RestrictAreaComponent, children: [
  { path: 'restrict', component: WelcomeComponent },
  { path: 'categories', component: CategoriesComponent }
]},
{ path: '**', redirectTo: '', pathMatch: 'full'}];
</code>```

When I try to reach the application, the free area (landing page) works fine, but it is not with the restrict area. The restrict navbar is rendered, but the content is not.

Some certainties I have:

The RestrictAreaComponent is reached, because I put a console.log
inside its ngOnInit and it was logged and the restrict navbar is rendered

The canActivateChild rule is
returning positive, I mean, it recognizes that the user is logged in.

The WelcomeComponent is not being trigged. I put a console.log on its ngOnInit and nothing was logged at console.

If repeating the path of a route in its child is not a problem, why is this happening?

答:
You realize that the 2 childrens of restricted can be reached by the following paths:

```<code>root/restrict/restrict -> WelcomeComponent (injected into router outlet in RestrictAreaComponent)
root/resitrct/categories -> CategoriesComponent (injected into router outlet in RestrictAreaComponent)
</code>```

If you are just navigating to root/restricted, you will not get any content injected in the router outlet inside of the RestrictAreaComponent.

If you want the WelcomeComponent to be injected on navigation to root/restricted, then u need to change the routing definiton.

UPDATE:
By changing to:

```<code>const appRoutes: Routes =[
{ path: '', component: FreeAreaComponent, children: [
  { path: '', component: LandingComponent, pathMatch: 'full' },
  { path: 'signup', component: SignupComponent },
  { path: 'signin', component: SigninComponent }
]},
{ path: 'restrict', canActivateChild: [AuthGuard], component: RestrictAreaComponent, children: [
  { path: '', component: WelcomeComponent, pathMatch: 'full' },
  { path: 'categories', component: CategoriesComponent }
]},
{ path: '**', redirectTo: '', pathMatch: 'full'}];
</code>```

You should now be able to navigate in the following way:

```<code>root/restrict -> WelcomeComponent (injected into router outlet in RestrictAreaComponent)
root/restrict/categories -> CategoriesComponent (injected into router outlet in RestrictAreaComponent)
</code>```

Hope it helps

Body:
My application has two main areas - one free and one private. Each one needs to have its own navbar and content. Because of that, I have a router outlet where I want both areas be rendered, one at a time - free area for any user and private area for logged in users.

app.component.html

<router-outlet></router-outlet>

The FreeAreaComponent and RestrictAreaComponent, as said before, has its own navbar and content. Thinking on reusability of code, I keep the navbar and routes only the content as a child router outlet, like bellow:

FreeAreaComponent

<app-free-navbar></app-free-navbar>
<router-outlet></router-outlet>

RestrictAreaComponent

<app-restrict-navbar></app-restrict-navbar>
<router-outlet></router-outlet>

On the free area, the default component that needs to be called is LandingComponent, that is my landing "page" (quotation because we know it is a SPA).

On the restrict area, the default one is WelcomeComponent, that is just a welcome "page" (quotation because we know it is a SPA).

Because of the behavior described above, the routing rules are like bellow:

app-routing.module.ts

const appRoutes: Routes =[
{ path: '', component: FreeAreaComponent, children: [
  { path: '', component: LandingComponent, pathMatch: 'full' },
  { path: 'signup', component: SignupComponent },
  { path: 'signin', component: SigninComponent }
]},
{ path: 'restrict', canActivateChild: [AuthGuard], component: RestrictAreaComponent, children: [
  { path: 'restrict', component: WelcomeComponent },
  { path: 'categories', component: CategoriesComponent }
]},
{ path: '**', redirectTo: '', pathMatch: 'full'}];

When I try to reach the application, the free area (landing page) works fine, but it is not with the restrict area. The restrict navbar is rendered, but the content is not.

Some certainties I have:

The RestrictAreaComponent is reached, because I put a console.log
inside its ngOnInit and it was logged and the restrict navbar is rendered

The canActivateChild rule is
returning positive, I mean, it recognizes that the user is logged in.

The WelcomeComponent is not being trigged. I put a console.log on its ngOnInit and nothing was logged at console.

If repeating the path of a route in its child is not a problem, why is this happening?

Body:
You realize that the 2 childrens of restricted can be reached by the following paths:

root/restrict/restrict -> WelcomeComponent (injected into router outlet in RestrictAreaComponent)
root/resitrct/categories -> CategoriesComponent (injected into router outlet in RestrictAreaComponent)

If you are just navigating to root/restricted, you will not get any content injected in the router outlet inside of the RestrictAreaComponent.

If you want the WelcomeComponent to be injected on navigation to root/restricted, then u need to change the routing definiton.

UPDATE:
By changing to:

const appRoutes: Routes =[
{ path: '', component: FreeAreaComponent, children: [
  { path: '', component: LandingComponent, pathMatch: 'full' },
  { path: 'signup', component: SignupComponent },
  { path: 'signin', component: SigninComponent }
]},
{ path: 'restrict', canActivateChild: [AuthGuard], component: RestrictAreaComponent, children: [
  { path: '', component: WelcomeComponent, pathMatch: 'full' },
  { path: 'categories', component: CategoriesComponent }
]},
{ path: '**', redirectTo: '', pathMatch: 'full'}];

You should now be able to navigate in the following way:

root/restrict -> WelcomeComponent (injected into router outlet in RestrictAreaComponent)
root/restrict/categories -> CategoriesComponent (injected into router outlet in RestrictAreaComponent)

Hope it helps


问:
Idling thread between curl_multi_perform
I have an update thread which runs curl_multi_perform in a while loop in it. I want to make sure the thread doesn't just sit there and spin, so I'd like to throttle it to a few updates per second. This works fine, except for when doing file uploads or downloads on 10+ MB files, when curl_multi_perform has to be called pretty much continuously to get around the upload/download chunk limit.

Is there a way to poll if curl_multi_perform will need to be called right away again in the next update loop, or if it's okay to let the thread idle for ~100 ms? I thought curl_multi_wait would be used for this, but the thread seems to be spinning up the CPU while inside curl_multi_wait anyway, so that doesn't seem right.

答:
So for future reference, what I ended up doing was just idling the thread 10ms every iteration. This effectively caps the up speed to 1.6 mbps when using the default value for CURL_MAX_WRITE_SIZE in curl.h. For faster speeds I guess I'd have to either up the CURL_MAX_WRITE_SIZE define, or idle the thread for a shorter time.

Rough pseudocode:

```<code>while(runUpdateThread)
{
    curl_multi_perform(mCurlHandle, &handleCount);

    /* handle call results */

    std::this_thread::sleep_for( std::chrono::milliseconds(10) );
}
</code>```

Body:
So for future reference, what I ended up doing was just idling the thread 10ms every iteration. This effectively caps the up speed to 1.6 mbps when using the default value for CURL_MAX_WRITE_SIZE in curl.h. For faster speeds I guess I'd have to either up the CURL_MAX_WRITE_SIZE define, or idle the thread for a shorter time.

Rough pseudocode:

while(runUpdateThread)
{
    curl_multi_perform(mCurlHandle, &handleCount);

    /* handle call results */

    std::this_thread::sleep_for( std::chrono::milliseconds(10) );
}


问:
Ideas for a 2D game for a neural network to play
I am currently trying to implement my own neural-network library, and I would like to test it by letting it (and networks made with other librarys) play a 2D game. The problem is I can't really find a good game for a neural network to play.

Requirements for the game:

It should not involve skills like reaction time, precision. It should instead require some tactical skills.

It should be easily scorable, in order to create an efficient evolutional algorithm.

It should be relatively simple.

It does not have to be a game that already exists, you can come up with one if you have an idea.

It may be a single-player game (like mario) or a 1v1 game (like pong).

It must not be any kind of MMO, RPG etc. I am looking for a small kind of mini-game.

The game should be well playable by a neural network. This means it should have a fixed amount of inputs somehow normalizable between 0 and 1. Inputs can be sensors, angles to closest objects etc. inputs should NOT be the pixels of the screen because 3*1920*1080 is just too much. Up to about 100 inputs are manageable (because I am a beginner and can't afford to let my computer calculate for hours just to get one generation evolved or so).
Also the game should definitely be a 2D game since i am going to use a AWT JPanel to draw on.

答:
I'm the main developer of Neataptic.js, basically a neural network library with neuro-evolution built in to it. Just to give you some ideas, you might want to look at my following articles:

Agar.io AI

Target-seeking AI

Some other suggestions:

Snake

Flappy bird

Bomberman

Neural networks have been tested on most simple 2D games, so if you're stuck you will always find code that might help you.


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
Ignoring warnings is definitely an antipattern; so yes, it's an anti-pattern (and I can guarantee that if you learn to suppress warnings, one of them will come back and bite you in the posterior, if not worse).

Also, while the second version is more verbose, it gives the uninitialized variable a known state (or can be used to handle the problem, if the variable is supposed to be filled).

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.


问:
How to Dict.get a case insensitive key?
I'd like to grab the Total-Records key of a response.headers HTTP response.

Problem is that in some browser it is as returned by the server Total-Records but in some other, it is in lower case.

I'd like to get the value of the Total-Records header regardless of its case.
How would you do that?

答:
Yet another alternative is to use the find function from elm-community/dict-extra to provide a custom comparison operator:

import Dict.Extra

caseInsensitiveGet : String -> Dict String v -> Maybe v
caseInsensitiveGet key =
    let
        lowerKey = String.toLower key
    in
        Dict.Extra.find (\k _ -> String.toLower k == lowerKey)
            >> Maybe.map Tuple.second
```

Title: How to Dict.get a case insensitive key?


问:
What is the difference between steps and epochs in TensorFlow?
In most of the models, there is a steps parameter indicating the number of steps to run over data. But yet I see in most practical usage, we also execute the fit function N epochs.

What is the difference between running 1000 steps with 1 epoch and running 100 steps with 10 epoch? Which one is better in practice? Any logic changes between consecutive epochs? Data shuffling?

答:
A training step is one gradient update. In one step batch_size examples are processed.

An epoch consists of one full cycle through the training data. This is usually many steps. As an example, if you have 2,000 images and use a batch size of 10 an epoch consists of:

```<code>2,000 images / (10 images / step) = 200 steps.
</code>```

If you choose your training image randomly (and independently) in each step, you normally do not call it epoch. [This is where my answer differs from the previous one. Also see my comment.]

Body:
A training step is one gradient update. In one step batch_size examples are processed.

An epoch consists of one full cycle through the training data. This is usually many steps. As an example, if you have 2,000 images and use a batch size of 10 an epoch consists of:

2,000 images / (10 images / step) = 200 steps.

If you choose your training image randomly (and independently) in each step, you normally do not call it epoch. [This is where my answer differs from the previous one. Also see my comment.]


问:
How to get local file system path in azure websites
I have a file hosted on the disk along with my website that I want to read .Not sure how do I access the file when I use System.Environment.CurrentDirectory it point to a D drive location .Can someone please tell me how can I get to my file stored at the root of where my site is hosted.

Thanks

答:
This works for me in both localhost and azure:

```<code>Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "file_at_root.txt");
</code>```

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath is the full local path to your site's root.

Body:
This works for me in both localhost and azure:

Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "file_at_root.txt");

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath is the full local path to your site's root.


问:
multiple processes to update to the correct grid location
I am trying to create three processes that will each eventually pull from a text file and do more complex calculations, but at the moment I am just experimenting with tkinter and multiprocessing. I want each of the three labels(lbl1,lbl2,lbl3) to add 1,2,or 3 to their label and return that value. I am new to pipeing and events and dont understand the way to return the values to the synchronize the values so that they return to the correct places, so the output is random in accordance to the position in the grid. How can I make it so that anything I return only returns to the correct position in the grid which I have already specified?</p>

```<code>import matplotlib.pyplot as plt
import  socket, time, datetime, sys, struct
from datetime import datetime
import numpy as np
import shutil
import os
from random import randint
import Tkinter as tk
from multiprocessing import *
#from Tkinter import *

def count1(pipe,stop):
    x = 0
    while not stop.is_set():
        x+=1
        pipe.send(x)
        time.sleep(1)
def count2(pipe,stop):
    y = 0
    while not stop.is_set():
        y+=2
        pipe.send(y)
        time.sleep(1)
def count3(pipe,stop):
    z = 0
    while not stop.is_set():
        z+=3
        pipe.send(z)
        time.sleep(1)

class UpdatingGUI(tk.Frame):
    def __init__(self,parent):
        tk.Frame.__init__(self,parent)
        self.parent = parent
        self.parent_pipe, self.child_pipe = Pipe()

        self.stop_event = Event()

        self.num1=tk.Label(self, text="Number 1")
        self.num1.grid(row=0, column=0)
        self.num2=tk.Label(self, text="Number 2")
        self.num2.grid(row=0, column=1)
        self.num3=tk.Label(self, text="Number 3")
        self.num3.grid(row=0, column=2)

        # label to show count value
        self.updating_int1 = tk.IntVar()
        self.updating_int1.set(0)
        self.updating_lbl1 = tk.Label(self,textvariable=self.updating_int1)
        self.updating_lbl1.grid(row=1, column=0)

        self.updating_int2 = tk.IntVar()
        self.updating_int2.set(0)
        self.updating_lbl2 = tk.Label(self,textvariable=self.updating_int2)
        self.updating_lbl2.grid(row=1, column=1)

        self.updating_int3 = tk.IntVar()
        self.updating_int3.set(0)
        self.updating_lbl3 = tk.Label(self,textvariable=self.updating_int3)
        self.updating_lbl3.grid(row=1, column=2)

        # launch count as a process
        self.counter1 = Process(target=count1,args=(self.child_pipe,self.stop_event))
        self.counter1.start()
        self.update()

        self.counter2 = Process(target=count2,args=(self.child_pipe,self.stop_event))
        self.counter2.start()
        self.update()

        self.counter3 = Process(target=count3,args=(self.child_pipe,self.stop_event))
        self.counter3.start()
        self.update()

    def update(self):
    # While the pipe has data, read and update the StringVar
        while self.parent_pipe.poll():
            self.updating_int1.set(self.parent_pipe.recv())
            self.updating_int2.set(self.parent_pipe.recv())
            self.updating_int3.set(self.parent_pipe.recv())

        self.parent.after(1000,self.update)

def main():
    root = tk.Tk()
    root.geometry("400x200")
    gui = UpdatingGUI(root)
    gui.pack()
    root.mainloop()

if __name__ == "__main__":
    main()
</code>```

答:
Question: ... anything I return only returns to the correct position

Generalize your def count (..., to do so add a position Parameter.
For instance:

```<code>def count(position, pipe, stop):
    x = 0
    while not stop.is_set():
        x += 1
        pipe.send((position, x))
        time.sleep(1)

def update(self):
    # While the pipe has data, read and update the StringVar
    while self.parent_pipe.poll():
        position, data = self.parent_pipe.recv()
        if position == 1:
            self.updating_int1.set(data)
        elif position == 2:
            # and so on
</code>```

Body:
I am trying to create three processes that will each eventually pull from a text file and do more complex calculations, but at the moment I am just experimenting with tkinter and multiprocessing. I want each of the three labels(lbl1,lbl2,lbl3) to add 1,2,or 3 to their label and return that value. I am new to pipeing and events and dont understand the way to return the values to the synchronize the values so that they return to the correct places, so the output is random in accordance to the position in the grid. How can I make it so that anything I return only returns to the correct position in the grid which I have already specified?

import matplotlib.pyplot as plt
import  socket, time, datetime, sys, struct
from datetime import datetime
import numpy as np
import shutil
import os
from random import randint
import Tkinter as tk
from multiprocessing import *
#from Tkinter import *

def count1(pipe,stop):
    x = 0
    while not stop.is_set():
        x+=1
        pipe.send(x)
        time.sleep(1)
def count2(pipe,stop):
    y = 0
    while not stop.is_set():
        y+=2
        pipe.send(y)
        time.sleep(1)
def count3(pipe,stop):
    z = 0
    while not stop.is_set():
        z+=3
        pipe.send(z)
        time.sleep(1)

class UpdatingGUI(tk.Frame):
    def __init__(self,parent):
        tk.Frame.__init__(self,parent)
        self.parent = parent
        self.parent_pipe, self.child_pipe = Pipe()

        self.stop_event = Event()

        self.num1=tk.Label(self, text="Number 1")
        self.num1.grid(row=0, column=0)
        self.num2=tk.Label(self, text="Number 2")
        self.num2.grid(row=0, column=1)
        self.num3=tk.Label(self, text="Number 3")
        self.num3.grid(row=0, column=2)

        # label to show count value
        self.updating_int1 = tk.IntVar()
        self.updating_int1.set(0)
        self.updating_lbl1 = tk.Label(self,textvariable=self.updating_int1)
        self.updating_lbl1.grid(row=1, column=0)

        self.updating_int2 = tk.IntVar()
        self.updating_int2.set(0)
        self.updating_lbl2 = tk.Label(self,textvariable=self.updating_int2)
        self.updating_lbl2.grid(row=1, column=1)

        self.updating_int3 = tk.IntVar()
        self.updating_int3.set(0)
        self.updating_lbl3 = tk.Label(self,textvariable=self.updating_int3)
        self.updating_lbl3.grid(row=1, column=2)

        # launch count as a process
        self.counter1 = Process(target=count1,args=(self.child_pipe,self.stop_event))
        self.counter1.start()
        self.update()

        self.counter2 = Process(target=count2,args=(self.child_pipe,self.stop_event))
        self.counter2.start()
        self.update()

        self.counter3 = Process(target=count3,args=(self.child_pipe,self.stop_event))
        self.counter3.start()
        self.update()

    def update(self):
    # While the pipe has data, read and update the StringVar
        while self.parent_pipe.poll():
            self.updating_int1.set(self.parent_pipe.recv())
            self.updating_int2.set(self.parent_pipe.recv())
            self.updating_int3.set(self.parent_pipe.recv())

        self.parent.after(1000,self.update)

def main():
    root = tk.Tk()
    root.geometry("400x200")
    gui = UpdatingGUI(root)
    gui.pack()
    root.mainloop()

if __name__ == "__main__":
    main()

Body:
Question: ... anything I return only returns to the correct position

Generalize your def count (..., to do so add a position Parameter.
For instance:

def count(position, pipe, stop):
    x = 0
    while not stop.is_set():
        x += 1
        pipe.send((position, x))
        time.sleep(1)

def update(self):
    # While the pipe has data, read and update the StringVar
    while self.parent_pipe.poll():
        position, data = self.parent_pipe.recv()
        if position == 1:
            self.updating_int1.set(data)
        elif position == 2:
            # and so on


问:
os.path.join() gives InMemoryUploadFile error
I have written a POST api which posts a file. I want to open the file and parse a JSON content in the file. But the line os.path.join() doesnt seem to work. I am getting "'InMemoryUploadedFile' object has no attribute 'startswith'" exception. Have included the code used below.

```<code>def schedule_load(file_name):
    print file_name
    file_json = default_storage.open(os.path.join("schedule_files", file_name), 'r')
    var = file_json.read()
    print var
    file_json.close()
    schedule = json.loads(var)
</code>```

My POST method :

```<code>@api_view(['POST'])
def post_schedule(request):
print "post_schedule"
if request.method == 'POST':
    print "if POST"
    form = ScheduleForm(request.POST, request.FILES)
    file_name = form['schedule_file'].value()

    if form.is_valid():
        print "is_valid"
        form.save()
        schedule_load(file_name)
        return JsonResponse({"status": "success"}, status=status.HTTP_200_OK)
    else:
        return JsonResponse({"status": "Invalid file"}, status=status.HTTP_200_OK)
</code>```

答:
Because what you are dealing with is a InMemoryUploadedFile rather than a file name. Your code should change as

```<code>def schedule_load(file_name):
    var = file_name.read()
    print var
</code>```

Body:
I have written a POST api which posts a file. I want to open the file and parse a JSON content in the file. But the line os.path.join() doesnt seem to work. I am getting "'InMemoryUploadedFile' object has no attribute 'startswith'" exception. Have included the code used below.

def schedule_load(file_name):
    print file_name
    file_json = default_storage.open(os.path.join("schedule_files", file_name), 'r')
    var = file_json.read()
    print var
    file_json.close()
    schedule = json.loads(var)

My POST method :

@api_view(['POST'])
def post_schedule(request):
print "post_schedule"
if request.method == 'POST':
    print "if POST"
    form = ScheduleForm(request.POST, request.FILES)
    file_name = form['schedule_file'].value()

    if form.is_valid():
        print "is_valid"
        form.save()
        schedule_load(file_name)
        return JsonResponse({"status": "success"}, status=status.HTTP_200_OK)
    else:
        return JsonResponse({"status": "Invalid file"}, status=status.HTTP_200_OK)

Body:
Because what you are dealing with is a InMemoryUploadedFile rather than a file name. Your code should change as

def schedule_load(file_name):
    var = file_name.read()
    print var


问:
Displaying millions of objects in JavaScript
I have somewhere between 2M and 10M static objects which I would like overlay on Google Maps. I've previously tried HeatmapLayer successfully on much smaller sets. Due to the shear volume I'm a bit concerned, and I must to lump the objects together to avoid performance problems. The target platform is Chrome on a standard desktop.

What is the best way to space partition and merge objects in close proximity? Should I try some type of loose quad tree to lump the objects together, and then display each node with its respective weight using the HeatmapLayer? Or should I try to dynamically build some type of triangle mesh where vertices can be dynamically merged and triangles gain weight as more objects are added to them and then display the triangles on top of Google Maps? HeatmapLayer is pretty fast (looks like it's implemented in GL shaders), but I doubt Polygon is.

I've tried searching for open source loose quad tree JavaScript implementations and other fast space partition JavaScript implementations but found nothing. Is my best bet to port some C++ implementation? Any answers/comments from someone who built something similar would be helpful!

答: I settled on preprocessing my data in the backend using a space partitioning implementation. I recommend it for anybody who has the luxury of doing so.</p>


问:
How do I use enums in TSQL without hard coding magic number all over my SQL scripts/procs?
We have enums in our C# code:

```<code>public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}
</code>```

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

```<code>SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)
</code>```

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

答:
You can always pass the value from the enumeration into the stored proc/command that you are trying to execute.  This way, you never have to worry about the enumerations in the database.

If you want to store the enumerations in the database, then I suggest you create a view (possibly titled with your enumeration), like so:

```<code>create view JobStatus
    select 0 as Ready, 1 as Running, 2 as Cancelling
</code>```

You can then access/join on the view if you need it to.

Note, the query optimizer treats any reference to the above as a constant scan/scalar operation, not a table scan, so you aren't incurring the reads that would occur if you were accessing an actual table.

Body:
We have enums in our C# code:

public enum JobStatus
{
  Ready = 0,
  Running = 1,
  Cancelling = 2,
}

These values are also stored in database fields, and we have lots of TSQL (mostly stored procs, as well as some batches and SSIS) that also processes the data:

SELECT TOP 1 @JobSID = JobSID
FROM Job
WHERE Status = 0 /* JobStatus.Ready */
ORDER BY SubmitDate ASC

CREATE TABLE ImportCrossEffect(
    /* lots deleted */
    Source tinyint
      DEFAULT 1 NOT NULL -- 0: Unknown (default), 1:Imported, 2:Keyed
)

How do I avoid hard coding the “magic numbers” in the TSQL?

How do I remove the risk of the enumerations not matching on the C# and TSQL sides?

(I have included the C# tag, as I would like solution that “single sourced”  the definitions of the enums on both the C# and TSQL sides)

Updates:

We don't have tables in the database with the Enum names in them, the values are just stored in tiny int columns.

I was hoping for something like a SQL pre-processor that would "expand" all the enum to there "magic value".

Body:
You can always pass the value from the enumeration into the stored proc/command that you are trying to execute.  This way, you never have to worry about the enumerations in the database.

If you want to store the enumerations in the database, then I suggest you create a view (possibly titled with your enumeration), like so:

create view JobStatus
    select 0 as Ready, 1 as Running, 2 as Cancelling

You can then access/join on the view if you need it to.

Note, the query optimizer treats any reference to the above as a constant scan/scalar operation, not a table scan, so you aren't incurring the reads that would occur if you were accessing an actual table.


问:
T-SQL - How to remove text to the left of a specific character
I have a table that returns variable string lengths in the format below:

```<code>Example Text: More example text
</code>```

How do I remove all the text before the colon and the colon to leave just the text to the right of the colon, so I have the result of:

```<code>More example text
</code>```

The text to the right can be any length.

Thanks

答:
This was the answer that worked for me. Script.Topic is the column name:</p>

```<code>SELECT RIGHT('{Script.Topic}', len('{Script.Topic}') - charindex(':', '{Script.Topic}'))
</code>```

Body:
I have a table that returns variable string lengths in the format below:

Example Text: More example text

How do I remove all the text before the colon and the colon to leave just the text to the right of the colon, so I have the result of:

More example text

The text to the right can be any length.

Thanks

Body:
This was the answer that worked for me. Script.Topic is the column name:

SELECT RIGHT('{Script.Topic}', len('{Script.Topic}') - charindex(':', '{Script.Topic}'))


问:
Why are these FactoryGirl factory instances not being created to pass this index test?
I am trying to test presence of all model objects in an index view, index renders just fine with manual in browser use, so the problem must be with with my FactoryGirl factory and or the way I'm passing arguments into the FactoryGirl.create method, though research fails to reveal to me what exactly I'm doing wrong, any ideas? Thanks

quotes.rb

```<code>FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end

    factory :quote3 do
    end
  end
end
</code>```

quotes_page_spec.rb

```<code>    require 'rails_helper'

feature 'index page' do
    let(:user) { FactoryGirl.create(:user) }
    let(:quote) { FactoryGirl.create(:quote, user: user, co_name: "Co1") }
    let(:quote2) { FactoryGirl.create(:quote, user: user, co_name: "Co2") }
    let(:quote3) { FactoryGirl.create(:quote, user: user, co_name: "Co3") }

    before do
        login_as(user, :scope => :user)
    end

    scenario 'when user view all their quotes' do
        visit("/quotes")
        expect(page).to have_content("Co1")
        expect(page).to have_content("Co2")
        expect(page).to have_content("Co3")
    end
</code>```

This is the failure message i get;

```<code> 1) index page when user view all their quotes
 Failure/Error: expect(page).to have_content("Co1")
   expected to find text "Co1" in "Toggle navigation QuoteEngine My Quotes My Account Sign out"
 # ./spec/features/quotes_page_spec.rb:15:in `block (2 levels) in <top (required)>'
</code>```

答: The issue here is that you’re using let.  let is lazily evaluated, so the object is not actually created until the first time it is referenced in the test.  Since you never reference the quote objects in your test they are never created.  To have the objects always created use let! rather than let

Body:
I am trying to test presence of all model objects in an index view, index renders just fine with manual in browser use, so the problem must be with with my FactoryGirl factory and or the way I'm passing arguments into the FactoryGirl.create method, though research fails to reveal to me what exactly I'm doing wrong, any ideas? Thanks

quotes.rb

FactoryGirl.define do
  factory :quote do
    prev_cover true
    sequence(:co_name) { |n| "Acme Co #{n}" }
    co_number 9999
    postcode "al1 1aa"
    industry :financial_services
    lives_overseas true
    scheme_start_date "2018-01-01"
    payment_frequency :monthly
    commission_level 12
    gla 1

    factory :quote2 do
    end

    factory :quote3 do
    end
  end
end

quotes_page_spec.rb

    require 'rails_helper'

feature 'index page' do
    let(:user) { FactoryGirl.create(:user) }
    let(:quote) { FactoryGirl.create(:quote, user: user, co_name: "Co1") }
    let(:quote2) { FactoryGirl.create(:quote, user: user, co_name: "Co2") }
    let(:quote3) { FactoryGirl.create(:quote, user: user, co_name: "Co3") }

    before do
        login_as(user, :scope => :user)
    end

    scenario 'when user view all their quotes' do
        visit("/quotes")
        expect(page).to have_content("Co1")
        expect(page).to have_content("Co2")
        expect(page).to have_content("Co3")
    end

This is the failure message i get;

 1) index page when user view all their quotes
 Failure/Error: expect(page).to have_content("Co1")
   expected to find text "Co1" in "Toggle navigation QuoteEngine My Quotes My Account Sign out"
 # ./spec/features/quotes_page_spec.rb:15:in `block (2 levels) in <top (required)>'


问:
R: Need to check relationship between two variables across observations
Take a data frame like mtcars (but much bigger)

I would like to get a list of observations where the value of vs==1 and the value of am != 1. I don't want to have to scroll through a long list of 1s and zeros, but actually get a list of the observations. I could write a loop but is there a more R'ish way of answering that question?

Additional information

My actual example is looking for values in first which are NA while in Grade they are not NA. And this does not seem to work. Does NA get treated special?

```<code>x = subset(spreadgrades, first == NA & Grade == NA)
</code>```

Body:
Take a data frame like mtcars (but much bigger)

I would like to get a list of observations where the value of vs==1 and the value of am != 1. I don't want to have to scroll through a long list of 1s and zeros, but actually get a list of the observations. I could write a loop but is there a more R'ish way of answering that question?

Additional information

My actual example is looking for values in first which are NA while in Grade they are not NA. And this does not seem to work. Does NA get treated special?

x = subset(spreadgrades, first == NA & Grade == NA)

Body:
Using data.table:

library(data.table)
mtcars<-data.table(mtcars)
mtcars[(vs==1 & am!=1),]

     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
1: 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
2: 18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
3: 24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
4: 22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
5: 19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
6: 17.8   6 167.6 123 3.92 3.440 18.90  1  0    4    4
7: 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1


问:
nginx file_put_contents permission denied
I have a problem.
I use this box 'rasmus/php7dev',it works,no problem,But problem so...

system use nginx as default.
When I created a directory named 'apix' via vagrantfile.
it creates 'apix directory' in /usr/share/nginx/html

```<code>sudo touch /usr/share/nginx/html/index.php
</code>```

run above code on terminal.

```<code><?php
file_put_contents('foo.php',[]);

it does not work..
Warning: file_put_contents(foo.php): failed to open stream: Permission denied in /var/www/default/apix/index.php on line 3
</code>```

to solve it
  sudo chmod -R 777 /usr/share/nginx/html/apix

but the result is false!!!!!

what can I do?

答:
If permissions on apix directory is ok, check that you try to write in apix directory. For example, put whole path - file_put_contents('/usr/share/nginx/html/apix/foo.php',[]);
May be you just write from wrong dir.</p>

Body:
I have a problem.
I use this box 'rasmus/php7dev',it works,no problem,But problem so...

system use nginx as default.
When I created a directory named 'apix' via vagrantfile.
it creates 'apix directory' in /usr/share/nginx/html

sudo touch /usr/share/nginx/html/index.php

run above code on terminal.

<?php
file_put_contents('foo.php',[]);

it does not work..
Warning: file_put_contents(foo.php): failed to open stream: Permission denied in /var/www/default/apix/index.php on line 3

to solve it
  sudo chmod -R 777 /usr/share/nginx/html/apix

but the result is false!!!!!

what can I do?