问:
Is there a way to customize the OpenFileDialog to select folders instead of a file?
I have a VB/C# .NET 2.0 project that, if possible, I would like to customize the OpenFileDialog box to select a directory rather than a file. The reason for this is because the FolderBrowserDialog is ugly and a pain for most of my users to navigate using.

I know how to filter extensions using OpenFileDialog, but is there a flag or variable I can set that will allow me to only show directories and select those directories that is built into .NET? And if not, what is a good third party dialog to use/where should I begin if I am to create my own?

I apologize, I do not have much experience creating frontends. Any help or direction on this would be greatly appreciated :)

答:
After checking the question that Mayank posted, I found out that there is no native way to do this in .NET. However, one of the posts by Scott Wisniewski yielded the exactly what I was looking for.

The only thing I had to do to make this work in .NET 2.0 was add the following code to my project in a file called ExtensionAttribute.cs. This method is not needed in .NET 3.5+, but please note that this is reported to not work at all with Visual Studio 2005.

```<code>namespace System.Runtime.CompilerServices
{
   [AttributeUsage(AttributeTargets.Method)]
   public sealed class ExtensionAttribute : Attribute
   {
      public ExtensionAttribute() { }
   }
}
</code>```

Again, this code snippet only works with Visual Studio 2008, it will not work with VS 2005.

Body:
After checking the question that Mayank posted, I found out that there is no native way to do this in .NET. However, one of the posts by Scott Wisniewski yielded the exactly what I was looking for.

The only thing I had to do to make this work in .NET 2.0 was add the following code to my project in a file called ExtensionAttribute.cs. This method is not needed in .NET 3.5+, but please note that this is reported to not work at all with Visual Studio 2005.

namespace System.Runtime.CompilerServices
{
   [AttributeUsage(AttributeTargets.Method)]
   public sealed class ExtensionAttribute : Attribute
   {
      public ExtensionAttribute() { }
   }
}

Again, this code snippet only works with Visual Studio 2008, it will not work with VS 2005.


来源: stackexchange

问:
ForEach inside API does not work properly
I am using angualr 4.

i have an array.

Here is my array;

```<code>this.bookings = [
    {
     'id':'dsjdsfhkdsjhfjkds01'
    },
    {
     'id':'dsjdsfhkdsjhfjkds01'
    }
]
</code>```

I need retrieve data from database based on id.

Here is my script.

```<code>let scope = this;
scope.bookings.forEach(function(BookingItem){
  var bId = BookingItem.id;
  console.log("BId",bId);
  scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
    var responseVal = booking;
  })
})
</code>```

I need  like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.

But i consoled value of  bId.

ForEach taken on id values one by one After retreive data from database.

How can i fix this pblm.

Kindly advice me,

Thanks.

答:
Since the api call response takes some time, you should wait for the response untill it is recieved.

You can use Observable forkJoin which works like a promise and processes all requests in loop and returns response.

```<code>import {Observable} from 'rxjs/Rx';

let observables = new Array();

this.bookings.forEach(function(booking){
    observables.push(this.Bservice.getbooking(this.at,booking.id));
})

Observable.forkJoin(observables).subscribe(
    res => console.log(res),
    error => console.log('Error: ', error)
);
</code>```

Here is a documentation for forkJoin

ContentLicense: CC BY-SA 3.0

Body:
I am using angualr 4.

i have an array.

Here is my array;

this.bookings = [
    {
     'id':'dsjdsfhkdsjhfjkds01'
    },
    {
     'id':'dsjdsfhkdsjhfjkds01'
    }
]

I need retrieve data from database based on id.

Here is my script.

let scope = this;
scope.bookings.forEach(function(BookingItem){
  var bId = BookingItem.id;
  console.log("BId",bId);
  scope.Bservice.getbooking(scope.at,bId).subscribe(booking => {
    var responseVal = booking;
  })
})

I need  like forEach Take on firstvalue then get retrive data from database.After going to second value of booking then get data from database.

But i consoled value of  bId.

ForEach taken on id values one by one After retreive data from database.

How can i fix this pblm.

Kindly advice me,

Thanks.

Body:
Since the api call response takes some time, you should wait for the response untill it is recieved.

You can use Observable forkJoin which works like a promise and processes all requests in loop and returns response.

import {Observable} from 'rxjs/Rx';

let observables = new Array();

this.bookings.forEach(function(booking){
    observables.push(this.Bservice.getbooking(this.at,booking.id));
})

Observable.forkJoin(observables).subscribe(
    res => console.log(res),
    error => console.log('Error: ', error)
);

Here is a documentation for forkJoin


问:
dynamically include a layout to another layout file inside a fragment
I have a fragment layout to which i want to add another sub layout dynamically ,

I tried this https://stackoverflow.com/a/22592269/8476022

sub-layout xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>
</code>```

this is my main layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

inside my fragment i included the sublayout

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}
</code>```

but i am getting error near addView the screenshot is below

can anyone please help to find the error

答:
You are passing the layout id only,Define a layout first like:</p>

```<code>LinearLayout sublayout = (LinearLayout)v.findViewBYId(R.layout.sub_layout)
flContainer.addView(sublayout);
</code>```

Body:
I have a fragment layout to which i want to add another sub layout dynamically ,

I tried this https://stackoverflow.com/a/22592269/8476022

sub-layout xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="Question"
    android:textColor="@color/colorTextBlack"
    android:textSize="16dp" />
</android.support.constraint.ConstraintLayout>

this is my main layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f2f2f2"
android:orientation="vertical">
<FrameLayout
    android:id="@+id/flContainer"
    android:layout_width="match_parent"
    android:layout_margin="20dp"
    android:layout_height="wrap_content"/>
</LinearLayout>

inside my fragment i included the sublayout

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_start_question, container, false);
     flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
     flContainer.addView(R.layout.sub_layout);
    return v;
}

but i am getting error near addView the screenshot is below

can anyone please help to find the error

Body:
You are passing the layout id only,Define a layout first like:

LinearLayout sublayout = (LinearLayout)v.findViewBYId(R.layout.sub_layout)
flContainer.addView(sublayout);


问:
Find correct Boost version installed and how to remove the old version
I had boost previously installed by

```<code>sudo apt-get libboost-dev
sudo apt-get libboost-all-dev
</code>```

and I think I got boost 1.58.

Then I needed the latest boost for boost_serialization, for that I tried installing boost by downloading from here, and then the following commands.

```<code>tar --bzip2 -xf boost_1_65_1.tar.bz2
./bootstrap.sh --prefix=/usr/
sudo checkinstall ./b2 install
</code>```

I checked the boost version installed by different ways.

First

```<code>std::cout << "Using Boost "
            << BOOST_VERSION / 100000     << "."  // major version
            << BOOST_VERSION / 100 % 1000 << "."  // minor version
            << BOOST_VERSION % 100                // patch level
            << std::endl;
</code>```

Which gives Using Boost 1.65.1

Second

```<code>dpkg -S /usr/include/boost/version.hpp
</code>```

Which gives libboost1.58-dev:amd64: /usr/include/boost/version.hpp

Third

```<code>cat /usr/include/boost/version.hpp | grep "BOOST_LIB_VERSION"
</code>```

which displays //  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION #define BOOST_LIB_VERSION "1_65_1"

Fourth

```<code>dpkg -s libboost-dev | grep 'Version'
</code>```

which displays Version: 1.58.0.1ubuntu1

Which is the difference? Do I have both the versions installed or only 1.65?

I tried removing 1.58 by sudo apt-get autoremove,  but I get the same information again.

I also tried removing the old by

```<code>dpkg -S /usr/include/boost/version.hpp
sudo apt-get autoremove package
</code>```

