问:
Displaying Rating star from Data-table column render is not working
I have used server side datatable for some of the reason and i am trying to display rating stars from one of the column, all the data correctly displaying,

Here is my .js code

```<code>$(document).ready(function(){
    table = $('.dataTables-example').DataTable({
        "serverSide": true,
        "ajax": {
            "url": "<?php echo base_url('admin/Review/get_Data')?>",
            "type": "POST"
        },
        "columns": [
            { "data": "review_id", "name":"review_id"},
            { "data": "hotel_name", "name":"hotel_name"},
            { "data": "review_by", "name":"review_by"},
            { "data": "review_title", "name":"review_title"},
            { "data": "review_desc",
                "render":function(data, type, row){
                    var review = row.review_desc;
                    var id = row.review_id;
                    if(row.review_desc.length > 50) {
                        var desc = '<div class="showbox">'+review.substring(0, 50)+'</div><span class="'+id+'more" style="display:none;">'+review.substring(50)+'</span><br><span onclick="see_more('+id+')" class="'+id+'readmore" style="color:red; cursor:pointer;">See More</span><span class="'+id+'nomore" onclick="nomore('+id+')" style="color:red;display:none; cursor:pointer;">See Less</span>';
                    }
                    else{
                        var desc = review;
                    };
                    return desc;
                },searchable: false, sortable: false
            },
            { "data": "created_at",
                render: function(created_at){
                    return moment(created_at).format("DD/MM/YYYY HH:mm A");
                }
            },
            { "data": "rating_star",
                render: function(rating_star){
                    return '<div class="star_rating_customer_reviews"><input value="'+rating_star+'" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true"></div>';
                }, searchable: false, sortable: false
            }
        ],
        "order": [ 0, 'desc' ],
        "columnDefs": [
            {
                "targets": [ 0 ],
                "visible": false,
                "searchable": false
            }
        ]
    });
});
</code>```

Here, i am trying to display rating star from column rating_star external rating css and js are not applying on that and it display like,

Look at the raings column it displays input field,
and i have done it in html like,

```<code><div class="star_rating_customer_reviews"><input value="1" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true"></div>
</code>```

It displaying perfectly above the select num of record to display dropdown. which looks like that external scripts are not accessing from datatable column.
I am stuck in this,

```<code>       { "data": "rating_star",
            render: function(rating_star){
                return '<div class="star_rating_customer_reviews"><input value="'+rating_star+'" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true"></div>';
            }, searchable: false, sortable: false
        }
</code>```

Please help me out,
used ajax datatable :- datatables.net

and the rating plugin i have used is :- star rating

答:
You can try something like this:</p>

```<code> columns:..,
 order: ...,
 createdRow: function (row, data, dataIndex) {

                            // any manipulation in the row element
                           var ratingInput = $(row).find('.rating');
                           $(ratingInput).rating();

                        }
</code>```

Body:
I have used server side datatable for some of the reason and i am trying to display rating stars from one of the column, all the data correctly displaying,

Here is my .js code

$(document).ready(function(){
    table = $('.dataTables-example').DataTable({
        "serverSide": true,
        "ajax": {
            "url": "<?php echo base_url('admin/Review/get_Data')?>",
            "type": "POST"
        },
        "columns": [
            { "data": "review_id", "name":"review_id"},
            { "data": "hotel_name", "name":"hotel_name"},
            { "data": "review_by", "name":"review_by"},
            { "data": "review_title", "name":"review_title"},
            { "data": "review_desc",
                "render":function(data, type, row){
                    var review = row.review_desc;
                    var id = row.review_id;
                    if(row.review_desc.length > 50) {
                        var desc = '
'+review.substring(0, 50)+'
'+review.substring(50)+'
See MoreSee Less';
                    }
                    else{
                        var desc = review;
                    };
                    return desc;
                },searchable: false, sortable: false
            },
            { "data": "created_at",
                render: function(created_at){
                    return moment(created_at).format("DD/MM/YYYY HH:mm A");
                }
            },
            { "data": "rating_star",
                render: function(rating_star){
                    return '
<input value="'+rating_star+'" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true">
';
                }, searchable: false, sortable: false
            }
        ],
        "order": [ 0, 'desc' ],
        "columnDefs": [
            {
                "targets": [ 0 ],
                "visible": false,
                "searchable": false
            }
        ]
    });
});

Here, i am trying to display rating star from column rating_star external rating css and js are not applying on that and it display like,

Look at the raings column it displays input field,
and i have done it in html like,

<input value="1" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true">

It displaying perfectly above the select num of record to display dropdown. which looks like that external scripts are not accessing from datatable column.
I am stuck in this,

       { "data": "rating_star",
            render: function(rating_star){
                return '
<input value="'+rating_star+'" type="number" class="rating" min=0 max=5 step=0.1 data-size="sm" data-stars="5" href="#" readonly="true">
';
            }, searchable: false, sortable: false
        }

Please help me out,
used ajax datatable :- datatables.net

and the rating plugin i have used is :- star rating

Body:
You can try something like this:

 columns:..,
 order: ...,
 createdRow: function (row, data, dataIndex) {

                            // any manipulation in the row element
                           var ratingInput = $(row).find('.rating');
                           $(ratingInput).rating();

                        }


来源: stackexchange

问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
Below is sample refactoring to make your code cleaner, it can further be refactor if perform_action_and_exit() is the same method all throughout your code</p>

```<code>if (group == G1) {
  doG1Stuff();
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

void doG1Stuff(){
 if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (shouldActionBePerformed()) {
        perform_action_and_exit();
    }
  }
}

boolean shouldActionBePerformed(){
    return role == R1 && (level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3));
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
Below is sample refactoring to make your code cleaner, it can further be refactor if perform_action_and_exit() is the same method all throughout your code

if (group == G1) {
  doG1Stuff();
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

void doG1Stuff(){
 if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (shouldActionBePerformed()) {
        perform_action_and_exit();
    }
  }
}

boolean shouldActionBePerformed(){
    return role == R1 && (level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3));
}


问:
git cherry: How to identify equivalent commit by commit message
In my project there are a stable branch and a dev branch. Commits are cherry-picked from dev branch to stable branch.

In order to filter all commits on dev that have not been merged to stable, git cherry -v stable dev looks like a good choice. However it identifies equivalence by diff, which usually changes after resolving merge conflict during cherry-pick:

The equivalence test is based on the diff, after removing whitespace
  and line numbers. git-cherry therefore detects when commits have been
  "copied" by means of git-cherry-pick(1), git-am(1) or git-rebase(1).

I was wondering that is there any command that works like git cherry, but identifies equivalent commits by commit message?

答:
You want to use patch-id. This is the mechanism used by git cherry.

To find an equivalent of commit 3642151 run:

git show 3642151 | git patch-id

You should get a line with two hashes; the first is the patchid (call
it PATCHID_FROM_ABOVE)

git log -p | git patch-id | grep PATCHID_FROM_ABOVE

This should give you a list of all commits that correspond to that patchid.

Stolen from: http://git.661346.n2.nabble.com/git-cherry-to-find-equivalent-commit-IDs-td3440883.html


问:
Is this actually mutating the state?
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

```<code>import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (
      <div className="App">
        <h1>This is an app</h1>
        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />
      </div>
    );
  }
}

