问:
RecyclerView Multiple Layout View(s) in an Adapter class
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

```<code>public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}
</code>```

答:
Yes you need to override getItemViewType(int position) method which helps to inflate different views in recyclerview.

I am posting a sample code which may help you.

```<code>public class TransactionHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int TYPE_HEADER = 1;
private final int TYPE_CHILD = 2;
private final Context mContext;
private final List<TransactionResultEntity> mTransactionList;

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType) {
        case TYPE_HEADER:
            View headerView = LayoutInflater.from(mContext)
                    .inflate(R.layout.row_transaction_header, parent, false);
            return new ParentTypeDataObjectHolder(headerView);
        case TYPE_CHILD:
            View childView = LayoutInflater.from(mContext)
                    .inflate(R.layout.row_transaction_child, parent, false);
            return new ChildTypeDataObjectHolder(childView);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case TYPE_HEADER:
            ParentTypeDataObjectHolder parentTypeDataObjectHolder = (ParentTypeDataObjectHolder) holder;
            parentTypeDataObjectHolder.headerYearMonthTv.setText(mTransactionList.get(holder.getAdapterPosition()).getRowLabel());
            break;

        case TYPE_CHILD:
            ChildTypeDataObjectHolder childTypeDataObjectHolder = (ChildTypeDataObjectHolder) holder;
           childTypeDataObjectHolder.txnAmountTv.setText(mTransactionList.get(holder.getAdapterPosition()).getTransactionAmount());
            break;
    }
}

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

@Override
public int getItemViewType(int position) {
    if (mTransactionList.get(position).getDataType() == TYPE_HEADER)
        return TYPE_HEADER;
    else
        return TYPE_CHILD;
}

class ParentTypeDataObjectHolder extends RecyclerView.ViewHolder {

    private final TextView headerYearMonthTv;

    public ParentTypeDataObjectHolder(View itemView) {
        super(itemView);
        headerYearMonthTv = (TextView) itemView.findViewById(R.id.row_transaction_header_tv);
    }
}

class ChildTypeDataObjectHolder extends RecyclerView.ViewHolder {
    TextView txnAmountTv;

    public ChildTypeDataObjectHolder(View itemView) {
        super(itemView);
        txnAmountTv = (TextView) itemView.findViewById(R.id.transaction_child_txn_amount_tv);
                }
}
</code>```

}

Body:
Here is what I have achieved ? 3 different sections, 10 different items in each section.

Here is the tutorial link I am following and below is the Screenshot:

Trying to show different Views for each and every Section. Like:

For Section 1 (layout_1.xml)

For Section 2 (layout_2.xml)

For Section 3 (layout_3.xml)

But showing layout view of layout_1.xml in every Section... (Section 1, 2, 3)

May I know where I am doing mistake in my code, what I have missed ?

public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {

    private ArrayList<SingleItemModel> itemsList;
    private Context mContext;

    public SectionListDataAdapter(Context context, ArrayList<SingleItemModel> itemsList) {
        this.itemsList = itemsList;
        this.mContext = context;
    }

    @Override
    public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        switch (i) {

            case 0:
                View viewONE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_1, null, false);
                SingleItemRowHolder rowONE = new SingleItemRowHolder(viewONE);
                return rowONE;

            case 1:
                View viewTWO = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_2, null, false);
                SingleItemRowHolder rowTWO = new SingleItemRowHolder(viewTWO);
                return rowTWO;

            case 2:
                View viewTHREE = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_3, null, false);
                SingleItemRowHolder rowTHREE = new SingleItemRowHolder(viewTHREE);
                return rowTHREE;

        }

        return null;

    }

    @Override
    public void onBindViewHolder(SingleItemRowHolder holder, int i) {

        SingleItemModel singleItem = itemsList.get(i);
        holder.tvTitle.setText(singleItem.getName());
    }

    @Override
    public int getItemCount() {
        return (null != itemsList ? itemsList.size() : 0);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        protected TextView tvTitle;

        protected ImageView itemImage;

        public SingleItemRowHolder(View view) {
            super(view);

            this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            this.itemImage = (ImageView) view.findViewById(R.id.itemImage);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();

                }
            });

        }

    }

}

Body:
Yes you need to override getItemViewType(int position) method which helps to inflate different views in recyclerview.

I am posting a sample code which may help you.

public class TransactionHistoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final int TYPE_HEADER = 1;
private final int TYPE_CHILD = 2;
private final Context mContext;
private final List<TransactionResultEntity> mTransactionList;

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType) {
        case TYPE_HEADER:
            View headerView = LayoutInflater.from(mContext)
                    .inflate(R.layout.row_transaction_header, parent, false);
            return new ParentTypeDataObjectHolder(headerView);
        case TYPE_CHILD:
            View childView = LayoutInflater.from(mContext)
                    .inflate(R.layout.row_transaction_child, parent, false);
            return new ChildTypeDataObjectHolder(childView);
    }
    return null;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    switch (holder.getItemViewType()) {
        case TYPE_HEADER:
            ParentTypeDataObjectHolder parentTypeDataObjectHolder = (ParentTypeDataObjectHolder) holder;
            parentTypeDataObjectHolder.headerYearMonthTv.setText(mTransactionList.get(holder.getAdapterPosition()).getRowLabel());
            break;

        case TYPE_CHILD:
            ChildTypeDataObjectHolder childTypeDataObjectHolder = (ChildTypeDataObjectHolder) holder;
           childTypeDataObjectHolder.txnAmountTv.setText(mTransactionList.get(holder.getAdapterPosition()).getTransactionAmount());
            break;
    }
}

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

@Override
public int getItemViewType(int position) {
    if (mTransactionList.get(position).getDataType() == TYPE_HEADER)
        return TYPE_HEADER;
    else
        return TYPE_CHILD;
}

class ParentTypeDataObjectHolder extends RecyclerView.ViewHolder {

    private final TextView headerYearMonthTv;

    public ParentTypeDataObjectHolder(View itemView) {
        super(itemView);
        headerYearMonthTv = (TextView) itemView.findViewById(R.id.row_transaction_header_tv);
    }
}

class ChildTypeDataObjectHolder extends RecyclerView.ViewHolder {
    TextView txnAmountTv;

    public ChildTypeDataObjectHolder(View itemView) {
        super(itemView);
        txnAmountTv = (TextView) itemView.findViewById(R.id.transaction_child_txn_amount_tv);
                }
}

}


来源: stackexchange

问:
Grant access to private constructor without friends?
I am working on some code, where I encountered a situation similar to this one:

```<code>struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}
</code>```

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

答:
If you do not want to introduce another class, you can shrink the circle of friendship and make Bar's constructor Foo's friend. It requires Bar's definition to be available to Foo, and it still gives Bar's constructor unrestricted access to Foo's private implementation:

```<code>struct Foo;

struct Bar {
   Foo* f;
   Bar();
   ~Bar();
};

struct Foo{
    friend Bar::Bar();
private:
    Foo(){}
    void f(){}
    void g(){}
};

Bar::Bar() : f(new Foo()) {
}

Bar::~Bar() {
    delete f;
}
</code>```

This does not achieve exactly what you want, but it makes friendship a lot more targeted.

ContentLicense: CC BY-SA 3.0

Body:
I am working on some code, where I encountered a situation similar to this one:

struct Bar;

struct Foo{
    friend struct Bar;
private:
    Foo(){}
    void f(){}
    void g(){}
};

struct Bar {
   Foo* f;
   Bar()  { f = new Foo();}
   ~Bar() { delete f;}
};

int main(){
  Bar b;
}