and it just display the following information

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package package
</code>```

答: Building and installing  the tarball is not going to update what apt thinks is installed, since you used /usr as your prefix it may well have overwritten the actual files but apt will still think the old version is installed.</p>

Body:
I had boost previously installed by

sudo apt-get libboost-dev
sudo apt-get libboost-all-dev

and I think I got boost 1.58.

Then I needed the latest boost for boost_serialization, for that I tried installing boost by downloading from here, and then the following commands.

tar --bzip2 -xf boost_1_65_1.tar.bz2
./bootstrap.sh --prefix=/usr/
sudo checkinstall ./b2 install

I checked the boost version installed by different ways.

First

std::cout << "Using Boost "
            << BOOST_VERSION / 100000     << "."  // major version
            << BOOST_VERSION / 100 % 1000 << "."  // minor version
            << BOOST_VERSION % 100                // patch level
            << std::endl;

Which gives Using Boost 1.65.1

Second

dpkg -S /usr/include/boost/version.hpp

Which gives libboost1.58-dev:amd64: /usr/include/boost/version.hpp

Third

cat /usr/include/boost/version.hpp | grep "BOOST_LIB_VERSION"

which displays //  BOOST_LIB_VERSION must be defined to be the same as BOOST_VERSION #define BOOST_LIB_VERSION "1_65_1"

Fourth

dpkg -s libboost-dev | grep 'Version'

which displays Version: 1.58.0.1ubuntu1

Which is the difference? Do I have both the versions installed or only 1.65?

I tried removing 1.58 by sudo apt-get autoremove,  but I get the same information again.

I also tried removing the old by

dpkg -S /usr/include/boost/version.hpp
sudo apt-get autoremove package

and it just display the following information

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package package


问:
Passing data using array from View (Blade) to Controller in laravel
I have a blade form which has a repeater input box and a select box, the repeater works fine but how do i pass the data from those fields to back-end controller in laravel?

add.balde.php

```<code><!--begin::Add-Invoice-Form-->
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" action="{{route('store_invoice')}}" method="POST" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="m-portlet__body">
        <div class="form-group m-form__group row">

            <div class="col-lg-4">
                <label>
                    Customer Name:
                </label>
                <select class="form-control m-select2" id="m_select2_1" name="customerId">
                    @foreach($customer_list as $customer)
                        <option value=" {{ $customer->id }} ">
                        {{ $customer->fName }} {{ $customer->mName }} {{ $customer->lName }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-lg-4">
                <label>
                    Invoice Type:
                </label>
                <div class="m-radio-inline">
                    <label class="m-radio m-radio--solid">
                        <input type="radio" name="invoiceType" checked value="billable">
                        Billable
                        <span></span>
                    </label>
                    <label class="m-radio m-radio--solid">
                        <input type="radio" name="invoiceType" value="nonbillable">
                        Non Billable
                        <span></span>
                    </label>
                </div>
            </div>
        </div>

     <div id="m_repeater_1">

        <div class="form-group row" id="m_repeater_1">
            <div data-repeater-list="" class="col-lg-12">
                <div data-repeater-item class="form-group m-form__group row align-items-center">
                    <div class="col-lg-4">
                <label>
                    Summary Number:
                </label>
                <select class="form-control m-select2" id="m_select2_2" name="certificateId[]">
                    @foreach($certificate_list as $certificate)
                        <option value=" {{ $certificate->id }} ">
                        {{ $certificate->summary_no }} ( {{ $certificate->certificateType() }} )
                        </option>
                    @endforeach
                </select>
            </div>
                    <div class="col-lg-3">
                                <label>
                                    Rate:
                                </label>
                                <input type="number" class="form-control m-input" name="rate" placeholder="Enter rate">
                    </div>
                    <div class="col-lg-3">
                        <br/>
                        <div data-repeater-delete="" class="btn btn btn-danger m-btn m-btn--icon">
                            <span>
                                <i class="la la-trash-o"></i>
                                <span>
                                    Remove
                                </span>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="m-form__group form-group row">
            <div class="col-lg-4">
                <div data-repeater-create="" class="btn btn btn-warning m-btn m-btn--icon">
                    <span>
                        <i class="la la-plus"></i>
                        <span>
                            Add
                        </span>
                    </span>
                </div>
            </div>
        </div></div>

    </div>

    <div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit">
        <div class="m-form__actions m-form__actions--solid">
            <div class="row">
                <div class="col-lg-4"></div>
                <div class="col-lg-8">
                    <button type="submit" class="btn btn-primary">
                        Submit
                    </button>
                    <button type="reset" class="btn btn-secondary">
                        Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</form>
<!--end::Add-Invoice-Form-->
</code>```

How do I send the values in array format when multiple select box have been filed using repeater?This images shows the UI for the form

Thank you

答:
Change your

```<code><div data-repeater-list="" class="col-lg-12">
</code>```

To

```<code><div data-repeater-list="arrayName" class="col-lg-12">
</code>```

and It should work.

This makes the all the input names to have an  array format of arrayName[number][input]  and the number increments for each input and finally in the request sent you will have all the inputs in the arrayName

Body:
I have a blade form which has a repeater input box and a select box, the repeater works fine but how do i pass the data from those fields to back-end controller in laravel?

add.balde.php

<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" action="{{route('store_invoice')}}" method="POST" enctype="multipart/form-data">
    {{ csrf_field() }}

                    Customer Name:

                <select class="form-control m-select2" id="m_select2_1" name="customerId">
                    @foreach($customer_list as $customer)
                        <option value=" {{ $customer->id }} ">
                        {{ $customer->fName }} {{ $customer->mName }} {{ $customer->lName }}
                        </option>
                    @endforeach
                </select>

                    Invoice Type:

                        <input type="radio" name="invoiceType" checked value="billable">
                        Billable

                        <input type="radio" name="invoiceType" value="nonbillable">
                        Non Billable

                    Summary Number:

                <select class="form-control m-select2" id="m_select2_2" name="certificateId[]">
                    @foreach($certificate_list as $certificate)
                        <option value=" {{ $certificate->id }} ">
                        {{ $certificate->summary_no }} ( {{ $certificate->certificateType() }} )
                        </option>
                    @endforeach
                </select>

                                    Rate:

                                <input type="number" class="form-control m-input" name="rate" placeholder="Enter rate">

                                    Remove

                            Add

                    <button type="submit" class="btn btn-primary">
                        Submit
                    </button>
                    <button type="reset" class="btn btn-secondary">
                        Cancel
                    </button>

</form>

How do I send the values in array format when multiple select box have been filed using repeater?This images shows the UI for the form

Thank you

Body:
Change your

<div data-repeater-list="" class="col-lg-12">

To

<div data-repeater-list="arrayName" class="col-lg-12">

and It should work.

This makes the all the input names to have an  array format of arrayName[number][input]  and the number increments for each input and finally in the request sent you will have all the inputs in the arrayName


问:
Combobox Render with optional params
I am solving a requirement which can be simplified as following. I am fairly new to Ext.js and I need help in achieving the below.

I have 4 tables as follows.

So, I have 3000 companies and 9000 users mapped across various companies. I need to map moderators for each company in a grid.

I have an add button, which adds a row in the grid.

I achieved displaying the companies in the first column of a grid. Easy. So user can pick one.

I achieved displaying users belonging to that company in the second column of the grid. FYI, User can multi select moderators here.

Problem:
At this point, when I add a new row, pick a new company, the companyusers store gets refreshed, so, the values selected in 1st row are not valid values anymore and the first row's user column is displaying empty text (or) only the id's

My models are as follows

```<code>Ext.define('Mine.CompanyModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', {name: 'Name', type:'string'}]});

Ext.define('Mine.UsersModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', {name: 'Name', type:'string'}]});

Ext.define('Mine.CompanyUsersModel', {
    extend: 'Ext.data.Model',
    fields: ['company_user_id', 'UserName']}); //<companyuser Id>

Ext.define('Mine.CompanyModeratorModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', 'CompanyUserId']});
</code>```

My stores are

```<code>Ext.define('Mine.CompanyStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyModel',
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    })
});

Ext.define('Mine.UsersStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.UsersModel',
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),
});

Ext.define('Mine.CompanyUserStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyUserModel',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),
    //will add extra params here
});

Ext.define('Mine.CompanyModeratorStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyModeratorModel',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),

});
</code>```

My grid columns are

```<code>{
     text: 'Company', width: '10%', dataIndex: 'id',
     renderer: companyRenderer(combo_company), editor: combo_company
 },
 {
     text: 'Users', width: '16%', dataIndex: 'company_user_id',
     renderer: companyUsersRenderer(companyUsersCbo), editor: companyUsersCbo
 }
