答:
EDIT: With regard to your comment, it sounds like you want to load a different slideshow depending on the day of the week.

Here's a simple generic example of how it could be done.

```<code>  // Insert the code that loads the individual slideshows in the functions below
var slideshows = [
    function() { /* insert code to load some slideshow */ },
    function() { /* insert code to load some other slideshow */ },
    function() { /* insert code to load a different slideshow */ },
    function() { /* insert code to load yet another slideshow */ }
];
  // call a slideshow function depending on the day of week
slideshows[ new Date().getDate() % slideshows.length ]();
</code>```

This will call a different function from the Array depending on the day of week. You don't need seven of them. It will automatically rotate.

There are other ways to approach this, but I'd need to see how the slideshows are set up. This is a simple approach.

If you have more than 7 different slideshows, it will need to be changed a bit.

EDIT: This answer assumes you meant different per day of week. Not sure if that was your intention.

This is probably better than my original answer since it doesn't require loading all the banners.

javascript only version

Example: http://jsfiddle.net/patrick_dw/5drgu/4/

```<code>var banners = [
    "http://dummyimage.com/120x90/f00/fff.png&text=my+image",
    "http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
    "http://dummyimage.com/120x90/00f/fff.png&text=my+image",
    "http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
    ];
var banner = new Image();
banner.src = banners[ new Date().getDate() % banners.length ];
document.getElementById('container').appendChild( banner );
</code>```

jQuery version

Example: http://jsfiddle.net/patrick_dw/5drgu/7/

(changed it a bit so it doesn't start with an empty )

```<code>var banners = [
    "http://dummyimage.com/120x90/f00/fff.png&text=my+image",
    "http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
    "http://dummyimage.com/120x90/00f/fff.png&text=my+image",
    "http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
    ];
var banner =  $('<img>', { src:banners[ new Date().getDate() % banners.length ]})
                          .appendTo('#container');
</code>```

html

```<code><div id='container'></div>
</code>```

Original answer:

<s>
Here's one way:

Example: http://jsfiddle.net/patrick_dw/5drgu/

```<code>var banners = $('#container img').hide();
banners.eq( new Date().getDate() % banners.length ).show();
</code>```

html

```<code><div id='container'>
   <img src = "http://dummyimage.com/120x90/f00/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/0f0/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/00f/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/ff0/fff.png&text=my+image" />
</div>
</code>```

</s>

Title: using javascript/jQuery to show certain elements on certain dates?

Body:
Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.

My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.

Any help/ideas are appreciated :)

-Wayne

Body:
EDIT: With regard to your comment, it sounds like you want to load a different slideshow depending on the day of the week.

Here's a simple generic example of how it could be done.

  // Insert the code that loads the individual slideshows in the functions below
var slideshows = [
    function() { /* insert code to load some slideshow */ },
    function() { /* insert code to load some other slideshow */ },
    function() { /* insert code to load a different slideshow */ },
    function() { /* insert code to load yet another slideshow */ }
];
  // call a slideshow function depending on the day of week
slideshows[ new Date().getDate() % slideshows.length ]();

This will call a different function from the Array depending on the day of week. You don't need seven of them. It will automatically rotate.

There are other ways to approach this, but I'd need to see how the slideshows are set up. This is a simple approach.

If you have more than 7 different slideshows, it will need to be changed a bit.

EDIT: This answer assumes you meant different per day of week. Not sure if that was your intention.

This is probably better than my original answer since it doesn't require loading all the banners.

javascript only version

Example: http://jsfiddle.net/patrick_dw/5drgu/4/

var banners = [
    "http://dummyimage.com/120x90/f00/fff.png&text=my+image",
    "http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
    "http://dummyimage.com/120x90/00f/fff.png&text=my+image",
    "http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
    ];
var banner = new Image();
banner.src = banners[ new Date().getDate() % banners.length ];
document.getElementById('container').appendChild( banner );

jQuery version

Example: http://jsfiddle.net/patrick_dw/5drgu/7/

(changed it a bit so it doesn't start with an empty <img>)

var banners = [
    "http://dummyimage.com/120x90/f00/fff.png&text=my+image",
    "http://dummyimage.com/120x90/0f0/fff.png&text=my+image",
    "http://dummyimage.com/120x90/00f/fff.png&text=my+image",
    "http://dummyimage.com/120x90/ff0/fff.png&text=my+image"
    ];
var banner =  $('<img>', { src:banners[ new Date().getDate() % banners.length ]})
                          .appendTo('#container');

html

<div id='container'></div>

Original answer:

<s>
Here's one way:

Example: http://jsfiddle.net/patrick_dw/5drgu/

var banners = $('#container img').hide();
banners.eq( new Date().getDate() % banners.length ).show();

html

<div id='container'>
   <img src = "http://dummyimage.com/120x90/f00/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/0f0/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/00f/fff.png&text=my+image" />
   <img src = "http://dummyimage.com/120x90/ff0/fff.png&text=my+image" />
</div>

</s>


来源: stackexchange

问:
Duplicate declaration error. Assembly
I'm using masm and dosbox. In my program I have 3 procedures similar to the proc down_left (below). In each of these 4 proc are used the same names:  "down_edge, right_edge, left_edge, up_edge, corner, done, next, normal, czykrawedzboczna".

How can I make these names local for each proc?
I tried something like "LOCAL down_edge, right_edge, ....". But it doesn't work.

```<code>proc down_left
    pusha
    LOCAL down_edge, right_edge, left_edge, up_edgelcorner, done, next, normal, czykrawedzboczna
    mov ah,es:[bishop]      ;x - biskupa
    mov al,es:[bishop+1]    ;y - biskupa

    cmp ah,0
    jne next
        cmp al,8
        je done
    next:

    cmp al,8
    je down_edge            ; dolna krawedz

    cmp ah,0                     ;Czy x=0, y<{0,1,2,3,4,5,6,7,8}
    jne normal
        mov cl,0
        czykrawedzboczna:            ;lewa krawedz
            cmp al,cl
            je left_edge
            add cl,1
            cmp cl,8
            ja normal
       jmp czykrawedzboczna

    normal:
        dec ah
        dec al
        jmp done

    down_edge:
        dec ah
        jmp done
    left_edge:
        dec al
        jmp done

    done:
        xor bx,bx
        mov bl,nr ah al
        inc es:[tablica+bx]
        mov es:[bishop],ah      ;x - biskupa  ZAPISZ BIERZACE POLOZENIE BISKUPA
        mov es:[bishop+1],al    ;y - biskupa
    popa
    ret
down_left  endp
</code>```

答:
Labels in newer MASM (>=6) are local between PROC and ENDP. Older MASM need additionally a langtype in the .MODEL directive, e.g. .MODEL small, C.

Emu8086 doesn't provide local "procedure"-labels. You could tricky work with macros, but I advise against it

Regarding debugging in DOSBox, google for "turbo debugger".

ContentLicense: CC BY-SA 3.0

Title: Duplicate declaration error. Assembly

Body:
I'm using masm and dosbox. In my program I have 3 procedures similar to the proc down_left (below). In each of these 4 proc are used the same names:  "down_edge, right_edge, left_edge, up_edge, corner, done, next, normal, czykrawedzboczna".

How can I make these names local for each proc?
I tried something like "LOCAL down_edge, right_edge, ....". But it doesn't work.

proc down_left
    pusha
    LOCAL down_edge, right_edge, left_edge, up_edgelcorner, done, next, normal, czykrawedzboczna
    mov ah,es:[bishop]      ;x - biskupa
    mov al,es:[bishop+1]    ;y - biskupa

    cmp ah,0
    jne next
        cmp al,8
        je done
    next:

    cmp al,8
    je down_edge            ; dolna krawedz

    cmp ah,0                     ;Czy x=0, y<{0,1,2,3,4,5,6,7,8}
    jne normal
        mov cl,0
        czykrawedzboczna:            ;lewa krawedz
            cmp al,cl
            je left_edge
            add cl,1
            cmp cl,8
            ja normal
       jmp czykrawedzboczna

    normal:
        dec ah
        dec al
        jmp done

    down_edge:
        dec ah
        jmp done
    left_edge:
        dec al
        jmp done

    done:
        xor bx,bx
        mov bl,nr ah al
        inc es:[tablica+bx]
        mov es:[bishop],ah      ;x - biskupa  ZAPISZ BIERZACE POLOZENIE BISKUPA
        mov es:[bishop+1],al    ;y - biskupa
    popa
    ret
down_left  endp


问:
How to update mongoose schema?
just started learning mongodb, currently i have this schema

```<code>var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
    type: Date,
    default: Date.now
}});
</code>```

and i wanted to update it to be like this, but currently its not working right now, when i checked it on the mongo console the schema is still the old one

```<code>var BlogSchema = new mongoose.Schema({
        title: String,
        image: String,
        body: String,
        created: {
            type: Date,
            default: Date.now
        },
        author: {
            id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User"
            },
            username: String
        }
    });
</code>```

this is the best i've come up with after reading this post, but it throw me an error TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays.

```<code>var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: {
           type: String,
           required: true,
           default: null
        }
    }
});
</code>```

答:
You can't use Schema like that instead just make another authorSchema and use it as array.

```<code>var mongoose = require('mongoose');

var authorSchema = new mongoose.Schema({
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    username: {
        type: String,
        required: true,
    }
})

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: [authorSchema]
})
</code>```

Title: How to update mongoose schema?

Body:
just started learning mongodb, currently i have this schema

var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
    type: Date,
    default: Date.now
}});

and i wanted to update it to be like this, but currently its not working right now, when i checked it on the mongo console the schema is still the old one

var BlogSchema = new mongoose.Schema({
        title: String,
        image: String,
        body: String,
        created: {
            type: Date,
            default: Date.now
        },
        author: {
            id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "User"
            },
            username: String
        }
    });

this is the best i've come up with after reading this post, but it throw me an error TypeError: Undefined type undefined at author.required Did you try nesting Schemas? You can only nest using refs or arrays.

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: {
           type: String,
           required: true,
           default: null
        }
    }
});

Body:
You can't use Schema like that instead just make another authorSchema and use it as array.

var mongoose = require('mongoose');

var authorSchema = new mongoose.Schema({
    id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    username: {
        type: String,
        required: true,
    }
})

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: [authorSchema]
})


问:
Assign few connections from a connection pool to each specific task
I have a connection pool with 50 connections.

I want to dedicate

10 among these to task A

20 for task B

Is this a good practice? Is this possible in java while creating connection pools or thread pools?

答:
Sharing resources between different participants is a good practice.

It is also a well-established practice to not do that blindly, but in context of priorities/goals/policies. Very often that happens on a higher level (think of load balancing); but of course, you could also built that into your application directly.