I would prefer to have Bar not as friend of Foo, because besides Foos constructor Bar does not need access to any of Foos private methods (and thus should not have access). Is there a way to allow only Bar to create Foos without making them friends?

PS: realized that the question might not be 100% clear. I don't mind if it is via friends or not, just the fact that all Bar has access to all private methods is disturbing me (which is usually the case with friends) and that is what I want to avoid. Fortunately none of the answers given so far had a problem with that lousy formulation.

Body:
If you do not want to introduce another class, you can shrink the circle of friendship and make Bar's constructor Foo's friend. It requires Bar's definition to be available to Foo, and it still gives Bar's constructor unrestricted access to Foo's private implementation:

struct Foo;

struct Bar {
   Foo* f;
   Bar();
   ~Bar();
};

struct Foo{
    friend Bar::Bar();
private:
    Foo(){}
    void f(){}
    void g(){}
};

Bar::Bar() : f(new Foo()) {
}

Bar::~Bar() {
    delete f;
}

This does not achieve exactly what you want, but it makes friendship a lot more targeted.


问:
general-purpose binary protocols
I'm trying to find a suitable protocol middleware for my next distributed application. I've found several specifications in the last few days and was wondering if I missed an important one? It should be a binary protocol, support RPCs and optionally have open-source implementations in different languages. Here's the list of protocols I found:

CORBA

ICE

AMQP

Thrift

And this is the list of dismissed protocols:

XML based protocols because they are text based (XML-RCP, SOAP, hand-rolled, etc.)

Protocol Buffers (Closed Source)

COM (Windows-only)

答: Joe Armstrong's UBF doesn't seem to have caught on, but it satisfies your requirements with a tasteful design.</p>

ContentLicense: CC BY-SA 2.5

Title: general-purpose binary protocols

LastEditorDisplayName: zacherates

OwnerDisplayName: Darius Bacon


问:
How can I create a common file between JavaScript and C/C++ for a constant?
I have a C++ program with the following in the header file:
#define VARIABLE_X 100

Also, a JavaScript file with the global: VARIABLE_X = 100;

These values will always need to be the same.

Instead of having to change them in both places (.h and .js), I need a common file where both can get this value, thus only needing to be changed in one place.

How can I create a common file between JavaScript and C/C++........ for a #define/constant ?

Thank You.

答:
You have an actual script-driven build process, right?

Just stick a rule in your makefile that regenerates constants.h if constants.js has been changed.


问:
Method should have "self" as first argument: pylint error for decorator
I have a decorator function:

```<code>def abc(f):
    def _abc(self, *args, **kwargs):
        # some statements
        return f(self, *args, **kwargs)
    return _abc
</code>```

I am using pylint to solve linting errors. It is giving me error as:

Method should have "self" as first argument

I am not able to find the solution for this. Anyone know this error?

答: If I'm correctly picturing what you're trying to do, move the decorating function outside of the class and the apply it inside the class using the @-notation.</p>

Body:
I have a decorator function:

def abc(f):
    def _abc(self, *args, **kwargs):
        # some statements
        return f(self, *args, **kwargs)
    return _abc

I am using pylint to solve linting errors. It is giving me error as:

Method should have "self" as first argument

I am not able to find the solution for this. Anyone know this error?


问:
Cannot read property of undefined when using interpolation
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}
```

<p>And below code is my view:</p>

<pre class="lang-js prettyprint-override"><code><div class='table-responsive'>
    <table class='table'
        *ngIf='products && products.length'>
        <thead>
            <tr>
                <th>
                    <button class='btn btn-primary'>
                        Show Image
                    </button>
                </th>

                <th>Product</th>
                <th>Code</th>
                <th>Available</th>
                <th>Price</th>
                <th>5 Star Rating</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor='let product of products'></tr>
            <td></td>
            <td>{{ product.productName }}</td>
            <td>{{ product.productCode }}</td>
            <td>{{ product.releaseDate }}</td>
            <td>{{ product.price }}</td>
            <td>{{ product.starRating }}</td>

        </tbody>
    </table>

</div>
</code>```

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

答:
You don't need to close your
 there. Actually you "close" the ngFor loop on the same level and product is undefined. You have to close is after your  cells.

This works:

```<code><tbody>
    <tr *ngFor='let product of products'>
        <td></td>
        <td>{{ product.productName }}</td>
        <td>{{ product.productCode }}</td>
        <td>{{ product.releaseDate }}</td>
        <td>{{ product.price }}</td>
        <td>{{ product.starRating }}</td>
     </tr>
</tbody>
</code>```

Body:
I have put an effort before asking this question to search and make sure this question is not duplicated, but I didn't find anything similar to my issue.

I am newbie to Angular 2, and my component class is like below:

import {Component} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
 selector: 'pm-products',
 templateUrl: 'app/products/product-list.component.html'
})

export class ProductListComponent{
pageTitle: string = 'Product List';
products: any[] = [
    {
        "productId": 1,
        "productName": "Leaf Rake",
        "productCode": "GDN-0011",
        "releaseDate": "March 19, 2016",
        "description": "Leaf rake with 48-inch wooden handle.",
        "price": 19.95,
        "starRating": 3.2,
        "imageUrl": "SOME URL"
    },
    {
        "productId": 2,
        "productName": "Garden Cart",
        "productCode": "GDN-0023",
        "releaseDate": "March 18, 2016",
        "description": "15 gallon capacity rolling garden cart",
        "price": 32.99,
        "starRating": 4.2,
        "imageUrl": "SOME URL"
    }

    ];
}

And below code is my view:

                    <button class='btn btn-primary'>
                        Show Image
                    </button>

                Product
                Code
                Available
                Price
                5 Star Rating

            {{ product.productName }}
            {{ product.productCode }}
            {{ product.releaseDate }}
            {{ product.price }}
            {{ product.starRating }}

When I run this code I get an error saying "Error in app/products/product-list.component.html:38:16 caused by: Cannot read property 'productName' of undefined", and "Cannot read property 'productName' of undefined"

Using the interpolation in my view, my expectation is to see the products object properties values within the  tags.

Body:
You don't need to close your <tr> there. Actually you "close" the ngFor loop on the same level and product is undefined. You have to close is after your <td> cells.

This works:

<tbody>
    <tr *ngFor='let product of products'>
        <td></td>
        <td>{{ product.productName }}</td>
        <td>{{ product.productCode }}</td>
        <td>{{ product.releaseDate }}</td>
        <td>{{ product.price }}</td>
        <td>{{ product.starRating }}</td>
     </tr>
</tbody>


问:
Youtube Live Streaming API usage limitations
Youtube Live Streaming API has really thorough documentation, and I went through it as well as usage examples. Recently I started to get 403 error.

The full signature of the error is:

```<code>Error calling POST

https://www.googleapis.com/youtube/v3/liveBroadcasts?part=snippet%2Cstatus%2CcontentDetails:

(403) Request is not authorized
</code>```

And I can't find out the reason behind it. On a day start it was all working fine with a google account credentials and OAuth keys. Then after a few requests succeeded it went down with the 403. Same credentials and keys were used.

I strongly believe there are limitations in play, but which are this limitations or how to bypass them I can't help to find in docs or elsewhere.

the code goes like this (up to the breaking point):

```<code>$liveStreamingApi = new LiveStreamingApi();
$youtube = $liveStreamingApi->setLiveBroadcasts($returnUrl, null, LiveStreamingApi::CREATE);

$broadcastSnippet = new \Google_Service_YouTube_LiveBroadcastSnippet();
$broadcastSnippet->setTitle($model->name);

$broadcastSnippet->setScheduledStartTime(STARTTIME);
$broadcastSnippet->setIsDefaultBroadcast('1');

$status = new \Google_Service_YouTube_LiveBroadcastStatus();
$status->setPrivacyStatus($privacy);

$broadcastInsert = new \Google_Service_YouTube_LiveBroadcast();
$broadcastInsert->setSnippet($broadcastSnippet);
$broadcastInsert->setStatus($status);
$broadcastInsert->setKind('youtube#liveBroadcast');

$broadcastsResponse = $youtube->liveBroadcasts->insert('snippet,status,contentDetails', $broadcastInsert, array());
</code>```