</code>```

My editor is

```<code>var companyUsersCbo = Ext.create('Ext.form.ComboBox', {
             xtype: 'combo',
             id: 'company_users',
             name: 'company_users',
             valueField: 'Id',
             displayField: 'name',
             allowBlank: false,
             store: 'Mine.CompanyUsersStore',
             multiSelect: false,
             editable: true,
             queryMode: 'local',
             pickerAlign: 'bl',
             listConfig: {
                 getInnerTpl: function (display) {
                     return '<div class="x-combo-list-item"><img src="' + Ext.BLANK_IMAGE_URL + '" class="chkCombo-default-icon chkCombo" /> {' + display + '} </div>';
                 }
             }
             listeners: {
                 expand: function () {
                     var mainGrid = Ext.getCmp('mygrid');
                     var selmodel = mainGrid.getSelectionModel();
                     var record = selmodel.getSelection();
                     if (record[0].get('id') != null) {
                         this.getStore().getProxy().setExtraParam('company_id', record[0].get('id')); // am storing the company id in a model
                         this.getStore().load();
                     }
                 }
             }
        });
</code>```

My renderer is

```<code>        var companyUsersRenderer = function (combo) {
        return function (resources) {
             var result = [];
             resources = resources || [];
             for (var idx = 0, len = resources.length; idx < len; idx++) {
                 var value = combo.getStore().find(combo.valueField, resources[idx]);
                 if (value != -1) {
                     var rec = combo.getStore().getAt(value);
                     result.push(rec.get(combo.displayField));
                 }
             }
             return result.join(', ');
         }
    }
</code>```

What am I missing? What should I do so that the values (names) displayed in the combo box remain independent of the next rows.

What have I tried:: I have added a separate hidden column and set it to the names, added to the record. It worked fine, but its not the correct way. Also, when I double click the cell for editing, it shows the numbers (id's and not text) but after I expand, it shows the text.

答:
naga Sandeep,
    try to send params with your URL to get filtered records.</p>

```<code>like,
url:'someThing/abc/1435'+'id='+record.id;

filter your store accordingly.
</code>```

Title: Combobox Render with optional params

Body:
I am solving a requirement which can be simplified as following. I am fairly new to Ext.js and I need help in achieving the below.

I have 4 tables as follows.

So, I have 3000 companies and 9000 users mapped across various companies. I need to map moderators for each company in a grid.

I have an add button, which adds a row in the grid.

I achieved displaying the companies in the first column of a grid. Easy. So user can pick one.

I achieved displaying users belonging to that company in the second column of the grid. FYI, User can multi select moderators here.

Problem:
At this point, when I add a new row, pick a new company, the companyusers store gets refreshed, so, the values selected in 1st row are not valid values anymore and the first row's user column is displaying empty text (or) only the id's

My models are as follows

Ext.define('Mine.CompanyModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', {name: 'Name', type:'string'}]});

Ext.define('Mine.UsersModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', {name: 'Name', type:'string'}]});

Ext.define('Mine.CompanyUsersModel', {
    extend: 'Ext.data.Model',
    fields: ['company_user_id', 'UserName']}); //<companyuser Id>

Ext.define('Mine.CompanyModeratorModel', {
    extend: 'Ext.data.Model',
    fields: ['Id', 'CompanyUserId']});

My stores are

Ext.define('Mine.CompanyStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyModel',
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    })
});

Ext.define('Mine.UsersStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.UsersModel',
    autoLoad: true,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),
});

Ext.define('Mine.CompanyUserStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyUserModel',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),
    //will add extra params here
});

Ext.define('Mine.CompanyModeratorStore', {
    extend: 'Ext.data.Store',
    model: 'Mine.CompanyModeratorModel',
    autoLoad: false,
    proxy: new Ext.data.HttpProxy({
        url: '/somecontroller/someaction',
        reader: {
            type: 'json',
            root: 'Data'
        }
    }),

});

My grid columns are

{
     text: 'Company', width: '10%', dataIndex: 'id',
     renderer: companyRenderer(combo_company), editor: combo_company
 },
 {
     text: 'Users', width: '16%', dataIndex: 'company_user_id',
     renderer: companyUsersRenderer(companyUsersCbo), editor: companyUsersCbo
 }

My editor is

var companyUsersCbo = Ext.create('Ext.form.ComboBox', {
             xtype: 'combo',
             id: 'company_users',
             name: 'company_users',
             valueField: 'Id',
             displayField: 'name',
             allowBlank: false,
             store: 'Mine.CompanyUsersStore',
             multiSelect: false,
             editable: true,
             queryMode: 'local',
             pickerAlign: 'bl',
             listConfig: {
                 getInnerTpl: function (display) {
                     return '
 {' + display + '}
';
                 }
             }
             listeners: {
                 expand: function () {
                     var mainGrid = Ext.getCmp('mygrid');
                     var selmodel = mainGrid.getSelectionModel();
                     var record = selmodel.getSelection();
                     if (record[0].get('id') != null) {
                         this.getStore().getProxy().setExtraParam('company_id', record[0].get('id')); // am storing the company id in a model
                         this.getStore().load();
                     }
                 }
             }
        });

My renderer is

        var companyUsersRenderer = function (combo) {
        return function (resources) {
             var result = [];
             resources = resources || [];
             for (var idx = 0, len = resources.length; idx < len; idx++) {
                 var value = combo.getStore().find(combo.valueField, resources[idx]);
                 if (value != -1) {
                     var rec = combo.getStore().getAt(value);
                     result.push(rec.get(combo.displayField));
                 }
             }
             return result.join(', ');
         }
    }

What am I missing? What should I do so that the values (names) displayed in the combo box remain independent of the next rows.

What have I tried:: I have added a separate hidden column and set it to the names, added to the record. It worked fine, but its not the correct way. Also, when I double click the cell for editing, it shows the numbers (id's and not text) but after I expand, it shows the text.

Body:
naga Sandeep,
    try to send params with your URL to get filtered records.

like,
url:'someThing/abc/1435'+'id='+record.id;

filter your store accordingly.


问:
Substring assignment
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

```<code><head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

<script type="text/javascript">

var text= test.length;

for (i=0;i< test.length;i++)

function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}

    </script>

</head>

<body>
<h1>Assignment 14</h1>
    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

</body>
</code>```

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

答:
You have to rewrite a script.When you want to extract one by one you can use substring(); function.

How to Call : StringObject.substring (StartPoint,endPoint);

Solution:

```<code><script type="text/javascript">

function printit(){

var test=document.getElementById("test").value;
var text= test.length;

for (i=0;i<= text;i++)
{

    var res = test.substring (i, 0);
    document.write(res);
    document.write("<br/>");
}
}
    </script>
</code>```

Title: Substring assignment

Body:
I have an assignment in school but I'm totally stuck.

My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.

My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:

<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>

Assignment 14

    <form name="f1">
    <input type="text" id="test" value="" />
    <input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />

    </form>

Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.

Body:
You have to rewrite a script.When you want to extract one by one you can use substring(); function.

How to Call : StringObject.substring (StartPoint,endPoint);

Solution:

<script type="text/javascript">

function printit(){

var test=document.getElementById("test").value;
var text= test.length;

for (i=0;i<= text;i++)
{

    var res = test.substring (i, 0);
    document.write(res);
    document.write("<br/>");
}
}
    </script>


问:
Uncaught ReferenceError: Popper is not defined - with Bootstrap 4 and Webpack 3.8.1
I am using the Visual Studio 2017 Angular template with .NET Core 2.0. The template has numerous older dependencies which I have updated, including to Angular 5.0.0. Running the vanilla template with Bootstrap 3.x.x works. However, using Bootstrap 4.0.0-beta.2 results in the following error:

Uncaught ReferenceError: Popper is not defined

I have followed the instructions here to the best of my ability:

http://getbootstrap.com/docs/4.0/getting-started/webpack/

I have looked at this issue:

Bootstrap 4: Uncaught ReferenceError: Popper is not defined

Per the solutions listed there, I have to to either register popper before bootstrap or to use the min version of boostrap since it comes with popper already. However, I am using webpack 2.5.1 (which I am just now learning) and I don't know how to implement either of those solutions in the webpack.config.js file which was provided as part of the template and includes the modification called out by the boostrap-webpack docs.

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
                // In case you imported plugins individually, you must also require them here:
                //Util: "exports-loader?Util!bootstrap/js/dist/util",
                //Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};
</code>```