But to my knowledge, there are no simple mechanism in the (standard) java libraries to do that.

Long story short: if you want to use something like this; then you might have to step back and implement your own solution. In other words: you create your own connection pool that knows about "different" tasks; and that allows you to give priorities to them; and then the pool decides on such policies who will be served next.

On the downside: implementing something like this can turn out pretty complicated pretty quickly. Thus my first advise: go for two independent pools; make experiments and see how things work out for you. Only when you find that this solution is too inefficient for you; then start looking into your building your "load balancing"!


问:
How to configure external compiler like gcc +14 with microsoft visual studio 2017?
I want to use debugging quality of microsoft visual studio and its built in compiler does not allow me to declare array like int a[n] giving errors like it should be constant value and thus my time is being wasted on dynamically allocating it. Also I am unable to include libraries like bits/stdc++.h

I am using windows 10. Please tell me how can I configure my compiler.For my purpose I will be having just one cpp file.

My main purpose will be to solve questions from spoj,codeforces etc

答:
There are three different options.

Create a Custom Build Tool

Makefile Project

Cross-Platform Development

Theres a similar question with a good answer with the explanation of my Options
How to use GCC with Microsoft Visual Studio?


问:
If two columns match paste them together, otherwise do nothing
I have a DF1

```<code>SNP a
rs1 1
rs2 2
rs3 3
rs4 4
</code>```

And DF2

```<code>SNP  GENE
rs1   A
rs2   B
</code>```

I am looking for the way to get DF3

```<code>SNP    a
rs1_A  1
rs2_B  2
rs3    3
rs4    4
</code>```

I have tried to use ifelse statement such as

```<code>ifelse(DF1$SNP %in% DF2$SNP,paste(DF1$SNP, DF2$GENE,sep="_"),DF1$SNP)
</code>```

But it didnt work.
Thank you for any help.

答:
We need to replace the %in% with , in paste

```<code>DF1$SNP <- ifelse(DF1$SNP %in% DF2$SNP,paste(DF1$SNP, DF2$GENE,sep="_"),DF1$SNP)
DF1$SNP
#[1] "rs1_A" "rs2_B" "rs3"   "rs4"
</code>```

If we are creating a new objects

```<code>DF3 <- transform(DF1, SNP = ifelse(SNP %in% DF2$SNP, paste(SNP, DF2$GENE, sep="_"), SNP))
</code>```

NOTE: Here, we assume the columns are character class and not factor

Body:
I have a DF1

SNP a
rs1 1
rs2 2
rs3 3
rs4 4

And DF2

SNP  GENE
rs1   A
rs2   B

I am looking for the way to get DF3

SNP    a
rs1_A  1
rs2_B  2
rs3    3
rs4    4

I have tried to use ifelse statement such as

ifelse(DF1$SNP %in% DF2$SNP,paste(DF1$SNP, DF2$GENE,sep="_"),DF1$SNP)

But it didnt work.
Thank you for any help.

Body:
We need to replace the %in% with , in paste

DF1$SNP <- ifelse(DF1$SNP %in% DF2$SNP,paste(DF1$SNP, DF2$GENE,sep="_"),DF1$SNP)
DF1$SNP
#[1] "rs1_A" "rs2_B" "rs3"   "rs4"

If we are creating a new objects

DF3 <- transform(DF1, SNP = ifelse(SNP %in% DF2$SNP, paste(SNP, DF2$GENE, sep="_"), SNP))

NOTE: Here, we assume the columns are character class and not factor


问:
nil can't be coerced into BigDecimal - Ruby On Rails(rails 2.3.2)
I was try below codes.i got error for "nil can't be coerced into BigDecimal".
anyone help me.thanks.

migration file

```<code>class AddPaidAmountToVoucher < ActiveRecord::Migration
  def self.up
    add_column :vouchers, :paid_amount, :decimal, :precision => 18, :scale => 2
  end

  def self.down
    remove_column :vouchers, :paid_amount
  end
end
</code>```

Model class(voucher_payment.rb)

```<code>after_update :update_voucher_paid_amount

def update_voucher_paid_amount
    voucher = self.voucher
    paidAmount = 0
    voucher.voucher_payments.each do |voucher_payment|
      paidAmount += voucher_payment.paid_amount if voucher_payment.is_approved == true
    end
    voucher.paid_amount = paidAmount

    voucher.save
  end
</code>```

答:
While looping through voucher.voucher_payments one/some of the voucher_payment has paid_amount as nil.

```<code>voucher_payment.paid_amount = nil
</code>```

So when you add paidAmount to a nil value, this error shows up.

Body:
I was try below codes.i got error for "nil can't be coerced into BigDecimal".
anyone help me.thanks.

migration file

class AddPaidAmountToVoucher < ActiveRecord::Migration
  def self.up
    add_column :vouchers, :paid_amount, :decimal, :precision => 18, :scale => 2
  end

  def self.down
    remove_column :vouchers, :paid_amount
  end
end

Model class(voucher_payment.rb)

after_update :update_voucher_paid_amount

def update_voucher_paid_amount
    voucher = self.voucher
    paidAmount = 0
    voucher.voucher_payments.each do |voucher_payment|
      paidAmount += voucher_payment.paid_amount if voucher_payment.is_approved == true
    end
    voucher.paid_amount = paidAmount

    voucher.save
  end

Body:
While looping through voucher.voucher_payments one/some of the voucher_payment has paid_amount as nil.

voucher_payment.paid_amount = nil

So when you add paidAmount to a nil value, this error shows up.


问:
How to Replace Bad Words in a Comment with Asterisks Using PHP

Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

```<code><?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String <br> $input_string <br><br><hr><br>Input String Fixed <br> $fixed";
?>
</code>```

答:
```<code><?php
   $abusive_words = file_get_contents('Bad_Words.txt');
   $abusive_words = explode("\n", $abusive_words); // here you got an array of strings
   $input_string = 'Catch that bastard, Idiot .... !!';

   $fixed=$input_string;
   foreach ($abusive_words as $ab_word) // then you need to use loop to get each element of array
      $fixed = str_ireplace($ab_word,'*****',$fixed); //replacing any array string to *****

   echo "Input String <br> $input_string <br><br><hr><br>Input String  Fixed <br> $fixed";
 ?>
</code>```

Body:
Hope All Of You are Fine.

I have a File in Of Bad Words, I want to Replace Bad Words in a Comments with Asterisks.

Bad Words URL : https://gist.githubusercontent.com/anonymous/e8e6798137b1ff4836d6ebcf73fef7dc/raw/415dfc8cbab13fa6033fbb4d4ce9eae7a9dbe7cd/Bad_Words.txt

I wrote Below Lines Of Code But It's not Working :(

Kindly Help.

<?php
$abusive_words = file_get_contents('Bad_Words.txt');
$abusive_words = explode("\n", $abusive_words);
$input_string = 'Catch that bastard, Idiot .... !!';
$fixed = str_ireplace($abusive_words,'*****',$input_string);
echo "Input String
 $input_string

Input String Fixed
 $fixed";
?>


问:
Jira Soap API get project version start/end date
I am trying to the get start and end date of a jira project version.
Can I do this with the Jira SOAP API, and how cand I do this? </p>

答:
There's no such thing as 'start date' for version in JIRA, and Release Date is available via SOAP. E.g. in Java:</p>

```<code>JiraSoapService js = new JiraSoapServiceServiceLocator().getJirasoapserviceV2();
String token = js.login(username, password);
RemoteVersion[] versions = js.getVersions(token, "KEY");
Calendar releaseDate = versions[0].getReleaseDate();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
There's no such thing as 'start date' for version in JIRA, and Release Date is available via SOAP. E.g. in Java:

JiraSoapService js = new JiraSoapServiceServiceLocator().getJirasoapserviceV2();
String token = js.login(username, password);
RemoteVersion[] versions = js.getVersions(token, "KEY");
Calendar releaseDate = versions[0].getReleaseDate();


问:
How to uncheck all the checkboxes in expandable listview?
I want to uncheck all the checkboxes in child of expandable listview but the problem is that it uncheck only visible checkboxes in a view group. The invisible checkboxes are not getting unchecked. Please help me.</p>

```<code>public void uncheckAllChildrenCascade(ViewGroup vg) {
    for (int i = 0; i < vg.getChildCount(); i++) {
        View v = vg.getChildAt(i);
        if (v instanceof CheckBox) {
            ((CheckBox) v).setChecked(false);
        } else if (v instanceof ViewGroup) {
            uncheckAllChildrenCascade((ViewGroup) v);
        }
    }
}
</code>```

答:
```<code>private final Set<Pair<Long, Long>> mCheckedItems = new HashSet<Pair<Long, Long>>();
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb_checkbox);
    RelativeLayout relativelayout=(RelativeLayout) convertView.findViewById(R.id.rl_selected);
    txtListChild.setText(childText);
    final Pair<Long, Long> tag = new Pair<Long, Long>(getGroupId(groupPosition), getChildId(groupPosition, childPosition));
    cb.setTag(tag);
        cb.setChecked(mCheckedItems.contains(tag));
relativelayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cb.isChecked()) {
                cb.setChecked(false);
                mCheckedItems.remove(tag);
                Shop.iv_shopbyCategory.setVisibility(View.GONE);
                Shop.tv_rl_selectedshopByCategory.setText(" ");
            }
            else
                {
                    mCheckedItems.clear();
                    cb.setChecked(true);
                    mCheckedItems.add(tag);
                    final String SelectedGrouposition=(String) getGroup(groupPosition);
                    final String SelectedChildposition=(String) getChild(groupPosition, childPosition);

                    listAdapter.notifyDataSetChanged();
            }
        }
    });