export default App;
</code>```

答:
As setState is asynchronous to increase the age by one it is advisable to pass the prevState as an argument to the setState callback function as below. Also there is no mutation of state if you add 1 to the previous state as below:

```<code> increaseAgeHandler = () => {

    this.setState(prevState => {
      persons: [
        { name: 'Max', age: prevState.persons[0].age + 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });

  }
</code>```

Title: Is this actually mutating the state?

Body:
I've just put together a really basic bit of React functionality to show someone and my console tab is accusing me of mutating the state directly.  I thought that as long as you're using this.setState() that you're basically fine.

This little bit of code just spits out the first person from the person object stored in the state and then when you click the button it increments the age (this actually all works, incidentally).

Am I actually directly mutating the state by doing this?  And if I am, what is the correct way of doing this?

import React, { Component } from 'react';
import './App.css';
import Person from './Person/Person';

class App extends Component {
  state = {
    persons: [
      { name: 'Max', age: 28 },
      { name: 'Stephanie', age: 26 },
      { name: 'Manu', age: 29 },
    ],
  }

  increaseAgeHandler = () => {
    this.setState({
      persons: [
        { name: 'Max', age: this.state.persons[0].age += 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });
  }

  render() {
    return (

This is an app

        <button onClick={this.increaseAgeHandler}>Add to age</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age} />

    );
  }
}

export default App;

Body:
As setState is asynchronous to increase the age by one it is advisable to pass the prevState as an argument to the setState callback function as below. Also there is no mutation of state if you add 1 to the previous state as below:

 increaseAgeHandler = () => {

    this.setState(prevState => {
      persons: [
        { name: 'Max', age: prevState.persons[0].age + 1 },
        { name: 'Stephanie', age: 26 },
        { name: 'Manu', age: 29 },
      ],
    });

  }


问:
Objects in JSON array - Can't get multidimenson arrays
I have a JSON file with a String like this:

```<code>[{"Ean":"","Barcode":"010258100139","Bezeichnung":"Alia","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":129.90,"Vk":129.90}]
</code>```

with PHP I try to get it into arrays so I can get the data:

```<code>$jsonarray = json_decode($jsonfile);
$jsonarray = json_decode(json_encode($jsonarray), true);
var_dump( $jsonarray );
</code>```

What I get is following:

```<code>array (size=3)
   0 =>
   array (size=8)
     'Ean' => string '' (length=0)
     'Barcode' => string '010258100139' (length=12)
     'Bezeichnung' => string 'Alia' (length=4)
     'Bestaende' =>
         array (size=1)
            0 =>
              array (size=5)
                  ...
     'Bestand' => int 1
     'Dispo' => int 0
     'Uvp' => float 129.9
     'Vk' => float 129.9
</code>```

And thats it! I try many examples from here wit nested objects.
If I try to get data like

```<code>echo $jsonarray[0]['Barcode'];
</code>```

I get my Barcode String without problems. But the data in "array (size=5)" I can't access.
I try many things like nested foreach loops, functions from here like "object_to_array", "json_encode2" and so on.

Can anybody give me a tip how I can access it? I Try to get ""Menge":1".

Thanks in advance.
Tyv

答:
You really only need one json_decode, like so:

```<code>$data = '[{"Ean":"","Barcode":"010258100139","Bezeichnung":"Alia","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":129.90,"Vk":129.90}]';

$jsonarray = json_decode($data,true);
</code>```

When you print it out, you get:

```<code>print_r($jsonarray);// I use print_r as its output looks more like how you use it

Array
(
    [0] => Array
        (
            [Ean] =>
            [Barcode] => 010258100139
            [Bezeichnung] => Alia
            [Bestaende] => Array
                (
                    [0] => Array
                        (
                            [Filiale] => 1
                            [FilialeBez] => Laden
                            [Menge] => 1
                            [Gln] =>
                            [Dispo] => 0
                        )
                )
            [Bestand] => 1
            [Dispo] => 0
            [Uvp] => 129.9
            [Vk] => 129.9
        )
)
</code>```

So from there, you can see how you can get at certain points of data. For example you wanted Bestaende's first data array, so you would grab it as:

```<code>$jsonarray['0']['Bestaende']['0']; // for the whole group
$jsonarray['0']['Bestaende']['0']['Menge']; // for specific items
</code>```

If you have multiple groups under Bestaende, then you could loop them doing what you need to do with each:

```<code>foreach($jsonarray['0']['Bestaende'] as $idx => $Bestaende) {
    $Bestaende['Menge']; // to use that specific data of that group this loop
}
</code>```

Body:
I have a JSON file with a String like this:

[{"Ean":"","Barcode":"010258100139","Bezeichnung":"Alia","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":129.90,"Vk":129.90}]

with PHP I try to get it into arrays so I can get the data:

$jsonarray = json_decode($jsonfile);
$jsonarray = json_decode(json_encode($jsonarray), true);
var_dump( $jsonarray );

What I get is following:

array (size=3)
   0 =>
   array (size=8)
     'Ean' => string '' (length=0)
     'Barcode' => string '010258100139' (length=12)
     'Bezeichnung' => string 'Alia' (length=4)
     'Bestaende' =>
         array (size=1)
            0 =>
              array (size=5)
                  ...
     'Bestand' => int 1
     'Dispo' => int 0
     'Uvp' => float 129.9
     'Vk' => float 129.9

And thats it! I try many examples from here wit nested objects.
If I try to get data like

echo $jsonarray[0]['Barcode'];

I get my Barcode String without problems. But the data in "array (size=5)" I can't access.
I try many things like nested foreach loops, functions from here like "object_to_array", "json_encode2" and so on.

Can anybody give me a tip how I can access it? I Try to get ""Menge":1".

Thanks in advance.
Tyv

Body:
You really only need one json_decode, like so:

$data = '[{"Ean":"","Barcode":"010258100139","Bezeichnung":"Alia","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":129.90,"Vk":129.90}]';

$jsonarray = json_decode($data,true);

When you print it out, you get:

print_r($jsonarray);// I use print_r as its output looks more like how you use it

Array
(
    [0] => Array
        (
            [Ean] =>
            [Barcode] => 010258100139
            [Bezeichnung] => Alia
            [Bestaende] => Array
                (
                    [0] => Array
                        (
                            [Filiale] => 1
                            [FilialeBez] => Laden
                            [Menge] => 1
                            [Gln] =>
                            [Dispo] => 0
                        )
                )
            [Bestand] => 1
            [Dispo] => 0
            [Uvp] => 129.9
            [Vk] => 129.9
        )
)

So from there, you can see how you can get at certain points of data. For example you wanted Bestaende's first data array, so you would grab it as:

$jsonarray['0']['Bestaende']['0']; // for the whole group
$jsonarray['0']['Bestaende']['0']['Menge']; // for specific items

If you have multiple groups under Bestaende, then you could loop them doing what you need to do with each:

foreach($jsonarray['0']['Bestaende'] as $idx => $Bestaende) {
    $Bestaende['Menge']; // to use that specific data of that group this loop
}


问:
Angular 5: Subject's .next() is not a function
I'm trying to push a new string to a Subject called period with .next() but the console gives me a this.period.next is not a function error.

option.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
    selector: 'app-option',
    templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
    public period: Subject<string> = new Subject<string>();

    constructor() {}

    ngOnInit() {}

    setPeriod(period: string) {
        this.period.next(period);
    }
}
</code>```

option.component.html

```<code><mat-radio-group [(ngModel)]="period" (ngModelChange)="setPeriod($event)">
    <span *ngFor="let option of httpHeader.option"><mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button><br /></span>
</mat-radio-group>
</code>```

I'm running rxjs 5.5.2. The function setPeriod is triggered when a user selects a radio button.

What am I doing wrong? I use the same method in a http service and that works but in this component it doesn't.

答:
[(ngModel)]="period" is a two-way binding on your component's period property. I believe it's updating the period property to be equal to the radio group's value, overwriting the instance of Subject that you assign when the component is created. That's why it no longer has property .next when you call setPeriod.

The simple case usage of mat-radio-group in a template-driven form is this:

```<code><mat-radio-group class="example-radio-group"
                 [(ngModel)]="favoriteSeason">
    <mat-radio-button class="example-radio-button"
                      *ngFor="let season of seasons" [value]="season">
        {{season}}
    </mat-radio-button>
</mat-radio-group>
<div class="example-selected-value">
    Your favorite season is: {{favoriteSeason}}
</div>

...
export class RadioNgModelExample {
    favoriteSeason: string;

    seasons = [
        'Winter',
        'Spring',
        'Summer',
        'Autumn',
    ];
}
</code>```

Ref: https://material.angular.io/components/radio/examples

If you want to emit on a subject on every change to this radio group, I suggest you use reactive forms:

```<code>export class Example {
    radio: FormControl = new FormControl();
    period: Subject<string> = new Subject<string>();

    ...

    ngOnInit() {
        this.radio.valueChanges.subscribe(value => {
            this.period.next(value);
        });
    }
}

<mat-radio-group [formControl]="radio">
    <span *ngFor="let option of httpHeader.option">
        <mat-radio-button [checked]="option.default"
                          [value]="option.param" >
            {{ option.desc }}
        </mat-radio-button>
        <br />
   </span>
</mat-radio-group>
</code>```

Body:
I'm trying to push a new string to a Subject called period with .next() but the console gives me a this.period.next is not a function error.

option.component.ts

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
    selector: 'app-option',
    templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
    public period: Subject<string> = new Subject<string>();

    constructor() {}

    ngOnInit() {}

    setPeriod(period: string) {
        this.period.next(period);
    }
}

option.component.html

<mat-radio-group [(ngModel)]="period" (ngModelChange)="setPeriod($event)">
    <mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button>

</mat-radio-group>

I'm running rxjs 5.5.2. The function setPeriod is triggered when a user selects a radio button.

What am I doing wrong? I use the same method in a http service and that works but in this component it doesn't.

Body:
[(ngModel)]="period" is a two-way binding on your component's period property. I believe it's updating the period property to be equal to the radio group's value, overwriting the instance of Subject that you assign when the component is created. That's why it no longer has property .next when you call setPeriod.

The simple case usage of mat-radio-group in a template-driven form is this:

<mat-radio-group class="example-radio-group"
                 [(ngModel)]="favoriteSeason">
    <mat-radio-button class="example-radio-button"
                      *ngFor="let season of seasons" [value]="season">
        {{season}}
    </mat-radio-button>
</mat-radio-group>
<div class="example-selected-value">
    Your favorite season is: {{favoriteSeason}}
</div>

...
export class RadioNgModelExample {
    favoriteSeason: string;

    seasons = [
        'Winter',
        'Spring',
        'Summer',
        'Autumn',
    ];
}

Ref: https://material.angular.io/components/radio/examples

If you want to emit on a subject on every change to this radio group, I suggest you use reactive forms:

export class Example {
    radio: FormControl = new FormControl();
    period: Subject<string> = new Subject<string>();

    ...

    ngOnInit() {
        this.radio.valueChanges.subscribe(value => {
            this.period.next(value);
        });
    }
}

<mat-radio-group [formControl]="radio">
    <span *ngFor="let option of httpHeader.option">
        <mat-radio-button [checked]="option.default"
                          [value]="option.param" >
            {{ option.desc }}
        </mat-radio-button>
        <br />
   </span>
</mat-radio-group>


问:
SQL Dependency & SignalR - Two web apps with the same code, one is working while the other is not

Brief Introduction:

There's a TL;DR at the end (:

I have two versions of a web app that uses SQL Dependency and SignalR to automatically refresh views when a change in DB is detected.

The previous version of the application works correctly, while the new version does not. The strange thing is that, at first sight, both versions have the same code, there was no change in the part of SignalR between both web apps.

What could this be?

Is there anything else that I should keep in mind and that I have forgotten?

How can it be that the code that is responsible for triggering the refresh event when a change in the database occurs does not trigger the event?

NotifierEntity.cs:

When you start the application, both versions correctly execute the following code in the backend:

```<code>void RegisterForNotifications()
{
    using (var sqlConnection = new SqlConnection(notificationEntity.SqlConnectionString))
    using (var sqlCommand = new SqlCommand(notificationEntity.SqlQuery, sqlConnection))
    {
        foreach (var sqlParameter in notificationEntity.SqlParameters)
            sqlCommand.Parameters.Add(sqlParameter);

        sqlCommand.Notification = null;
        var sqlDependency = new SqlDependency(sqlCommand);
        sqlDependency.OnChange += OnSqlDependencyChange;
        if (sqlConnection.State == ConnectionState.Closed)
            sqlConnection.Open();
        sqlCommand.ExecuteNonQuery();
        sqlCommand.Parameters.Clear();
    }
}
</code>```

NOTE: The OnChangeevent in the new version is never triggered.

The view I want to refresh:

The view I want to refresh automatically contains the following script, whose function is to subscribe to the event of changing a table in the DB.

Like the code above, this code is the same between both versions of the web app.

```<code><script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script src="~/Scripts/anotherScript.min.js"></script>
<script type="text/javascript">
    var signalRHubInitialized2 = false;

    $(function () {
        InitializeSignalRHubStore2();
    });
    function InitializeSignalRHubStore2() {
        if (signalRHubInitialized2)
            return;
        try {
            var clientHub2 = $.connection.hubNotificacion;
            clientHub2.client.updateTableVehicles = function (message) {
                if (message === "Refresh")
                    ReloadIndexPartial2();
            };
            $.connection.hub.start().done(function () {
                clientHub2.server.initializeTableDependencyVehicles();
                signalRHubInitialized2 = true;
            });
        } catch (err) {
            signalRHubInitialized2 = false;
        }
    };
    function ReloadIndexPartial2() {
        location.reload();
    }
</script>
</code>```

The Hub:

When you load the view and run that script, the following hub code is accessed in the backend. The first part of the code seems to work just fine in both versions of the web application:

```<code>public void InitializeTableDependencyVehicles()
{
    if (!flag)
    {
        using (var db = new ApplicationDbContext())
        {
            string data = db.GetNotifierEntity<Vehicle>(db.Vehicles).ToJson();
            NotifierEntity NotifierEntity1 = NotifierEntity.FromJson(data);
            Action<String> dispatcher = (t) => { DispatchToClientTablesVehicles(); };
            PushSqlDependency.Instance(NotifierEntity1, dispatcher);
            flag = true;
        }
    }
}
</code>```

But the second code automatically runs only on one of the versions of the web application. The other version does not seem to trigger the refresh event when a record is updated in the database.  Please remember that, to the naked eye, both webs have the same code in the SignalR and SQL Dependency part.

```<code>public void DispatchToClientTablesVehicles()
{
    Clients.All.updateTableVehicles("Refresh");
}
</code>```

 TL;DR

Two versions of the same web app have the same code, however one of the versions of the web app detects the changes in the DB and triggers one event while the other version does not.

Both Web Applications run the same code (the SignalR and SQL Dependency stuff)

One Web Application does refresh automatically the view, but the other does not.

Can anybody help me with this?

答:
I managed to solve this problem by deleting the database and creating it again.
I have generated the scripts to fill again the data and it worked again.

Important: restoring the database from a .bak backup file didn't worked. I had to create a new database from scratch.

P.S. (so that you avoid later headaches): I've noticed that SignalR stops working quickly as some concurrent connections are generated. It's not a good idea if you're planning to log in with 10 users at the same time.

Body:
Brief Introduction:

There's a TL;DR at the end (:

I have two versions of a web app that uses SQL Dependency and SignalR to automatically refresh views when a change in DB is detected.

The previous version of the application works correctly, while the new version does not. The strange thing is that, at first sight, both versions have the same code, there was no change in the part of SignalR between both web apps.

What could this be?

Is there anything else that I should keep in mind and that I have forgotten?

How can it be that the code that is responsible for triggering the refresh event when a change in the database occurs does not trigger the event?

NotifierEntity.cs:

When you start the application, both versions correctly execute the following code in the backend:

void RegisterForNotifications()
{
    using (var sqlConnection = new SqlConnection(notificationEntity.SqlConnectionString))
    using (var sqlCommand = new SqlCommand(notificationEntity.SqlQuery, sqlConnection))
    {
        foreach (var sqlParameter in notificationEntity.SqlParameters)
            sqlCommand.Parameters.Add(sqlParameter);

        sqlCommand.Notification = null;
        var sqlDependency = new SqlDependency(sqlCommand);
        sqlDependency.OnChange += OnSqlDependencyChange;
        if (sqlConnection.State == ConnectionState.Closed)
            sqlConnection.Open();
        sqlCommand.ExecuteNonQuery();
        sqlCommand.Parameters.Clear();
    }
}

NOTE: The OnChangeevent in the new version is never triggered.

The view I want to refresh:

The view I want to refresh automatically contains the following script, whose function is to subscribe to the event of changing a table in the DB.

Like the code above, this code is the same between both versions of the web app.

The Hub:

When you load the view and run that script, the following hub code is accessed in the backend. The first part of the code seems to work just fine in both versions of the web application:

public void InitializeTableDependencyVehicles()
{
    if (!flag)
    {
        using (var db = new ApplicationDbContext())
        {
            string data = db.GetNotifierEntity<Vehicle>(db.Vehicles).ToJson();
            NotifierEntity NotifierEntity1 = NotifierEntity.FromJson(data);
            Action<String> dispatcher = (t) => { DispatchToClientTablesVehicles(); };
            PushSqlDependency.Instance(NotifierEntity1, dispatcher);
            flag = true;
        }
    }
}

But the second code automatically runs only on one of the versions of the web application. The other version does not seem to trigger the refresh event when a record is updated in the database.  Please remember that, to the naked eye, both webs have the same code in the SignalR and SQL Dependency part.

public void DispatchToClientTablesVehicles()
{
    Clients.All.updateTableVehicles("Refresh");
}

 TL;DR

Two versions of the same web app have the same code, however one of the versions of the web app detects the changes in the DB and triggers one event while the other version does not.

Both Web Applications run the same code (the SignalR and SQL Dependency stuff)

One Web Application does refresh automatically the view, but the other does not.

Can anybody help me with this?


问:
MongoDb connection refused
This is my first attempt to consume MongoDB. I've got Mongo running:

```<code>ps -ef | grep [m]ongo
mongodb  11023  1  0 Jun24 ? 00:00:03 /usr/lib/mongodb/mongod --config /etc/mongodb.conf
</code>```

And the error comes as the result of doing

```<code>Datastore.save( stuff );  // (pseudo code)
</code>```

The error:

```<code>Jun 27, 2011 3:20:29 PM com.mongodb.DBTCPConnector fetchMaxBsonObjectSize
WARNING: Exception determining maxBSON size using0
java.io.IOException: couldn't connect to [russ-elite-book/127.0.1.1:27017] bc:java.net.ConnectException: Connection refused
    at com.mongodb.DBPort._open(DBPort.java:206)
    at com.mongodb.DBPort.go(DBPort.java:94)
    at com.mongodb.DBPort.go(DBPort.java:75)
    at com.mongodb.DBPort.findOne(DBPort.java:129)
    at com.mongodb.DBPort.runCommand(DBPort.java:138)
    ...
</code>```

Note that I'm using 127.0.0.1:27017 for my connection, which works to the Mongo shell. Also, I get the admin page in the browser using http://localhost:28017.

Profuse thanks for any and all ideas!

答: For me, it was a completely different solution. I am using Spring MVC framework, and all I had to do is to confirm that the configuration XML files are saying the same thing in the /target folder as well as the non-target folders.  Once that was adjusted, everything worked.  The problem was that everything worked when run from a STS, but when deployed, I had the mentioned error.</p>

Title: MongoDb connection refused

Body:
This is my first attempt to consume MongoDB. I've got Mongo running:

ps -ef | grep [m]ongo
mongodb  11023  1  0 Jun24 ? 00:00:03 /usr/lib/mongodb/mongod --config /etc/mongodb.conf

And the error comes as the result of doing

Datastore.save( stuff );  // (pseudo code)

The error:

Jun 27, 2011 3:20:29 PM com.mongodb.DBTCPConnector fetchMaxBsonObjectSize
WARNING: Exception determining maxBSON size using0
java.io.IOException: couldn't connect to [russ-elite-book/127.0.1.1:27017] bc:java.net.ConnectException: Connection refused
    at com.mongodb.DBPort._open(DBPort.java:206)
    at com.mongodb.DBPort.go(DBPort.java:94)
    at com.mongodb.DBPort.go(DBPort.java:75)
    at com.mongodb.DBPort.findOne(DBPort.java:129)
    at com.mongodb.DBPort.runCommand(DBPort.java:138)
    ...

Note that I'm using 127.0.0.1:27017 for my connection, which works to the Mongo shell. Also, I get the admin page in the browser using http://localhost:28017.

Profuse thanks for any and all ideas!


问:
Why isn't my variable available inside the scope of an AngularJS promise?
I write promises to take from back-end some data. But function end() don't see my variable witch contains this data. What I'm doing wrong, and how to return overlappingProjects variable?

Console.log(1 and 2) shows massive with data but console.log(4) already have empty object.

```<code>this.checkSingleInvitation = function(invitation) {
    console.log('Оверлап сингл');
    var dtoArray = [];
    var overlappingProjects = {};

    InvitationService.acceptedProjects.models.forEach(function(accepted) {
        if(!(dateHelper.parseDate(accepted.dt_from) > dateHelper.parseDate(invitation.dt_to) || dateHelper.parseDate(accepted.dt_to) < dateHelper.parseDate(invitation.dt_from))) {
            var dto = {
                target: invitation.project_has_musicians_id,
                goal: accepted.project_id
            };
            dtoArray.push(dto);
        }
    });

    var promises = [];
    angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};
        //async fun
        InvitationService.checkOverlapping(dto)
            .before(function() {
                progressBars.progressbar.requestsInProgress++;
            })
            .success(function(data) {
                // TODO: overlappingProjects - ???
                if(Object.keys(data).length) {
                    console.log('1');
                    console.log(data);
                    overlappingProjects = data;
                    console.log(overlappingProjects);
                }
                console.log('2');
                console.log(data);
                deferred.resolve(data);
            })
            .error(function(error) {
                deferred.reject(error);
            })
            .finally(function() {
                progressBars.progressbar.requestsInProgress--;
            });
        promises.push(deferred.promise);
    }));
    $q.all(promises).then(console.log(promises)).then(
        end()
    );

    function end() {
        console.log('4');
        console.log(overlappingProjects);
        return overlappingProjects;
    }
}
</code>```

答:
The problem seems to be that you are defining overlappingProjects twice.
Remove the second definition:

```<code>  angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};  //  <-- remove this line
</code>```

Body:
I write promises to take from back-end some data. But function end() don't see my variable witch contains this data. What I'm doing wrong, and how to return overlappingProjects variable?

Console.log(1 and 2) shows massive with data but console.log(4) already have empty object.

this.checkSingleInvitation = function(invitation) {
    console.log('Оверлап сингл');
    var dtoArray = [];
    var overlappingProjects = {};

    InvitationService.acceptedProjects.models.forEach(function(accepted) {
        if(!(dateHelper.parseDate(accepted.dt_from) > dateHelper.parseDate(invitation.dt_to) || dateHelper.parseDate(accepted.dt_to) < dateHelper.parseDate(invitation.dt_from))) {
            var dto = {
                target: invitation.project_has_musicians_id,
                goal: accepted.project_id
            };
            dtoArray.push(dto);
        }
    });

    var promises = [];
    angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};
        //async fun
        InvitationService.checkOverlapping(dto)
            .before(function() {
                progressBars.progressbar.requestsInProgress++;
            })
            .success(function(data) {
                // TODO: overlappingProjects - ???
                if(Object.keys(data).length) {
                    console.log('1');
                    console.log(data);
                    overlappingProjects = data;
                    console.log(overlappingProjects);
                }
                console.log('2');
                console.log(data);
                deferred.resolve(data);
            })
            .error(function(error) {
                deferred.reject(error);
            })
            .finally(function() {
                progressBars.progressbar.requestsInProgress--;
            });
        promises.push(deferred.promise);
    }));
    $q.all(promises).then(console.log(promises)).then(
        end()
    );

    function end() {
        console.log('4');
        console.log(overlappingProjects);
        return overlappingProjects;
    }
}