Also, here is the main entry point file boot.browser.ts provided as part of the template:

```<code>import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';

if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector('app');
        const newRootElem = document.createElement('app');
        oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
        modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

答:
I installed a particular version of popper.js I knew was working with bootstrap 4.0.0-beta like so:

```<code>npm install popper.js@1.12.5 --save-dev
</code>```

Then I only had to add it to my webpack.config.vendor.js like so:

```<code>new webpack.ProvidePlugin(
            {
                $: 'jquery',
                jQuery: 'jquery', // }, Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
                jquery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: 'popper.js/dist/umd/popper.js'
            }
        ),
</code>```

and I no longer received the Uncaught ReferenceError: Popper is not defined error.

I made no code changes, only webpack and npm changes.

Body:
I am using the Visual Studio 2017 Angular template with .NET Core 2.0. The template has numerous older dependencies which I have updated, including to Angular 5.0.0. Running the vanilla template with Bootstrap 3.x.x works. However, using Bootstrap 4.0.0-beta.2 results in the following error:

Uncaught ReferenceError: Popper is not defined

I have followed the instructions here to the best of my ability:

http://getbootstrap.com/docs/4.0/getting-started/webpack/

I have looked at this issue:

Bootstrap 4: Uncaught ReferenceError: Popper is not defined

Per the solutions listed there, I have to to either register popper before bootstrap or to use the min version of boostrap since it comes with popper already. However, I am using webpack 2.5.1 (which I am just now learning) and I don't know how to implement either of those solutions in the webpack.config.js file which was provided as part of the template and includes the modification called out by the boostrap-webpack docs.

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
                // In case you imported plugins individually, you must also require them here:
                //Util: "exports-loader?Util!bootstrap/js/dist/util",
                //Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

Also, here is the main entry point file boot.browser.ts provided as part of the template:

import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';

if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector('app');
        const newRootElem = document.createElement('app');
        oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
        modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);

Body:
I installed a particular version of popper.js I knew was working with bootstrap 4.0.0-beta like so:

npm install popper.js@1.12.5 --save-dev

Then I only had to add it to my webpack.config.vendor.js like so:

new webpack.ProvidePlugin(
            {
                $: 'jquery',
                jQuery: 'jquery', // }, Maps these identifiers to the jQuery package (because Bootstrap expects it to be a global variable)
                jquery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: 'popper.js/dist/umd/popper.js'
            }
        ),

and I no longer received the Uncaught ReferenceError: Popper is not defined error.

I made no code changes, only webpack and npm changes.


问:
String concatenation: concat() vs "+" operator
Assuming String a and b:

```<code>a += b
a = a.concat(b)
</code>```

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

```<code>public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}
</code>```

答:
No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

```<code>public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}
</code>```

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

```<code>java.lang.String cat(java.lang.String, java.lang.String);
  Code:
   0:   new     #2; //class java/lang/StringBuilder
   3:   dup
   4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   7:   aload_1
   8:   invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   11:  aload_2
   12:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   15:  invokevirtual   #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/    String;
   18:  astore_1
   19:  aload_1
   20:  areturn
</code>```

So, a += b is the equivalent of

```<code>a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();
</code>```

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

OwnerDisplayName: shs

Body:
Assuming String a and b:

a += b
a = a.concat(b)

Under the hood, are they the same thing?

Here is concat decompiled as reference. I'd like to be able to decompile the + operator as well to see what that does.

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

LastEditorDisplayName: shs

Body:
No, not quite.

Firstly, there's a slight difference in semantics. If a is null, then a.concat(b) throws a NullPointerException but a+=b will treat the original value of a as if it were null. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects). So the concat() method is more strict in what it accepts.

To look under the hood, write a simple class with a += b;

public class Concat {
    String cat(String a, String b) {
        a += b;
        return a;
    }
}

Now disassemble with javap -c (included in the Sun JDK). You should see a listing including:

java.lang.String cat(java.lang.String, java.lang.String);
  Code:
   0:   new     #2; //class java/lang/StringBuilder
   3:   dup
   4:   invokespecial   #3; //Method java/lang/StringBuilder."<init>":()V
   7:   aload_1
   8:   invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   11:  aload_2
   12:  invokevirtual   #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   15:  invokevirtual   #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/    String;
   18:  astore_1
   19:  aload_1
   20:  areturn

So, a += b is the equivalent of

a = new StringBuilder()
    .append(a)
    .append(b)
    .toString();

The concat method should be faster. However, with more strings the StringBuilder method wins, at least in terms of performance.

The source code of String and StringBuilder (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final String. In practice memory allocation is surprisingly fast.

Update: As Pawel Adamski notes, performance has changed in more recent HotSpot. javac still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing System.identityHashCode (not String.hashCode) shows the StringBuffer code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From @lukaseder, a list of HotSpot JVM intrinsics.

OwnerDisplayName: Tom Hawtin - tackline


问:
Windows window docking
I'm wondering how to dock / snap a window to the side of the screen in Windows, preferably with straight Win32 API. The effect I'm looking for is like the task bar -- a window that has a reserved space on screen, so that maximizing another window makes that window take up the rest of the screen, but leaves my window in place and visible.

I know various IM clients do this, but haven't been able to find any resources on how to do it. Not sure what the appropriate name for it is either.

Edit: "Application Desktop Toolbar" is the search term to use to find info on this.

答:
"App Bar" - you turn a window into an App Bar by sending the ABM_NEW message. Examples on MSDN:

http://msdn.microsoft.com/en-us/library/cc144177(VS.85).aspx
http://support.microsoft.com/kb/134206

OwnerDisplayName: slicedlime

ContentLicense: CC BY-SA 2.5

Title: Windows window docking

LastEditorDisplayName: slicedlime

OwnerDisplayName: Andrew Medico


问:
Django sometimes gives 404 and sometimes gives 200
With the same configuration in Django, visiting the same URL

```<code>http://<URL>/basic/insert/adafd
</code>```

sometimes gives me a 404 while it will give me a 200 later. Any idea how would this happen and how to solve it?

(Looks like it occurs after I tried to use channels)

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^insert/(.*)$', views.insert),
    url(r'^list$', views.list),
]
</code>```

Other code cut down as follows:

```<code>def listfrom(request, last):
    stack = infoStack.objects.all()
    listing = []
    for info in stack:
        if info.id()>last:
            listing.append(info.as_dict())
            request.session['last'] = info.id()
    return render(request, "basic/list.html", {"listings": json.dumps(listing)})

def list(request):
    last = 0
    if request.session.keys():
        sid = request.session.session_key
        s = Session.objects.get(pk=sid)
        last = s.get_decoded()['last']
    return listfrom(request, last)

def insert(request, info):
    ip = get_client_ip(request)
    q = infoStack()
    q.infoIP = ip
    q.infoText = info
    q.save()
    response = HttpResponse()
    response.status_code = 200
    return response
</code>```

Channel related config/code as follows:

```<code>@channel_session
def ws_message(message):
    print "message"

@channel_session
def ws_connect(message):
    print "connect"
    Group("wsg").add(message.reply_channel)
    message.reply_channel.send({"accept": True})

@channel_session
def ws_disconnect(message):
    print "disconnect"
    Group("wsg").discard(message.reply_channel)

# routing.py
from basic.views import ws_message, ws_connect, ws_disconnect

channel_routing = {
    'websocket.connect': ws_connect,
    'websocket.receive': ws_message,
    'websocket.disconnect': ws_disconnect,
}
</code>```

答:
Eventually found a post about this, https://github.com/django/channels/issues/489

Basically, the issue gone after I have uninstalled the redis-server and install it again.

Body:
With the same configuration in Django, visiting the same URL

http://<URL>/basic/insert/adafd

sometimes gives me a 404 while it will give me a 200 later. Any idea how would this happen and how to solve it?

(Looks like it occurs after I tried to use channels)

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^insert/(.*)$', views.insert),
    url(r'^list$', views.list),
]

Other code cut down as follows:

def listfrom(request, last):
    stack = infoStack.objects.all()
    listing = []
    for info in stack:
        if info.id()>last:
            listing.append(info.as_dict())
            request.session['last'] = info.id()
    return render(request, "basic/list.html", {"listings": json.dumps(listing)})

def list(request):
    last = 0
    if request.session.keys():
        sid = request.session.session_key
        s = Session.objects.get(pk=sid)
        last = s.get_decoded()['last']
    return listfrom(request, last)

def insert(request, info):
    ip = get_client_ip(request)
    q = infoStack()
    q.infoIP = ip
    q.infoText = info
    q.save()
    response = HttpResponse()
    response.status_code = 200
    return response

Channel related config/code as follows:

@channel_session
def ws_message(message):
    print "message"

@channel_session
def ws_connect(message):
    print "connect"
    Group("wsg").add(message.reply_channel)
    message.reply_channel.send({"accept": True})

@channel_session
def ws_disconnect(message):
    print "disconnect"
    Group("wsg").discard(message.reply_channel)

# routing.py
from basic.views import ws_message, ws_connect, ws_disconnect

channel_routing = {
    'websocket.connect': ws_connect,
    'websocket.receive': ws_message,
    'websocket.disconnect': ws_disconnect,
}


问:
Compile C library on pip install
I made a Python application which needs to execute C functions. To do so, I compiled the C functions in a shared library using gcc and called the library in my Python script using ctypes.

I'm trying to pack my application in a pip package but found no way to create the shared library upon pip install.

I tried the following (setup.py) :

```<code>from setuptools import setup
from setuptools.command.install import install
import subprocess

class compileLibrary(install):
    def run(self):
        install.run(self)
        command = "cd packageName"
        command += " && git clone https://mygit.com/myAwesomeCLibrary.git"
        command += " && gcc -my -many -options"
    process = subprocess.Popen(command, shell=True)
    process.wait()

setup(
    name='packageName',
    version='0.1',
    packages=['packageName'],
    install_requires=[
        ...
    ],
cmdclass={'install': compileLibrary},
</code>```

)

This works when doing python setup.py install but, when installing from pip, while the install process is successful, the shared library is not in the package folder (pythonx.x/site-packages/packageName).

I tried using distutils with the same result.

Based on the question Run Makefile on pip install I also tried the following setup.py :

```<code>from setuptools import setup
from distutils.command.build import build
import subprocess

class Build(build):
    def run(self):
        command = "cd packageName"
        command += " && git clone https://mygit.com/myAwesomeCLibrary.git"
        command += " && gcc -my -many -options"
        process = subprocess.Popen(command, shell=True)
        process.wait()
        build.run(self)

setup(
    name='packageName',
    version='0.1',
    packages=['packageName'],
    install_requires=[
        ...
    ],
    cmdclass={'build': Build},
)
</code>```

Here is the architecture of my package

```<code>packageName/
├── packageName/
│   ├── __init__.py
│   ├── myFunctions.c
├── MANIFEST.in
├── README.md
├── setup.py
</code>```

Note : After installing the package with pip, I only have __init__.py and __pycache__ in the install folder (pythonx.x/site-packages/packageName).

How can I create the shared library during pip install so It can be used by my package ?

答:
you can add the shared library in MANIFEST.in.
like this:

include *.so *.dylib

Title: Compile C library on pip install

Body:
I made a Python application which needs to execute C functions. To do so, I compiled the C functions in a shared library using gcc and called the library in my Python script using ctypes.

I'm trying to pack my application in a pip package but found no way to create the shared library upon pip install.

I tried the following (setup.py) :

from setuptools import setup
from setuptools.command.install import install
import subprocess

class compileLibrary(install):
    def run(self):
        install.run(self)
        command = "cd packageName"
        command += " && git clone https://mygit.com/myAwesomeCLibrary.git"
        command += " && gcc -my -many -options"
    process = subprocess.Popen(command, shell=True)
    process.wait()

setup(
    name='packageName',
    version='0.1',
    packages=['packageName'],
    install_requires=[
        ...
    ],
cmdclass={'install': compileLibrary},

)

This works when doing python setup.py install but, when installing from pip, while the install process is successful, the shared library is not in the package folder (pythonx.x/site-packages/packageName).

I tried using distutils with the same result.

Based on the question Run Makefile on pip install I also tried the following setup.py :

from setuptools import setup
from distutils.command.build import build
import subprocess

class Build(build):
    def run(self):
        command = "cd packageName"
        command += " && git clone https://mygit.com/myAwesomeCLibrary.git"
        command += " && gcc -my -many -options"
        process = subprocess.Popen(command, shell=True)
        process.wait()
        build.run(self)

setup(
    name='packageName',
    version='0.1',
    packages=['packageName'],
    install_requires=[
        ...
    ],
    cmdclass={'build': Build},
)

Here is the architecture of my package

packageName/
├── packageName/
│   ├── __init__.py
│   ├── myFunctions.c
├── MANIFEST.in
├── README.md
├── setup.py

Note : After installing the package with pip, I only have __init__.py and __pycache__ in the install folder (pythonx.x/site-packages/packageName).

How can I create the shared library during pip install so It can be used by my package ?


答:
You want to use:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_start_question, container, false);
    // flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
        // flContainer.addView(R.layout.sub_layout);
    LinearLayout linPhoneNumber = (LinearLayout) v.findViewById(R.id.linPhoneNumber);
    View viewPhoneNumber  =  getActivity().getLayoutInflater().inflate(R.layout.fragment_contact_phone, null);
    LinearLayout linPhoneLayout = (LinearLayout) viewPhoneNumber.findViewById(R.id.linPhoneLayout);
    TextView txtPhoneNumber = (TextView) viewPhoneNumber.findViewById(R.id.txtPhoneNumber);
    txtPhoneNumber.setText(phone);
    linPhoneNumber.addView(viewPhoneNumber);
    return v;
}
</code>```

put one linear layout in fragment_start_question.xml :

```<code><LinearLayout
    android:id="@+id/linPhoneNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"></LinearLayout>
</code>```

then fragment_contact_phone.xml

```<code><LinearLayout
    android:id="@+id/linPhoneLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/margin_top_10"
    android:orientation="horizontal"
    android:padding="@dimen/margin_top">

    <ImageView
        android:id="@+id/imgCall"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/icon_call" />

    <Textview
        android:id="@+id/txtPhoneNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/margin_top_1"
        android:textColor="@color/menu_text_color"
        android:textSize="@dimen/margin_top_1"/>
</LinearLayout>
</code>```

Title: dynamically include a layout to another layout file inside a fragment

Body:
You want to use:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_start_question, container, false);
    // flContainer = (FrameLayout) v.findViewById(R.id.flContainer);
        // flContainer.addView(R.layout.sub_layout);
    LinearLayout linPhoneNumber = (LinearLayout) v.findViewById(R.id.linPhoneNumber);
    View viewPhoneNumber  =  getActivity().getLayoutInflater().inflate(R.layout.fragment_contact_phone, null);
    LinearLayout linPhoneLayout = (LinearLayout) viewPhoneNumber.findViewById(R.id.linPhoneLayout);
    TextView txtPhoneNumber = (TextView) viewPhoneNumber.findViewById(R.id.txtPhoneNumber);
    txtPhoneNumber.setText(phone);
    linPhoneNumber.addView(viewPhoneNumber);
    return v;
}

put one linear layout in fragment_start_question.xml :

<LinearLayout
    android:id="@+id/linPhoneNumber"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"></LinearLayout>

then fragment_contact_phone.xml

<LinearLayout
    android:id="@+id/linPhoneLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/margin_top_10"
    android:orientation="horizontal"
    android:padding="@dimen/margin_top">

    <ImageView
        android:id="@+id/imgCall"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center_vertical"
        android:src="@drawable/icon_call" />

    <Textview
        android:id="@+id/txtPhoneNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="@dimen/margin_top_1"
        android:textColor="@color/menu_text_color"
        android:textSize="@dimen/margin_top_1"/>
</LinearLayout>


问:
Makefile:1: *** missing separator. Stop
I'm creating a project on c and when i make my Makefile and try to run it it gives me this error:

```<code>Makefile:1: *** missing separator.  Stop.
</code>```

My makefile code is:

```<code>CC=gcc
OBJ=./objetos
INC=./include
FON=./aqsFonte
BIB=./bibliotecas
OPBIB=-lBiblioteca
ProjetoFinal: libFinal.a
    $(CP) $(FON)/ProjetoFinal.c -I$(INC) -L$(BIB) $(OPBIB) -o ProjetoFinal