where $liveStreamingApi->setLiveBroadcasts sets all the essential scopes in https (force-ssl, youtube, youtubepartner)
$youtube->liveBroadcasts->insert throws the aforementioned error

答:
There is a quota limitation on youtube API that limit your request that you can make in day. The default quota value it's 1000000 per day splitted for the whole day. however every API request cost a different number of quota points.If you pass your quota limit you'd get an error message that is insufficientLivePermissions.
you can check your quota usage here:
https://developers.google.com/youtube/v3/determine_quota_cost
however you can consider that a insert request cost about 1600 of quota.</p>

Body:
Youtube Live Streaming API has really thorough documentation, and I went through it as well as usage examples. Recently I started to get 403 error.

The full signature of the error is:

Error calling POST

https://www.googleapis.com/youtube/v3/liveBroadcasts?part=snippet%2Cstatus%2CcontentDetails:

(403) Request is not authorized

And I can't find out the reason behind it. On a day start it was all working fine with a google account credentials and OAuth keys. Then after a few requests succeeded it went down with the 403. Same credentials and keys were used.

I strongly believe there are limitations in play, but which are this limitations or how to bypass them I can't help to find in docs or elsewhere.

the code goes like this (up to the breaking point):

$liveStreamingApi = new LiveStreamingApi();
$youtube = $liveStreamingApi->setLiveBroadcasts($returnUrl, null, LiveStreamingApi::CREATE);

$broadcastSnippet = new \Google_Service_YouTube_LiveBroadcastSnippet();
$broadcastSnippet->setTitle($model->name);

$broadcastSnippet->setScheduledStartTime(STARTTIME);
$broadcastSnippet->setIsDefaultBroadcast('1');

$status = new \Google_Service_YouTube_LiveBroadcastStatus();
$status->setPrivacyStatus($privacy);

$broadcastInsert = new \Google_Service_YouTube_LiveBroadcast();
$broadcastInsert->setSnippet($broadcastSnippet);
$broadcastInsert->setStatus($status);
$broadcastInsert->setKind('youtube#liveBroadcast');

$broadcastsResponse = $youtube->liveBroadcasts->insert('snippet,status,contentDetails', $broadcastInsert, array());

where $liveStreamingApi->setLiveBroadcasts sets all the essential scopes in https (force-ssl, youtube, youtubepartner)
$youtube->liveBroadcasts->insert throws the aforementioned error


问:
Angular 2 Two-way Binding updates mock service constant
As I was going through the "Tour of Heroes" Angular 2 tutorial, I have noticed that when ngModel changes, the change propagates to other components utilizing the same object. But when I tried to log the mock service constant HEROES on the console, its value also changed.

mock-heroes.ts

```<code>import { Hero } from './shared/hero.model';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
];
</code>```

hero.service.ts

```<code>import { Injectable } from '@angular/core';
import { Hero } from './hero.model';
import { HEROES } from '../mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    console.log(HEROES); // print the constant HEROES value
    return Promise.resolve(HEROES);
  }
}
</code>```

hero-detail.component.html

```<code><div *ngIf="hero">
  <h2>{{hero.name}} details!</h2>
  <div><label>id: </label>{{hero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="hero.name" placeholder="name"/>
  </div>
</div>
</code>```

heroes.component.html

```<code><h3>My Heroes</h3>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>
<hero-detail [hero]="selectedHero"></hero-detail>
</code>```

heroes.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Hero } from './shared/hero.model';
import { HeroService } from './shared/hero.service';

@Component({
  selector: 'my-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes);
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}
</code>```

The HeroService is injected from the AppModule providers array (global service provider).

Changing the name from "Narco" to "Narcosssss" through the input:

updates the constant HEROES as seen on the console:

Can someone please explain to me how it works?

答: Your hero objects have  the same reference throughout your app. So, if you change the referenced object. The property will change wherever it's been referenced.

Body:
As I was going through the "Tour of Heroes" Angular 2 tutorial, I have noticed that when ngModel changes, the change propagates to other components utilizing the same object. But when I tried to log the mock service constant HEROES on the console, its value also changed.

mock-heroes.ts

import { Hero } from './shared/hero.model';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
];

hero.service.ts

import { Injectable } from '@angular/core';
import { Hero } from './hero.model';
import { HEROES } from '../mock-heroes';

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    console.log(HEROES); // print the constant HEROES value
    return Promise.resolve(HEROES);
  }
}

hero-detail.component.html

{{hero.name}} details!

id: {{hero.id}}

    name:
    <input [(ngModel)]="hero.name" placeholder="name"/>

heroes.component.html

My Heroes

    {{hero.id}} {{hero.name}}

<hero-detail [hero]="selectedHero"></hero-detail>

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from './shared/hero.model';
import { HeroService } from './shared/hero.service';

@Component({
  selector: 'my-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private heroService: HeroService) { }

  ngOnInit(): void {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .then(heroes => this.heroes = heroes);
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}

The HeroService is injected from the AppModule providers array (global service provider).

Changing the name from "Narco" to "Narcosssss" through the input:

updates the constant HEROES as seen on the console:

Can someone please explain to me how it works?


问:
TortoiseGit / Browse References: What does the Current Branch button do?
Seems to just exit the dialog.  Help doesn't say anything about it.

答: When the Browse References dialog is used to select a reference, the button is a shortcut to select the current branch. - If the browse references dialog is not opened for selection, the button just closes the dialog.</p>


问:
Check if value is available in a list or not along with available value
In SQL Server 2008, I have table with records like these,

```<code>Name
----
John
Amy
Peter
Jack
Alan
Linda
</code>```

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

```<code>Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null
</code>```

答:
You should just need a left (or right) join on your two tables, something like:</p>

```<code>select n.name, u.name
from names n
  left join users u on n.name=u.name
</code>```

Body:
In SQL Server 2008, I have table with records like these,

Name
----
John
Amy
Peter
Jack
Alan
Linda

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null

Body:
You should just need a left (or right) join on your two tables, something like:

select n.name, u.name
from names n
  left join users u on n.name=u.name


问:
How to validate password and confirm password field in Accelerated Mobile Pages (AMP)?
In amp-form POST method., how to validate password and confirm password field?

And also how to validate already exist username and email ID and show error message

答: AMP doesn't allow client side JS/JQuery, so you have to do server side validation after the form submission. </p>


问:
How to check if 2017-03-29T06:45:00.000Z is equal to the date and time now?
I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?

If I check with

```<code>var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){
</code>```

its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST)
Any input appreciated, thanks

答:
You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.

```<code>"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false
</code>```

You can just parse your date string to a Date object using Date.parse()

```<code>Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared
</code>```

Body:
I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?

If I check with

var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){

its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST)
Any input appreciated, thanks

Body:
You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.

"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false

You can just parse your date string to a Date object using Date.parse()

Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared


问:
Simplest way to read JSON from a URL in Java
This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it's a matter of few lines of code. Java examples that I find are ridiculously long (and have huge exception handling block).

All I want to do is to read the content of this link.

答:
Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

```<code>package so4308554;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

package so4308554;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonReader {

  private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
    System.out.println(json.toString());
    System.out.println(json.get("id"));
  }
}