</code>```

I have a expandable listview in which when i click on relative layout it changes the checkbox checked or unchecked and when i select new  check it will remove all selected check..

for me its working and hope it will work for u also...

Try this

Body:
I want to uncheck all the checkboxes in child of expandable listview but the problem is that it uncheck only visible checkboxes in a view group. The invisible checkboxes are not getting unchecked. Please help me.

public void uncheckAllChildrenCascade(ViewGroup vg) {
    for (int i = 0; i < vg.getChildCount(); i++) {
        View v = vg.getChildAt(i);
        if (v instanceof CheckBox) {
            ((CheckBox) v).setChecked(false);
        } else if (v instanceof ViewGroup) {
            uncheckAllChildrenCascade((ViewGroup) v);
        }
    }
}

Body:
private final Set<Pair<Long, Long>> mCheckedItems = new HashSet<Pair<Long, Long>>();
final CheckBox cb = (CheckBox) convertView.findViewById(R.id.cb_checkbox);
    RelativeLayout relativelayout=(RelativeLayout) convertView.findViewById(R.id.rl_selected);
    txtListChild.setText(childText);
    final Pair<Long, Long> tag = new Pair<Long, Long>(getGroupId(groupPosition), getChildId(groupPosition, childPosition));
    cb.setTag(tag);
        cb.setChecked(mCheckedItems.contains(tag));
relativelayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (cb.isChecked()) {
                cb.setChecked(false);
                mCheckedItems.remove(tag);
                Shop.iv_shopbyCategory.setVisibility(View.GONE);
                Shop.tv_rl_selectedshopByCategory.setText(" ");
            }
            else
                {
                    mCheckedItems.clear();
                    cb.setChecked(true);
                    mCheckedItems.add(tag);
                    final String SelectedGrouposition=(String) getGroup(groupPosition);
                    final String SelectedChildposition=(String) getChild(groupPosition, childPosition);

                    listAdapter.notifyDataSetChanged();
            }
        }
    });

I have a expandable listview in which when i click on relative layout it changes the checkbox checked or unchecked and when i select new  check it will remove all selected check..

for me its working and hope it will work for u also...

Try this


问:
Find adjacent groups in a string
I need to find how many large groups are in a string s.
A small group is simply a contiguous segment(same character repeats).
A large group is a contiguous segment formed from 2 or more small groups.

It`s clearer with code,below I get all the small groups

var s = "ccccoodeffffiiighhhhhhhhhhttttttts";

sgroups= s.match(/(.)\1+/g);
console.log(sgroups)```
</div>
</div>
</p>

<p>How do I find the large groups?</p>

```"ccccoo",
 "ffffiii",
 "hhhhhhhhhhttttttt"
```

<p>In another example</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var s = "soooooldieeeeeer";
var sgroups= s.match(/(.)\1+/g);
console.log(sgroups)</code>```

In the code above,since the 2 small groups are not contiguous in the original string,there are no large groups.

答:
You may use:

var rx = /(?:(.)\1+(?!\1)){2,}/g;
console.log("soooooldieeeeeer".match(rx));
console.log("soooooldieeeeeerrr".match(rx));```

Details:

(?: - start of  a non-capturing group (does not create a numbered capture for us to be able to still use \1 backreference later and keep the match "clean")

(.) - capturing group 1 matching any char  (but a line break char)

\1+  - one or more occurrences of the same char as stored in Group 1 (where \1 is the backreference to the value kept in Group 1 and + is a one or more occurrences quantifier)

(?!\1) - makes sure the chunk of identical characters is not followed with the same char, so as not to allow backtracking match strings where 4 or more consecutive identical characters appear.

){2,} - two or more occurrences of the non-capturing group pattern.

Title: Find adjacent groups in a string

Body:
I need to find how many large groups are in a string s.
A small group is simply a contiguous segment(same character repeats).
A large group is a contiguous segment formed from 2 or more small groups.

It`s clearer with code,below I get all the small groups

var s = "ccccoodeffffiiighhhhhhhhhhttttttts";

sgroups= s.match(/(.)\1+/g);
console.log(sgroups)

How do I find the large groups?

"ccccoo",
 "ffffiii",
 "hhhhhhhhhhttttttt"

In another example

var s = "soooooldieeeeeer";
var sgroups= s.match(/(.)\1+/g);
console.log(sgroups)

In the code above,since the 2 small groups are not contiguous in the original string,there are no large groups.

Body:
You may use:

var rx = /(?:(.)\1+(?!\1)){2,}/g;
console.log("soooooldieeeeeer".match(rx));
console.log("soooooldieeeeeerrr".match(rx));

Details:

(?: - start of  a non-capturing group (does not create a numbered capture for us to be able to still use \1 backreference later and keep the match "clean")

(.) - capturing group 1 matching any char  (but a line break char)

\1+  - one or more occurrences of the same char as stored in Group 1 (where \1 is the backreference to the value kept in Group 1 and + is a one or more occurrences quantifier)

(?!\1) - makes sure the chunk of identical characters is not followed with the same char, so as not to allow backtracking match strings where 4 or more consecutive identical characters appear.

){2,} - two or more occurrences of the non-capturing group pattern.


问:
Which Linux header(s) to remove?
I have run out of inodes (IUse% = 100%) and repeatedly running the command from this answer, I narrowed the culprit to /usr/src, specifically linux-headers*.  From the same post but different answer, I want to remove said linux-headers but am confused about which are the oldest (and not used so can safely be deleted).

The contents of /usr/src/linux-headers* is:

```<code>linux-headers-3.13.0-24
linux-headers-3.13.0-24-generic
linux-headers-3.13.0-33
linux-headers-3.13.0-33-generic
linux-headers-3.13.0-34
linux-headers-3.13.0-34-generic
linux-headers-3.13.0-37
linux-headers-3.13.0-37-generic
linux-headers-3.13.0-39
linux-headers-3.13.0-39-generic
<snip>
linux-headers-3.13.0-112
linux-headers-3.13.0-112-generic
linux-headers-3.13.0-113
linux-headers-3.13.0-113-generic
</code>```

From uname -r gives 3.13.0-34-generic.

So which can I delete?  If I am running -34 then -37 through to -113 are newer and so cannot be deleted.

Now at AskUbuntu.

答:
You can avoid removal if you move the src directory to another mounted volume which has more space, and create a symbolic link /usr/src which will point to the new location.

Typically, the /usr/src is only required to be able to build some SW which has dependencies from your kernel, or to rebuild the kernel itself. Also, if this is not your case, then you can remove /usr/src at all. Beforewards check that you don't boot the built kernel from this tree by a chance.

UPDATED. If you use all the time the same kernel version (3.13.0-34-generic), you can harmfree remove headers of all other versions. Always remember about backups however!

Title: Which Linux header(s) to remove?

Body:
I have run out of inodes (IUse% = 100%) and repeatedly running the command from this answer, I narrowed the culprit to /usr/src, specifically linux-headers*.  From the same post but different answer, I want to remove said linux-headers but am confused about which are the oldest (and not used so can safely be deleted).

The contents of /usr/src/linux-headers* is:

linux-headers-3.13.0-24
linux-headers-3.13.0-24-generic
linux-headers-3.13.0-33
linux-headers-3.13.0-33-generic
linux-headers-3.13.0-34
linux-headers-3.13.0-34-generic
linux-headers-3.13.0-37
linux-headers-3.13.0-37-generic
linux-headers-3.13.0-39
linux-headers-3.13.0-39-generic
<snip>
linux-headers-3.13.0-112
linux-headers-3.13.0-112-generic
linux-headers-3.13.0-113
linux-headers-3.13.0-113-generic

From uname -r gives 3.13.0-34-generic.

So which can I delete?  If I am running -34 then -37 through to -113 are newer and so cannot be deleted.

Now at AskUbuntu.


问:
how to avoid mutating this.state or redux object
For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.

Is it bad practice to do this?

```<code>Object.keys(this.state).map(k => this.state[k]);
</code>```

Thanks

答:
React Mutating State.

```<code>let state = {
    age    : 25,
    name   : 'Robin',
    friends: ['Barney', 'Ted']
}
</code>```

Change Age

```<code>this.setState({age: 26})
</code>```

Change Name

```<code>this.setState({name: 'Lily'})
</code>```

Add Friend

```<code>this.setState({
    friends: this.state.friends.concat(['Marshall'])
})
</code>```

Try this library immutability-helper for complex state updates.

Body:
For example, if I want to do any operation on this.state or some other object, such as Object.keys(this.state).map() to get access to all the values in the object.

Is it bad practice to do this?

Object.keys(this.state).map(k => this.state[k]);

Thanks

Body:
React Mutating State.

let state = {
    age    : 25,
    name   : 'Robin',
    friends: ['Barney', 'Ted']
}

Change Age

this.setState({age: 26})

Change Name

this.setState({name: 'Lily'})

Add Friend

this.setState({
    friends: this.state.friends.concat(['Marshall'])
})

Try this library immutability-helper for complex state updates.


问:
HttpWebRequest.CachePolicy: questions about caching
If I set my HttpWebRequest.CachePolicy as follows:

```<code>var webRequest = (HttpWebRequest) WebRequest.Create(url);
var policy = new HttpRequestCachePolicy( HttpCacheAgeControl.MaxAge,
                                         TimeSpan.FromMinutes(1) );
webRequest.CachePolicy = policy;
</code>```

and make two async requests for the same URL at exactly the same moment, what happens to the second request? Does the second complete only when the first has cached, or will 2 requests be issued because nothing is in cache at the time of issue?

Also, in this context, what is the cache? Where does it live? Do we get more control over it?

答:
Two such requests in the .NET code will cause two such HTTP requests, which can be checked quite easily by just building something that does so, running it, and then testing what happens at the server.

This is appropriate because it may be that the two requests will receive a different response, especially considering that one of them might suffer an error that the other doesn't. There are other reasons (e.g. the server may send a response that differs every time along with instructions that it shouldn't be cached).