Bibliotecas.a: Caminho.o Libs_Defines.o Matrizes.o Proc_Imagens.o Vetores.o
    ar -q $(BIB)/libFinal.a Caminho.o ibs_Defines.o Matrizes.o Proc_Imagens.o Vetores.o

Caminho.o:
    $(CP) $(FON)/Caminho.c -o Caminho.o
Libs_Defines.o :
    $(CP) $(FON)/Libs_Defines.c -o Libs_Defines.o
Matrizes.o:
    $(CP) $(FON)/Matrizes.c -o Matrizes.o
Proc_Imagens.o:
    $(CP) $(FON)/Proc_Imagens.c -o Proc_Imagens.o
Vetores.o:
    $(CP) $(FON)/Vetores.c -o Vetores.o
</code>```

Also, it's all tabbed correctly I guess.

答:
I just meet the same problem when compliling my source code with auto generated  gcc makefile.

I finally found it was caused by the utf-8 BOM characters at the beginning of the makefile.These charaters are invisible in some text editors.

so try save the file as utf-8 without BOM.

ContentLicense: CC BY-SA 4.0

Title: Makefile:1: *** missing separator. Stop

Body:
I'm creating a project on c and when i make my Makefile and try to run it it gives me this error:

Makefile:1: *** missing separator.  Stop.

My makefile code is:

CC=gcc
OBJ=./objetos
INC=./include
FON=./aqsFonte
BIB=./bibliotecas
OPBIB=-lBiblioteca
ProjetoFinal: libFinal.a
    $(CP) $(FON)/ProjetoFinal.c -I$(INC) -L$(BIB) $(OPBIB) -o ProjetoFinal

Bibliotecas.a: Caminho.o Libs_Defines.o Matrizes.o Proc_Imagens.o Vetores.o
    ar -q $(BIB)/libFinal.a Caminho.o ibs_Defines.o Matrizes.o Proc_Imagens.o Vetores.o

Caminho.o:
    $(CP) $(FON)/Caminho.c -o Caminho.o
Libs_Defines.o :
    $(CP) $(FON)/Libs_Defines.c -o Libs_Defines.o
Matrizes.o:
    $(CP) $(FON)/Matrizes.c -o Matrizes.o
Proc_Imagens.o:
    $(CP) $(FON)/Proc_Imagens.c -o Proc_Imagens.o
Vetores.o:
    $(CP) $(FON)/Vetores.c -o Vetores.o

Also, it's all tabbed correctly I guess.


问:
Advantage to SQL 2008 Linked Server Access Denied Error
I am trying to create a linked server in SQL 2008 to an Advantage v7 database server.  I've successfully created the linked server in SQL 2008 using the commands below and the connection tests out fine.  Also, the Advantage DB I'm connecting to does not have a data dictionary.

SQL to create the Linked Server

```<code>EXEC master.dbo.sp_addlinkedserver
  @server = N'ADVANTAGE', @srvproduct=N'Advantage',
  @provider=N'Advantage.OLEDB',
  @datasrc=N'\\asc1\questtest$\spaulrun'
 /* For security reasons the linked server remote logins password is changed with ######## */

EXEC master.dbo.sp_addlinkedsrvlogin
  @rmtsrvname=N'ADVANTAGE',
  @useself=N'False',
  @locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL
</code>```

When I run the following query:

```<code>select * from
openquery(ADVANTAGE,'select * from members')
</code>```

I get this error:

```<code>Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Advantage.OLEDB" for linked server "ADVANTAGE" reported an error. Access denied.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Advantage.OLEDB" for linked server "ADVANTAGE".
</code>```

I've verified that this is not an NT File permissions issue.  Also, just before the error messages are displayed, I can see all of the column names on the screen for just a second.  So I'm getting at least some table information back from Advantage.  I just don't know why I'm getting the Access denied message.

Any help is greatly appreciated!

答:
This sounds familiar, but I don't remember the exact error message I got.

Try going to the Advantage OLE DB Provider in the Linked Server setup and right click and choose properties and set "Allow Inprocess".

If I remember correctly, in Management Studio Express i went to
Server Objects -> Linked Servers -> Providers -> Advantage OLE DB Provider (Right Click->Properties or Double Click)

Set "Allow Inprocess"

Body:
I am trying to create a linked server in SQL 2008 to an Advantage v7 database server.  I've successfully created the linked server in SQL 2008 using the commands below and the connection tests out fine.  Also, the Advantage DB I'm connecting to does not have a data dictionary.

SQL to create the Linked Server

EXEC master.dbo.sp_addlinkedserver
  @server = N'ADVANTAGE', @srvproduct=N'Advantage',
  @provider=N'Advantage.OLEDB',
  @datasrc=N'\\asc1\questtest$\spaulrun'
 /* For security reasons the linked server remote logins password is changed with ######## */

EXEC master.dbo.sp_addlinkedsrvlogin
  @rmtsrvname=N'ADVANTAGE',
  @useself=N'False',
  @locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL

When I run the following query:

select * from
openquery(ADVANTAGE,'select * from members')

I get this error:

Msg 7399, Level 16, State 1, Line 1
The OLE DB provider "Advantage.OLEDB" for linked server "ADVANTAGE" reported an error. Access denied.
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Advantage.OLEDB" for linked server "ADVANTAGE".

I've verified that this is not an NT File permissions issue.  Also, just before the error messages are displayed, I can see all of the column names on the screen for just a second.  So I'm getting at least some table information back from Advantage.  I just don't know why I'm getting the Access denied message.

Any help is greatly appreciated!


问:
Run a function returning a set on a set, and get back a larger set
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

```<code>ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }
</code>```

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

答:
The best one-liner, IMO is this:</p>

```<code>q = { 1, 2, 3, 4 }
l = set(elem **2 for elem in q).union(q)
</code>```

Body:
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

Body:
The best one-liner, IMO is this:

q = { 1, 2, 3, 4 }
l = set(elem **2 for elem in q).union(q)


问:
Type of “id” (number) in user.json is not supported. Use objects or arrays of objects error when using json-server, why?
I am working on an Angular 4 App.
I am trying to get data from a JSON file for building a user dashboard.

I created a json file and tried loading it using JSON server using this: $ json-server --watch user.json and I am getting the following error:

Type of "id" (number) in user.json is not supported. Use objects or arrays of objects..

When I remove the "id" field in the file, I get the same error with "name".

I feel there is something wrong with the way I have created the json files. I am new to web development, so don't mind if it's a very fundamental mistake.

This is my json file:

```<code>{
 "id": 1,
 "name":"Kajal Agarwal",
 "department":"Information Technology",
 "college":"Indian Institute of Engineering Science and Technology, Shibpur",
 "subjects":[
    {
        "title":"Data Structures",
        "active":true,
        "faculty":"Prasun Ghosal",
        "notifications":4,
        "color":"#9c27b0"
    },
    {
        "title":"Operating System",
        "active":true,
        "faculty":"Niharika Singh",
        "notifications":0,
        "color":"#ffc107"
    },
    {
        "title":"Algorithms",
        "active":true,
        "faculty":"Debojit Mondal",
        "notifications":1,
        "color":"#009688"
    },
    {
        "title":"Web Technologies",
        "active":true,
        "faculty":"Shantanu Saurabh",
        "notifications":2,
        "color":"#ff5722"
    },
    {
        "title":"Formal Language and Automata Theory",
        "active":true,
        "faculty":"Sudhanshu Sekhar",
        "notifications":3,
        "color":"#03a9f4"
    },
    {
        "title":"Digital Logic and Circuit Design",
        "active":false,
        "faculty":"",
        "notifications":0,
        "color":"#9e9e9e"
    }
  ]
}
</code>```

答:
Maybe I'm late for the response, but this is just for future readers since I too faced similar problem until I understood more about json-server.

As such there is nothing wrong with your JSON object. The reason why you are getting that error has to do with how json-server works.

Each and every key directly exposed at the root of the JSON object is considered as a separate URL in json-server. In your case, if you wrap your entire JSON object inside a key eg: 'data', your error would be resolved. Your JSON object would look something like below

```<code>{
"data":{
 "id": 1,
 "name":"Kajal Agarwal",
 "department":"Information Technology",
 "college":"Indian Institute of Engineering Science and Technology, Shibpur",
 "subjects":[
    {
        "title":"Data Structures",
        "active":true,
        "faculty":"Prasun Ghosal",
        "notifications":4,
        "color":"#9c27b0"
    },
    {
        "title":"Operating System",
        "active":true,
        "faculty":"Niharika Singh",
        "notifications":0,
        "color":"#ffc107"
    },
    {
        "title":"Algorithms",
        "active":true,
        "faculty":"Debojit Mondal",
        "notifications":1,
        "color":"#009688"
    },
    {
        "title":"Web Technologies",
        "active":true,
        "faculty":"Shantanu Saurabh",
        "notifications":2,
        "color":"#ff5722"
    },
    {
        "title":"Formal Language and Automata Theory",
        "active":true,
        "faculty":"Sudhanshu Sekhar",
        "notifications":3,
        "color":"#03a9f4"
    },
    {
        "title":"Digital Logic and Circuit Design",
        "active":false,
        "faculty":"",
        "notifications":0,
        "color":"#9e9e9e"
    }
  ]
}
}
</code>```

Now if you try to access the root key from URL like below. You would be able to fetch your entire JSON object.

```<code>localhost:3000/data
</code>```

If you were to add another key called "data2" at the root of the JSON object and assign some other object then you would have another URL as below

```<code>localhost:3000/data2
</code>```

Hope this makes sense and is helpful.
You could also visit here to see an example of how json-server works

Body:
I am working on an Angular 4 App.
I am trying to get data from a JSON file for building a user dashboard.

I created a json file and tried loading it using JSON server using this: $ json-server --watch user.json and I am getting the following error:

Type of "id" (number) in user.json is not supported. Use objects or arrays of objects..

When I remove the "id" field in the file, I get the same error with "name".

I feel there is something wrong with the way I have created the json files. I am new to web development, so don't mind if it's a very fundamental mistake.

This is my json file:

{
 "id": 1,
 "name":"Kajal Agarwal",
 "department":"Information Technology",
 "college":"Indian Institute of Engineering Science and Technology, Shibpur",
 "subjects":[
    {
        "title":"Data Structures",
        "active":true,
        "faculty":"Prasun Ghosal",
        "notifications":4,
        "color":"#9c27b0"
    },
    {
        "title":"Operating System",
        "active":true,
        "faculty":"Niharika Singh",
        "notifications":0,
        "color":"#ffc107"
    },
    {
        "title":"Algorithms",
        "active":true,
        "faculty":"Debojit Mondal",
        "notifications":1,
        "color":"#009688"
    },
    {
        "title":"Web Technologies",
        "active":true,
        "faculty":"Shantanu Saurabh",
        "notifications":2,
        "color":"#ff5722"
    },
    {
        "title":"Formal Language and Automata Theory",
        "active":true,
        "faculty":"Sudhanshu Sekhar",
        "notifications":3,
        "color":"#03a9f4"
    },
    {
        "title":"Digital Logic and Circuit Design",
        "active":false,
        "faculty":"",
        "notifications":0,
        "color":"#9e9e9e"
    }
  ]
}

Body:
Maybe I'm late for the response, but this is just for future readers since I too faced similar problem until I understood more about json-server.

As such there is nothing wrong with your JSON object. The reason why you are getting that error has to do with how json-server works.

Each and every key directly exposed at the root of the JSON object is considered as a separate URL in json-server. In your case, if you wrap your entire JSON object inside a key eg: 'data', your error would be resolved. Your JSON object would look something like below

{
"data":{
 "id": 1,
 "name":"Kajal Agarwal",
 "department":"Information Technology",
 "college":"Indian Institute of Engineering Science and Technology, Shibpur",
 "subjects":[
    {
        "title":"Data Structures",
        "active":true,
        "faculty":"Prasun Ghosal",
        "notifications":4,
        "color":"#9c27b0"
    },
    {
        "title":"Operating System",
        "active":true,
        "faculty":"Niharika Singh",
        "notifications":0,
        "color":"#ffc107"
    },
    {
        "title":"Algorithms",
        "active":true,
        "faculty":"Debojit Mondal",
        "notifications":1,
        "color":"#009688"
    },
    {
        "title":"Web Technologies",
        "active":true,
        "faculty":"Shantanu Saurabh",
        "notifications":2,
        "color":"#ff5722"
    },
    {
        "title":"Formal Language and Automata Theory",
        "active":true,
        "faculty":"Sudhanshu Sekhar",
        "notifications":3,
        "color":"#03a9f4"
    },
    {
        "title":"Digital Logic and Circuit Design",
        "active":false,
        "faculty":"",
        "notifications":0,
        "color":"#9e9e9e"
    }
  ]
}
}

Now if you try to access the root key from URL like below. You would be able to fetch your entire JSON object.

localhost:3000/data

If you were to add another key called "data2" at the root of the JSON object and assign some other object then you would have another URL as below

localhost:3000/data2

Hope this makes sense and is helpful.
You could also visit here to see an example of how json-server works


问:
How to set or change the default Java (JDK) version on macOS?
How can you change the default version of Java on a mac?</p>

答:
JDK Switch Script

I have adapted the answer from @Alex above and wrote the following to fix the code for Java 9.

```<code>$ cat ~/.jdk
#!/bin/bash

#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
  echo "Switching java version $1";

  requestedVersion=$1
  oldStyleVersion=8
  # Set the version
  if [ $requestedVersion -gt $oldStyleVersion ]; then
    export JAVA_HOME=$(/usr/libexec/java_home -v $1);
  else
    export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
  fi

  echo "Setting JAVA_HOME=$JAVA_HOME"

  which java
  java -version;
}
</code>```

Switch to Java 8

```<code>$ jdk 8
Switching java version 8
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
</code>```

Switch to Java 9

```<code>$ jdk 9
Switching java version 9
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
/usr/bin/java
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
</code>```

Body:
JDK Switch Script

I have adapted the answer from @Alex above and wrote the following to fix the code for Java 9.

$ cat ~/.jdk
#!/bin/bash

#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
  echo "Switching java version $1";

  requestedVersion=$1
  oldStyleVersion=8
  # Set the version
  if [ $requestedVersion -gt $oldStyleVersion ]; then
    export JAVA_HOME=$(/usr/libexec/java_home -v $1);
  else
    export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
  fi

  echo "Setting JAVA_HOME=$JAVA_HOME"

  which java
  java -version;
}

Switch to Java 8

$ jdk 8
Switching java version 8
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Switch to Java 9

$ jdk 9
Switching java version 9
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
/usr/bin/java
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)


Title: rearrange groups in dataframe based on day and month from another dataframe index

Body:
I have 2 dataframes:

df_a

datetime      var
2016-10-15    110.232790
2016-10-16    111.020661
2016-10-17    112.193496
2016-10-18    113.638143
2016-10-19    115.241448
2017-01-01    113.638143
2017-01-02    115.241448

and df_b

datetime      var
2000-01-01    165.792185
2000-01-02    166.066959
2000-01-03    166.411669
2000-01-04    167.816046
2000-01-05    169.777814
2000-10-15    114.232790
2000-10-16    113.020661
2001-01-01    164.792185
2001-01-02    161.066959
2001-01-03    156.411669
2002-01-04    167.816046
2002-01-05    169.777814
2002-10-15    174.232790
2003-10-16    114.020661

df_a has information for the year 2016, 2017 and df_b has information for years from 2000 to 2015 (there is no overlap in the years).

Can I arrange each group in the df_b dataframe to have the same order in terms of day of year as df_a? A group is defined as rows with the same year e.g. 2000

Body:
You can chain new condition for check year:

df = df_b[df_b.index.month.isin(df_a.index.month) &
          df_b.index.day.isin(df_a.index.day) &
          (df_b.index.year == 2000)]
print (df)
                   var
datetime
2000-01-01  165.792185
2000-01-02  166.066959
2000-10-15  114.232790
2000-10-16  113.020661

EDIT:

df = df_b[df_b.index.month.isin(df_a.index.month) & df_b.index.day.isin(df_a.index.day)]
print (df)
                   var
datetime
2000-01-01  165.792185
2000-01-02  166.066959
2000-10-15  114.232790
2000-10-16  113.020661
2001-01-01  164.792185
2001-01-02  161.066959
2002-10-15  174.232790
2003-10-16  114.020661

#create dictionary of weights by factorize
a = pd.factorize(df_a.index.strftime('%m-%d'))
d = dict(zip(a[1], a[0]))
print (d)
{'01-02': 6, '10-19': 4, '10-18': 3, '10-15': 0, '01-01': 5, '10-16': 1, '10-17': 2}

#ordering Series, multiple by 1000 becasue possible 1 to 366 MMDD
order = pd.Series(df.index.strftime('%m-%d'), index=df.index).map(d) + df.index.year * 1000
print (order)
datetime
2000-01-01    2000005
2000-01-02    2000006
2000-10-15    2000000
2000-10-16    2000001
2001-01-01    2001005
2001-01-02    2001006
2002-10-15    2002000
2003-10-16    2003001
Name: datetime, dtype: int64

Last reindex by sorted order index:

df = df.reindex(order.sort_values().index)
print (df)
                   var
datetime
2000-10-15  114.232790
2000-10-16  113.020661
2000-01-01  165.792185
2000-01-02  166.066959
2001-01-01  164.792185
2001-01-02  161.066959
2002-10-15  174.232790
2003-10-16  114.020661


问:
How can I initialize a std::vector with a size parameter and have each object constructed independently?
I like creating vectors with a given size and value, for example like this:

```<code>std::vector<std::string> names(10);
</code>```

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

```<code>#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}
</code>```

Console output:

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

It does make sense when looking at std::vector's constructor:

```<code>explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());
</code>```

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

答:
Vector is copy-constructing the elements for initialization.

Try that:

```<code>#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber(bool automatic = true)
        : mValue(automatic?sInstanceCount++:Special)
    { }

    UniqueNumber(UniqueNumber const& other)
        : mValue(other.mValue==Special?sInstanceCount++:other.mValue)
    { }

    unsigned int value() const
    {
        return mValue;
    }