问:
How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?
I want to downgrade php version from 7.1.1 to 5.6 in xampp 7.1.1. But I can't find any option.

答: Just delete this xampp, and download 5.6 version.</p>


问:
RSpec/Capybara - Testing a page for a table
Does anyone know what matcher I can use to check a page in capybara to see if it contains a html table? And then maybe a matcher to check if that table has specific content inside?

expect(page).to have_content(table)

anything like this? :s

答:
I hope this solution can help you. (I port a table_helpers.rb in spreewald library that using in cucumber.)

Here is my scenario:

```<code>scenario "table's data after click to sort with '会場名称'", js: true do
  screening_rooms = (1..5).each do |n|
     create :screening_room, m_branch_id: "#{n}", name: "name-#{n}"
  end
  visit screening_rooms_path
  within("table#common_list thead") do
    click_link "会場名称"
  end
  expected_table = <<-EOF
    |拠点|会場名称|会場住所|登録日時|更新日時| |
    | * |name-5 |*      |*     |*      |*|
    | * |name-4 |*      |*     |*      |*|
    | * |name-3 |*      |*     |*      |*|
    | * |name-2 |*      |*     |*      |*|
    | * |name-1 |*      |*     |*      |*|
  EOF

  document = Nokogiri::HTML(page.body)
  tables = document.xpath('//table').collect {|table| table.xpath('.//tr').collect {|row| row.xpath('.//th|td')}}
  parsed_table = parse_table(expected_table)
  tables.should contain_table(parsed_table)
end
</code>```

and my support/helpers/table_helpers.rb

table_helpers.rb

Body:
I hope this solution can help you. (I port a table_helpers.rb in spreewald library that using in cucumber.)

Here is my scenario:

scenario "table's data after click to sort with '会場名称'", js: true do
  screening_rooms = (1..5).each do |n|
     create :screening_room, m_branch_id: "#{n}", name: "name-#{n}"
  end
  visit screening_rooms_path
  within("table#common_list thead") do
    click_link "会場名称"
  end
  expected_table = <<-EOF
    |拠点|会場名称|会場住所|登録日時|更新日時| |
    | * |name-5 |*      |*     |*      |*|
    | * |name-4 |*      |*     |*      |*|
    | * |name-3 |*      |*     |*      |*|
    | * |name-2 |*      |*     |*      |*|
    | * |name-1 |*      |*     |*      |*|
  EOF

  document = Nokogiri::HTML(page.body)
  tables = document.xpath('//table').collect {|table| table.xpath('.//tr').collect {|row| row.xpath('.//th|td')}}
  parsed_table = parse_table(expected_table)
  tables.should contain_table(parsed_table)
end

and my support/helpers/table_helpers.rb

table_helpers.rb


问:
Cannot install @angular/cli
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

```<code>C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree
</code>```

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?

答:
Make sure.,you already installed nodejs.

npm install -g angular-cli

ng help

ng new PROJECT_NAME
cd PROJECT_NAME
ng serve

ng serve --host 0.0.0.0 --port 4201 --live-reload-port 49153

Title: Cannot install @angular/cli

Body:
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?


问:
PHP5 how to add simplexml?
When i check my phpinfo , it displays like below and i have to use  simplexml, but getting ;

"Fatal error: Call to undefined function simplexml_load_file()
  in..."

message.

disable-xml' '--disable-simplexml' '--disable-dom' '--disable-libxml' '--disable-xmlreader' '--disable-xmlwriter' '--disable-debug'

How can i enable simplexml ?

答:
Install:

```<code>apt-get install php-xml
</code>```

Check:

```<code>php -m | grep xml
</code>```

Restart:

```<code>service php5-fpm restart
</code>```

Title: PHP5 how to add simplexml?

Body:
Install:

apt-get install php-xml

Check:

php -m | grep xml

Restart:

service php5-fpm restart


问:
Second CSS class not applying to div
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="./css/main.css">
</head>

<div class="topheader">
  <h1>KivaGIS</h1>
</div>

<div class="footer">
  <h1>Footer</h1>
</div></code>```

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine

答:
As many on here pointed out, the code itself was fine. I did not realize that Chrome would cache the CSS file. I've spent all night updating the file without seeing any changes because Chrome was using an older version.

As you can see from the attached screencap, I disabled the cache and everything is working perfectly now.

Title: Second CSS class not applying to div

Body:
I'm attempting to break my html into separate php files and have an error I can't seem to crack. Here is the first file, index.php

.topheader {
  background-color: #404040;
  color: white;
  padding: 16px;
}

.footer {
  background-color: #404040;
  color: white;
  padding: 16px;
}

  <link rel="stylesheet" href="./css/main.css">

KivaGIS

Footer

As of right now, only .topheader is applying to the html. I understand that both classes are identical, I plan to expand on each once I confirm they are applying individually. Can someone please take a look and advise why .footer wouldn't be applying to the sheet?

Here is a sample of the output on my machine


问:
Doctrine2 (Symfony 2.8) connection to MS SQL Server 2016 Exp not working
I try to connect to a MS SQl Server 2016 Express with Doctrine(2.4.8) in Symfony(2.8.17).

OS: Windows 10 - 64 bit
 - Webserver: IIS 10

When I execute the statment:

php app/console doctrine:database:create

I get the following Message back:

[Doctrine\DBAL\Driver\SQLSrv\SQLSrvException]

SQLSTATE [08001, 10061]: [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made becaus
    e the target machine actively refused it.

SQLSTATE [HYT00, 0]: [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired

SQLSTATE [08001, 10061]: [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has
     occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance n
    ame is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Boo
    ks Online.

The SQL Server is on the same Maschine as the WebServer and the IDE.

I checked that it is possible to login on the DB with the DB-User I used in Doctrine. I also can create a connection when I manually build them in the ODBC Manager.

It's also possible to connect to the DB over Network.

Here are the connection parameters:

```<code>driver: sqlsrv
database_host: localhost\SQLEXPRESS
database_port: 1433
database_name: symfony
database_user: userdb
database_password: dbonepass
</code>```

THX and greetings Sitox

答:
I "solved" the problem. I build a new developer maschine with Win 10 64bit, Apache 2.4 and php 7. On the new maschine there is no problem to execute the statment to create a new Database.

Greetings

Body:
I try to connect to a MS SQl Server 2016 Express with Doctrine(2.4.8) in Symfony(2.8.17).

OS: Windows 10 - 64 bit
 - Webserver: IIS 10

When I execute the statment:

php app/console doctrine:database:create

I get the following Message back:

[Doctrine\DBAL\Driver\SQLSrv\SQLSrvException]

SQLSTATE [08001, 10061]: [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made becaus
    e the target machine actively refused it.

SQLSTATE [HYT00, 0]: [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired

SQLSTATE [08001, 10061]: [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has
     occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance n
    ame is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Boo
    ks Online.

The SQL Server is on the same Maschine as the WebServer and the IDE.

I checked that it is possible to login on the DB with the DB-User I used in Doctrine. I also can create a connection when I manually build them in the ODBC Manager.

It's also possible to connect to the DB over Network.

Here are the connection parameters:

driver: sqlsrv
database_host: localhost\SQLEXPRESS
database_port: 1433
database_name: symfony
database_user: userdb
database_password: dbonepass

THX and greetings Sitox


问:
What's a good way to generate a random number for a valid credit card?
I am developing a set of tools in Java for validating and working with credit cards. So far I have support for:

LUHN validation.

Date validation (simple expiration).

Card code length validation (CVV, CVC, CID) based on the brand (Visa, MasterCard, etc).

Credit card number length validation (based on the brand).

BIN/IIN validation (against a database of valid numbers).

Hiding the digits (425010 * * * * * * 1234)

To make the tool set a bit more complete, I would like to create a credit card random number generator based on the different card brands. This functionality will (hopefully) make my test cases a bit more reliable.

Basically, I would like to be able to generate numbers which are:

LUHN valid

Valid based on the brand prefixes

Valid based on the BIN/IIN prefix numbers

For BIN/IIN valid card numbers, I am thinking of looking up a random BIN/IIN number from the database (based on the brand of course) and then appending the remaining digits using Random. Obviously, that would not be valid most of the time and I will have to increment one of the digits until it passes the LUHN validation.

I can't seem to be able to think of a better way. Perhaps someone could suggest something a little smarter...?

Looking forward to your suggestions! Thanks in advance! :)

答:
Not so long ago I've authored a library called MockNeat. One of the features is to allow the developer to generate different valid credit card numbers.

Check this method: creditCards().

A short example to write 1000 Credit Cards AMEX and Mastercard in a file for later use:

```<code> MockNeat m = MockNeat.threadLocal();
    final Path path = Paths.get("cc.txt");