Body:
The problem seems to be that you are defining overlappingProjects twice.
Remove the second definition:

  angular.forEach(dtoArray, (function(dto) {
        var deferred = $q.defer();
        var overlappingProjects = {};  //  <-- remove this line


问:
how convert unix timestamp to datetime
I'm trying to convert this unix timestamp
1415115303410
in DateTime, in this way:

```<code>private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
        return dtDateTime;
}
</code>```

But I get a wrong date:
Date: {04/11/0045 00:00:00}

NOTE: dtDateTime.AddSeconds(unixTimeStamp) throws an exception.. my number is in Milliseconds.

with this online conversion tool http://www.epochconverter.com/ I get the right conversion:

04/11/2014 15:35:03 GMT+0:00

How I can convert this one?

答:
Microsoft continue thinking about us! All solutions to add seconds/milliseconds is not working with Visual Studio 2017 (.Net 4.6.1). But there is a new solution:

```<code>public static DateTime numStrToDate(String val)
{
    DateTime dRet = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    long dSec;
    if (long.TryParse(val, out dSec))
    {
        TimeSpan ts = new TimeSpan(dSec*10l);
        dRet = dRet.Add(ts);
    }
    return dRet;
}
</code>```

If you need a UTC time - just add 'System.DateTimeKind.Utc' to the DateTime constructor call.

Title: how convert unix timestamp to datetime

Body:
I'm trying to convert this unix timestamp
1415115303410
in DateTime, in this way:

private static DateTime UnixTimeStampToDateTime(long unixTimeStamp)
{
        System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        dtDateTime = dtDateTime.AddMilliseconds(unixTimeStamp);
        return dtDateTime;
}

But I get a wrong date:
Date: {04/11/0045 00:00:00}

NOTE: dtDateTime.AddSeconds(unixTimeStamp) throws an exception.. my number is in Milliseconds.

with this online conversion tool http://www.epochconverter.com/ I get the right conversion:

04/11/2014 15:35:03 GMT+0:00

How I can convert this one?

Body:
Microsoft continue thinking about us! All solutions to add seconds/milliseconds is not working with Visual Studio 2017 (.Net 4.6.1). But there is a new solution:

public static DateTime numStrToDate(String val)
{
    DateTime dRet = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    long dSec;
    if (long.TryParse(val, out dSec))
    {
        TimeSpan ts = new TimeSpan(dSec*10l);
        dRet = dRet.Add(ts);
    }
    return dRet;
}

If you need a UTC time - just add 'System.DateTimeKind.Utc' to the DateTime constructor call.


问:
smtp StartTLS office 365 (wordpress)
I have a problem regarding mail going to the junk folder. I have found a lot of smtp plugins that support SSL and TLS but non that fully support StartTLS. Is there a plugin that I've missed or how would I solve this problem without a plugin?</p>

答:
Well this question is 6 months old at the time of this writing, with 209 views. Glad I know I'm not the only one with this problem!

Anyway I found a solution - use the plugin called WP Mail SMTP (by WPForms) https://wordpress.org/plugins/wp-mail-smtp/

I have a client using Office365 and their StartTLS was not having it with the Easy WP SMTP or Cimy plugins. Not sure what WP Mail SMTP is doing differently but it works, I'm gonna check out their code to see what the other plugins are missing.

Title: smtp StartTLS office 365 (wordpress)


问:
Multi-user sharing excel files and automated refresh
Any recommendation on having a shared excel file auto-refresh itself?

We will need 3 users of an excel file on the fileserver. One user will be making changes. Others are read-only, but they must see the change as quickly as possible. Any pointers on how to do this?

答:
Save main excel file (A) on the server and give access to editor so that he can edit. Copy same file and name it (B) and link it to main file (A) to read data and protect. You can do this simply by referencing respective cells to main file. Distribute copies of file (B) to users to read the data.

How to link?: Open both files on your PC, in file (B) Sheet-1 click in Cell A1, type = and go to File (A) Sheet-1 and click in Cell A1. In formula bar if cell reference is absolute ('[(A).xlsx]Sheet1'!$A$1) change it to normal ('[(A).xlsx]Sheet1'!A1) by hitting F4 3 times. and hit Enter. Cell A1 in File (B) has been linked to respective cell in main file (A).
Now select cell A1 in file (B) and drag it towards last required cell on right then select line 1 and drag downwards as required. Now the whole page is linked back to your file (A). Similarly do for other sheets. Any changes done on file (A) will reflect in File (B) in real time if both are open, otherwise on reopening file (B) you will be asked to update, click yes and that is it. Hope this helps.


问:
c# Split string using another string as delimiter and include delimiter as part of the splitted string
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

```<code>string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};
</code>```

Expected output:

```<code>outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings
</code>```

What I tried:

```<code>var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);
</code>```

Output I got:

```<code>result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"
</code>```

I couldnt find an API in string.split or in Regex to split as the expect result.

答:
```<code>string content = "heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
string[] delimters = new string[] { "heading1:", "heading2:", "heading3:" };

var dels = string.Join("|", delimters);
var pattern = "(" + dels + ").*?(?=" + dels + "|\\Z)";

var outputArray = Regex.Matches(content, pattern);

foreach (Match match in outputArray)
    Console.WriteLine(match);
</code>```

The pattern is the following:

```<code>(heading1:|heading2:|heading3:).*?(?=heading1:|heading2:|heading3:|\Z)
</code>```

It looks like the answer of Wiktor Stribiżew.

And of course we should use Regex.Escape, as he has shown.

Body:
I need to split an input string using c# regex.
need to know how to include the delimiter content in the output as given below.

input:

string content="heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";

string[] delimters = new string[] {"heading1:","heading2:","heading3:"};

Expected output:

outputArray[0] = heading1: contents with respect to heading1
outputArray[1] = heading2: heading2 contents
outputArray[2] = heading3: heading 3 related contents sample strings

What I tried:

var result = content.Split(delimters,StringSplitOptions.RemoveEmptyEntries);

Output I got:

result [0]: " contents with respect to heading1 "
result [1]: " heading2 contents "
result [2]: " heading 3 related contents sample strings"

I couldnt find an API in string.split or in Regex to split as the expect result.

Body:
string content = "heading1: contents with respect to heading1 heading2: heading2 contents heading3: heading 3 related contents sample strings";
string[] delimters = new string[] { "heading1:", "heading2:", "heading3:" };

var dels = string.Join("|", delimters);
var pattern = "(" + dels + ").*?(?=" + dels + "|\\Z)";

var outputArray = Regex.Matches(content, pattern);

foreach (Match match in outputArray)
    Console.WriteLine(match);

The pattern is the following:

(heading1:|heading2:|heading3:).*?(?=heading1:|heading2:|heading3:|\Z)

It looks like the answer of Wiktor Stribiżew.

And of course we should use Regex.Escape, as he has shown.


问:
How can I pass the data from one activity to another listview activity?
I need to pass the data from one activity to a ListView inside another activity. Currently I have set a single TextView to see all the details in second activity. But instead I need to view those items in ListView with adapter for each item.

MainActivity.java:

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
    String[] place={"Karur","Salem","Namakkal","Trichy","Madurai"};

    EditText Name;
    EditText Email;
    EditText Number;
    Button submit;
    RadioGroup radioGroup;
    RadioButton maleradioButton,femaleradioButton;
    CheckBox BEcheckbox,MEcheckbox;
    Spinner spin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         spin = (Spinner)findViewById(R.id.spinner);
        spin.setOnItemSelectedListener(this);

        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, place);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(aa);

        Name = (EditText)findViewById(R.id.Name);
        Email = (EditText)findViewById(R.id.Email);
        Number = (EditText)findViewById(R.id.Number);
        submit = (Button)findViewById(R.id.submit);
        radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
      ////  maleradioButton = (RadioButton)findViewById(R.id.maleradioButton);
        femaleradioButton = (RadioButton)findViewById(R.id.femaleradioButton);
        BEcheckbox = (CheckBox)findViewById(R.id.BEcheckBox);
        MEcheckbox = (CheckBox)findViewById(R.id.MEcheckbox);
       final RadioGroup rgroup = (RadioGroup)findViewById(R.id.radioGroup);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String spinText = spin.getSelectedItem().toString();
                String name = Name.getText().toString();
                String email = Email.getText().toString();
                String number = Number.getText().toString();
String val="";
String radio;
if (BEcheckbox.isChecked()) {
    val="BE";
} if(MEcheckbox.isChecked()) {
                    val="ME";

                }
                int select=rgroup.getCheckedRadioButtonId();
                maleradioButton=(RadioButton)findViewById(select);
                radio=maleradioButton.getText().toString();
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("Name",name);
                intent.putExtra("Email",email);
                intent.putExtra("Number",number);
                intent.putExtra("Degree",val);
                intent.putExtra("Gender",radio);
                intent.putExtra("Place",spinText);

                startActivity(intent);
            }
        });

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
</code>```

SecondActivity.java:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

    String Name;
    String Email;
    String Number;
    String Degree;
    String Gender;
    String Place;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        result = (TextView)findViewById(R.id.result);

        Name = getIntent().getExtras().getString("Name");
        Email = getIntent().getExtras().getString("Email");
        Number = getIntent().getExtras().getString("Number");
        Degree = getIntent().getExtras().getString("Degree");
        Gender = getIntent().getExtras().getString("Gender");
        Place = getIntent().getExtras().getString("Place");

        result.setText("Name:"+""+Name +'\n'+"Email"+" "+Email+'\n'+"Number:"+" "+Number+'\n'+"Degree:"+" "+Degree+'\n'+"Gender:"+" "+Gender+'\n'+"Place:"+" "+Place);
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.project.MainActivity">

    <EditText
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/Email"
        android:ems="10"
        android:hint="Enter your Name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Name"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Enter your Email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/Number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/Email"
        android:layout_below="@+id/Email"
        android:ems="10"
        android:hint="Enter your Mobile Number"
        android:inputType="phone" />

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/Number"
        android:id="@+id/radioGroup">

        <CheckBox
            android:id="@+id/BEcheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignTop="@+id/radioGroup"
            android:layout_marginTop="74dp"
            android:layout_weight="1"
            android:text="BE" />

        <CheckBox
            android:id="@+id/MEcheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ME" />

        <RadioButton
            android:id="@+id/maleradioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Male" />

        <RadioButton
            android:id="@+id/femaleradioButton"
            android:layout_width="442dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Female" />

    </RadioGroup>

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="11dp"
        android:text="SUBMIT"
        android:textColor="#ffffff"
        android:background="@color/colorPrimaryDark"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/submit"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="27dp" />

</RelativeLayout>
</code>```