However, there can be an exception. There is a default limit on the number of requests that will simultaneously be sent to the same domain, which is configurable but defaults to two (this is something often complained about because it is inappropriate in some use-cases - however two requests per server does give the highest total throughput in most cases, so it's there for a good reason).

Because of this, it's quite possible that one of the two requests will be delayed as it is queued due to this rule. Even if the default limit is increased, it's possible that that limit was still surpassed.

Now, as Marc notes a response can be cached once its response stream has been read to the end*, and this may have happened by the time the second request begins, which would lead to it using the cached response if applicable (the response was cacheable and there were no errors in downloading it).

So, on balance we would expect there to be two separate downloads and we should be glad of that (in case one has an error), but there are possible conditions in which there will be only one download as the two "simultaneous" requests are forced to not actually be simultaneous.

*Actually, while the documentation says the stream has to be read to the end, it actually has to be read to the end and closed, whether manually, by disposing it (e.g. from using) or from its finaliser being executed.

Body:
If I set my HttpWebRequest.CachePolicy as follows:

var webRequest = (HttpWebRequest) WebRequest.Create(url);
var policy = new HttpRequestCachePolicy( HttpCacheAgeControl.MaxAge,
                                         TimeSpan.FromMinutes(1) );
webRequest.CachePolicy = policy;

and make two async requests for the same URL at exactly the same moment, what happens to the second request? Does the second complete only when the first has cached, or will 2 requests be issued because nothing is in cache at the time of issue?

Also, in this context, what is the cache? Where does it live? Do we get more control over it?


问:
How to retrieve a list from another object that is in the list using stream
I have a little problem. From earlier steps I get this list:

```<code>List<Foo> fooList;
</code>```

I need now get all id to separate list:

```<code>List<Integer> newListIds;
</code>```

Is it possible to do it using streams, possibly as otherwise the easiest way to do it?

My clases:

```<code>public class Foo {

   List<Bar> barList;

   //getter, setter
}

public class Bar {

   private Integer id;

   //geter, setter
}
</code>```

答:
You can do it using flatMap:

```<code>fooList.stream()
           .map(foo -> foo.barList)
           .flatMap(List::stream)
           .map(bar -> bar.id)
           .collect(Collectors.toList());
</code>```

Or using method reference for getter and setter:

```<code>fooList.stream()
           .map(Foo::getBarList)
           .flatMap(List::stream)
           .map(Bar::getId)
           .collect(Collectors.toList());
</code>```

Body:
I have a little problem. From earlier steps I get this list:

List<Foo> fooList;

I need now get all id to separate list:

List<Integer> newListIds;

Is it possible to do it using streams, possibly as otherwise the easiest way to do it?

My clases:

public class Foo {

   List<Bar> barList;

   //getter, setter
}

public class Bar {

   private Integer id;

   //geter, setter
}

Body:
You can do it using flatMap:

fooList.stream()
           .map(foo -> foo.barList)
           .flatMap(List::stream)
           .map(bar -> bar.id)
           .collect(Collectors.toList());

Or using method reference for getter and setter:

fooList.stream()
           .map(Foo::getBarList)
           .flatMap(List::stream)
           .map(Bar::getId)
           .collect(Collectors.toList());


问:
How to change colors automatically once a parameter is changed
In the following code, the color of bars changes as the threshold is changed. Instead of using the threshold and plotting the horizontal line in the code, I want to use the y parameter in the OnMouseMove function so that the user can change the location of "threshold". Then, I want the colors to be updated as the y is changed.

I think what I need is called "observer pattern" or perhaps a trick using the animation tools but not sure how to implement it. I appreciate any insight on how to do this. Thanks

```<code>%matplotlib notebook
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.colors as mcol
import matplotlib.cm as cm
import matplotlib.pyplot as plt

np.random.seed(12345)
df = pd.DataFrame([np.random.normal(335,1500,300),
                   np.random.normal(410,900,300),
                   np.random.normal(410,1200,300),
                   np.random.normal(480,550,300)],
                  index=[1,2,3,4])

fig, ax = plt.subplots()
plt.show()
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')

fig = plt.gcf()
threshold=420
plt.axhline(y = threshold, color = 'grey', alpha = 0.5)

cm1 = mcol.LinearSegmentedColormap.from_list("Test",["b", "white", "purple"])
cpick = cm.ScalarMappable(cmap=cm1)
cpick.set_array([])

percentages = []
for bar in bars:
    percentage = (bar.get_height()-threshold)/bar.get_height()
    if percentage>1: percentage = 1
    if percentage<0: percentage=0
    percentages.append(percentage)

cpick.to_rgba(percentages)
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = cpick.to_rgba(percentages))
plt.colorbar(cpick, orientation='horizontal')

def onMouseMove(event):
    ax.lines = [ax.lines[0]]
    plt.axhline(y=event.ydata, color="k")

fig.canvas.mpl_connect('motion_notify_event', onMouseMove)

plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)
</code>```

答:
First you should use exactly one bar plot and exactly one axhline (using more will make everything chaotic). You can set the colors of the bars via

```<code>for bar in bars:
    bar.set_color(..)
</code>```

and you can update the axhline's position via line.set_ydata(position).

Now, for every mouse move event you need to update the axhline's position, calculate the percentages and apply a new colors to the bars. So those things should be done in a function, which is called every time the mouse move event is triggered. After those settings have been applied the canvas needs to be drawn for them to become visible.

Here is a complete code.

```<code>import pandas as pd
import numpy as np
import matplotlib.colors as mcol
import matplotlib.cm as cm
import matplotlib.pyplot as plt

np.random.seed(12345)
df = pd.DataFrame([np.random.normal(335,1500,300),
                   np.random.normal(410,900,300),
                   np.random.normal(410,1200,300),
                   np.random.normal(480,550,300)],
                  index=[1,2,3,4])

fig, ax = plt.subplots()

threshold=420.
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')
axline = plt.axhline(y = threshold, color = 'grey', alpha = 0.5)

cm1 = mcol.LinearSegmentedColormap.from_list("Test",["b", "white", "purple"])
cpick = cm.ScalarMappable(cmap=cm1)
cpick.set_array([])
plt.colorbar(cpick, orientation='horizontal')

def percentages(threshold):
    percentages = []
    for bar in bars:
        percentage = (bar.get_height()-threshold)/bar.get_height()
        if percentage>1: percentage = 1
        if percentage<0: percentage=0
        percentages.append(percentage)
    return percentages

def update(threshold):
    axline.set_ydata(threshold)
    perc = percentages(threshold)
    for bar, p in zip(bars, perc):
        bar.set_color(cpick.to_rgba(p))

# update once before showing
update(threshold)

def onMouseMove(event):
    if event.inaxes == ax:
        update(event.ydata)
        fig.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', onMouseMove)

plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)

plt.show()
</code>```

Body:
In the following code, the color of bars changes as the threshold is changed. Instead of using the threshold and plotting the horizontal line in the code, I want to use the y parameter in the OnMouseMove function so that the user can change the location of "threshold". Then, I want the colors to be updated as the y is changed.

I think what I need is called "observer pattern" or perhaps a trick using the animation tools but not sure how to implement it. I appreciate any insight on how to do this. Thanks

%matplotlib notebook
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.colors as mcol
import matplotlib.cm as cm
import matplotlib.pyplot as plt

np.random.seed(12345)
df = pd.DataFrame([np.random.normal(335,1500,300),
                   np.random.normal(410,900,300),
                   np.random.normal(410,1200,300),
                   np.random.normal(480,550,300)],
                  index=[1,2,3,4])

fig, ax = plt.subplots()
plt.show()
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')

fig = plt.gcf()
threshold=420
plt.axhline(y = threshold, color = 'grey', alpha = 0.5)

cm1 = mcol.LinearSegmentedColormap.from_list("Test",["b", "white", "purple"])
cpick = cm.ScalarMappable(cmap=cm1)
cpick.set_array([])

percentages = []
for bar in bars:
    percentage = (bar.get_height()-threshold)/bar.get_height()
    if percentage>1: percentage = 1
    if percentage<0: percentage=0
    percentages.append(percentage)

cpick.to_rgba(percentages)
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = cpick.to_rgba(percentages))
plt.colorbar(cpick, orientation='horizontal')

def onMouseMove(event):
    ax.lines = [ax.lines[0]]
    plt.axhline(y=event.ydata, color="k")

fig.canvas.mpl_connect('motion_notify_event', onMouseMove)

plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)

Body:
First you should use exactly one bar plot and exactly one axhline (using more will make everything chaotic). You can set the colors of the bars via

for bar in bars:
    bar.set_color(..)

and you can update the axhline's position via line.set_ydata(position).

Now, for every mouse move event you need to update the axhline's position, calculate the percentages and apply a new colors to the bars. So those things should be done in a function, which is called every time the mouse move event is triggered. After those settings have been applied the canvas needs to be drawn for them to become visible.

Here is a complete code.

import pandas as pd
import numpy as np
import matplotlib.colors as mcol
import matplotlib.cm as cm
import matplotlib.pyplot as plt

np.random.seed(12345)
df = pd.DataFrame([np.random.normal(335,1500,300),
                   np.random.normal(410,900,300),
                   np.random.normal(410,1200,300),
                   np.random.normal(480,550,300)],
                  index=[1,2,3,4])

fig, ax = plt.subplots()

threshold=420.
bars = plt.bar(range(df.shape[0]), df.mean(axis = 1), color = 'lightslategrey')
axline = plt.axhline(y = threshold, color = 'grey', alpha = 0.5)

cm1 = mcol.LinearSegmentedColormap.from_list("Test",["b", "white", "purple"])
cpick = cm.ScalarMappable(cmap=cm1)
cpick.set_array([])
plt.colorbar(cpick, orientation='horizontal')

def percentages(threshold):
    percentages = []
    for bar in bars:
        percentage = (bar.get_height()-threshold)/bar.get_height()
        if percentage>1: percentage = 1
        if percentage<0: percentage=0
        percentages.append(percentage)
    return percentages

def update(threshold):
    axline.set_ydata(threshold)
    perc = percentages(threshold)
    for bar, p in zip(bars, perc):
        bar.set_color(cpick.to_rgba(p))

# update once before showing
update(threshold)

def onMouseMove(event):
    if event.inaxes == ax:
        update(event.ydata)
        fig.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', onMouseMove)

plt.xticks(range(df.shape[0]), df.index, alpha = 0.8)

plt.show()


问:
How to use JavaScript variable as a param on @Messages
Is it possible to use a JS variable inside @Messages as a parameter? When I use this, I get the following error:

not found: value name

```<code>var name = "some name";
var title = "@Messages("message", name)"
</code>```

答:
jsMessages is a good solution.

If you want a more generic solution for any kind of code, not just messages, you can try out this: JavascriptRouting

It enables you to pass javascript variables to any call to an endpoint in your application. But true, you would have to set up a Play route for your Messages.

ContentLicense: CC BY-SA 4.0

Body:
Is it possible to use a JS variable inside @Messages as a parameter? When I use this, I get the following error:

not found: value name

var name = "some name";
var title = "@Messages("message", name)"


问:
Convert string to int[,]
I have weird requirement in matrix clustering.

My inputs are like

```<code>string param = "1100,1110,0110,0001";
</code>```

and what I want is

```<code> var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };
</code>```

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

```<code>string[] resultantArray = param.Split(',').ToArray();
</code>```

And then I tried to convert my string[] to int[], using below code.

```<code>var intArray = resultantArray .Select(int.Parse).ToArray();
</code>```

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

答:
This should be the fastest approach</p>

```<code>string param = "1100,1110,0110,0001";
int[,] result = new int[4,4];
int i = 0, j = 0;

for (int x = 0; x < param.Length; x++)
{
    if (param[x] == ',')
    {
        i++;
        j = 0;
    }
    else
    {
        result[i, j] = param[x] - '0';
        j++;
    }
}
</code>```

Title: Convert string to int[,]

Body:
I have weird requirement in matrix clustering.

My inputs are like

string param = "1100,1110,0110,0001";

and what I want is

 var matrix = new[,]
        {
              {1,1,0,0},
              {1,1,1,0},
              {0,1,1,0},
              {0,0,0,1}
        };