// Write in a file 1000 credit cards AMEX and Mastercard:
 m.creditCards()
            .types(MASTERCARD, AMERICAN_EXPRESS)
            .list(1000)
            .consume(list -> {
                try { Files.write(path, list, CREATE, WRITE); }
                catch (IOException e) { e.printStackTrace(); }
            });
</code>```

Body:
Not so long ago I've authored a library called MockNeat. One of the features is to allow the developer to generate different valid credit card numbers.

Check this method: creditCards().

A short example to write 1000 Credit Cards AMEX and Mastercard in a file for later use:

 MockNeat m = MockNeat.threadLocal();
    final Path path = Paths.get("cc.txt");

// Write in a file 1000 credit cards AMEX and Mastercard:
 m.creditCards()
            .types(MASTERCARD, AMERICAN_EXPRESS)
            .list(1000)
            .consume(list -> {
                try { Files.write(path, list, CREATE, WRITE); }
                catch (IOException e) { e.printStackTrace(); }
            });


问:
XPath of text from child element
I'm trying to get an XPath to select text from a web page. Upon inspecting element, I see this. I'm trying to get Florida State University. When I right-click to copy XPath, I get this:

```<code>//*[@id="clue_J_3_2"]/em
</code>```

However, when I run the python code:

```<code>from lxml import html
import requests
game_url = 'http://www.j-archive.com/showgame.php?game_id=5566'
page = requests.get(game_url)
tree = html.fromstring(page.content)
path = '//*[@id="clue_J_3_2"]/em'
print tree.xpath(path)
</code>```

the output I get is []. I have tried many variations including:

//*[@id="clue_J_3_2"]/em/text()

/*/[@id="clue_J_3_2"]/em

//*[@id="clue_J_3_2"]//em[@class="correct_response"]/text()

Please let me know how to fix my XPath to get the text I want!

答:
I have checked source code of this page, I found that some element is dynamically created by javascript, as request can only get HTML code, so this is why you get an empty result when using tree.xpath(path).

After I changed path to '//*[@id="clue_J_3_2"],I got some text.

Remember, if you want to use print , you should do like this : print tree.xpath(path)[0].text.

Title: XPath of text from child element

Body:
I'm trying to get an XPath to select text from a web page. Upon inspecting element, I see this. I'm trying to get Florida State University. When I right-click to copy XPath, I get this:

//*[@id="clue_J_3_2"]/em

However, when I run the python code:

from lxml import html
import requests
game_url = 'http://www.j-archive.com/showgame.php?game_id=5566'
page = requests.get(game_url)
tree = html.fromstring(page.content)
path = '//*[@id="clue_J_3_2"]/em'
print tree.xpath(path)

the output I get is []. I have tried many variations including:

//*[@id="clue_J_3_2"]/em/text()

/*/[@id="clue_J_3_2"]/em

//*[@id="clue_J_3_2"]//em[@class="correct_response"]/text()

Please let me know how to fix my XPath to get the text I want!


问:
How to put an image over the content of a div?
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

```<code>.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}
</code>```

and the HTML is not special but I put it:

```<code><template name="machine">
    <li class="liMachine switch">
        <div id="nameMachine">
            <h3>{{nameMachine}}</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">{{stateMachine}}</span>
        </div>
        {{#if isLocked}}
        <div>
          <img class="imgCadenas">
        </div>
        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}<i class="fa fa-spinner fa-spin"></i>
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}<i class="fa fa-spinner fa-spin"></i>
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}<i class="fa fa-spinner fa-spin"></i>{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}
    </li>
</template>
</code>```

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

答:
add the following to .imgCadenas class</p>

```<code>float: right;
</code>```

Body:
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}

and the HTML is not special but I put it:

<template name="machine">

{{nameMachine}}

            State:{{stateMachine}}

        {{#if isLocked}}

        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}

</template>

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

Body:
add the following to .imgCadenas class

float: right;


问:
SED expression for turning Yeseva+One into --font-yeseva-one: "Yeseva One";
I have a series of font values like this (Command separated one line):

```<code>Yeseva+One, Yrsa, ...
</code>```

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

```<code>--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";
</code>```

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

答:
With Pure Bash :</p>

```<code>IFS="[, ]" read -r -a list <<<"Yeseva+One, Yrsa"  #Convert values to array
for k in "${list[@]}";do
  k2="${k,,}" #The bash way to convert everything from upper to lower
  printf -- '--font-%s:\"%s\";\n' "${k2//+/-}" "${k//+/ }"  #bash way to replace strings
done
#Output
--font-yeseva-one:"Yeseva One";
--font-yrsa:"Yrsa";
</code>```

Body:
I have a series of font values like this (Command separated one line):

Yeseva+One, Yrsa, ...

I'm looking for a SED (Or other bash tool expression) for turn each value into line statements like this:

--font-yeseva-one: "Yeseva One";
--font-yrsa: "Yrsa";

Thoughts?

Update

Just wanted to say thanks for all the great help with this and if anyone needs google fonts as CSS variables / properties they are all available here (MIT License):
https://github.com/superfly-css/superfly-css-variables-fonts/blob/master/src/main/css/index.css

I'll also be providing utilities for using google fonts here:
https://github.com/superfly-css/superfly-css-utilities-fonts

Body:
With Pure Bash :

IFS="[, ]" read -r -a list <<<"Yeseva+One, Yrsa"  #Convert values to array
for k in "${list[@]}";do
  k2="${k,,}" #The bash way to convert everything from upper to lower
  printf -- '--font-%s:\"%s\";\n' "${k2//+/-}" "${k//+/ }"  #bash way to replace strings
done
#Output
--font-yeseva-one:"Yeseva One";
--font-yrsa:"Yrsa";


问:
Webpack definePlugin not setting/reading node_env variable
I'm having real issues injecting the node_env var into my code through Webpack's definePlugin and after reading numerous posts nothing seems to work. I have a feeling I'm missing something...

So my production webpack config is -

```<code>// Config
import path from 'path';
import webpack from 'webpack';
import config from './config';

/**
 * Webpack config for compiling the
 * React/Redux/ES6 scripts.
 *
 * ENV = production
 *
 * @type {Object}
 */