activity_second.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.project.SecondActivity">

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="55dp"
        android:layout_marginTop="43dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="16sp"/>
</RelativeLayout>
</code>```

I've just used single TextView to see the details whatever I have entered in MainActivity.java. But now I need to show the details in ListView with each details (name, email, number, etc...) in a separate adapter.

答:
If you want to display many information inside a row of ListView. Create a custom Adapter for your ListView and custom POJO class to store multiple field of data in single object.

Create Info.java:

```<code>class Info {
    String name;
    String email;

    public Info(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() { return name; }
    public String getEmail() { return email; }
}
</code>```

Create row.xml to make custom layout for a single row of your ListView:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/name"
    android:text="Name"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:id="@+id/email"/>
</LinearLayout>
</code>```

Define an adapter to create rows and populate data on your rows. Create InfoAdapter.java:

```<code>class InfoAdapter extends BaseAdapter {

    Context context;
    List<Info> data;
    private static LayoutInflater inflater = null;

    public InfoAdapter(Context context, List<Info> data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView name = (TextView) vi.findViewById(R.id.name);
        TextView email = (TextView) vi.findViewById(R.id.email);
        name.setText(data.get(position).getName());
        email.setText(data.get(position).getEmail());

        return vi;
    }
}
</code>```

Put ListView inside your activity_second.xml and config the layout whatever you want.

```<code><ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
</ListView>
</code>```

Inside SecondActivity.java create a ListView instance and array of data:

```<code>listView = (ListView) findViewById(R.id.list);
//Getting extras (Name, Email,..)
listInfo.add(new Info(Name, Email,...); //Create Info object base on extras information
</code>```

Init adapter and set:

```<code>InfoAdapter adapter = new InfoAdapter(this, listInfo);
listView.setAdapter(adapter);
</code>```

Body:
I need to pass the data from one activity to a ListView inside another activity. Currently I have set a single TextView to see all the details in second activity. But instead I need to view those items in ListView with adapter for each item.

MainActivity.java:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
    String[] place={"Karur","Salem","Namakkal","Trichy","Madurai"};

    EditText Name;
    EditText Email;
    EditText Number;
    Button submit;
    RadioGroup radioGroup;
    RadioButton maleradioButton,femaleradioButton;
    CheckBox BEcheckbox,MEcheckbox;
    Spinner spin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         spin = (Spinner)findViewById(R.id.spinner);
        spin.setOnItemSelectedListener(this);

        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item, place);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(aa);

        Name = (EditText)findViewById(R.id.Name);
        Email = (EditText)findViewById(R.id.Email);
        Number = (EditText)findViewById(R.id.Number);
        submit = (Button)findViewById(R.id.submit);
        radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
      ////  maleradioButton = (RadioButton)findViewById(R.id.maleradioButton);
        femaleradioButton = (RadioButton)findViewById(R.id.femaleradioButton);
        BEcheckbox = (CheckBox)findViewById(R.id.BEcheckBox);
        MEcheckbox = (CheckBox)findViewById(R.id.MEcheckbox);
       final RadioGroup rgroup = (RadioGroup)findViewById(R.id.radioGroup);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String spinText = spin.getSelectedItem().toString();
                String name = Name.getText().toString();
                String email = Email.getText().toString();
                String number = Number.getText().toString();