so It should be array of int[4,4].

What I tried?

I tried many ways for this conversation.

First Of all I convert my string to string[], using below code.

string[] resultantArray = param.Split(',').ToArray();

And then I tried to convert my string[] to int[], using below code.

var intArray = resultantArray .Select(int.Parse).ToArray();

but I ended up with removed leading zeros.

Is there any way,
 I can achieve int[4,4] array from string?

Body:
This should be the fastest approach

string param = "1100,1110,0110,0001";
int[,] result = new int[4,4];
int i = 0, j = 0;

for (int x = 0; x < param.Length; x++)
{
    if (param[x] == ',')
    {
        i++;
        j = 0;
    }
    else
    {
        result[i, j] = param[x] - '0';
        j++;
    }
}


问:
Application Insights - Custom TrackRequest is creating duplicate messages
I want to be able to add custom properties to a request telemetry. I am able to do this with code such as:

public void LogRequest(IDictionary<string,string> properties)
{
    var client  = new TelemetryClient();
    var request = new RequestTelemetry();

    foreach(var prop in properties)
    {
        request.Properties.Add(prop );
    }
    client.TrackRequest(request);
}
```
<p>This code works in the sense that it creates a request telemetry with all of the custom properties I wanted, however the application insights SDK is also creating a duplicate request telemetry (without my custom properties). So it's sending its own request telemetry and the one that I created.</p>
<p>While trying to do some research I found this:
https://github.com/Azure/Azure-Functions/wiki/App-Insights-Early-Preview</p>
<blockquote>
<p>Custom telemetry</p>
<p>You can bring the .NET App Insights SDK in and create your own TelemetryClient. There isn’t any conflicts, but there is some advice:</p>
<p>Don’t create TrackRequest or use the StartOperation methods if you don’t want <strong>duplicate requests</strong> – we do this automatically.</p>
</blockquote>
<p>So my question is, is there anyway to send in my own custom request telemetry without the sdk automatically creating a duplicate message?</p>
<p>Also I would like to avoid using TrackEvent. Most of the information I need is already in the request object so I would prefer to use TrackRequest.</p>
<p>This is what I have in my application insights config in the track request section:</p>
```<TelemetryModules>
    <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
        <Handlers>
            <Add>System.Web.Handlers.TransferRequestHandler</Add>
            <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
            <Add>System.Web.StaticFileHandler</Add>
            <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
            <Add>System.Web.Optimization.BundleHandler</Add>
            <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
            <Add>System.Web.Handlers.TraceHandler</Add>
            <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
            <Add>System.Web.HttpDebugHandler</Add>
        </Handlers>
    </Add>
</TelemetryModules>
```

答:
The reason is that AI SDK automatically track requests for you, and therefore you get dups (the one w/o your properties is the one created automatically).

As PeterBons suggested, using Telemetry Initializer you can add the properties to the auto-generated request.

Body:
I want to be able to add custom properties to a request telemetry. I am able to do this with code such as:

public void LogRequest(IDictionary<string,string> properties)
{
    var client  = new TelemetryClient();
    var request = new RequestTelemetry();

    foreach(var prop in properties)
    {
        request.Properties.Add(prop );
    }
    client.TrackRequest(request);
}

This code works in the sense that it creates a request telemetry with all of the custom properties I wanted, however the application insights SDK is also creating a duplicate request telemetry (without my custom properties). So it's sending its own request telemetry and the one that I created.

While trying to do some research I found this:
https://github.com/Azure/Azure-Functions/wiki/App-Insights-Early-Preview

Custom telemetry

You can bring the .NET App Insights SDK in and create your own TelemetryClient. There isn’t any conflicts, but there is some advice:

Don’t create TrackRequest or use the StartOperation methods if you don’t want duplicate requests – we do this automatically.

So my question is, is there anyway to send in my own custom request telemetry without the sdk automatically creating a duplicate message?

Also I would like to avoid using TrackEvent. Most of the information I need is already in the request object so I would prefer to use TrackRequest.

This is what I have in my application insights config in the track request section:

<TelemetryModules>
    <Add Type="Microsoft.ApplicationInsights.Web.RequestTrackingTelemetryModule, Microsoft.AI.Web">
        <Handlers>
            <Add>System.Web.Handlers.TransferRequestHandler</Add>
            <Add>Microsoft.VisualStudio.Web.PageInspector.Runtime.Tracing.RequestDataHttpHandler</Add>
            <Add>System.Web.StaticFileHandler</Add>
            <Add>System.Web.Handlers.AssemblyResourceLoader</Add>
            <Add>System.Web.Optimization.BundleHandler</Add>
            <Add>System.Web.Script.Services.ScriptHandlerFactory</Add>
            <Add>System.Web.Handlers.TraceHandler</Add>
            <Add>System.Web.Services.Discovery.DiscoveryRequestHandler</Add>
            <Add>System.Web.HttpDebugHandler</Add>
        </Handlers>
    </Add>
</TelemetryModules>


问:
If any input field value entered zero then disable else enable
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

答:
In your fiddle, you have all of your inputs of type number. When first onchange event happens, it evaluates all of the inputs. Even if some the inputs do not have values, because they are of type number, their default value is 0. And your code is working at first because you are not checking inputs until the first onchange event fires.

You can check this if you enter all input fields with a non-zero value, then your button should be enabled. If you remove a value from one of them, it should be disabled again.


问:
inner join large table with small table , how to speed up
dear php and mysql expertor
i have two table one large for posts artices 200,000records (index colume: sid) , and one small table (index colume topicid ) for topics has 20 record .. have same topicid

curent im using : ( it took round 0.4s)

+do get last 50 record from table:

SELECT sid, aid, title, time, topic, informant, ihome, alanguage, counter, type, images, chainid FROM veryzoo_stories ORDER BY sid DESC LIMIT 0,50

+then do while loop in each records for find the maching name of topic in each post:

while ( .. ) {
SELECT topicname FROM veryzoo_topics WHERE topicid='$topic'"
....
}

+Now
I going to use Inner Join for speed up process but as my test it took much longer from 1.5s up to 3.5s

SELECT a.sid, a.aid, a.title, a.time, a.topic, a.informant, a.ihome, a.alanguage, a.counter, a.type, a.images, a.chainid, t.topicname FROM veryzoo_stories a INNER JOIN veryzoo_topics t ON a.topic = t.topicid ORDER BY sid DESC LIMIT 0,50

It look like the inner join do all joining 200k records from two table fist then limit result at 50 .. that took long time..

Please help to point me right way doing this..
eg take last 50 records from table one.. then join it to table 2 .. ect

答:
I'm just give test to nested query + inner join and suprised that performace increase much:  it now took only 0.22s .  Here is my query:

```<code>SELECT a.*, t.topicname
FROM (SELECT sid, aid, title, TIME, topic, informant, ihome, alanguage, counter, TYPE, images, chainid
  FROM  veryzoo_stories
  ORDER BY sid DESC
  LIMIT 0, 50) a
  INNER JOIN veryzoo_topics t ON a.topic = t.topicid
</code>```

if no more solution come up , i may use this one .. thanks for anyone look at this post

Body:
I'm just give test to nested query + inner join and suprised that performace increase much:  it now took only 0.22s .  Here is my query:

SELECT a.*, t.topicname
FROM (SELECT sid, aid, title, TIME, topic, informant, ihome, alanguage, counter, TYPE, images, chainid
  FROM  veryzoo_stories
  ORDER BY sid DESC
  LIMIT 0, 50) a
  INNER JOIN veryzoo_topics t ON a.topic = t.topicid

if no more solution come up , i may use this one .. thanks for anyone look at this post


问:
Error in smtp mail sending in aspdotnet using csharp
I have shared my code below which throws errors while sending mail.

var fromAddress = new MailAddress("sender@gmail.com", "Customer");
        var toAddress = new MailAddress("reciever@gmail.com", "HR");
        const string fromPassword = "senderpass";
        const string subject = "Subject";
        const string body = "Body";

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }```

this is the updated code but this also not working

答:
Try to configure your host from the Web-config as below:

```<code><system.net>
    <mailSettings>
      <smtp from="mail####hr@gmail.com">
        <network host="smtp.gmail.com" port="587" userName="mail####hr@gmail.com" password="##########"/>
      </smtp>
    </mailSettings>
  </system.net>
</code>```

In your class file change the method as follows and let me know:

```<code>   string strMailBody ="test";
   string strToEmailId ="da###dotnet@gmail.com";
   string strSubject = "Mail Testing";
   SmtpClient Client = new SmtpClient();
   Client.EnableSsl = true;
   System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
    message.To.Add("mail####hr@gmail.com");
            message.Bcc.Add(strToEmailId);// (ToEmailId);
            message.Subject = strSubject;// "Subject";
            message.IsBodyHtml = true;
            message.Body = strMailBody;//Content;
            try
            {
                Client.Send(message);
            }
            catch (Exception ex)
            {

            }
</code>```

Body:
I have shared my code below which throws errors while sending mail.

var fromAddress = new MailAddress("sender@gmail.com", "Customer");
        var toAddress = new MailAddress("reciever@gmail.com", "HR");
        const string fromPassword = "senderpass";
        const string subject = "Subject";
        const string body = "Body";

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }

this is the updated code but this also not working

Body:
Try to configure your host from the Web-config as below:

<system.net>
    <mailSettings>
      <smtp from="mail####hr@gmail.com">
        <network host="smtp.gmail.com" port="587" userName="mail####hr@gmail.com" password="##########"/>
      </smtp>
    </mailSettings>
  </system.net>

In your class file change the method as follows and let me know:

   string strMailBody ="test";
   string strToEmailId ="da###dotnet@gmail.com";
   string strSubject = "Mail Testing";
   SmtpClient Client = new SmtpClient();
   Client.EnableSsl = true;
   System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
    message.To.Add("mail####hr@gmail.com");
            message.Bcc.Add(strToEmailId);// (ToEmailId);
            message.Subject = strSubject;// "Subject";
            message.IsBodyHtml = true;
            message.Body = strMailBody;//Content;
            try
            {
                Client.Send(message);
            }
            catch (Exception ex)
            {

            }


问:
Why doesn't this objects variable expression work?
Can someone please explain why hotel.availableRooms is NaN? I am trying to learn objects in JavaScript. Thanks!

var hotel = {
  name: 'The Shining',
  totalRooms: 238,
  bookedRooms: 0,
  availableRooms: this.totalRooms - this.bookedRooms,
  roomTypes: ['single', 'double', 'haunted'],
  bookRoom: function() {
    this.availableRooms -= 1;
    this.bookedRooms += 1;
  }
};