module.exports = {
    entry: path.resolve(__dirname, '../', config.assets.scripts.src_dir, config.assets.scripts.entry),
    devtool: false,
    output: {
        path: path.resolve(__dirname, config.assets.scripts.dist_dir),
        filename: config.assets.scripts.dist_min
    },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0',
                exclude: /node_modules/
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({})
    ]
};
</code>```

I've tried setting alias's for react, react-dom and react-redux with absolutely no avail, React still warns me i'm using a minified version outside of node_env=production (Also redux still throws me this error).

FYI, i'm using webpack version 2.2.1.

Is it something to do with the babel-loader conflicting in some way? If anyone can point me in the right direction that would be great.

答:
Try changing your DefinePlugin for NODE_ENV to this one -

```<code>plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV' : JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin({
        minimize : true,
        compress : {
            warnings : false
        }
    })
]
</code>```

Body:
I'm having real issues injecting the node_env var into my code through Webpack's definePlugin and after reading numerous posts nothing seems to work. I have a feeling I'm missing something...

So my production webpack config is -

// Config
import path from 'path';
import webpack from 'webpack';
import config from './config';

/**
 * Webpack config for compiling the
 * React/Redux/ES6 scripts.
 *
 * ENV = production
 *
 * @type {Object}
 */
module.exports = {
    entry: path.resolve(__dirname, '../', config.assets.scripts.src_dir, config.assets.scripts.entry),
    devtool: false,
    output: {
        path: path.resolve(__dirname, config.assets.scripts.dist_dir),
        filename: config.assets.scripts.dist_min
    },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0',
                exclude: /node_modules/
            },
            {
                test: /\.json$/,
                loader: 'json-loader'
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }
        }),
        new webpack.optimize.UglifyJsPlugin({})
    ]
};

I've tried setting alias's for react, react-dom and react-redux with absolutely no avail, React still warns me i'm using a minified version outside of node_env=production (Also redux still throws me this error).

FYI, i'm using webpack version 2.2.1.

Is it something to do with the babel-loader conflicting in some way? If anyone can point me in the right direction that would be great.

Body:
Try changing your DefinePlugin for NODE_ENV to this one -

plugins: [
    new webpack.DefinePlugin({
        'process.env.NODE_ENV' : JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin({
        minimize : true,
        compress : {
            warnings : false
        }
    })
]


问:
Is DROP CONSTRAINT of default values a size of data operation
If I have a table with some values in it and I
ALTER TABLE [table_name] ADD [column_name] BIGINT NOT NULL CONSTRAINT [default_constraint] DEFAULT (1). This won't be a size of data operation as the default value will be stored once and referenced in each existing row in the new column.

But what if I decide later to drop the [default_constraint]? Will that become a size of data operation?

答:
ALTER TABLE [table_name] ADD [column_name] BIGINT NOT NULL CONSTRAINT [default_constraint] DEFAULT (1). This won't be a size of data operation as the default value will be stored once and referenced in each existing row in the new column.

This is incorrect. SQL Server has to alter every existing row and physically store a copy of the default value in every row. When a table has a default constraint (after any operation which adds it), the constraint is used only at INSERT time - it doesn't treat the defaulted value differently or try to optimize storage by only storing one instance of the value across the whole table.

Conversely, just dropping the constraint is a metadata-only operation, since it doesn't alter the existing values that are already stored in the rows.


问:
Cycle image caption doesn't work
I've cycle slideshow gallery and I put a caption on my images but there is something wrong why I don't understand..Only my attribute name showing on my caption I don't want to attribute name I want to get attribute value what's wrong with me ?

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{data-caption}}",
    pauseOnHover: true,
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}</code>```

```

答:
It seems that captionTemplate has to be set to an attribute of the top level element, the slide, in this case, the a element.

This seems to work.

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{target}}",
    pauseOnHover: true,
  });
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}</code>```

```

It doesn't seem to work with custom attributes, that is why I've used target. If you don't wrap your images in a elements, you could use the image's alt attribute, that will be more appropriate.

Title: Cycle image caption doesn't work

Body:
I've cycle slideshow gallery and I put a caption on my images but there is something wrong why I don't understand..Only my attribute name showing on my caption I don't want to attribute name I want to get attribute value what's wrong with me ?

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{data-caption}}",
    pauseOnHover: true,
  });
})

.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}

Body:
It seems that captionTemplate has to be set to an attribute of the top level element, the slide, in this case, the a element.

This seems to work.

$(document).ready(function() {

  $('.mySlideShow').cycle({
    log: false,
    fx: 'fade',
    slides: ">a",
    caption: '.cycle-caption',
    captionTemplate: "{{target}}",
    pauseOnHover: true,
  });
})

.slide-gallery {
  position: relative;
  width: 790px;
  overflow: hidden;
  height: 500px;
}

.slide-gallery img {
  max-width: 100%;
  height: 100%;
}

.cycle-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, .8);
  padding: 10px;
  color: #FFF;
  z-index: 1000;
  width: 100%;
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.cycle2/2.1.6/jquery.cycle2.min.js"></script>

<div class="slide-gallery">
  <div class="mySlideShow">

    <a target="Lorem ipsum dolor sit amet..">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/dandelion-lightbox.jpg">
    </a>
    <a target="This is my caption....">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/daffodil-flowers-lightbox.jpg">
    </a>
    <a target="bla.....">
      <img src="https://amazingcarousel.com/wp-content/uploads/amazingcarousel/7/images/lightbox/tulips-lightbox.jpg">
    </a>
  </div>

  <div class="cycle-caption"></div>
</div>

It doesn't seem to work with custom attributes, that is why I've used target. If you don't wrap your images in a elements, you could use the image's alt attribute, that will be more appropriate.


问:
What's wrong with the for() loop in my case?
I'm a beginner in Java and HBase, I want to shorten my code so I use a for-loop in my code. If the input String stumber is "AAAA0000?0", the results should be "AAAA000000","AAAA000010","AAAA000020","AAAA000030" …… "AAAA000090"

This origin code works well:

```<code>    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
        get = new Get((stumber.replace(stumber.charAt(8), '0')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '1')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '2')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '3')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '4')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '5')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '6')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '7')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '8')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '9')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);
</code>```

But after I modify with for-loop, the code failed to give out the results. Why?

```<code>    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
            for (int i =0; i<10; i++){
                get = new Get((stumber.replace(stumber.charAt(8), 'i')).getBytes());
                get.setMaxVersions(versions);
                gets.add(get);
            }
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);
</code>```

答:
Inside for loop should be:

```<code>get = new Get((stumber.replace(stumber.charAt(8), (char)(i + '0'))).getBytes());
</code>```

what gives you i value as a char.

Body:
I'm a beginner in Java and HBase, I want to shorten my code so I use a for-loop in my code. If the input String stumber is "AAAA0000?0", the results should be "AAAA000000","AAAA000010","AAAA000020","AAAA000030" …… "AAAA000090"

This origin code works well:

    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
        get = new Get((stumber.replace(stumber.charAt(8), '0')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '1')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '2')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '3')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '4')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '5')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '6')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '7')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '8')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        get = new Get((stumber.replace(stumber.charAt(8), '9')).getBytes());
        get.setMaxVersions(versions);
        gets.add(get);
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);

But after I modify with for-loop, the code failed to give out the results. Why?

    List<Get> gets = new ArrayList<>();
    for (String stumber : stumbersArr) {
        if(stumber.charAt(8) == '?'){
            for (int i =0; i<10; i++){
                get = new Get((stumber.replace(stumber.charAt(8), 'i')).getBytes());
                get.setMaxVersions(versions);
                gets.add(get);
            }
        }else{
            get = new Get(stumber.trim().getBytes());
            get.setMaxVersions(versions);
            gets.add(get);
        }
    }
    Result[] results = table.get(gets);

Body:
Inside for loop should be:

get = new Get((stumber.replace(stumber.charAt(8), (char)(i + '0'))).getBytes());

what gives you i value as a char.


问:
JQuery How do I pass a variable in
I have already asked a similar question, but let me try with a sligthly reworded piece of code.
In the code as below, how do I define a general case $('.add_field_button_sub_'+x), instead than several single cases $('.add_field_button_sub_0'), $('.add_field_button_sub_1'), ...
(Yes, I know, I miss some basic understanding on how JS works, please help anyway)

<title> test </title>

TEST

    <button class="add_field_button">Fonti</button>

```