String val="";
String radio;
if (BEcheckbox.isChecked()) {
    val="BE";
} if(MEcheckbox.isChecked()) {
                    val="ME";

                }
                int select=rgroup.getCheckedRadioButtonId();
                maleradioButton=(RadioButton)findViewById(select);
                radio=maleradioButton.getText().toString();
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("Name",name);
                intent.putExtra("Email",email);
                intent.putExtra("Number",number);
                intent.putExtra("Degree",val);
                intent.putExtra("Gender",radio);
                intent.putExtra("Place",spinText);

                startActivity(intent);
            }
        });

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}

SecondActivity.java:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

    String Name;
    String Email;
    String Number;
    String Degree;
    String Gender;
    String Place;
    TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        result = (TextView)findViewById(R.id.result);

        Name = getIntent().getExtras().getString("Name");
        Email = getIntent().getExtras().getString("Email");
        Number = getIntent().getExtras().getString("Number");
        Degree = getIntent().getExtras().getString("Degree");
        Gender = getIntent().getExtras().getString("Gender");
        Place = getIntent().getExtras().getString("Place");

        result.setText("Name:"+""+Name +'\n'+"Email"+" "+Email+'\n'+"Number:"+" "+Number+'\n'+"Degree:"+" "+Degree+'\n'+"Gender:"+" "+Gender+'\n'+"Place:"+" "+Place);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.project.MainActivity">

    <EditText
        android:id="@+id/Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/Email"
        android:ems="10"
        android:hint="Enter your Name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/Email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Name"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:hint="Enter your Email"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/Number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/Email"
        android:layout_below="@+id/Email"
        android:ems="10"
        android:hint="Enter your Mobile Number"
        android:inputType="phone" />

    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/Number"
        android:id="@+id/radioGroup">

        <CheckBox
            android:id="@+id/BEcheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignTop="@+id/radioGroup"
            android:layout_marginTop="74dp"
            android:layout_weight="1"
            android:text="BE" />

        <CheckBox
            android:id="@+id/MEcheckbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ME" />

        <RadioButton
            android:id="@+id/maleradioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Male" />

        <RadioButton
            android:id="@+id/femaleradioButton"
            android:layout_width="442dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Female" />

    </RadioGroup>

    <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="11dp"
        android:text="SUBMIT"
        android:textColor="#ffffff"
        android:background="@color/colorPrimaryDark"/>

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/submit"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="27dp" />