private:
    static int sInstanceCount;
    unsigned int mValue;
    static unsigned int const Special = ~0U;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10,UniqueNumber(false));
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}
</code>```

Body:
I like creating vectors with a given size and value, for example like this:

std::vector<std::string> names(10);

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}

Console output:

0 0 0 0 0 0 0 0 0 0

It does make sense when looking at std::vector's constructor:

explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

Body:
Vector is copy-constructing the elements for initialization.

Try that:

#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber(bool automatic = true)
        : mValue(automatic?sInstanceCount++:Special)
    { }

    UniqueNumber(UniqueNumber const& other)
        : mValue(other.mValue==Special?sInstanceCount++:other.mValue)
    { }

    unsigned int value() const
    {
        return mValue;
    }

private:
    static int sInstanceCount;
    unsigned int mValue;
    static unsigned int const Special = ~0U;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10,UniqueNumber(false));
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}


问:
Get all possible (2^N) combinations of a list’s elements, of any length
I have a list with 15 numbers. How can I produce all 32,768 combinations of those numbers (i.e., any number of elements, in the original order)?

I thought of looping through the decimal integers 1–32768 and using the binary representation of each numbers as a filter to pick out the appropriate list elements. Is there a better way to do it?

For combinations of a specific length, see Get all (n-choose-k) combinations of length n. Please use that question to close duplicates instead where appropriate.

When closing questions about combinatorics as duplicates, it is very important to make sure of what OP actually wants, not the words that were used to describe the problem. It is extremely common for people who want, for example, a Cartesian product (see How to get the cartesian product of multiple lists) to ask about "combinations".

答:
If someone is looking for a reversed list, like I was:</p>

```<code>stuff = [1, 2, 3, 4]

def reverse(bla, y):
    for subset in itertools.combinations(bla, len(bla)-y):
        print list(subset)
    if y != len(bla):
        y += 1
        reverse(bla, y)

reverse(stuff, 1)
</code>```

OwnerDisplayName: Ben

Body:
If someone is looking for a reversed list, like I was:

stuff = [1, 2, 3, 4]

def reverse(bla, y):
    for subset in itertools.combinations(bla, len(bla)-y):
        print list(subset)
    if y != len(bla):
        y += 1
        reverse(bla, y)

reverse(stuff, 1)


问:
Button Click in Bootstrap, how to toggle class of nav?
I am trying to setup a wizard-style theme on one of my pages for building a profile, and I want to be able to toggle the class of the pill nav on bootstrap by clicking next, although I am not entirely sure how to do so. My nav for the tabs layout is like this:

```<code><!-- Nav tabs -->
<ul class="nav nav-pills" role="tablist">
    <li role="presentation" class="active"><a href="#aaa" aria-controls="aaa" role="tab" data-toggle="tab">aaa</a></li>
    <li role="presentation"><a href="#bbb" aria-controls="bbb" role="tab" data-toggle="tab">bbb</a></li>
    <li role="presentation"><a href="#ccc" aria-controls="ccc" role="tab" data-toggle="tab">ccc</a></li>
    <li role="presentation"><a href="#ddd" aria-controls="ddd" role="tab" data-toggle="tab">ddd</a></li>
</ul>
</code>```

My buttons look something like this, and they work, but they don't toggle the "active" class on the corresponding nav-pills:

```<code><a href="#bbb" aria-controls="bbb" role="tab" data-toggle="tab" class="btn btn-success btn-lg bottomright">Next</a>
</code>```

Is there a way I an target the nav-pills to toggle the active class?

答:
```<code>$('.nav-tabs > .active').next('li').find('a').trigger('click');
</code>```

This JQuery code in next button click may helps you to set next item in list as active.
Also i think that you should remove href="#bbb" from 'Next' button.

Body:
I am trying to setup a wizard-style theme on one of my pages for building a profile, and I want to be able to toggle the class of the pill nav on bootstrap by clicking next, although I am not entirely sure how to do so. My nav for the tabs layout is like this:

aaa

bbb

ccc

ddd

My buttons look something like this, and they work, but they don't toggle the "active" class on the corresponding nav-pills:

Next

Is there a way I an target the nav-pills to toggle the active class?

Body:
$('.nav-tabs > .active').next('li').find('a').trigger('click');

This JQuery code in next button click may helps you to set next item in list as active.
Also i think that you should remove href="#bbb" from 'Next' button.


问:
How to set constraints on Horizontal line programmatically in Swift?
How to set constraints on Horizontal line programmatically in Swift ?
I set this line in "Try Again" button. So, please tell me how to set constraints on this line.

Code is :

```<code>let hrzLine = UIView(frame: CGRect(x: 0, y: 647, width: 265, height: 1))

hrzLine.backgroundColor = UIColor.white

self.view.addSubview(hrzLine)
</code>```

enter image description here

答:
change the value of constants accordingly. and make sure you declare hrzline.translatesAutoresizingMaskIntoConstraints before view.addSubview just like i did below

```<code>   let hrzline = UIView()
   hrzLine.backgroundColor = UIColor.white

    hrzline.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(hrzLine)

    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 265))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .top, relatedBy: .equal, toItem: yourTryAgainButton, attribute: .top, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 10))
</code>```

Body:
How to set constraints on Horizontal line programmatically in Swift ?
I set this line in "Try Again" button. So, please tell me how to set constraints on this line.

Code is :

let hrzLine = UIView(frame: CGRect(x: 0, y: 647, width: 265, height: 1))

hrzLine.backgroundColor = UIColor.white

self.view.addSubview(hrzLine)

enter image description here

Body:
change the value of constants accordingly. and make sure you declare hrzline.translatesAutoresizingMaskIntoConstraints before view.addSubview just like i did below

   let hrzline = UIView()
   hrzLine.backgroundColor = UIColor.white

    hrzline.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(hrzLine)

    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 265))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .top, relatedBy: .equal, toItem: yourTryAgainButton, attribute: .top, multiplier: 1, constant: 10))
    self.view.addConstraint(NSLayoutConstraint(item: hrzline, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: 10))