答:
You could use jQuery's attribute contains selector. This will match all button elements having a class that contains add_field_button_sub_:

```<code>$("button[class*='add_field_button_sub_']")
</code>```

Note that it might make more sense to give all your buttons the same class and do your insert operations relative to the current element (referenced by $(this) in e.g. the click callback).

Title: JQuery How do I pass a variable in

Body:
You could use jQuery's attribute contains selector. This will match all button elements having a class that contains add_field_button_sub_:

$("button[class*='add_field_button_sub_']")

Note that it might make more sense to give all your buttons the same class and do your insert operations relative to the current element (referenced by $(this) in e.g. the click callback).


问:
javascript focus search form on keydown ? (question mark)
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

```<code><form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>
</code>```

答:
Check this code.

Create an object to store the keypress and add an eventListener which add each key press to the Object.

Then check for the keyCodes Shift(16) and /(191)

var map = {}; //to store the keycodes
onkeydown = onkeyup = function(e){
    e = e || event;

    map[e.keyCode] = e.type == 'keydown';

    if(map["16"]==true && map["191"]==true){  // 16 => shift and 191 /
      e.preventDefault();
      var elm=document.getElementById('inputMessage');
      elm.focus();

    }
    /* insert conditional here */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form></code>```

Body:
How do I focus search form input field when these two keys are pressed using Javascript?

shift + / will generate the ?

So basically, on keydown for question mark, the search form gets autofocus.

Here is my current bootstrap 3 search form code:

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">

        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">

    <button type="submit" class="btn btn-default"></button>
</form>

Body:
Check this code.

Create an object to store the keypress and add an eventListener which add each key press to the Object.

Then check for the keyCodes Shift(16) and /(191)

var map = {}; //to store the keycodes
onkeydown = onkeyup = function(e){
    e = e || event;

    map[e.keyCode] = e.type == 'keydown';

    if(map["16"]==true && map["191"]==true){  // 16 => shift and 191 /
      e.preventDefault();
      var elm=document.getElementById('inputMessage');
      elm.focus();

    }
    /* insert conditional here */
}

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>


问:
Query to get name from a table with 2 ID columns
I have 2 tables. The first has a structure like

```<code>id (int)
parent_id (int)
category_name (varchar)
</code>```

The second has a structure like:

```<code>id (int)
old_category (int)
new_category (int)
</code>```

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

答:
I will take a guess at what you meant:

tblOne

id

cat_name

tblTwo

id

tblOneId (old_cat) int

new_cat int

```<code>select * from tblOne t1, tblTwo t2 Where t1.id = t2.tblOneId
</code>```

Body:
I have 2 tables. The first has a structure like

id (int)
parent_id (int)
category_name (varchar)

The second has a structure like:

id (int)
old_category (int)
new_category (int)

I want to make a query to pull the old category and new category names all in one query for the parents. That is, I want to get the name of the old parent, then get the name of the new parent. The second table contains a historical list of all the parent ID changes made in the first table. How can I do this? Thanks!

Body:
I will take a guess at what you meant:

tblOne

id

cat_name

tblTwo

id

tblOneId (old_cat) int

new_cat int

select * from tblOne t1, tblTwo t2 Where t1.id = t2.tblOneId


问:
Not able to display google maps on VS 2015 using angular 2
this is my component:

```<code> import { Component } from '@angular/core';
 @Component({
selector: 'my-app',
styles: [`.sebm-google-map-container {
 height: 300px;}`],
template: `<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
 </sebm-google-map>`})
</code>```

just a simple example to display the map. But all this does is display the content in the (my-app) tag.

and the module is :

```<code>import { AgmCoreModule } from 'angular2-google-maps/core';
@NgModule({
imports: [
    .
    .
    .
    AgmCoreModule.forRoot({
        apiKey: 'MY_API_KEY'
    })
],
</code>```

the value of lat and lang i'm getting from AppComponent.

```<code>export class AppComponent {
title: string = 'My first angular2-google-maps project';
lat: number = 51.678418;
lng: number = 7.809007;}
</code>```

I have been successful in implementing this same code using console(angular2 cli) but when I tried this using Visual Studio 2015 it is not displaying the maps. To be specific it only shows the content in the anchor tag in index.html.

plus I would to mention I am to able to run angular2 Quickstart on VS 2015.

If anyone can point out what I am doing wrong or have some suggestion it would be really helpful.

答: Solution to this was just downgrading the version of angular2-google-maps in project.json from 0.17.0 to 0.16.0.  </p>

Body:
this is my component:

 import { Component } from '@angular/core';
 @Component({
selector: 'my-app',
styles: [`.sebm-google-map-container {
 height: 300px;}`],
template: `<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
 </sebm-google-map>`})

just a simple example to display the map. But all this does is display the content in the (my-app) tag.

and the module is :

import { AgmCoreModule } from 'angular2-google-maps/core';
@NgModule({
imports: [
    .
    .
    .
    AgmCoreModule.forRoot({
        apiKey: 'MY_API_KEY'
    })
],

the value of lat and lang i'm getting from AppComponent.

export class AppComponent {
title: string = 'My first angular2-google-maps project';
lat: number = 51.678418;
lng: number = 7.809007;}

I have been successful in implementing this same code using console(angular2 cli) but when I tried this using Visual Studio 2015 it is not displaying the maps. To be specific it only shows the content in the anchor tag in index.html.

plus I would to mention I am to able to run angular2 Quickstart on VS 2015.

If anyone can point out what I am doing wrong or have some suggestion it would be really helpful.


问:
Why doesn't the value change in Java
I just thought of this question: Using Java

```<code>int x = 1
int y = x;
x = 5;
</code>```

why doesn't y = 5 now?

答:
```<code>int x = 1; //Some memory is initialized(say at location ox00001) and x is pointing to that

int y = x ; //Some memory is initialized(say at location ox00050) and value of x is copied to that memory

x = 5 ; //value of memory location of x (i.e. ox00001) is changed to 5 but is not impacting memory location of y
</code>```

But in case of Non-Primitive data type it shares memory location instead of data.
For reference http://javarevisited.blogspot.in/2015/09/difference-between-primitive-and-reference-variable-java.html

Title: Why doesn't the value change in Java

Body:
I just thought of this question: Using Java

int x = 1
int y = x;
x = 5;

why doesn't y = 5 now?

Body:
int x = 1; //Some memory is initialized(say at location ox00001) and x is pointing to that

int y = x ; //Some memory is initialized(say at location ox00050) and value of x is copied to that memory

x = 5 ; //value of memory location of x (i.e. ox00001) is changed to 5 but is not impacting memory location of y

But in case of Non-Primitive data type it shares memory location instead of data.
For reference http://javarevisited.blogspot.in/2015/09/difference-between-primitive-and-reference-variable-java.html


问:
select from one database and update into another with matching rows
select a database values and update into another database with same id :
 where the error i getting is
Trying to get property of non-object
how can i achieve it is there any solution ??</p>

```<code>   $servername = "localhost";
   $username = "root";
   $password = "pass";
   $dbname = "db1";
   $dbname2="db2";

   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
   }

   $conn2 = new mysqli($servername, $username, $password, $dbname2);

   if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
   }

   $sql = "SELECT * FROM affiliates";
   $result = $conn->query($sql);

   if ($result->num_rows > 0) {
   //output data of each row

      while($row = $result->fetch_assoc()) {
            echo "from db1 id: " . $row["id"]. "publish " .$row["publishinsuppliercontants"]. "<br>";

      $sql2 = "UPDATE a1_affilates_cstm SET publish_in_supplier_contacts_c=".$row["publishinsuppliercontants"]." WHERE id_c=".$row["id"]."";
     $result2 = $conn2->query($sql2);

    $sql2 = "SELECT * FROM a1_affilates_cstm WHERE id_c = ". $row["id"]."";

    $result2=mysqli_query($conn2,$sql2) or die mysqli_error($conn2);
    $row1 = mysqli_fetch_array($result2);
   ///check whether inserted ...
           echo "from db2 id: " . $row1["id_c"]. " - publish: ".row1["publish_in_supplier_contacts_c"]. " <br>";

       }
   } else {
       echo "0 results";
   }
</code>```

答:
It looks like you don't get the result object. Is the SELECT query was successfully ?

You need to check the select query state/result before make operation with result object.

For example in your case:

```<code>$sql = "SELECT * FROM affiliates";
if ( $result = $conn->query($sql) ) {
  if ($result->num_rows > 0) {
     ... some logic ...
</code>```

From PHP mysqli manual:

"Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE."

Body:
select a database values and update into another database with same id :
 where the error i getting is
Trying to get property of non-object
how can i achieve it is there any solution ??

   $servername = "localhost";
   $username = "root";
   $password = "pass";
   $dbname = "db1";
   $dbname2="db2";

   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
   }

   $conn2 = new mysqli($servername, $username, $password, $dbname2);

   if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
   }

   $sql = "SELECT * FROM affiliates";
   $result = $conn->query($sql);

   if ($result->num_rows > 0) {
   //output data of each row

      while($row = $result->fetch_assoc()) {
            echo "from db1 id: " . $row["id"]. "publish " .$row["publishinsuppliercontants"]. "
";

      $sql2 = "UPDATE a1_affilates_cstm SET publish_in_supplier_contacts_c=".$row["publishinsuppliercontants"]." WHERE id_c=".$row["id"]."";
     $result2 = $conn2->query($sql2);

    $sql2 = "SELECT * FROM a1_affilates_cstm WHERE id_c = ". $row["id"]."";

    $result2=mysqli_query($conn2,$sql2) or die mysqli_error($conn2);
    $row1 = mysqli_fetch_array($result2);
   ///check whether inserted ...
           echo "from db2 id: " . $row1["id_c"]. " - publish: ".row1["publish_in_supplier_contacts_c"]. "
";

       }
   } else {
       echo "0 results";
   }

Body:
It looks like you don't get the result object. Is the SELECT query was successfully ?

You need to check the select query state/result before make operation with result object.

For example in your case:

$sql = "SELECT * FROM affiliates";
if ( $result = $conn->query($sql) ) {
  if ($result->num_rows > 0) {
     ... some logic ...

From PHP mysqli manual:

"Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE."


问:
Check if value is available in a list or not along with available value
In SQL Server 2008, I have table with records like these,

```<code>Name
----
John
Amy
Peter
Jack
Alan
Linda
</code>```

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

```<code>Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null
</code>```

答:
You could do the following:

```<code>CREATE TABLE #tmpNames (UserName varchar(10));

INSERT INTO #tmpNames
VALUES ('John'), ('Adam'), ('Amy'), ('Frank');

SELECT t.UserName AS Name, myTable.Name AS Available
FROM #tmpNames t
LEFT OUTER JOIN myTable m ON t.UserName = m.name
</code>```

Edit: The solution assumes that names in the table and the list are unique; otherwise, there is the potential for duplicate rows in the results.

Body:
In SQL Server 2008, I have table with records like these,

Name
----
John
Amy
Peter
Jack
Alan
Linda

I have another list of user ('John', 'Adam', 'Amy', 'Frank')
How do I check that which user in list is in table and not, without creating temp table

Expected output table

Name   Available
----   ---------
John   John
Adam   Null
Amy    Amy
Frank  Null

Body:
You could do the following:

CREATE TABLE #tmpNames (UserName varchar(10));

INSERT INTO #tmpNames
VALUES ('John'), ('Adam'), ('Amy'), ('Frank');

SELECT t.UserName AS Name, myTable.Name AS Available
FROM #tmpNames t
LEFT OUTER JOIN myTable m ON t.UserName = m.name

Edit: The solution assumes that names in the table and the list are unique; otherwise, there is the potential for duplicate rows in the results.


问:
using collapsing Toolbar with tabhost
I am using a Toolbar that is collapsible and a Tabhost having 3 tabs. But unfortunately, the Tabhost is overlaying the Toolbar. I want the Tabhost just below the Toolbar.

MainActivity.java

```<code>package com.chandra.user.newstrailerapp.app;

import android.app.LocalActivityManager;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TabHost;

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
    toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, false);
    mLocalActivityManager.dispatchCreate(savedInstanceState);
    tabHost.setup(mLocalActivityManager);

    //RecycleVIew
    RecyclerView recyclerView=(RecyclerView)findViewById(R.id.list);
    recyclerView.setHasFixedSize(true);

    //to use RecycleView, you need a layout manager. default is LinearLayoutManager
    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);
    YoutubecardAdapter adapter=new YoutubecardAdapter(MainActivity.this);
    recyclerView.setAdapter(adapter);

}
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.chandra.user.newstrailerapp.app.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/red"
        android:id="@+id/toolbar"
        app:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:layout_scrollFlags="scroll|enterAlways">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/tabhost">

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:orientation="vertical"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">

            <RelativeLayout
                android:id="@+id/tab1"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list1">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/tab2"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list2">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/tab3"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list3">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

        </FrameLayout>

    </LinearLayout>