</RelativeLayout>

activity_second.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.project.SecondActivity">

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="55dp"
        android:layout_marginTop="43dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="16sp"/>
</RelativeLayout>

I've just used single TextView to see the details whatever I have entered in MainActivity.java. But now I need to show the details in ListView with each details (name, email, number, etc...) in a separate adapter.

Body:
If you want to display many information inside a row of ListView. Create a custom Adapter for your ListView and custom POJO class to store multiple field of data in single object.

Create Info.java:

class Info {
    String name;
    String email;

    public Info(String name, String email) {
        this.name = name;
        this.email = email;
    }

    public String getName() { return name; }
    public String getEmail() { return email; }
}

Create row.xml to make custom layout for a single row of your ListView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/name"
    android:text="Name"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Email"
    android:id="@+id/email"/>
</LinearLayout>

Define an adapter to create rows and populate data on your rows. Create InfoAdapter.java:

class InfoAdapter extends BaseAdapter {

    Context context;
    List<Info> data;
    private static LayoutInflater inflater = null;

    public InfoAdapter(Context context, List<Info> data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView name = (TextView) vi.findViewById(R.id.name);
        TextView email = (TextView) vi.findViewById(R.id.email);
        name.setText(data.get(position).getName());
        email.setText(data.get(position).getEmail());

        return vi;
    }
}

Put ListView inside your activity_second.xml and config the layout whatever you want.

<ListView
        android:id="@+id/list"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
</ListView>

Inside SecondActivity.java create a ListView instance and array of data:

listView = (ListView) findViewById(R.id.list);
//Getting extras (Name, Email,..)
listInfo.add(new Info(Name, Email,...); //Create Info object base on extras information

Init adapter and set:

InfoAdapter adapter = new InfoAdapter(this, listInfo);
listView.setAdapter(adapter);


问:
How to address error "Did not load script at 'script name' because non script MIME types are not allowed when 'X-Content-Type: nosniff' is given
I have a fairly simple Angular 1.x app that was working fine until i upgraded to Safari 11. Now, it doesn't work because almost all of the js files are blocked.

The same was true for CSS files, but removing the "rel" attribute and adding type="text/css" fixed the CSS issues.

For the JS files, I've made sure to add type="text/javascript" to the script tags. I also just tried adding ./ to the beginning of the src's for giggles and they still won't load.

Does anyone know how to fix this?

Thanks,
Wayne

答:
I want to just delete the question but I hope maybe this answer will still be helpful to someone.

So, my problem was actually that I had a bad clone of my project and it was missing files!

However, for anyone having the same issue:

ensuring that type="text/css" for stylesheets and type="text/javascript" did fix the issue. (for the files that actually existed)


问:
Injecting a Angular Service in the main.ts file
Currently my main.ts file looks like this:

```<code>declare const require;
const translations = require("raw-loader!./locale/messages.de.xlf");

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    { provide: TRANSLATIONS, useValue: translations },
    { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
  ]
});
</code>```

Instead of hardcoding this "raw-loader!./locale/messages.de.xlf" I would like to use a service instead which provides this string, like for example:

```<code>const translations = require(translationService.localeString); //does not work!
</code>```

Is there a possible way of doing this? I have already created a Service for that but I can't find a way to inject it into the main.ts file.

答:
To Use the service, we need instance of it. We can create instance without constructor using Injector.

DemoService:

```<code>@Injectable()
export class DemoService {
  test="hi";
  localeString="abc";
}
</code>```

Main.ts:

```<code>    import {Injectable, ReflectiveInjector } from '@angular/core';
    var injector = ReflectiveInjector.resolveAndCreate([DemoService]);
    var demoService = injector.get(DemoService)
    alert(demoService.test)
    platformBrowserDynamic().bootstrapModule(AppModule, {
     providers: [
      { provide: TRANSLATIONS, useValue: demoService.localeString },
      { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
     ]
    });
</code>```

Now we can use the variableor method of service as i am using inside alert()

Demo: http://plnkr.co/edit/Df6xSxJPaCZVupyMmtUp?p=preview

We don't need service to access the constant values. another recommended way of doing this would be, keep your constant variable in separate file(i.e. environment.ts).

environment.ts:

```<code>export const environment = {
  localeString: "raw-loader!./locale/messages.de.xlf"
};
</code>```

Modify the main.ts:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    { provide: TRANSLATIONS, useValue: environment.localeString },
    { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
  ]
});
</code>```

Body:
Currently my main.ts file looks like this:

declare const require;
const translations = require("raw-loader!./locale/messages.de.xlf");

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    { provide: TRANSLATIONS, useValue: translations },
    { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
  ]
});

Instead of hardcoding this "raw-loader!./locale/messages.de.xlf" I would like to use a service instead which provides this string, like for example:

const translations = require(translationService.localeString); //does not work!

Is there a possible way of doing this? I have already created a Service for that but I can't find a way to inject it into the main.ts file.

Body:
To Use the service, we need instance of it. We can create instance without constructor using Injector.

DemoService:

@Injectable()
export class DemoService {
  test="hi";
  localeString="abc";
}

Main.ts:

    import {Injectable, ReflectiveInjector } from '@angular/core';
    var injector = ReflectiveInjector.resolveAndCreate([DemoService]);
    var demoService = injector.get(DemoService)
    alert(demoService.test)
    platformBrowserDynamic().bootstrapModule(AppModule, {
     providers: [
      { provide: TRANSLATIONS, useValue: demoService.localeString },
      { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
     ]
    });

Now we can use the variableor method of service as i am using inside alert()

Demo: http://plnkr.co/edit/Df6xSxJPaCZVupyMmtUp?p=preview

We don't need service to access the constant values. another recommended way of doing this would be, keep your constant variable in separate file(i.e. environment.ts).

environment.ts:

export const environment = {
  localeString: "raw-loader!./locale/messages.de.xlf"
};

Modify the main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    { provide: TRANSLATIONS, useValue: environment.localeString },
    { provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
  ]
});


问:
How to call clang-format over a cpp project folder?
Is there a way to call something like clang-format --style=Webkit for an entire cpp project folder, rather than running it separately for each file?

I am using clang-format.py and vim to do this, but I assume there is a way to apply this once.

答:
I recently found a bash-script which does exactly what you need:

https://github.com/eklitzke/clang-format-all

This is a bash script that will run clang-format -i on your code.

Features:

Finds the right path to clang-format on Ubuntu/Debian, which encode the LLVM version in the clang-format filename

Fixes files recursively

Detects the most common file extensions used by C/C++ projects

On Windows, I used it successfully in Git Bash and WSL.

ContentLicense: CC BY-SA 4.0


问:
WPF - How to write a trigger for mouse over of grid?
I see that Button object has a IsMouseOVer property.

But how do create an effect for the mouse over of a grid or other
element that does not have IsMouseOver??

Thanks
Malcolm

Edit: i figured it out. I was using the wrong method for setting the trigger.

答: That would be the "MouseEnter" and "MouseLeave" actions on the WPF object.</p>

OwnerDisplayName: Malcolm

LastEditorDisplayName: Malcolm

ContentLicense: CC BY-SA 2.5


问:
Azure WebJob Loses Connection Strings
I have a web job in Azure with the following code:

```<code>    public static void ProcessQueueMessage([QueueTrigger("ticketprocessorqueue")] string message, TextWriter log)
    {
        foreach (var c in ConfigurationManager.ConnectionStrings)
        {
            log.WriteLine(c.ToString());
        }
    }
</code>```

Immediately after I publish the web job and trigger it, I get the following output:

```<code>DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****

DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****

Server=tcp:northtech.database.windows.net,1433;Database=****;User
ID=****;Password=*****;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
</code>```

And that's what I would expect. However, when I trigger the same web job 30 minutes later, I get this:

```<code>""
</code>```

Absolutely nothing. What's happening to my connection strings?

This is a snippet of what is in my app config (for the web job) as well as the web config (for the parent web app):

```<code>  <connectionStrings>
    <add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****" />
    <add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****" />
    <add name="RingCloneDatabase" connectionString="Server=tcp:northtech.database.windows.net,1433;Database=****;User ID=****;Password=****;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" />
  </connectionStrings>
</code>```

What's happening to my connection strings?

答:
After much digging, I found (partially) what was causing the connection strings to "disappear" in my web job. I say "partially" because I found a way to fix it, but the action I performed to "fix" it doesn't make any sense. If anyone can shed some light on it, feel free to chime in.

What it came down to was this: I recently created an additional "Deployment slot" in my azure app service. And we were using this additional deployment slot to test the app before a final deployment (a staging environment). The trouble seemed to start when I added that deployment slot. When I removed that deployment slot completely, the problem went away. So, that's it. That's all I know.

But this creates many more questions for me. And here are some thoughts and questions to consider:

The connection strings and app settings were exactly the same in my parent app service and my additional deployment slot.

On the traffic routing, I had 100% of all traffic going to my main (parent) app service, and 0% going to the staging deployment slot (we hit the staging url directly for all staging tests).

This seems to indicate that there was some sort of conflict in the connection strings and/or app settings between the web jobs in my parent app service and the web jobs in my deployment slot.

If this is the case, how does azure determine which web job "instance" to use when there is one in the parent app, and the same one in the deployment slot?

Even if there was a conflict between my parent app service and my deployment slot, Why would it just be blank? Wouldn't it pick up the connection string from that "instance".

Finally, how does azure handle web jobs that are in a deployment slot, when that same job is in the parent app? I mean, both jobs use the same queue name. Do they both get fired off when a message is added to the queue?

I can't seem to find any how deployment slots relate to web jobs. I see how to route some of your web traffic to one deployment slot or another. But nothing about the web jobs. Can anyone shed any light on this? Has anyone experienced symptoms like this before?

Title: Azure WebJob Loses Connection Strings

Body:
I have a web job in Azure with the following code:

    public static void ProcessQueueMessage([QueueTrigger("ticketprocessorqueue")] string message, TextWriter log)
    {
        foreach (var c in ConfigurationManager.ConnectionStrings)
        {
            log.WriteLine(c.ToString());
        }
    }

Immediately after I publish the web job and trigger it, I get the following output:

DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****

DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****

Server=tcp:northtech.database.windows.net,1433;Database=****;User
ID=****;Password=*****;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

And that's what I would expect. However, when I trigger the same web job 30 minutes later, I get this:

""

Absolutely nothing. What's happening to my connection strings?

This is a snippet of what is in my app config (for the web job) as well as the web config (for the parent web app):

  <connectionStrings>
    <add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****" />
    <add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****" />
    <add name="RingCloneDatabase" connectionString="Server=tcp:northtech.database.windows.net,1433;Database=****;User ID=****;Password=****;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" />
  </connectionStrings>

What's happening to my connection strings?


问:
Customizing the views in authy-devise
I am trying to implement two factor authentication via authy 2FA of twilio using devise-authy gem.

I want to customize the views with three pages for 2FA.

first page - My login page where user enters username and password, on submit it will be redirected to a page

Second page - In this page he can select the 2FA method to receive the code via phone or sms after which he is redirected

Third page - Here he finally enters the code.

I am able to configure the first two pages.

My PROBLEM is that in the third page, where i am setting up the authy form for code verification, I am getting error undefined method id for nil class

```<code><%= verify_authy_form do %>
  <legend><%= I18n.t('submit_token_title', {:scope => 'devise'}) %></legend>
  <%= label_tag :token %>
      <%= text_field_tag :token, "", :autocomplete => :off, :id => 'authy-token' %>
  <label>
  <%= check_box_tag :remember_device %>
      <span><%= I18n.t('remember_device', {:scope => 'devise'}) %></span>
  </label>

  <!-- Help tooltip -->
  <!-- You need to configure a help message. -->
  <!-- See documentation: https://github.com/authy/authy-form-helpers#help-tooltip -->
  <!-- <%= link_to '?', '#', :id => 'authy-help' %> -->

  <%= authy_request_sms_link %>
  <%= authy_request_phone_call_link %>
  <%= submit_tag I18n.t('submit_token', {:scope => 'devise'}), :class => 'btn' %>
<% end %>
</code>```

I am getting error in this line  verify_authy_form
On inspecting the code of gem i found that i need @authy_id so i tried
<%@authy_id=User.find(session[:user_id]).authy_id%>
in view no still no success.

This is my Users::AuthyCustomController, where i have overridden some of the methods as stated in gem

```<code>class Users::AuthyCustomController  < Devise::DeviseAuthyController