hotel.bookRoom();

console.log(hotel.totalRooms);
console.log(hotel.bookedRooms);
console.log(hotel.availableRooms);```

答:
When the expression availableRooms: this.totalRooms - this.bookedRooms, is evaluated this is not hotel but whatever context you are running your code.

```<code>var hotel = {
  name: 'The Shining',
  totalRooms: 238,
  bookedRooms: 0,
  roomTypes: ['single', 'double', 'haunted'],
  bookRoom: function() {
    this.availableRooms -= 1;
    this.bookedRooms += 1;
  }
}

hotel.availableRooms = hotel.totalRooms - hotel.bookedRooms
</code>```

Or

```<code>  Object.defineProperty(hotel, 'availableRooms', {
      get: function() {
         return this.totalRooms - this.bookedRooms
      }
  })
</code>```

Body:
When the expression availableRooms: this.totalRooms - this.bookedRooms, is evaluated this is not hotel but whatever context you are running your code.

var hotel = {
  name: 'The Shining',
  totalRooms: 238,
  bookedRooms: 0,
  roomTypes: ['single', 'double', 'haunted'],
  bookRoom: function() {
    this.availableRooms -= 1;
    this.bookedRooms += 1;
  }
}

hotel.availableRooms = hotel.totalRooms - hotel.bookedRooms

Or

  Object.defineProperty(hotel, 'availableRooms', {
      get: function() {
         return this.totalRooms - this.bookedRooms
      }
  })


问:
Regex to add # after domain name
I need a regex to change the url from

```<code>http://example.com/page > https://example.com/#/page
</code>```

and

```<code>https://example.com/page > https://example.com/#/page
</code>```

I created this one and I added in 80 and 443 port virtualhosts apache and first redirect works but the second one doesn't

```<code>RewriteCond %{REQUEST_URI} !^.*%23.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}#%{REQUEST_URI} [R=301,L]
</code>```

答:
Your RewriteCond failed because You can not manipulate # (fregment) using rewriteRule as it's not sent to the server. If you want to redirect to # you can use this :

```<code>RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^ /#%{REQUEST_URI} [NE,L,R]
</code>```

NE flag is important otherwise apache converts # into %23

Title: Regex to add # after domain name

Body:
I need a regex to change the url from

http://example.com/page > https://example.com/#/page

and

https://example.com/page > https://example.com/#/page

I created this one and I added in 80 and 443 port virtualhosts apache and first redirect works but the second one doesn't

RewriteCond %{REQUEST_URI} !^.*%23.*$
RewriteRule ^(.*)$ https://%{HTTP_HOST}#%{REQUEST_URI} [R=301,L]

Body:
Your RewriteCond failed because You can not manipulate # (fregment) using rewriteRule as it's not sent to the server. If you want to redirect to # you can use this :

RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^ /#%{REQUEST_URI} [NE,L,R]

NE flag is important otherwise apache converts # into %23


问:
EXT JS: How to hide the fourth tab of the item based on some if condition?
I am new to ext js and I am trying to hide the fourth tab on my screen based on certain entity condition. As, I have coded I am able to disable
(blur) the 4th Setting tab, but the hidden or hide() function is failing.

Basically, I want to hide the fourth tab in items Payment.PaymentSettingsCfg on certain condition.
Any help would really appreciate, thanks in advance.

var bsdataloded = false;
Payment.PaymentSettingsCfg = {
  id: 'PaymentSettingsPanel',
  title: getMsg('PaymentAdmin', 'PaymentSettingsHeader'),
  xtype: 'PaymentSettingsPanels',
  listeners: {
    activate: function() {
      if (!bsdataloded) {
        this.loadSettings();
        bsdataloded = true;

      }
    }
  }

}
var hidePaymentSettingcfg = false;
debugger;
if (Payment.EntitySettings &&
  Payment.EntSettings["EntSITE|Payment_SWitch"] === "Y") {
  Payment.PaymentSettingsCfg.disabled = true; //working
  // Payment.PaymentSettingsCfg.hidden  = true;// not working, even hide() not working
  hidePaymentSettingcfg = true;

}
init: function() {
  Ext.QuickTips.init();
  Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
    expires: null
  }));

  app = new Payment.admin.AppContainer({
    id: 'main-panel',
    title: Payment.getMsg('PaymentAdmin', 'PaymentConfHeader'),
    el: 'bodydiv',
    border: true,
    layout: 'fit',
    defaults: {
      border: false
    },
    items: [{
      xtype: 'tabpanel',
      activeTab: 0,
      width: 500,
      deferredRender: false,
      hidden: false,
      defaults: {
        border: false
      },
      items: [
        Payment.PaymentItemCfg,
        Payment.PaymentPeriodCfg,
        Payment.PaymentTypeCfg,
        Payment.PaymentSettingsCfg
      ]
    }]
  });
  app.render();
}

};
}();```

答:
Here is the example to hide and show the tab based on if condition

i am hiding and showing the tab on checkbox checking but you can get your idea

i hope it will help you

here is the Fiddle...


问:
using javascript/jQuery to show certain elements on certain dates?
Pretty much as the title. I have been asked if it is possible to have a specific banner shown in a section on a website on different days without any external user input.

My first thoughts are the use of javascript/jquery. We are limited with the functionality however as the site is controlled by the horror that is Netsuite.

Any help/ideas are appreciated :)

-Wayne

答:
The first thought should be server-side.

If that is not an option then you could do it with javascript/jquery with the limitations it brings. Javascript enabled browsers.

You could name your files accordingly ie. image-19-7-2011.jpg and use the Date() object to create the filename to use for the current date.

Something like

```<code>var d = new Date();
var filename = 'image-' + d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear() + '.jpg';

document.getElementById('banner').src = '/path/to/' + filename;
</code>```

example at http://jsfiddle.net/rZaqx/

Body:
The first thought should be server-side.

If that is not an option then you could do it with javascript/jquery with the limitations it brings. Javascript enabled browsers.

You could name your files accordingly ie. image-19-7-2011.jpg and use the Date() object to create the filename to use for the current date.

Something like

var d = new Date();
var filename = 'image-' + d.getDate() + '-' + d.getMonth() + '-' + d.getFullYear() + '.jpg';

document.getElementById('banner').src = '/path/to/' + filename;

example at http://jsfiddle.net/rZaqx/


问:
Writing r shiny leaflet |popup|
Any solution/help about writing r shiny leaflet |popup|.
Thinks

I am trying to put some informations into my R shiny leaflet tool, and I got a problem to write something like that:

```<code>popup = paste(data$url,data$nom)
</code>```

The problem is that in the code the data$url is a website, and I want to render it like a link?

and when I try making with the ~symbol I got error messages ...

```<code>leaflet() %>%
  addTiles(
    urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png",
    attribution = 'Maps by <a href="http://www.mapbox.com/">Mapbox</a>'
  ) %>%
  setView(lng =  LONG, lat = LAT , zoom = ZOOM)%>%
  addMarkers(data,lng=data$Longitude,lat=data$Latitude,
  popup = paste(data$url,data$nom)
 ) %>%
</code>```

答:
You can use html tags for that. Just change your popup to the following:</p>

```<code> popup = paste("<a href=",data$url,">",data$url,"</a>",data$nom)
</code>```

Title: Writing r shiny leaflet |popup|

Body:
Any solution/help about writing r shiny leaflet |popup|.
Thinks

I am trying to put some informations into my R shiny leaflet tool, and I got a problem to write something like that:

popup = paste(data$url,data$nom)

The problem is that in the code the data$url is a website, and I want to render it like a link?

and when I try making with the ~symbol I got error messages ...

leaflet() %>%
  addTiles(
    urlTemplate = "//{s}.tiles.mapbox.com/v3/jcheng.map-5ebohr46/{z}/{x}/{y}.png",
    attribution = 'Maps by Mapbox'
  ) %>%
  setView(lng =  LONG, lat = LAT , zoom = ZOOM)%>%
  addMarkers(data,lng=data$Longitude,lat=data$Latitude,
  popup = paste(data$url,data$nom)
 ) %>%

Body:
You can use html tags for that. Just change your popup to the following:

 popup = paste("<a href=",data$url,">",data$url,"</a>",data$nom)


问:
symfony how to translate validation messages with expression
I´m trying to translate a validation message that uses expression  like GreaterThan() validation constrain class.

How can I translate this message "This value should be greater than {comparator_value}." ?

Other simple messages without expression it´s working fine

thanks

答:
If you want to to get the min value of GreaterThan. You must replace {comparator_value} with {{ compared_value }}, it will look like below:

```<code>This value should be greater than {{ compared_value }}
</code>```

Hope this can help you!

Body:
If you want to to get the min value of GreaterThan. You must replace {comparator_value} with {{ compared_value }}, it will look like below:

This value should be greater than {{ compared_value }}

Hope this can help you!


问:
Date and time conversion to some other Timezone in java
i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::

The current time in India is  :: Fri Feb 24 16:09:23 IST 2012

The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012

And the actual Time according to CST time zone is ::

```<code>Friday, 24 February 4:39:16 a.m(GMT - 6:00)
</code>```

So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::

```<code>package MyPackage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Temp2 {

    public static void main(String[] args) {

        try {
            Calendar currentdate = Calendar.getInstance();
            String strdate = null;
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            strdate = formatter.format(currentdate.getTime());
            TimeZone obj = TimeZone.getTimeZone("CST");

            formatter.setTimeZone(obj);
            //System.out.println(strdate);
            //System.out.println(formatter.parse(strdate));
            Date theResult = formatter.parse(strdate);

            System.out.println("The current time in India is  :: " +currentdate.getTime());

            System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
        } catch (ParseException e) {
           e.printStackTrace();
        }
    }
}
</code>```

答:
You can just use "CST6CDT"
because in some countries they follow CDT in summer and CST in winter

```<code> public static String getDateInCST() {
             Calendar calendar = Calendar.getInstance();
             DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
             formatter.setTimeZone(TimeZone.getTimeZone( "CST6CDT"));
             String strdate = formatter.format(calendar.getTime());
             TimeZone.getAvailableIDs();
             return strdate;
     }
</code>```

Body:
i have written this code to convert the current system date and time to some other timezone. I am not getting any error but i am not getting my output as expected. Like if i execute my program at a particular time.. My output is ::

The current time in India is  :: Fri Feb 24 16:09:23 IST 2012

The date and time in :: Central Standard Time is :: Sat Feb 25 03:39:23 IST 2012

And the actual Time according to CST time zone is ::

Friday, 24 February 4:39:16 a.m(GMT - 6:00)

So there's some time gap. and i don't know why this is happening. Any help will be appreciated.. The code is ::