</TabHost>

</android.support.design.widget.CoordinatorLayout>
</code>```

Also here the screenshot

Screenshot of MainActivity

答:
add android:layout_gravity="bottom" to your AppBarLayout

and android:gravity="top" to your toolbar

Title: using collapsing Toolbar with tabhost

Body:
I am using a Toolbar that is collapsible and a Tabhost having 3 tabs. But unfortunately, the Tabhost is overlaying the Toolbar. I want the Tabhost just below the Toolbar.

MainActivity.java

package com.chandra.user.newstrailerapp.app;

import android.app.LocalActivityManager;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TabHost;

public class MainActivity extends AppCompatActivity {

Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
    toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, false);
    mLocalActivityManager.dispatchCreate(savedInstanceState);
    tabHost.setup(mLocalActivityManager);

    //RecycleVIew
    RecyclerView recyclerView=(RecyclerView)findViewById(R.id.list);
    recyclerView.setHasFixedSize(true);

    //to use RecycleView, you need a layout manager. default is LinearLayoutManager
    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);
    YoutubecardAdapter adapter=new YoutubecardAdapter(MainActivity.this);
    recyclerView.setAdapter(adapter);

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.chandra.user.newstrailerapp.app.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/red"
        android:id="@+id/toolbar"
        app:theme="@style/ThemeOverlay.AppCompat.Dark"
        app:layout_scrollFlags="scroll|enterAlways">

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/tabhost">

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:orientation="vertical"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent">

            <RelativeLayout
                android:id="@+id/tab1"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list1">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/tab2"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list2">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

            <RelativeLayout
                android:id="@+id/tab3"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/list3">

                </android.support.v7.widget.RecyclerView>

            </RelativeLayout>

        </FrameLayout>

    </LinearLayout>

</TabHost>

</android.support.design.widget.CoordinatorLayout>

Also here the screenshot

Screenshot of MainActivity