protected
def after_authy_enabled_path_for(resource)
  my_own_path
end

def after_authy_verified_path_for(resource)
  my_own_path
end

def after_authy_disabled_path_for(resource)
  my_own_path
end

def invalid_resource_path
  my_own_path
end

def authentication_sms
end

def authentication_phone
  @authy_id=User.find(session[:user_id]).authy_id
  # redirect_to user_verify_authy_path
  # redirect_to user_verify_authy_path and return
end
end
</code>```

I have googled, but I was not able to find a solution

答:
I am getting error undefined method id for nil class

This is the form helper

```<code>def verify_authy_form(opts = {}, &block)
  opts = default_opts.merge(:id => 'devise_authy').merge(opts)
  form_tag([resource_name, :verify_authy], opts) do
    buffer = hidden_field_tag(:"#{resource_name}_id", @resource.id)
    buffer << capture(&block)
  end
end
</code>```

I belive that @resource is nil so when it does @resource.id triggers the error

I believe this form is managed from this controller action

```<code># verify 2fa
def POST_verify_authy
  token = Authy::API.verify({
    :id => @resource.authy_id,
    :token => params[:token],
    :force => true
  })

  if token.ok?
    @resource.update_attribute(:last_sign_in_with_authy, DateTime.now)

    session["#{resource_name}_authy_token_checked"] = true

    remember_device if params[:remember_device].to_i == 1
    if session.delete("#{resource_name}_remember_me") == true && @resource.respond_to?(:remember_me=)
      @resource.remember_me = true
    end
    sign_in(resource_name, @resource)

    set_flash_message(:notice, :signed_in) if is_navigational_format?
    respond_with resource, :location => after_sign_in_path_for(@resource)
  else
    handle_invalid_token :verify_authy, :invalid_token
  end
end
</code>```

and you can prove that by checking and including the relevant output from rake routes. So maybe you should debug that two pieces of code, the controller action is responsible to feeding @resource to the form

Title: Customizing the views in authy-devise

Body:
I am trying to implement two factor authentication via authy 2FA of twilio using devise-authy gem.

I want to customize the views with three pages for 2FA.

first page - My login page where user enters username and password, on submit it will be redirected to a page

Second page - In this page he can select the 2FA method to receive the code via phone or sms after which he is redirected

Third page - Here he finally enters the code.

I am able to configure the first two pages.

My PROBLEM is that in the third page, where i am setting up the authy form for code verification, I am getting error undefined method id for nil class

<%= verify_authy_form do %>
  <legend><%= I18n.t('submit_token_title', {:scope => 'devise'}) %></legend>
  <%= label_tag :token %>
      <%= text_field_tag :token, "", :autocomplete => :off, :id => 'authy-token' %>

  <%= check_box_tag :remember_device %>
      <%= I18n.t('remember_device', {:scope => 'devise'}) %>

  <%= authy_request_sms_link %>
  <%= authy_request_phone_call_link %>
  <%= submit_tag I18n.t('submit_token', {:scope => 'devise'}), :class => 'btn' %>
<% end %>

I am getting error in this line  verify_authy_form
On inspecting the code of gem i found that i need @authy_id so i tried
<%@authy_id=User.find(session[:user_id]).authy_id%>
in view no still no success.

This is my Users::AuthyCustomController, where i have overridden some of the methods as stated in gem

class Users::AuthyCustomController  < Devise::DeviseAuthyController

protected
def after_authy_enabled_path_for(resource)
  my_own_path
end

def after_authy_verified_path_for(resource)
  my_own_path
end

def after_authy_disabled_path_for(resource)
  my_own_path
end

def invalid_resource_path
  my_own_path
end

def authentication_sms
end

def authentication_phone
  @authy_id=User.find(session[:user_id]).authy_id
  # redirect_to user_verify_authy_path
  # redirect_to user_verify_authy_path and return
end
end

I have googled, but I was not able to find a solution

Body:
I am getting error undefined method id for nil class

This is the form helper

def verify_authy_form(opts = {}, &block)
  opts = default_opts.merge(:id => 'devise_authy').merge(opts)
  form_tag([resource_name, :verify_authy], opts) do
    buffer = hidden_field_tag(:"#{resource_name}_id", @resource.id)
    buffer << capture(&block)
  end
end

I belive that @resource is nil so when it does @resource.id triggers the error

I believe this form is managed from this controller action

# verify 2fa
def POST_verify_authy
  token = Authy::API.verify({
    :id => @resource.authy_id,
    :token => params[:token],
    :force => true
  })

  if token.ok?
    @resource.update_attribute(:last_sign_in_with_authy, DateTime.now)

    session["#{resource_name}_authy_token_checked"] = true

    remember_device if params[:remember_device].to_i == 1
    if session.delete("#{resource_name}_remember_me") == true && @resource.respond_to?(:remember_me=)
      @resource.remember_me = true
    end
    sign_in(resource_name, @resource)

    set_flash_message(:notice, :signed_in) if is_navigational_format?
    respond_with resource, :location => after_sign_in_path_for(@resource)
  else
    handle_invalid_token :verify_authy, :invalid_token
  end
end

and you can prove that by checking and including the relevant output from rake routes. So maybe you should debug that two pieces of code, the controller action is responsible to feeding @resource to the form


问:
How to add event handler to a C# AvalonEdit Caret PositionChanged event in xaml
I have a data template defined in xaml as:

```<code><DataTemplate>
<avalonEdit:TextEditor
    Name="xmlEditor"
    SyntaxHighlighting="XML"
    FontFamily="Consolas"
    FontSize="10pt"
/>
</DataTemplate>
</code>```

I need to add an ICSharpCode.AvalonEdit.TextEditor.TextArea.Caret.PositionChanged event to this. How can I do that?

答:
You can't access this in your xaml you have to set this in your code behind.

You can do this like this:

```<code>AvalonTextEditorControl.TextArea.Caret.PositionChanged += new EventHandler(
    (sender, args) => {
         // do some stuff
    }
);
</code>```

Or with a seperate event function instead, when you prefer it:

```<code>AvalonTextEditorControl.TextArea.Caret.PositionChanged += TextEditorCaret_PositionChanged;

private void TextEditorCaret_PositionChanged(object sender, EventArgs e)
{
    // do some stuff
}
</code>```

Update

If you want to use it in you XAML maybe because of your DataTemplate. You must implement this on your own. I thing than you got two options:

Get the source from ICSharpCode.AvalonEdit on GitHub and modify the TextEditor class. Just add an EventHandler and call it in the TextArea.Caret.PositionChanged Event.

Create you own UserControl which inherits from the ICSharpCode.AvalonEdit TextEditor and add the EventHandler like in option 1.

Body:
I have a data template defined in xaml as:

<DataTemplate>
<avalonEdit:TextEditor
    Name="xmlEditor"
    SyntaxHighlighting="XML"
    FontFamily="Consolas"
    FontSize="10pt"
/>
</DataTemplate>

I need to add an ICSharpCode.AvalonEdit.TextEditor.TextArea.Caret.PositionChanged event to this. How can I do that?

Body:
You can't access this in your xaml you have to set this in your code behind.

You can do this like this:

AvalonTextEditorControl.TextArea.Caret.PositionChanged += new EventHandler(
    (sender, args) => {
         // do some stuff
    }
);

Or with a seperate event function instead, when you prefer it:

AvalonTextEditorControl.TextArea.Caret.PositionChanged += TextEditorCaret_PositionChanged;

private void TextEditorCaret_PositionChanged(object sender, EventArgs e)
{
    // do some stuff
}

Update

If you want to use it in you XAML maybe because of your DataTemplate. You must implement this on your own. I thing than you got two options:

Get the source from ICSharpCode.AvalonEdit on GitHub and modify the TextEditor class. Just add an EventHandler and call it in the TextArea.Caret.PositionChanged Event.

Create you own UserControl which inherits from the ICSharpCode.AvalonEdit TextEditor and add the EventHandler like in option 1.


问:
Select div with a text inside in JS
I want to modify a div with a special text inside like this.

```<code><div>
<p>
A global issue
</p>
</div>
</code>```

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

答:
You can use jquery:

$('div:contains("A global issue")').css('background-color', 'red');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>A global issue</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Select div with a text inside in JS

Body:
I want to modify a div with a special text inside like this.

A global issue

How can I get it in JS without using id or class ? And only the div with the text "A global issue".

Is there a way to do it?

Body:
You can use jquery:

$('div:contains("A global issue")').css('background-color', 'red');

<div>A global issue</div>

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