package MyPackage;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Temp2 {

    public static void main(String[] args) {

        try {
            Calendar currentdate = Calendar.getInstance();
            String strdate = null;
            DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            strdate = formatter.format(currentdate.getTime());
            TimeZone obj = TimeZone.getTimeZone("CST");

            formatter.setTimeZone(obj);
            //System.out.println(strdate);
            //System.out.println(formatter.parse(strdate));
            Date theResult = formatter.parse(strdate);

            System.out.println("The current time in India is  :: " +currentdate.getTime());

            System.out.println("The date and time in :: "+ obj.getDisplayName() + "is ::" + theResult);
        } catch (ParseException e) {
           e.printStackTrace();
        }
    }
}

Body:
You can just use "CST6CDT"
because in some countries they follow CDT in summer and CST in winter

 public static String getDateInCST() {
             Calendar calendar = Calendar.getInstance();
             DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
             formatter.setTimeZone(TimeZone.getTimeZone( "CST6CDT"));
             String strdate = formatter.format(calendar.getTime());
             TimeZone.getAvailableIDs();
             return strdate;
     }


问:
Generate GUID in Windows with batch file
How can I generate a GUID in a batch file running using the commandline in Windows?</p>

答:
The Windows SDK comes with a tool called uuidgen (if you have Visual Studio, you'll have the Windows SDK, and you need to run the Visual Studio Command Prompt to set proper paths).

```<code>C:\>uuidgen
</code>```

This will output a new GUID, e.g.

cc23b318-156e-473f-aa6e-517bf091a0f0

Body:
The Windows SDK comes with a tool called uuidgen (if you have Visual Studio, you'll have the Windows SDK, and you need to run the Visual Studio Command Prompt to set proper paths).

C:\>uuidgen

This will output a new GUID, e.g.

cc23b318-156e-473f-aa6e-517bf091a0f0


问:
Hibernate entity with two unique keys using @NaturalId
I need a User entity that has a primary key ID and two unique not null (not primary) keys: email and username. Then I receive a username and an email and I need to retrieve a User entity that has either that received username or email.

I see that @NaturalId makes a column unique and not null. The problem is that when you have more than one @NaturalId, Hibernate creates a unique index on the pair (email, username), meaning that it won't be any rows with same pair (email, username) but it may appear one that has same email but different username.

Can it be solved with @NaturalId? If is possible how would I retrieve the entity matching either the received username or email but not necessarily both.

If it's not possible, would this be the optimal solution?

```<code> final Session session = HibernateUtil.openSession();
 final CriteriaBuilder builder = session.getCriteriaBuilder();
 final CriteriaQuery<User> criteria = builder.createQuery(User.class);
 final Root<User> userRoot = criteria.from(User.class);

 criteria.where(builder.equal(userRoot.get("username"), username));
 /* How do I join the criteria for username and email using ||?
 So that it gets me an entity that has that email or username. */

 final User foundUser = session.createQuery(criteria).uniqueResult();
</code>```

答:
your query will like:

```<code>  Session session = HibernateUtil.getSession();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.disjunction()
                    .add(Restrictions.eq("username", value))
                    .add(Restrictions.eq("email", value)));
    User user = (User)criteria.setMaxResults(1).uniqueResult();
</code>```

Hql query :

```<code> Query query = session.createQuery("from User as s where s.username = :userInputValue or s.email =:userInputValue");
        query.setParameter("userInputValue", userInputValue);
        query.setMaxResults(1);
        User user = (User) query.uniqueResult();
</code>```

you can't get unique result with your given result, because as you have mentioned, it may possible we have 2 rows which one of them have a username like "Jom@test.com" and another row have email "Jom@test.com".
So it's possible scenario to not get unique value, for fix it you need make a 2 unique constraint of any of filed, basically you need 2 unique filed in one row.

Body:
I need a User entity that has a primary key ID and two unique not null (not primary) keys: email and username. Then I receive a username and an email and I need to retrieve a User entity that has either that received username or email.

I see that @NaturalId makes a column unique and not null. The problem is that when you have more than one @NaturalId, Hibernate creates a unique index on the pair (email, username), meaning that it won't be any rows with same pair (email, username) but it may appear one that has same email but different username.

Can it be solved with @NaturalId? If is possible how would I retrieve the entity matching either the received username or email but not necessarily both.

If it's not possible, would this be the optimal solution?

 final Session session = HibernateUtil.openSession();
 final CriteriaBuilder builder = session.getCriteriaBuilder();
 final CriteriaQuery<User> criteria = builder.createQuery(User.class);
 final Root<User> userRoot = criteria.from(User.class);

 criteria.where(builder.equal(userRoot.get("username"), username));
 /* How do I join the criteria for username and email using ||?
 So that it gets me an entity that has that email or username. */

 final User foundUser = session.createQuery(criteria).uniqueResult();

Body:
your query will like:

  Session session = HibernateUtil.getSession();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.disjunction()
                    .add(Restrictions.eq("username", value))
                    .add(Restrictions.eq("email", value)));
    User user = (User)criteria.setMaxResults(1).uniqueResult();

Hql query :

 Query query = session.createQuery("from User as s where s.username = :userInputValue or s.email =:userInputValue");
        query.setParameter("userInputValue", userInputValue);
        query.setMaxResults(1);
        User user = (User) query.uniqueResult();

you can't get unique result with your given result, because as you have mentioned, it may possible we have 2 rows which one of them have a username like "Jom@test.com" and another row have email "Jom@test.com".
So it's possible scenario to not get unique value, for fix it you need make a 2 unique constraint of any of filed, basically you need 2 unique filed in one row.


问:
how to reload data after used $emit in angular js
i have some question about angularJs.. how to re init some variable in scope after i used emit . example code:

$scope.uiConfig = {title: "example"};

$scope.$emit('myCostumCalendar', 'Data to send');

$scope.$on('myCostumCalendar', function () {
  $scope.uiConfig = {title: "new Title"};
});```

答:
var myApp = angular.module('myApp',[]);

  myApp.controller('mainEventController', ['$scope', function($scope) {
    $scope.count = 0;
  }]);
  myApp.controller('EventController', ['$scope', function($scope) {
    debugger;

    $scope.$on('MyEvent', function() {
       debugger;

      $scope.count++;
    });
  }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE HTML>
<html>
 <head>
  <title>Basic on controllers</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="basiccontroller.js"></script>
 </head>
 <body ng-app="myApp">

  <!-- emit and broadcast -->
  <p><b>emit and broadcast</b></p>
  <p>----------------------------</p>
   <div ng-controller="mainEventController">
  Root scope <tt>MyEvent</tt> count: {{count}}
  <ul>
   <li ng-controller="EventController">
    <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
    <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
    <br>
    Middle scope <tt>MyEvent</tt> count: {{count}}
    <ul>
     <li  ng-controller="EventController">
      Leaf scope <tt>MyEvent</tt> count: {{count}}
     </li>
    </ul>
   </li>
  </ul>
  </div>

 </body>
</html></code>```

Body:
var myApp = angular.module('myApp',[]);

  myApp.controller('mainEventController', ['$scope', function($scope) {
    $scope.count = 0;
  }]);
  myApp.controller('EventController', ['$scope', function($scope) {
    debugger;

    $scope.$on('MyEvent', function() {
       debugger;

      $scope.count++;
    });
  }]);

<!DOCTYPE HTML>
<html>
 <head>
  <title>Basic on controllers</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="basiccontroller.js"></script>
 </head>
 <body ng-app="myApp">

  <!-- emit and broadcast -->
  <p><b>emit and broadcast</b></p>
  <p>----------------------------</p>
   <div ng-controller="mainEventController">
  Root scope <tt>MyEvent</tt> count: {{count}}
  <ul>
   <li ng-controller="EventController">
    <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
    <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
    <br>
    Middle scope <tt>MyEvent</tt> count: {{count}}
    <ul>
     <li  ng-controller="EventController">
      Leaf scope <tt>MyEvent</tt> count: {{count}}
     </li>
    </ul>
   </li>
  </ul>
  </div>

 </body>
</html>


问:
Function not defined when script appended to head and called from inline js
I've created this jsbin with a demo of my problem.

```<code>var textFromHTTPRequest = '<html>'
    + '<head>'
      + '<script>'
        + 'function myFunc() { alert("works"); }'
      + '</script>'
    + '</head>'
    + '<body>'
      + '<a href="#" onmouseover="myFunc()">test</a>'
    + '</body>'
  + '</html>';

// Parse the text to dom element.
var parser = new DOMParser();
var el = parser.parseFromString(textFromHTTPRequest, "text/html");

// Get the script and contents of body.
var menuBody = el.firstChild.querySelectorAll('body > *');
var menuScript = el.firstChild.querySelector('head script');

// Insert the script into current head tag.
document.head.appendChild(menuScript);

// Insert the contents of body into current body.
for (var i = 0; i < menuBody.length; ++i) {
  document.body.appendChild(menuBody[i]);
}
</code>```

The scenario it is replicating is using Fetch to pull up a HTML document.

The code parses the text, and then pulls out the body contents.  Something in the body uses an inline onmouseover.  So I also need to pull in the script tag.

But the onmouseover now doesn't work.

```<code>Uncaught ReferenceError: myFunc is not defined
</code>```

But if you use the Chrome Inspector - you can see the script has indeed been added.

(Please, let's not worry too much about why the page being fetched uses an onmouseover, I can't help that)

答:
I fixed it myself by using createElement and copying the script contents into that.  That works.  That'll do.</p>

```<code>var menuScript = el.firstChild.querySelector('head script');

var script = document.createElement( 'script' );
script.innerHTML = menuScript.innerHTML;

// Insert the script into current head tag.
document.head.appendChild(script);
</code>```

Body:
I've created this jsbin with a demo of my problem.

var textFromHTTPRequest = ''
    + ''
      + ''
    + ''
    + ''
      + 'test'
    + ''
  + '';

// Parse the text to dom element.
var parser = new DOMParser();
var el = parser.parseFromString(textFromHTTPRequest, "text/html");

// Get the script and contents of body.
var menuBody = el.firstChild.querySelectorAll('body > *');
var menuScript = el.firstChild.querySelector('head script');

// Insert the script into current head tag.
document.head.appendChild(menuScript);

// Insert the contents of body into current body.
for (var i = 0; i < menuBody.length; ++i) {
  document.body.appendChild(menuBody[i]);
}

The scenario it is replicating is using Fetch to pull up a HTML document.

The code parses the text, and then pulls out the body contents.  Something in the body uses an inline onmouseover.  So I also need to pull in the script tag.

But the onmouseover now doesn't work.

Uncaught ReferenceError: myFunc is not defined

But if you use the Chrome Inspector - you can see the script has indeed been added.

(Please, let's not worry too much about why the page being fetched uses an onmouseover, I can't help that)

Body:
I fixed it myself by using createElement and copying the script contents into that.  That works.  That'll do.

var menuScript = el.firstChild.querySelector('head script');

var script = document.createElement( 'script' );
script.innerHTML = menuScript.innerHTML;

// Insert the script into current head tag.
document.head.appendChild(script);


问:
Getting "package android.support.multidex does not exist" after upgrading to Android Studio 2.3
I updated from Android  Studio 2.2.3 to Android Studio 2.3 yesterday, and I ran into the following two problems:

Upon updating, Gradle 3.2 was installed by default, but syncing my
project would not work and I kept getting an error saying "Gradle 3.3
is required". Using the default Gradle wrapper doesn't work. The only way to fix this was to download Gradle 3.3
manually and point to the directory in build settings.

On running my project, I kept getting a string of errors involving my
BaseApplication class which extends MultiDexApplication. The
error goes something like this:

Error:(19, 62) error: package android.support.multidex does not exist

I am unable to resolve this error. I have buildToolsVersion '25.0.2', and my project compiled and ran properly before upgrading to Android Studio 2.3. Can anyone help me with this problem?

答:
I have passed the building. my solution is that adding explicit dependencies  in build.gradle.
    compile 'com.android.support:multidex:1.0.1'


问:
Call function which is added dynamically from controller
```<code>for (var i = 'A', k = 1; i <= 'Z', k <= $scope.noOfColumns; i = $scope.nextChar(i), k++)
{
    for (var j = 1; j <= $scope.noOfSeatsperRow; j++)
    {
        seats += '<div id=' + i + '' + j + ' class="seat" ng-click="selectOrDeselect($event)">'+ i + '' + j + '</div>';
        if (j == $scope.noOfSeatsperRow)
        {
            seats += '<br />';
        }
        if (j == $scope.noOfSeatsperRow/2)
        {
            seats += '<div class="gap"></div>';
        }
    }
}
angular.element(document.getElementsByClassName("seats")).html(seats);
</code>```

Here I am appending some HTML to pre-existing element. The problem is whenever I click ng-click event should invoke but it is not happening

I tried by giving statically in the view using for loop of razor there I can get the ng-click event invoked

What was the problem and how can I overcome with this?

答:
```<code>for (var i = 'A', k = 1; i <= 'Z', k <= $scope.noOfColumns; i = $scope.nextChar(i), k++)
{
    for (var j = 1; j <= $scope.noOfSeatsperRow; j++)
    {
        seats += '<div id=' + i + '' + j + ' class="seat" ng-click="selectOrDeselect($event)">' + i + '' + j + '</div>';
        if (j == $scope.noOfSeatsperRow)
        {
            seats += '<br />';
        }
        if (j == $scope.noOfSeatsperRow/2)
        {
            seats += '<div class="gap"></div>';
        }
    }
}

angular.element(document.getElementsByClassName("seats")).append($compile(seats)($scope));
</code>```

I got the solution using "append($compile(seats)($scope));" made that.

Body:
for (var i = 'A', k = 1; i <= 'Z', k <= $scope.noOfColumns; i = $scope.nextChar(i), k++)
{
    for (var j = 1; j <= $scope.noOfSeatsperRow; j++)
    {
        seats += '
'+ i + '' + j + '
';
        if (j == $scope.noOfSeatsperRow)
        {
            seats += '
';
        }
        if (j == $scope.noOfSeatsperRow/2)
        {
            seats += '

';
        }
    }
}
angular.element(document.getElementsByClassName("seats")).html(seats);

Here I am appending some HTML to pre-existing element. The problem is whenever I click ng-click event should invoke but it is not happening

I tried by giving statically in the view using for loop of razor there I can get the ng-click event invoked

What was the problem and how can I overcome with this?

Body:
for (var i = 'A', k = 1; i <= 'Z', k <= $scope.noOfColumns; i = $scope.nextChar(i), k++)
{
    for (var j = 1; j <= $scope.noOfSeatsperRow; j++)
    {
        seats += '<div id=' + i + '' + j + ' class="seat" ng-click="selectOrDeselect($event)">' + i + '' + j + '</div>';
        if (j == $scope.noOfSeatsperRow)
        {
            seats += '<br />';
        }
        if (j == $scope.noOfSeatsperRow/2)
        {
            seats += '<div class="gap"></div>';
        }
    }
}

angular.element(document.getElementsByClassName("seats")).append($compile(seats)($scope));

I got the solution using "append($compile(seats)($scope));" made that.


问:
something difficult when using ng-repeat with angular
I'm have two problem when using angular.

 I using ng-repeat to show all my item in database , but I want when click in img , go to review page , I have 30 item , but instead write 30 review page , is there another way better than it ? I'm using angular-ui  router

here is my code to show

```<code><tr ng-repeat ="data in mydata">
<td>{{data.code}}</td>
<td>{{data.name}}</td>
<td>{{data.price}}</td>
<td> <img ng-src={{data.img}}/>
</tr>
</code>```

I want when click img1 , go to url/code1 , click img2 , go to url/code2

And problem two is admin page

 I have form insert item in admin page , but I want when insert success , auto create review page item it . How can i do that.

Pls help me . Thank in advance

答:
First problem:

You need place link to review-page route in each of items:

```<code><li ng-repeat="dog in dogs">
  <a ui-sref="review-page({id:dog})">{{ dog }}</a>
</li>
</code>```

look at this plnkr at "partial-home.list"

Body:
I'm have two problem when using angular.

 I using ng-repeat to show all my item in database , but I want when click in img , go to review page , I have 30 item , but instead write 30 review page , is there another way better than it ? I'm using angular-ui  router

here is my code to show

{{data.code}}
{{data.name}}
{{data.price}}

I want when click img1 , go to url/code1 , click img2 , go to url/code2

And problem two is admin page

 I have form insert item in admin page , but I want when insert success , auto create review page item it . How can i do that.

Pls help me . Thank in advance

Body:
First problem:

You need place link to review-page route in each of items:

<li ng-repeat="dog in dogs">
  <a ui-sref="review-page({id:dog})">{{ dog }}</a>
</li>

look at this plnkr at "partial-home.list"


问:
visual studio 2017 install break : it not get start

I use the permission of Administrator to install vs_enterprise.exe.
But the install package don't work at all.

OS: win10 professional

The install log in appdata/local/temp/ is as follow:

dd_bootstrapper_20170313103210:

Beginning of the log. Start Time: 13/03/2017 10:32:10
VisualStudio Bootstrapper:13/03/2017 10:32:10: Current Optin root path does not
   exists
VisualStudio Bootstrapper:13/03/2017 10:32:11: Commandline
   arguments =

dd_vs_enterprise_decompression_log.txt:

[3/13/2017, 10:32:4] === Logging started: 2017/03/13 10:32:04 ===
[3/13/2017, 10:32:4] Executable: D:\vs2017\vs_enterprise.exe
   v15.0.26206.0
[3/13/2017, 10:32:4] --- logging level: standard ---

[3/13/2017, 10:32:4] Directory
   'C:\Users\gary\AppData\Local\Temp\b012f31d56525c685e\' has been
   selected for file extraction
[3/13/2017, 10:32:4] Extracting files
   to: C:\Users\gary\AppData\Local\Temp\b012f31d56525c685e\
[3/13/2017,
   10:32:5] Extraction took 484 milliseconds
[3/13/2017, 10:32:5]
   Executing extracted package:
   'vs_bootstrapper_d15\vs_setup_bootstrapper.exe ' with commandline ' '

[3/13/2017, 10:32:11] The entire Box execution exiting with result
   code: 0x0
[3/13/2017, 10:32:11] Launched extracted application
   exiting with result code: 0xc000000d
[3/13/2017, 10:32:11] ===
   Logging stopped: 2017/03/13 10:32:11 ===

Thank You~

答: I had the same Problem on two different Pc's (both win10) and the only thing that worked for me, was reinstalling Windows's and rerun the visual studio installer. I know, that's not a good, fast or easy solution, but it works.</p>


答:
The browser will not "use" script that was not created by hitself.

You have 2 options:

1- create a new script and use the other's .innerHTML

```<code>var menuScript = document.createElement('script');
menuScript.innerHTML = el.firstChild.querySelector('head script').innerHTML;
</code>```

jsBin: http://jsbin.com/dejerolozu/1/edit?html,css,js,output

2- use eval

You could run eval on that script, otherwise it will not be globalised by the browser:

```<code>// Insert the script into current head tag.
eval(menuScript.textContent);
</code>```

jsBin: http://jsbin.com/zuwolelozo/1/edit?html,css,js,output

Title: Function not defined when script appended to head and called from inline js

Body:
The browser will not "use" script that was not created by hitself.

You have 2 options:

1- create a new script and use the other's .innerHTML

var menuScript = document.createElement('script');
menuScript.innerHTML = el.firstChild.querySelector('head script').innerHTML;

jsBin: http://jsbin.com/dejerolozu/1/edit?html,css,js,output

2- use eval

You could run eval on that script, otherwise it will not be globalised by the browser:

// Insert the script into current head tag.
eval(menuScript.textContent);

jsBin: http://jsbin.com/zuwolelozo/1/edit?html,css,js,output


问:
If any input field value entered zero then disable else enable
I am trying to implement code in that if any of input value entered is zero then disable button otherwise enable. Its working fine when input value entered is zero but after I entered value other then zero it still disabled not enabling I am using counter and I have total nearly 40 text field to check so I am using input type with each statement.

following is fiddle which is I am implemented.

答:
It working for me :
HTML:

```<code><input type="text" class="form-input" id="input" >
<button id="fbtn">Submit</button>
</code>```

JQuery:

```<code><script type="text/javascript">
    $('#input').on('keyup',function(){
        var val = $('#input').val();
        if (val == 0) {
            $("#fbtn").attr("disabled","disabled");
        }else{
            $("#fbtn").removeAttr("disabled","disabled");
        }
    });
</script>
</code>```

You should add validation for input field. i mean accept only number etc.

Body:
It working for me :
HTML:

<input type="text" class="form-input" id="input" >
<button id="fbtn">Submit</button>

JQuery:

<script type="text/javascript">
    $('#input').on('keyup',function(){
        var val = $('#input').val();
        if (val == 0) {
            $("#fbtn").attr("disabled","disabled");
        }else{
            $("#fbtn").removeAttr("disabled","disabled");
        }
    });
</script>

You should add validation for input field. i mean accept only number etc.