问:
Pixel per Pixel image, transparent turned into black
I read a couple of thing about this, but I can't figure how to put it in my code.

Here it is :

```<code>function go($image) {
    // Open the image
    $getimage=imagecreatefrompng($image);
  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
   //init Count variable, when it reach the width, skip a line
   $count = 0;
   // For each line
   for($y=0;$y<$h;$y++) {
       // For each column
      for($x=0;$x<$w;$x++) {
        $rgba     = imagecolorat($getimage, $x, $y);
        $r = ($rgba >> 16) & 0xFF;
        $g = ($rgba >> 8) & 0xFF;
        $b = $rgba & 0xFF;
        $a     = ($rgba & 0x7F000000) >> 24;
        echo '<div class="pix" style="background-color: rgba('.$r.', '.$g.', '.$b.', '.$a.');"></div>';
        $count++;
        if($count==$w) {echo '<br>'; $count = 0; }

      }
   }
   echo $pixel_gen;

}
</code>```

If oyu want to see what it looks like, clic here: http://narks.xtreemhost.com/

And double-click on any icon,  popup will appear. (Note: dbl-clinking on any icon will show the same image (I didnt fixed this yet)

Any idea how i can make the black pixel appear like the real pixel with alpha) ?

Thanks for your help!

EDITED
(New code, i put only the first lines since i want to save space)

```<code>function go($image) {
    // Open the image
    $getimage=imagecreatefrompng($image);
    imagealphablending($getimage, false);
    imagesavealpha($getimage, true);

  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
[...]
</code>```

To see what it looks like now, visit the website above and double-click on an icon.

EDIT 2
I just tried (for a test) with :

```<code>$getimage=imagecreatefrompng('iconDB/lib/chat_fav_48.png');
imagealphablending($getimage, false);
imagesavealpha($getimage, true);

header("Content-type: image/png");
imagepng($getimage);
imagedestroy($getimage);
</code>```

and then with

```<code>$getimage=imagecreatefrompng('iconDB/lib/chat_fav_48.png');

header("Content-type: image/png");
imagepng($getimage);
imagedestroy($getimage);
</code>```

The first is okay and the second make pixels black. So it is when i get each pixel's RGB colors and when I display it. Anyone see a mistake there?

答:
Here is the correct working code, in order to complete this question.

```<code>function go($image) {
 // Open the image
 $getimage=imagecreatefrompng($image);
 imagealphablending($getimage, true);
 imagesavealpha($getimage, true);

  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
   //init Count variable, when it reach the width, skip a line
   $count = 0;
   // For each line
   for($y=0;$y<$h;$y++) {
    // For each column
      for($x=0;$x<$w;$x++) {
    // Get the image color for this pixel
  $rgba     = imagecolorat($getimage, $x, $y);
  $r = ($rgba >> 16) & 0xFF;
  $g = ($rgba >> 8) & 0xFF;
  $b = $rgba & 0xFF;
  $a = ($rgba & 0x7F000000) >> 24;
  //Calculating the correct Alpha value for rgba display in css
  $a = (127-$a)/127;
  echo '<div class="pix" style="background-color: rgba('.$r.', '.$g.', '.$b.', '.$a.');"></div>';
  $count++;
  if($count==$w) {echo '<br>'; $count = 0; }

      }
   }
   echo $pixel_gen;

}
</code>```

I hope it will be useful for someone

Body:
I read a couple of thing about this, but I can't figure how to put it in my code.

Here it is :

function go($image) {
    // Open the image
    $getimage=imagecreatefrompng($image);
  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
   //init Count variable, when it reach the width, skip a line
   $count = 0;
   // For each line
   for($y=0;$y<$h;$y++) {
       // For each column
      for($x=0;$x<$w;$x++) {
        $rgba     = imagecolorat($getimage, $x, $y);
        $r = ($rgba >> 16) & 0xFF;
        $g = ($rgba >> 8) & 0xFF;
        $b = $rgba & 0xFF;
        $a     = ($rgba & 0x7F000000) >> 24;
        echo '

';
        $count++;
        if($count==$w) {echo '
'; $count = 0; }

      }
   }
   echo $pixel_gen;

}

If oyu want to see what it looks like, clic here: http://narks.xtreemhost.com/

And double-click on any icon,  popup will appear. (Note: dbl-clinking on any icon will show the same image (I didnt fixed this yet)

Any idea how i can make the black pixel appear like the real pixel with alpha) ?

Thanks for your help!

EDITED
(New code, i put only the first lines since i want to save space)

function go($image) {
    // Open the image
    $getimage=imagecreatefrompng($image);
    imagealphablending($getimage, false);
    imagesavealpha($getimage, true);

  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
[...]

To see what it looks like now, visit the website above and double-click on an icon.

EDIT 2
I just tried (for a test) with :

$getimage=imagecreatefrompng('iconDB/lib/chat_fav_48.png');
imagealphablending($getimage, false);
imagesavealpha($getimage, true);

header("Content-type: image/png");
imagepng($getimage);
imagedestroy($getimage);

and then with

$getimage=imagecreatefrompng('iconDB/lib/chat_fav_48.png');

header("Content-type: image/png");
imagepng($getimage);
imagedestroy($getimage);

The first is okay and the second make pixels black. So it is when i get each pixel's RGB colors and when I display it. Anyone see a mistake there?

Body:
Here is the correct working code, in order to complete this question.

function go($image) {
 // Open the image
 $getimage=imagecreatefrompng($image);
 imagealphablending($getimage, true);
 imagesavealpha($getimage, true);

  //Get the width/height
   $w = imagesx($getimage);
   $h = imagesy($getimage);
   //init Count variable, when it reach the width, skip a line
   $count = 0;
   // For each line
   for($y=0;$y<$h;$y++) {
    // For each column
      for($x=0;$x<$w;$x++) {
    // Get the image color for this pixel
  $rgba     = imagecolorat($getimage, $x, $y);
  $r = ($rgba >> 16) & 0xFF;
  $g = ($rgba >> 8) & 0xFF;
  $b = $rgba & 0xFF;
  $a = ($rgba & 0x7F000000) >> 24;
  //Calculating the correct Alpha value for rgba display in css
  $a = (127-$a)/127;
  echo '<div class="pix" style="background-color: rgba('.$r.', '.$g.', '.$b.', '.$a.');"></div>';
  $count++;
  if($count==$w) {echo '<br>'; $count = 0; }

      }
   }
   echo $pixel_gen;

}

I hope it will be useful for someone


来源: stackexchange

问:
How to disable stylesheets in MS Edge without plugins
I tested a site for accessibility and I now have a QA validating that all of the changes were made. The QA needs to validate that the site is still readable with the stylesheets turned off. The QA can only use MS Edge and cannot install any plugins or browser extensions. Has anyone figured out how to turn off stylesheets? Googling this got me nowhere. When I evaluate the site, I use an extension in Chrome so I have never had this issue before.</p>

答:
Vanilla JS approach.

( [].slice.call( document.styleSheets ) ).map( function ( style ) {
  var node = style.ownerNode;
  node.parentNode.removeChild( node );
} );
```
<p>ES6 Vanilla JS Version</p>
<pre class="lang-js prettyprint-override"><code>[ ...document.styleSheets ].map( ( style ) => {
  const node = style.ownerNode;
  node.parentNode.removeChild( node );
} );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Vanilla JS approach.

( [].slice.call( document.styleSheets ) ).map( function ( style ) {
  var node = style.ownerNode;
  node.parentNode.removeChild( node );
} );

ES6 Vanilla JS Version

[ ...document.styleSheets ].map( ( style ) => {
  const node = style.ownerNode;
  node.parentNode.removeChild( node );
} );

ContentLicense: CC BY-SA 4.0


问:
Angular - Injecting component instance into the view of another component
I'm creating tabs control using Angular. The result should look like this:

```<code><tabs>
   <tab header="tab 1">
     hello
   </tab>
   <tab header="tab 2">
     world
   </tab>
</tabs>
</code>```

Now, the tab component looks like this:

```<code>@Component({
    selector: 'tab',
    template: `<ng-content></ng-content>`
})
export class TabComponent {
    @Input() header: string;
}
</code>```

And the tabs component looks like this:

```<code>@Component({
    selector: 'tabs',
    template: `
       <div class="tabs">
            <ul>
                <li *ngFor="let tab of tabs">
                    <a (click)="selectTab(tab)">
                        {{tab.header}}
                    </a>
                </li>
            </ul>
        </div>
    `,
})
export class TabsComponent {
    @ContentChildren(TabComponent) tabs;

    selectTab(tab: TabComponent) {

    }
 }
</code>```

Now, when the selectTab() method is called, I want the content of the pressed tab ("hello" or "world") to be rendered at the bottom of the template.

Basically there needs to be some kind of a tab placeholder in the TabsComponent, and it needs to be bonded to the currently selected TabComponent.

Anyway, I can't get it to work. I've tried using ng-template and createEmbeddedView, but I don't understand how to get the TemplateRef from the component, and I'm not completely sure that's the right way to go.

Thanks ahead!

答:
Alright, so I solved it, but I'm not sure this is the right solution.
I repeat my needs:
I want to make a fully-functioning tab-set component, that consists of tab headers and the currently selected tab.

Example:
https://s3.envato.com/files/169665336/Thetabs%20-%20Responsive%20HTML5%20&%20CSS3%20Tabs%202016-01-29%2005-57-05.png

So here's my solution. Please feel free to suggest a better one, as I'm not completely sure this is the example of a tab-set component:

```<code>@Directive({
    selector: 'tab',
})
export class TabDirective {
    private static seed = 0;

    readonly id: number;

    @Input() header: string;

    @HostBinding('hidden') isHidden: boolean;

    private isActive: boolean;
    @HostBinding('class.active') set active(value: boolean) {
        this.isActive = value;
        this.isHidden = !this.isActive;
    }

    get active(): boolean {
        return this.isActive;
    }

    constructor() {
        this.id = TabDirective.seed++;
        this.active = false;
    }
}

@Component({
    selector: 'bu-tabs',
    template: `
       <div class="tabs">
            <ul>
                <li *ngFor="let tab of tabs" [class.is-active]="tab.active">
                    <a (click)="selectTab(tab)">
                        <span>{{tab.header}}</span>
                    </a>
                </li>
            </ul>
        </div>

        <ng-content></ng-content>
    `,
})
export class TabsComponent implements AfterViewInit {
    @ContentChildren(TabDirective) tabs: QueryList<TabDirective>;

    @Output() select = new EventEmitter<TabDirective>();

    private selectedTab: TabDirective;

    selectTab(tab: TabDirective) {
        this.tabs.forEach((t: TabDirective) => t.active = (t.id === tab.id));
        this.selectedTab = tab;
    }

    ngAfterViewInit(): void {
        if (this.tabs && this.tabs.length > 0) {
            this.tabs.first.active = true;
        }
    }
}

@Component({
    template: `
        <tabs>
            <bu-tab header="hello">
                Hello!!
            </bu-tab>
            <bu-tab header="world">
                World!!
            </bu-tab>
        </tabs>
  `,
})
export class App { }
</code>```

Body:
I'm creating tabs control using Angular. The result should look like this:

<tabs>
   <tab header="tab 1">
     hello
   </tab>
   <tab header="tab 2">
     world
   </tab>
</tabs>

Now, the tab component looks like this:

@Component({
    selector: 'tab',
    template: `<ng-content></ng-content>`
})
export class TabComponent {
    @Input() header: string;
}

And the tabs component looks like this:

@Component({
    selector: 'tabs',
    template: `

                        {{tab.header}}

    `,
})
export class TabsComponent {
    @ContentChildren(TabComponent) tabs;

    selectTab(tab: TabComponent) {

    }
 }

Now, when the selectTab() method is called, I want the content of the pressed tab ("hello" or "world") to be rendered at the bottom of the template.

Basically there needs to be some kind of a tab placeholder in the TabsComponent, and it needs to be bonded to the currently selected TabComponent.

Anyway, I can't get it to work. I've tried using ng-template and createEmbeddedView, but I don't understand how to get the TemplateRef from the component, and I'm not completely sure that's the right way to go.

Thanks ahead!

Body:
Alright, so I solved it, but I'm not sure this is the right solution.
I repeat my needs:
I want to make a fully-functioning tab-set component, that consists of tab headers and the currently selected tab.

Example:
https://s3.envato.com/files/169665336/Thetabs%20-%20Responsive%20HTML5%20&%20CSS3%20Tabs%202016-01-29%2005-57-05.png

So here's my solution. Please feel free to suggest a better one, as I'm not completely sure this is the example of a tab-set component:

@Directive({
    selector: 'tab',
})
export class TabDirective {
    private static seed = 0;

    readonly id: number;

    @Input() header: string;

    @HostBinding('hidden') isHidden: boolean;

    private isActive: boolean;
    @HostBinding('class.active') set active(value: boolean) {
        this.isActive = value;
        this.isHidden = !this.isActive;
    }

    get active(): boolean {
        return this.isActive;
    }

    constructor() {
        this.id = TabDirective.seed++;
        this.active = false;
    }
}

@Component({
    selector: 'bu-tabs',
    template: `
       <div class="tabs">
            <ul>
                <li *ngFor="let tab of tabs" [class.is-active]="tab.active">
                    <a (click)="selectTab(tab)">
                        <span>{{tab.header}}</span>
                    </a>
                </li>
            </ul>
        </div>

        <ng-content></ng-content>
    `,
})
export class TabsComponent implements AfterViewInit {
    @ContentChildren(TabDirective) tabs: QueryList<TabDirective>;

    @Output() select = new EventEmitter<TabDirective>();

    private selectedTab: TabDirective;

    selectTab(tab: TabDirective) {
        this.tabs.forEach((t: TabDirective) => t.active = (t.id === tab.id));
        this.selectedTab = tab;
    }

    ngAfterViewInit(): void {
        if (this.tabs && this.tabs.length > 0) {
            this.tabs.first.active = true;
        }
    }
}

@Component({
    template: `
        <tabs>
            <bu-tab header="hello">
                Hello!!
            </bu-tab>
            <bu-tab header="world">
                World!!
            </bu-tab>
        </tabs>
  `,
})
export class App { }


问:
Stanford NLP named entity recognition libraries for biomedical entities
Where can I find Stanford NLP named entity recognition libraries for genes, proteins, hormones, transcription factors, neurotransmitters, cytokines, biomarkers,  epigenetic markers, enzymes, RNAs, organs, cells, drugs, and diseases?</p>

答:
In a nutshell: To my best knowledge, no BioNER models are (easily?) available for the Stanford tools. If you are looking for pre-trained models for biomedical entities, your best bets are (in alphabetical order):

ABNER

BANNER

ChemSpot

(Apache) cTAKES

GeneTUKit

GENIATagger

GNAT

Linnaeus

(The) NCBI Taggers collection

Neji2

OpenDMAP

training your own tagger ...

But none of those are built using the Stanford CoreNLP library, and not all are Java-based, either...


问:
jQuery daterangepicker: executes alert twice?
I want it to alert "ok" when you change/make a date. But i get two alerts instead of one?

How can i fix this?

here's the code:

```<code>$(document).ready(
function(){
   $('#datePicking')
       .daterangepicker({
       arrows:true,
       onChange: function(){
           $('#Viewer')
           alert('ok');
       }
       });
});
</code>```

here's a working example:  http://jsfiddle.net/BU5PJ/2/

jquery 1.4.4, UI 1.8.5,  + daterangepicker from filamentgroup.com

答:
In my case, I am using daterangepicker with angular. My purpose is to watch any change in the model that stores the date range value and save it for an AJAX call later. I face the same issue as it hits the event twice whenever the date is changed even if I select 'Today': Once it is object with startDate and endDate properties, and the other time it is a string.

It can be made use of as an advantage.

```<code>    $scope.$watch(
    'rangeOfDate',
    function (newValue) {
        // Due to a known bug of open source library daterangepicker, the event is hit twice
        //upon change. Once it is an object, and once it is a string. So, use appropriately.
        var selectedDateRange = new Object();
        if (typeof (newValue) == 'object') {
            selectedDateRange.startDate = new Date(newValue.startDate).toLocaleDateString();
            selectedDateRange.endDate = new Date(newValue.endDate).toLocaleDateString();
            //Do as you wish with this custom object
        }
        else if (typeof (newValue) == 'string') {
            alert("string");
        }
    },
    false);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I want it to alert "ok" when you change/make a date. But i get two alerts instead of one?

How can i fix this?

here's the code:

$(document).ready(
function(){
   $('#datePicking')
       .daterangepicker({
       arrows:true,
       onChange: function(){
           $('#Viewer')
           alert('ok');
       }
       });
});

here's a working example:  http://jsfiddle.net/BU5PJ/2/

jquery 1.4.4, UI 1.8.5,  + daterangepicker from filamentgroup.com

Body:
In my case, I am using daterangepicker with angular. My purpose is to watch any change in the model that stores the date range value and save it for an AJAX call later. I face the same issue as it hits the event twice whenever the date is changed even if I select 'Today': Once it is object with startDate and endDate properties, and the other time it is a string.

It can be made use of as an advantage.

    $scope.$watch(
    'rangeOfDate',
    function (newValue) {
        // Due to a known bug of open source library daterangepicker, the event is hit twice
        //upon change. Once it is an object, and once it is a string. So, use appropriately.
        var selectedDateRange = new Object();
        if (typeof (newValue) == 'object') {
            selectedDateRange.startDate = new Date(newValue.startDate).toLocaleDateString();
            selectedDateRange.endDate = new Date(newValue.endDate).toLocaleDateString();
            //Do as you wish with this custom object
        }
        else if (typeof (newValue) == 'string') {
            alert("string");
        }
    },
    false);


问:
Rotate xtick labels in seaborn boxplot?
I have a question that is basically the same as a question back from 2014 (see here). However, my script still throws an error.

Here is what I do: I have a pandas dataframe with a few columns. I plot a simple boxplot comparison.

```<code>g = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
g.set_xticklabels(rotation=30)
</code>```

The graph looks like this:

I'd like to rotate the x-labels by 30 degrees. Hence I use g.set_xticklabels(rotation=30). However, I get the following error:

set_xticklabels() missing 1 required positional argument: 'labels'

I don't know how to pass the matplotlib labels argument to seaborns sns.boxplot. Any ideas?

答:
The question you link to uses a factorplot. A factorplot returns its own class which has a method called set_xticklabels(rotation). This is different from the set_xticklabels method of the matplotlib Axes.

In the linked question's answers there are also other options which you may use

```<code>ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
ax.set_xticklabels(ax.get_xticklabels(),rotation=30)
</code>```

or

```<code>ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
plt.setp(ax.get_xticklabels(), rotation=45)
</code>```

Title: Rotate xtick labels in seaborn boxplot?

Body:
I have a question that is basically the same as a question back from 2014 (see here). However, my script still throws an error.

Here is what I do: I have a pandas dataframe with a few columns. I plot a simple boxplot comparison.

g = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
g.set_xticklabels(rotation=30)

The graph looks like this:

I'd like to rotate the x-labels by 30 degrees. Hence I use g.set_xticklabels(rotation=30). However, I get the following error:

set_xticklabels() missing 1 required positional argument: 'labels'

I don't know how to pass the matplotlib labels argument to seaborns sns.boxplot. Any ideas?

Body:
The question you link to uses a factorplot. A factorplot returns its own class which has a method called set_xticklabels(rotation). This is different from the set_xticklabels method of the matplotlib Axes.

In the linked question's answers there are also other options which you may use

ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
ax.set_xticklabels(ax.get_xticklabels(),rotation=30)

or

ax = sns.boxplot(x='categories', y='oxygen', hue='target', data=df)
plt.setp(ax.get_xticklabels(), rotation=45)


问:
Zendframework 3 - no zend registry
To whom it may concern:
I know I can use zend-session with zf3, yet is there a package for zend-registry to be used with Zend Framework 3?</p>

答: No, also in Zend Framework 2 there was no Zend_Registry anymore. Instead of this, there is the Service Manager. So in case yout want to access to session data, you can use the ServiceManager to get the SessionManager and writing/reading data to/from your session. The same for all other information, caching and so on. Just get the things you need from the Service Manager.</p>

Title: Zendframework 3 - no zend registry


问:
correct usage of setCellValueFactory
I am trying to do the following:

```<code>tableColumns[0].setCellValueFactory(
            new PropertyValueFactory<DiaryEntry,String>("username")
    );
tableColumns[1].setCellValueFactory(
            new PropertyValueFactory<DiaryEntry,Project>("project")
    );
</code>```

So the first one works perfectly fine. It uses the getUsername() Method in my class "DiaryEntry" in order to the Display the String. The second one is using the Method getProject() and tries to add the Project to my table. When doing that I end up with something like "2xProject2353asxk". This makes perfectly sense, since it can not simply display the Project object in the table.

In my Class Project I have a getter "getName()". So my Question here is: Is there any way I can change my second Statement, so that the table will enter the Project's name? I read a couple of threads about the setCellValueFactory() Method, but I still can't figure a solution out.

答:
Use a cellFactory in addition to the cellValueFactory

```<code>tableColumns[1].setCellValueFactory(
    new PropertyValueFactory<DiaryEntry,Project>("project")
);
tableColumns[1].setCellFactory(col -> new TableCell<DiaryEntry, Project>() {
    @Override
    protected void updateItem(Project project, boolean empty) {
        super.updateItem(project, empty);
        if (empty) {
            setText(null);
        } else {
            setText(project.getName());
        }
    }
});
</code>```

The cellValueFactory tells the column what value to display in its cells; the cellFactory tells it how to display the value.

Title: correct usage of setCellValueFactory

Body:
I am trying to do the following:

tableColumns[0].setCellValueFactory(
            new PropertyValueFactory<DiaryEntry,String>("username")
    );
tableColumns[1].setCellValueFactory(
            new PropertyValueFactory<DiaryEntry,Project>("project")
    );

So the first one works perfectly fine. It uses the getUsername() Method in my class "DiaryEntry" in order to the Display the String. The second one is using the Method getProject() and tries to add the Project to my table. When doing that I end up with something like "2xProject2353asxk". This makes perfectly sense, since it can not simply display the Project object in the table.

In my Class Project I have a getter "getName()". So my Question here is: Is there any way I can change my second Statement, so that the table will enter the Project's name? I read a couple of threads about the setCellValueFactory() Method, but I still can't figure a solution out.

Body:
Use a cellFactory in addition to the cellValueFactory

tableColumns[1].setCellValueFactory(
    new PropertyValueFactory<DiaryEntry,Project>("project")
);
tableColumns[1].setCellFactory(col -> new TableCell<DiaryEntry, Project>() {
    @Override
    protected void updateItem(Project project, boolean empty) {
        super.updateItem(project, empty);
        if (empty) {
            setText(null);
        } else {
            setText(project.getName());
        }
    }
});

The cellValueFactory tells the column what value to display in its cells; the cellFactory tells it how to display the value.


问:
NLP Frameworks for converting natural language to database queries
Are there any frameworks available,especially open source ones which can interpret natural language and convert it into RDBMS or NOSQL database queries?</p>

答:
Try Quepy!
It is a python framework to transform natural language questions to queries in a database query language.

As of June 2020 Quepy provides support for Sparql and MQL query languages.


问:
Unity - Steel Series Nimbus Input
I am trying to use my Steel Series Nimbus as a wireless remote for my iOS game but I can't get the input to work. The left and right stick work just fine but none of the buttons, triggers or bumpers work at all. I think it is something to do with my Input Manager Settings. If anyone can help it would be much appreciated if you could give me an answer.

Many Thanks,

Tommy :)

答:
It wont work unless you are testing your build directly on Apple tv or an iOS device.

I made a test scene that detects the joystick button 0  and so on and I can confirm this are the numbers for the keys for the nimbus.
I will help you out by writting them down here :)

Joysticks axis
Joystick Left   X axis, Y axis
Joystick Right X 3rd axis,  Y is 4th axis

Dpad
UP _ joystick button 4
LEFT _ joystick button 7
DOWN _ joystick button 6
RIGHT _ joystick button 5

L1  _ joystick button 8
L2 _ joystick button 10

R1 _ joystick button 9
R2_ joystick button 11

X_ joystick button 15
Y_ joystick button 12
A_ joystick button 14
B _ joystick button 13  // careful this is back button on apple tv and returns to dashboard

Menu center button _ joystick button 0

I am trying to figure out how to make menu and B buttons not take you out of the app

Title: Unity - Steel Series Nimbus Input


问:
checkbox validation angularjs
I have multiple checkboxes for a question.Atleast one checkbox needs to be selected.If none of the checkboxes get selected form should through validation error.Did i miss anything. Any ideas on how I would be able to achieve this behaviour?
My .JS code:

```<code>$scope.onCheckBoxSelected=function(){

                            var flag=false;
                            for(var key in selectedOptions){
                                console.log('Key -' +key +' val- '+selectedOptions[key]);
                                if(selectedOptions[key]){
                                    flag=true;
                                }
                            }
                            if(!flag){
                                selectedOptions=undefined;
                            }
                        };
</code>```

below is my html code :

```<code><div class="grid">
    <div class="col flex-10  mandatoryField" ng-class="{error: (!selectedOptions && formMissingFields)}">Hello please select atleast one</div>
    <div class="col flex-2">
    </div>
    <div class="col flex-5">

        <div style="padding-top: 2px">
            <input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
            </input>
        </div>

    </div>

</div>
</code>```

答:
It's best practice to use the AngularJS forms for checkbox validation - it will also help you if you intend on extending your form. You will have to refactor your code to use this functionality. </p>

```<code> <ng-form name="myForm">
    <span style="color:red;" ng-show="myForm.$invalid">Please select one</span>
    <br />
    <!-- your checkbox values will be in "choices" -->
    <p ng-repeat="choice in choices">
      <label class="checkbox" for="{{choice.id}}">
        <input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" ng-required="value.length==0" /> {{choice.label}}
      </label>
    </p>
    <input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
  </ng-form>
</code>```

<p>See this fiddle - note that it uses underscore.js. Also, this question may help. </p>

Title: checkbox validation angularjs

Body:
I have multiple checkboxes for a question.Atleast one checkbox needs to be selected.If none of the checkboxes get selected form should through validation error.Did i miss anything. Any ideas on how I would be able to achieve this behaviour?
My .JS code:

$scope.onCheckBoxSelected=function(){

                            var flag=false;
                            for(var key in selectedOptions){
                                console.log('Key -' +key +' val- '+selectedOptions[key]);
                                if(selectedOptions[key]){
                                    flag=true;
                                }
                            }
                            if(!flag){
                                selectedOptions=undefined;
                            }
                        };

below is my html code :

Hello please select atleast one

            <input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
            </input>

            <input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
            </input>

            <input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
            </input>

Body:
It's best practice to use the AngularJS forms for checkbox validation - it will also help you if you intend on extending your form. You will have to refactor your code to use this functionality.

 <ng-form name="myForm">
    <span style="color:red;" ng-show="myForm.$invalid">Please select one</span>
    <br />
    <!-- your checkbox values will be in "choices" -->
    <p ng-repeat="choice in choices">
      <label class="checkbox" for="{{choice.id}}">
        <input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" ng-required="value.length==0" /> {{choice.label}}
      </label>
    </p>
    <input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
  </ng-form>

See this fiddle - note that it uses underscore.js. Also, this question may help.


问:
Everything now is XML - but programming is still done with some legacy files obeying complicated syntax
Why is this ? Gcc is now providing a "C-to-XML" conversion since XML is more easily parsed.

Couldn't we benefit if our source code was XML?

Of course, nobody want's to edit XML files manually - but that's what IDEs are made for.

Would some programming language with less syntax (LISP, Smalltalk) better map to XML?

答: Programming languages are for programmers' convenience, not for ease of parsing.</p>


问:
How to Save R-squared in sas?
I have the following sas code (last few lines). What I need is to save r-squared, adjusted r-squared (besides keeping CUSIP6 trandate CRSPtrandate tshares shrvol dolvol BSI intercept mktrf smb hml umd).</p>

```<code>proc sort data=dailyFFrets;
    by CUSIP6 trandate CRSPtrandate tshares dolvol BSI shrvol;
run;

options nonotes;

proc reg data=dailyFFrets outest=alpha (keep=CUSIP6 trandate CRSPtrandate
        tshares shrvol dolvol BSI intercept mktrf smb hml umd) noprint;
    by CUSIP6 trandate CRSPtrandate tshares dolvol BSI shrvol;
    model rirf=mktrf smb hml umd;
quit;

options notes;

data alpha;
    set alpha;
    alpha=intercept*sign(tshares)*100;
run;
</code>```

答:
This might help: http://support.sas.com/kb/22/640.html

Use an ODS OUTPUT statement to save the table named FitStatistics to a data set. See this note for more on saving tables from procedures. For example,

```<code>   ods output FitStatistics = fitstats;
   proc reg data=in;
      model y = x;
      run;
</code>```

You can also specify the RSQUARE and EDF options in the PROC REG or
MODEL statement to add R2 and the error degrees of freedom,
respectively, to the OUTEST= data set. Requesting any additional
statistic results in R2 being added to the OUTEST= data set.

For example, if you specify the ADJRSQ option, then adjusted R2 (ADJRSQ)
and R2 (RSQ) are added to the OUTEST= data set.

Title: How to Save R-squared in sas?

Body:
I have the following sas code (last few lines). What I need is to save r-squared, adjusted r-squared (besides keeping CUSIP6 trandate CRSPtrandate tshares shrvol dolvol BSI intercept mktrf smb hml umd).

proc sort data=dailyFFrets;
    by CUSIP6 trandate CRSPtrandate tshares dolvol BSI shrvol;
run;

options nonotes;

proc reg data=dailyFFrets outest=alpha (keep=CUSIP6 trandate CRSPtrandate
        tshares shrvol dolvol BSI intercept mktrf smb hml umd) noprint;
    by CUSIP6 trandate CRSPtrandate tshares dolvol BSI shrvol;
    model rirf=mktrf smb hml umd;
quit;

options notes;

data alpha;
    set alpha;
    alpha=intercept*sign(tshares)*100;
run;

Body:
This might help: http://support.sas.com/kb/22/640.html

Use an ODS OUTPUT statement to save the table named FitStatistics to a data set. See this note for more on saving tables from procedures. For example,

   ods output FitStatistics = fitstats;
   proc reg data=in;
      model y = x;
      run;

You can also specify the RSQUARE and EDF options in the PROC REG or
MODEL statement to add R2 and the error degrees of freedom,
respectively, to the OUTEST= data set. Requesting any additional
statistic results in R2 being added to the OUTEST= data set.

For example, if you specify the ADJRSQ option, then adjusted R2 (ADJRSQ)
and R2 (RSQ) are added to the OUTEST= data set.


问:
Is it possible to configure retries with the AWS CLI?
I have a script which uses the AWS CLI (currently v1.11.90) to coordinate various AWS resources. Amongst other things it calls aws cloudformation list-stacks three or four times in a row.

I fairly frequently get errors because my requests are being throttled:

```<code>An error occurred (Throttling) when calling the ListStacks operation (reached max retries: 4): Rate exceeded
</code>```

In particular if I happen to have the CloudFormation console open in my browser this happens pretty reliably.

I would like to configure it to be more forgiving in these cases -- either to back off more aggressively, or to retry more times. I've tried to find a way of doing this and have seen a few references to being able to do it in boto, but I can't see how to do it via the CLI.

答:
If you are creating some resources and waiting for that one to create successfully, AWS cli provided wait module[1]
Since you want to retry for an error you can do a retry using while or until. Below code will run until command is successful.

```<code>while [ $? -ne 0 ]; do
YOUR COMMAND
GOOD CONDITION TO EXIT AFTER SOME RETRIES
done
</code>```

Make sure that you are using a good condition to exit after some retries otherwise it will end up with a infinite loop.

[1] http://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html

Body:
I have a script which uses the AWS CLI (currently v1.11.90) to coordinate various AWS resources. Amongst other things it calls aws cloudformation list-stacks three or four times in a row.

I fairly frequently get errors because my requests are being throttled:

An error occurred (Throttling) when calling the ListStacks operation (reached max retries: 4): Rate exceeded

In particular if I happen to have the CloudFormation console open in my browser this happens pretty reliably.

I would like to configure it to be more forgiving in these cases -- either to back off more aggressively, or to retry more times. I've tried to find a way of doing this and have seen a few references to being able to do it in boto, but I can't see how to do it via the CLI.

Body:
If you are creating some resources and waiting for that one to create successfully, AWS cli provided wait module[1]
Since you want to retry for an error you can do a retry using while or until. Below code will run until command is successful.

while [ $? -ne 0 ]; do
YOUR COMMAND
GOOD CONDITION TO EXIT AFTER SOME RETRIES
done

Make sure that you are using a good condition to exit after some retries otherwise it will end up with a infinite loop.

[1] http://docs.aws.amazon.com/cli/latest/reference/cloudformation/wait/index.html


问:
calling function inside function with same class and redirect in codeigniter
I am working on login and search functionality using CodeIgniter.

What Exactly I am doing?

When the user searches something in the search form and on submitting that form I put a check if the user is logged in then it will directly show the result & if the user is not logged in then it redirects the user to the login page and I saved the search data in session as search_session_data.

I have a controller which redirects user regarding the session. If the user came directly to the login page then the user is redirected to the dashboard after login. but if the user is coming from search page then the user is redirected to the search result page after login.

I have mentioned the problem inside the code with a comment.

This is the controller:

```<code>public function get_the_search_result() {

        $search_session_data = $this->session->userdata('search_session_data');
        $this->load->model ('my_model');
        $result_data = $this->my_model->find_data_regarding_search_criteria($search_session_data);

        $this->load->view ('app/app_statch_result',['result_data' => $result_data,]);
}

public function login_function() {
    //necessary  login code

    if ($this->session->userdata('search_session_data')) {

        //Here I want the if `search_session_data` available in session then
        // user goest to `get_the_search_result` and view the
         //'app/app_statch_result` but it is not working.

        $this->get_the_search_result();
    } else {
        return redirect('dashboard');
    }

}
</code>```

So How do I redirect the user to app_statch_result from
  login_function function?

Any suggestion regarding improvement is applicable. Thanks

答:
If I were you, I would do the following:

Create login controller, or better, library and put all login logic inside that class. Then you can load that library from any controller... For example:

Sample library

```<code>    class User_controll{
        private $CI;

        public function __construct() {
            $this->CI = &get_instance();
        }

        public function check_user_data($username, $password) {
            $tmpId;
            // To increase security you can encrypt password
            $user = $this->CI->db->from('users')->where(array('username' => $username, 'password' => $password))->get()->result();

            if(count($user) == 1){
                $this->CI->session->set_userdata('loggedIn', 1);
                redirect('user_page');
            }
        }
        protected function logout() {
            $this->CI->session->set_userdata('loggedIn', 0);
        }

        public function isLoggedIn() {
            return $this->CI->session->userdata('loggedIn') == 1;
        }

    }
</code>```

Sample Controller

```<code>    class User_page extends CI_Controller{

        public function __construct() {
            parent::__construct();
            $this->load->library('User_controll');
        }
        public function index() {
            if(!$this->user_controll->isLoggedIn()){
                redirect('user_page/loginForm');
            }
            else {
                // do whatever you want
            }
        }
    }
</code>```

Body:
I am working on login and search functionality using CodeIgniter.

What Exactly I am doing?

When the user searches something in the search form and on submitting that form I put a check if the user is logged in then it will directly show the result & if the user is not logged in then it redirects the user to the login page and I saved the search data in session as search_session_data.

I have a controller which redirects user regarding the session. If the user came directly to the login page then the user is redirected to the dashboard after login. but if the user is coming from search page then the user is redirected to the search result page after login.

I have mentioned the problem inside the code with a comment.

This is the controller:

public function get_the_search_result() {

        $search_session_data = $this->session->userdata('search_session_data');
        $this->load->model ('my_model');
        $result_data = $this->my_model->find_data_regarding_search_criteria($search_session_data);

        $this->load->view ('app/app_statch_result',['result_data' => $result_data,]);
}

public function login_function() {
    //necessary  login code

    if ($this->session->userdata('search_session_data')) {

        //Here I want the if `search_session_data` available in session then
        // user goest to `get_the_search_result` and view the
         //'app/app_statch_result` but it is not working.

        $this->get_the_search_result();
    } else {
        return redirect('dashboard');
    }

}

So How do I redirect the user to app_statch_result from
  login_function function?

Any suggestion regarding improvement is applicable. Thanks

Body:
If I were you, I would do the following:

Create login controller, or better, library and put all login logic inside that class. Then you can load that library from any controller... For example:

Sample library

    class User_controll{
        private $CI;

        public function __construct() {
            $this->CI = &get_instance();
        }

        public function check_user_data($username, $password) {
            $tmpId;
            // To increase security you can encrypt password
            $user = $this->CI->db->from('users')->where(array('username' => $username, 'password' => $password))->get()->result();

            if(count($user) == 1){
                $this->CI->session->set_userdata('loggedIn', 1);
                redirect('user_page');
            }
        }
        protected function logout() {
            $this->CI->session->set_userdata('loggedIn', 0);
        }

        public function isLoggedIn() {
            return $this->CI->session->userdata('loggedIn') == 1;
        }

    }

Sample Controller

    class User_page extends CI_Controller{

        public function __construct() {
            parent::__construct();
            $this->load->library('User_controll');
        }
        public function index() {
            if(!$this->user_controll->isLoggedIn()){
                redirect('user_page/loginForm');
            }
            else {
                // do whatever you want
            }
        }
    }


问:
How to pass time_t or simply its date information over COM
I have a Visual C++ ATL project which exposes a COM interface.

From my interface, I am calling into FlexNet Publisher libraries. I need to return back a date from these libraries, which expose a time_t object I can fetch (yes, I know their libraries are susceptible to the 2038 bug on 32-bit systems).

My IDL file has a method on it which needs to return this date.

Given that I can fetch time_t, how do I pass its date information across the COM interface boundary to a client application consuming my COM object? Should I just cast time_t as __int64 and define it as __int64 in my IDL? What's correct here? What's the standard way?

答:
I'd recommend using the oleautomation compliant DATE type.

To convert your existing time_t type, use the COleDateTime class, which is provided by ATL. One of its constructors accepts a time_t value and parses it to its equivalent DATE value.


问:
Android Browser textarea scrolls all over the place, is unusable
So I've built a nice, shiny HTML5 application that is targeted at mobile Safari, and Android's default browser. The Android versions I'm testing it on are 2.1 and 2.2.

My app has a textarea on one of its pages, and this textarea tends to have a good amount of text in it at times. Its basically a free-form writing field.

This works as expected in iOS. However on Android, as you type, the screen scrolls wildly up and down on every keystroke, often you can't see what it is you're typing as you type, and you get dizzy from all the jumping around. Furthermore, if the content within the textarea exceeds its height, it appears to be impossible to scroll within it.

Don't even get me started on landscape mode. The above issues are even more pronounced there.

This feels like a bug with Android as there really isn't anything fancy about my textarea. I've stripped it down to the bare essentials, and it behaves the same.

Wondering if anyone else has had this much fun with their textareas on Android, and could maybe give some advice, or at least empathize?

It seems that Google has managed to mostly solve this in the Gmail web interface for Android. I'm guessing there's some JS magic going on because my markup/CSS is identical.

答: There is no magic answer. Android keyboard input interactions with web forms is simply horrendous. You have to thread the needle very carefully to make it work properly, and keyboard behavior is not the same across Android versions. But it is possible with a LOT of work (see our Sencha Touch framework for what's possible today - the other mobile web frameworks are tackling the exact same problems too). </p>


问:
Using Python Regex to find a phrase between 2 tags
I've got a string that I want to use regex to find the characters encapsulated between two known patterns, "Cp_6%3A" then some characters then "&" and potentially more characters, or no & and just the end of string.

My code looks like this:

```<code>def extract_id_from_ref(ref):
  id = re.search("Cp\_6\%3A(.*?)(\& | $)", ref)
  print(id)
</code>```

But this isn't producing anything, Any ideas?

Thanks in advance

答:
The problem is that spaces in a regex pattern, are also taken into account. Furthermore in order to add a backspace to the string, you either have to add \\ (two backslashes) or use a raw string:

So you should write:

```<code>r"Cp_6\%3A(.*?)(?:\&|$)"
</code>```

If you then match with:

```<code>def extract_id_from_ref(ref):
    id = re.search(r"Cp_6\%3A(.*?)(?:\&|$)", ref)
    print(id)
</code>```

It should work.

Body:
I've got a string that I want to use regex to find the characters encapsulated between two known patterns, "Cp_6%3A" then some characters then "&" and potentially more characters, or no & and just the end of string.

My code looks like this:

def extract_id_from_ref(ref):
  id = re.search("Cp\_6\%3A(.*?)(\& | $)", ref)
  print(id)

But this isn't producing anything, Any ideas?

Thanks in advance

Body:
The problem is that spaces in a regex pattern, are also taken into account. Furthermore in order to add a backspace to the string, you either have to add \\ (two backslashes) or use a raw string:

So you should write:

r"Cp_6\%3A(.*?)(?:\&|$)"

If you then match with:

def extract_id_from_ref(ref):
    id = re.search(r"Cp_6\%3A(.*?)(?:\&|$)", ref)
    print(id)

It should work.


答:
Note that (\& | $) matches either the & char and a space after it, or a space and end of string (the spaces are meaningful here!).

Use a negated character class [^&]* (zero or more chars other than &) to simplify the regex (no need for an alternation group or lazy dot matching pattern) and then access .group(1):

```<code>def extract_id_from_ref(ref):
    m = re.search(r"Cp_6%3A([^&]*)", ref)
    if m:
        print(m.group(1))
</code>```

Note that neither _ nor % are special regex metacharacters, and do not have to be escaped.

See the regex demo.

Title: Using Python Regex to find a phrase between 2 tags

Body:
Note that (\& | $) matches either the & char and a space after it, or a space and end of string (the spaces are meaningful here!).

Use a negated character class [^&]* (zero or more chars other than &) to simplify the regex (no need for an alternation group or lazy dot matching pattern) and then access .group(1):

def extract_id_from_ref(ref):
    m = re.search(r"Cp_6%3A([^&]*)", ref)
    if m:
        print(m.group(1))

Note that neither _ nor % are special regex metacharacters, and do not have to be escaped.

See the regex demo.


问:
Is neural network suitable for supervised learning where the data (inputs and outputs) are continuous?
I am working on a regression model with a set of 158 inputs and 4 outputs of glass manufacturing project which is a continuous process of inputs and outputs. Is the usage of Neural Net a suitable solution for such kind of regression models? If yes, I have understood that Recurrent Neural Nets can be used for time series data, which Recurrent Neural Net shall I use? If usage of NN is not suitable, what are the other types of solutions available other than Linear Regression and Regression Trees?</p>

答:
Neural Networks are indeed suitable for continuous data. In fact, it is continous by default I would say. It is possible to have discrete I/O for sure, it all depend on your functions.

Secondly, it is true that RNN are suitable for time series, in a way. RNN are in fact suitable for timesteps more than timestamps. RNN are working by iterations. Typically, each iteration can be seen as a fixed step forward in time. This said, if you data is more like (date, value) (what I call timestamp), it may not be so good. It would not be absolutely impossible, but that's not the idea.

Hope it helps, start with simple RNN, try to understand how it works, then, if you need more, read about more complex cells.


问:
Find Overlapping Dates and Return Overlapping Records
What I need is to return all records that may overlap each other.

```<code>-- Create Temp Table
CREATE TABLE #Overlap

(SubType varchar(50),
Cause varchar(9),
CircuitID varchar(100),
BegDate date,
EndDate date,
AmtSought decimal(11,2),
Remarks varchar(max))

--Insert records

INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-01','2016-12-31',354.41,'Rec 1')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-08-11','2016-08-12',200.50,'Rec 2')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-11-15','2016-12-14',100.25,'Rec 3')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-16','2017-01-15',300.75,'Rec 4')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2017-01-01','2017-01-01',500.00,'Rec 5')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-07-01','2016-07-31',100.50,'Rec 6')
</code>```

My result would look like:

```<code>SubType   Cause     CircuitID                  BegDate    EndDate    AmtSought Remarks
------------------- -------------------------- ---------- ---------- --------- --------
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-11-15 2016-12-14 100.25    Rec 3
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-01 2016-12-31 354.41    Rec 1
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-16 2017-01-15 300.75    Rec 4
Original  201500018 36/KQ--/831670/IP /NUVX/   2017-01-01 2017-01-01 500.00    Rec 5
</code>```

I have tried this from a sample code I saw but it is not returning the desired result.

```<code>Select * from #Overlap a
Inner Join #Overlap b
on a.SubType = b.SubType
And a.Cause = b.Cause
And a.CircuitID = b.CircuitID
And b.BegDate between a.BegDate and a.endDate
And b.BegDate < a.endDate
</code>```

答:
Assuming that your #Overlap table has a primary key (or unique key) TableId

You could use this following query

```<code>SELECT * FROM #Overlap o
WHERE EXISTS
(
    SELECT 1 FROM #Overlap o2
    WHERE o2.SubType = o.SubType
    AND o2.Cause = o.Cause
    AND o2.CircuitID = o.CircuitID
    AND (
            o2.BegDate BETWEEN o.BegDate AND o.EndDate
            OR o2.EndDate BETWEEN o.BegDate AND o.EndDate
            OR o.BegDate BETWEEN o2.BegDate AND o2.EndDate
            OR o.EndDate BETWEEN o2.BegDate AND o2.EndDate
        )
    AND o2.TableId != o.TableId
)
ORDER BY o.SubType, o.Cause, o.BegDate
</code>```

Demo link: http://rextester.com/KBFX30109

As @HABO suggestion, you also can use to check overlapping

```<code>    AND o2.BegDate <= o.EndDate
    AND o.BegDate <= o2.EndDate
</code>```

Body:
What I need is to return all records that may overlap each other.

-- Create Temp Table
CREATE TABLE #Overlap

(SubType varchar(50),
Cause varchar(9),
CircuitID varchar(100),
BegDate date,
EndDate date,
AmtSought decimal(11,2),
Remarks varchar(max))

--Insert records

INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-01','2016-12-31',354.41,'Rec 1')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-08-11','2016-08-12',200.50,'Rec 2')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-11-15','2016-12-14',100.25,'Rec 3')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2016-12-16','2017-01-15',300.75,'Rec 4')
INSERT INTO #Overlap VALUES('Original','201500018','36/KQ--/831670/IP /NUVX/','2017-01-01','2017-01-01',500.00,'Rec 5')
INSERT INTO #Overlap VALUES('Original','201500009','36/VCID/826061/IP/NUVX','2016-07-01','2016-07-31',100.50,'Rec 6')

My result would look like:

SubType   Cause     CircuitID                  BegDate    EndDate    AmtSought Remarks
------------------- -------------------------- ---------- ---------- --------- --------
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-11-15 2016-12-14 100.25    Rec 3
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-01 2016-12-31 354.41    Rec 1
Original  201500018 36/KQ--/831670/IP /NUVX/   2016-12-16 2017-01-15 300.75    Rec 4
Original  201500018 36/KQ--/831670/IP /NUVX/   2017-01-01 2017-01-01 500.00    Rec 5

I have tried this from a sample code I saw but it is not returning the desired result.

Select * from #Overlap a
Inner Join #Overlap b
on a.SubType = b.SubType
And a.Cause = b.Cause
And a.CircuitID = b.CircuitID
And b.BegDate between a.BegDate and a.endDate
And b.BegDate < a.endDate

Body:
Assuming that your #Overlap table has a primary key (or unique key) TableId

You could use this following query

SELECT * FROM #Overlap o
WHERE EXISTS
(
    SELECT 1 FROM #Overlap o2
    WHERE o2.SubType = o.SubType
    AND o2.Cause = o.Cause
    AND o2.CircuitID = o.CircuitID
    AND (
            o2.BegDate BETWEEN o.BegDate AND o.EndDate
            OR o2.EndDate BETWEEN o.BegDate AND o.EndDate
            OR o.BegDate BETWEEN o2.BegDate AND o2.EndDate
            OR o.EndDate BETWEEN o2.BegDate AND o2.EndDate
        )
    AND o2.TableId != o.TableId
)
ORDER BY o.SubType, o.Cause, o.BegDate

Demo link: http://rextester.com/KBFX30109

As @HABO suggestion, you also can use to check overlapping

    AND o2.BegDate <= o.EndDate
    AND o.BegDate <= o2.EndDate


问:
Jquery：CKEDITOR Cannot read property 'GetData' of undefined
I use ckeditor.js to do TextArea Editor

To get the value, i used

```<code> CKEDITOR.instances.content.GetData();
</code>```

and i got this error

```<code>Cannot read property 'GetData' of undefined
</code>```

so how can I fix it?

This is my code

```<code><script src="js/Lib/CKEdit/ckeditor.js"></script>
<button type="button" onclick="test()">test</button>
<div class="col-lg-10">
    <textarea class="form-control" id="txtFT_Content" name ="txtFT_Content"></textarea>
    <script>
        CKEDITOR.replace( 'txtFT_Content', { } );
        function test()
        {
            var x = CKEDITOR.instances.content.GetData();
            alert( x );
        }
    </script>
</div>
</code>```

答:
You use a wrong instance id and a wrong method name. Try it with

```<code>CKEDITOR.instances["txtFT_Content"].getData();
</code>```

This should return the HTML content of that CKEditor instance.

Body:
I use ckeditor.js to do TextArea Editor

To get the value, i used

 CKEDITOR.instances.content.GetData();

and i got this error

Cannot read property 'GetData' of undefined

so how can I fix it?

This is my code

<button type="button" onclick="test()">test</button>

    <textarea class="form-control" id="txtFT_Content" name ="txtFT_Content"></textarea>

Body:
You use a wrong instance id and a wrong method name. Try it with

CKEDITOR.instances["txtFT_Content"].getData();

This should return the HTML content of that CKEditor instance.


问:
Can a Heroku app interface with Amazon EC2 instances
I am toying around with building a rails app in the near future and using Heroku to host it, but the app will need to interact with EC2 instances through SSH (unless I can find a better way).  I probably could build a pseudo API...but direct console access would be easier.  I am going to need the following:

1) Run commands on the EC2 console

2) Read the results

3) dynamically start and stop ec2 instances (a little unrelated but I am curious if heroku can do this)

I know heroku hosts their infrastructure on EC2, so latency would be grean and it would probably be more straight forward to just host my own rails server on an EC2 instance, but I really like the automation and tools available within Heroku.

答:
EC2 specific: http://rubygems.org/gems/amazon-ec2

Console Commands/Results: http://rubygems.org/gems/net-ssh

Both these Gems should address my issue.  Thanks Zabba for the ec2 gem.  I am a little new to rails, and should have started looking there.  I love how easy it is to install new functionality into the language.


问:
How do I get 'next batch' of users using MSGraphSDK in Swift 3
I'm using MSGraphSDK to get all users using the Microsoft Graph - but I can only get the first batch of users (default batch size is 100). I am able to get the first batch as shown below, but I can't see how the framework supports getting the next batch...</p>

```<code>func getUsers(...) {
  var i = 0

  self.graphClient.users().request().getWithCompletion{
    (collection:MSCollection?, nextLink:MSGraphUsersCollectionRequest?, error:Error?) in

    if let nsError = error {
      NSLog("failed - message: \(nsError.localizedDescription)")
    } else {
      if let users = collection {

        for user: MSGraphUser in users.value as! [MSGraphUser] {
          i = i+1
          print("\(i): \(user.optDisplayName ?? "<empty>")")

          self.save(user)
        }

        // TODO: Handle next batch...
        if users.nextLink != nil {
          //self.getNextUsers(users.nextLink)
        }
      }
    }
  }
}
</code>```

答: users.nextLink is the URL link, whereas nextLink is a request object that has been initialized with the next page's URL that you can invoke with getWithCompletion and follows the same pattern as the request shown.

Body:
I'm using MSGraphSDK to get all users using the Microsoft Graph - but I can only get the first batch of users (default batch size is 100). I am able to get the first batch as shown below, but I can't see how the framework supports getting the next batch...

func getUsers(...) {
  var i = 0

  self.graphClient.users().request().getWithCompletion{
    (collection:MSCollection?, nextLink:MSGraphUsersCollectionRequest?, error:Error?) in

    if let nsError = error {
      NSLog("failed - message: \(nsError.localizedDescription)")
    } else {
      if let users = collection {

        for user: MSGraphUser in users.value as! [MSGraphUser] {
          i = i+1
          print("\(i): \(user.optDisplayName ?? "<empty>")")

          self.save(user)
        }

        // TODO: Handle next batch...
        if users.nextLink != nil {
          //self.getNextUsers(users.nextLink)
        }
      }
    }
  }
}


问:
Trouble understanding __attribute__ tag
```<code>extern "C" int asnprintf (char **ret, size_t max_sz, const char *format, ...)
    __attribute__ ((format (printf, 3, 4)));
</code>```

Reading the source code of nmap I came accross this function declaration and I am having troubles understanding it.

Here is what this webpage says about it:

Based on

```<code>__attribute__((format(printf, m, n)));
</code>```

The (m) is the number of the "format string" parameter, and (n) is the number of the first variadic parameter.

I don't understand what is he refering to when saying "format string"; are they just the arguments which affects the behaviour of the function?

Also, what is the number of the first variadic parameter? In all the examples I have seen it is always one more than m, is this always true? Could you give a practical example where is not?

Thanks.

答:
```<code>extern "C" int asnprintf (char **ret, size_t max_sz, const char *format, ...)
                               ^1              ^2               ^3        ^4
</code>```

I don't understand what is he refering to when saying "format string"; are they just the arguments which affects the behaviour of the function?

The format string is the one you generally find in printf for example, like "%0.3f %s" ecc. and of course the function will act accordingly.

Also, what is the number of the first variadic parameter? In all the examples I have seen it is always one more than m, is this always true? Could you give a practical example where is not?

In that case, m = 3 and n = 4, but it need not be so. Let's say you have

```<code>int blablabla(const void *const data, const char *format, int data, ...)
</code>```

then m = 2 and n = 4.

Title: Trouble understanding __attribute__ tag

Body:
extern "C" int asnprintf (char **ret, size_t max_sz, const char *format, ...)
    __attribute__ ((format (printf, 3, 4)));

Reading the source code of nmap I came accross this function declaration and I am having troubles understanding it.

Here is what this webpage says about it:

Based on

__attribute__((format(printf, m, n)));

The (m) is the number of the "format string" parameter, and (n) is the number of the first variadic parameter.

I don't understand what is he refering to when saying "format string"; are they just the arguments which affects the behaviour of the function?

Also, what is the number of the first variadic parameter? In all the examples I have seen it is always one more than m, is this always true? Could you give a practical example where is not?

Thanks.

Body:
extern "C" int asnprintf (char **ret, size_t max_sz, const char *format, ...)
                               ^1              ^2               ^3        ^4

I don't understand what is he refering to when saying "format string"; are they just the arguments which affects the behaviour of the function?

The format string is the one you generally find in printf for example, like "%0.3f %s" ecc. and of course the function will act accordingly.

Also, what is the number of the first variadic parameter? In all the examples I have seen it is always one more than m, is this always true? Could you give a practical example where is not?

In that case, m = 3 and n = 4, but it need not be so. Let's say you have

int blablabla(const void *const data, const char *format, int data, ...)

then m = 2 and n = 4.


问:
Vectorizing a code that requires to complement some elements of a binary array
I have a matrix A of dimension m-by-n composed of zeros and ones, and a matrix J of dimension m-by-1 reporting some integers from [1,...,n].

I want to construct a matrix B of dimension m-by-n such that for i = 1,...,m

B(i,j) = A(i,j) for j=1,...,n-1

B(i,n) = abs(A(i,n)-1)

If sum(B(i,:)) is odd then B(i,J(i)) = abs(B(i,J(i))-1)

This code does what I want:

```<code>m = 4;
n = 5;
A = [1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 1];
J = [1;2;1;4];
B = zeros(m,n);
for i = 1:m
    B(i,n) = abs(A(i,n)-1);
    for j = 1:n-1
        B(i,j) = A(i,j);
    end
    if mod(sum(B(i,:)),2)~=0
       B(i,J(i)) = abs(B(i,J(i))-1);
    end
 end
</code>```

Can you suggest more efficient algorithms, that do not use the nested loop?

答:
No for loops are required for your question. It just needs an effective use of the colon operator and logical-indexing as follows:

```<code>% First initialize B to all zeros
B = zeros(size(A));
% Assign all but last columns of A to B
B(:, 1:end-1) = A(:, 1:end-1);
% Assign the last column of B based on the last column of A
B(:, end) = abs(A(:, end) - 1);
% Set all cells to required value
% Original code which does not work: B(oddRow, J(oddRow)) = abs(B(oddRow, J(oddRow)) - 1);
% Correct code:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
for ii = 1:numel(oddRow)
    B(oddRow(ii), J(oddRow(ii))) = abs(B(oddRow(ii), J(oddRow(ii))) - 1);
end
</code>```

I guess for the last part it is best to use a for loop.

Edit: See the neat trick by EBH to do the last part without a for loop

Body:
I have a matrix A of dimension m-by-n composed of zeros and ones, and a matrix J of dimension m-by-1 reporting some integers from [1,...,n].

I want to construct a matrix B of dimension m-by-n such that for i = 1,...,m

B(i,j) = A(i,j) for j=1,...,n-1

B(i,n) = abs(A(i,n)-1)

If sum(B(i,:)) is odd then B(i,J(i)) = abs(B(i,J(i))-1)

This code does what I want:

m = 4;
n = 5;
A = [1 1 1 1 1; ...
   0 0 1 0 0; ...
   1 0 1 0 1; ...
   0 1 0 0 1];
J = [1;2;1;4];
B = zeros(m,n);
for i = 1:m
    B(i,n) = abs(A(i,n)-1);
    for j = 1:n-1
        B(i,j) = A(i,j);
    end
    if mod(sum(B(i,:)),2)~=0
       B(i,J(i)) = abs(B(i,J(i))-1);
    end
 end

Can you suggest more efficient algorithms, that do not use the nested loop?

Body:
No for loops are required for your question. It just needs an effective use of the colon operator and logical-indexing as follows:

% First initialize B to all zeros
B = zeros(size(A));
% Assign all but last columns of A to B
B(:, 1:end-1) = A(:, 1:end-1);
% Assign the last column of B based on the last column of A
B(:, end) = abs(A(:, end) - 1);
% Set all cells to required value
% Original code which does not work: B(oddRow, J(oddRow)) = abs(B(oddRow, J(oddRow)) - 1);
% Correct code:
% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
for ii = 1:numel(oddRow)
    B(oddRow(ii), J(oddRow(ii))) = abs(B(oddRow(ii), J(oddRow(ii))) - 1);
end

I guess for the last part it is best to use a for loop.

Edit: See the neat trick by EBH to do the last part without a for loop


问:
Excel vba to set picture alignment in outlook
With the help of below coding, I am able to paste the picture from excel to outlook. I just wanted to know if we can set the picture alignment to center. Now it is left alignment</p>

```<code>With outMail
    .To = email
    .Subject = "OK"
    .Display
    Dim wordDoc As Word.Document
    Set wordDoc = outMail.GetInspector.WordEditor
    wordDoc.Range.Paste
    .Save
    .Close 1
End With
</code>```

答:
Try this way:</p>

```<code>With outMail
   .To = email
   .Subject = "OK"
   .Display
    Dim wordDoc As Word.Document
    Set wordDoc = outMail.GetInspector.WordEditor
    wordDoc.Range.Paste
    wordDoc.Application.Selection.Paragraphs.Alignment = wdAlignParagraphCenter
   .Save
   .Close 1
End With
</code>```

Body:
With the help of below coding, I am able to paste the picture from excel to outlook. I just wanted to know if we can set the picture alignment to center. Now it is left alignment

With outMail
    .To = email
    .Subject = "OK"
    .Display
    Dim wordDoc As Word.Document
    Set wordDoc = outMail.GetInspector.WordEditor
    wordDoc.Range.Paste
    .Save
    .Close 1
End With

Body:
Try this way:

With outMail
   .To = email
   .Subject = "OK"
   .Display
    Dim wordDoc As Word.Document
    Set wordDoc = outMail.GetInspector.WordEditor
    wordDoc.Range.Paste
    wordDoc.Application.Selection.Paragraphs.Alignment = wdAlignParagraphCenter
   .Save
   .Close 1
End With


问:
How to send a https request with a certificate golang
I have a server which has a rest API running over https. I want to make a call to this rest api in my application which is running in different port but since this is over https I am getting

```<code>Post https://localhost:8080/api/v1/myapi: x509: certificate signed by unknown authority
</code>```

I have 2 files pulic_key.pem and private_key which can used to verify the certificate. How can verify certificate while sending rest request using golang? I am using &http.Client{} to send a rest request. Here is what I am doing to ignore the certificate right now.

```<code>tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}

client := &http.Client{Transport: tr}
</code>```

答:
If the certificate is self-signed, you must add this option :</p>

```<code>TLSClientConfig: &tls.Config{
   RootCAs:      caCertPool,
   InsecureSkipVerify: true,
},
</code>```

Body:
I have a server which has a rest API running over https. I want to make a call to this rest api in my application which is running in different port but since this is over https I am getting

Post https://localhost:8080/api/v1/myapi: x509: certificate signed by unknown authority

I have 2 files pulic_key.pem and private_key which can used to verify the certificate. How can verify certificate while sending rest request using golang? I am using &http.Client{} to send a rest request. Here is what I am doing to ignore the certificate right now.

tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}

client := &http.Client{Transport: tr}

Body:
If the certificate is self-signed, you must add this option :

TLSClientConfig: &tls.Config{
   RootCAs:      caCertPool,
   InsecureSkipVerify: true,
},


问:
Label font size changing
So I am making a small game in visual basics and at one of the thing I need to do is change the label size following an If statement. Sadly, It seemed way more complicated than I expected... I tried the following but it is "Read only"

```<code>If condition = false then
      lbltmp.Font.Size = 12pts
end if
</code>```

I also Tried the following based on my friends advise:

```<code>With lbltmp.font
.size = 12
end with
</code>```

I found similar question but they were all in c#, Which I don't know how to code in yet

答:
You could actually change the size of it but you don't use code.
Instead just go to the properties of whatever you're trying to change the font size of, and go to the font property. Click on the 3 dots (...)  and a box will open. In that box, you can change the font and its size too. So you could change the size there!

(by the way this is the first time I've given an explanation on a website.)

Title: Label font size changing

Body:
So I am making a small game in visual basics and at one of the thing I need to do is change the label size following an If statement. Sadly, It seemed way more complicated than I expected... I tried the following but it is "Read only"

If condition = false then
      lbltmp.Font.Size = 12pts
end if

I also Tried the following based on my friends advise:

With lbltmp.font
.size = 12
end with

I found similar question but they were all in c#, Which I don't know how to code in yet


问:
Best Practice with jquery functions and ajax
I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.

```<code>$('.microContentWrap').click(function(){

    //perform some functions

});
</code>```

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.

```<code>$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});
</code>```

Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.

答:
```<code>$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});
</code>```

Is saying: "when I click within 'ajax-wrapper' check to see if the element I clicked is 'microContentWrap', if it is, then do this function". The benefit of this approach is that 'microContentWrap' doesn't need to exist when you bind the click even listener.

Another approach would be to add the event listener to 'microContentWrap' in your ajax callback function. So for example:

```<code>$.ajax({
    url:"getvalue.php",
    success:function(data) {
         $('body').append('<div class="microContentWrap"></div>');
         $('.microContentWrap').click(function(){});
    }
  });
</code>```

Body:
I'm new to ajax and want to best understand how to write my jQuery code so that then a page is called via ajax, my jQuery functions (simple stuff like slideshows and overlays) will still work.

Below is what I'm currently doing to make my jquery work on a stand alone page without ajax.

$('.microContentWrap').click(function(){

    //perform some functions

});

In order to make this same function work when this page has been loaded via ajax, I'm duplicating my code and binding it to a div called "ajax-wrapper" that loads normally on this page. Without this step, the above code was not executing on the ajax page.

$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});

Both of these things work, but is this the most efficient way? Seems repetitive to do this two step process for every single function in my file.

Body:
$("ajax-wrapper").on("click", ".microContentWrap", function() {

    //exact same functions as above

});

Is saying: "when I click within 'ajax-wrapper' check to see if the element I clicked is 'microContentWrap', if it is, then do this function". The benefit of this approach is that 'microContentWrap' doesn't need to exist when you bind the click even listener.

Another approach would be to add the event listener to 'microContentWrap' in your ajax callback function. So for example:

$.ajax({
    url:"getvalue.php",
    success:function(data) {
         $('body').append('<div class="microContentWrap"></div>');
         $('.microContentWrap').click(function(){});
    }
  });


问:
How should I test two nested immutable js data structures for deep equality?
Say I have the following nested immutable data structure:

```<code>import { Record, List } from 'immutable'

const foo = List([
        Record({
           id: 1,
           gameState: Record({})
         })
       ])
</code>```

How would I test that two nested immutable js data structures are equal to each other?

test.js

```<code>import jest from 'jest'
import { Record, List } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {
        const expected = List([
              Record({
                 id: 1,
                 gameState: Record({})
               })
             ])
        expect(foo).toEqual(expected)
    })
</code>```

答:
For most ImmutableJS types the test you've got would work fine.  The problem is the way you're using Records. Unlike Map, List etc the constructorRecord(...) doesn't return a new object, it returns a constructor which can then be used to create new objects.  From the docs (https://facebook.github.io/immutable-js/docs/#/Record):

[Record] Creates a new Class which produces Record instances. A record is similar to a JS object, but enforce a specific set of allowed string keys, and have default values.

If you want to user Record then you can write your test like this:

```<code>import { Record, List, is } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {
        const gameState = Record({});
        const gameRecord = Record({
            id: 1,
            gameState: new gameState()
        });

        const foo = List([
            new gameRecord()
        ]);

        const expected = List([
            new gameRecord()
        ]);
        expect(foo.equals(expected)).toBe(true);
    })
});
</code>```

Compare this to using a Map instead of a Record. The test below using jest's toEqual function passes as expected:

```<code>import { Map, List, is } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {

        const foo = List([
            Map({
                id: 1,
                gameState: Map({})
            })
        ]);

        const expected = List([
            Map({
                id: 1,
                gameState: Map({})
            })
        ])
        expect(foo).toEqual(expected);
    })
});
</code>```

Body:
Say I have the following nested immutable data structure:

import { Record, List } from 'immutable'

const foo = List([
        Record({
           id: 1,
           gameState: Record({})
         })
       ])

How would I test that two nested immutable js data structures are equal to each other?

test.js

import jest from 'jest'
import { Record, List } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {
        const expected = List([
              Record({
                 id: 1,
                 gameState: Record({})
               })
             ])
        expect(foo).toEqual(expected)
    })

Body:
For most ImmutableJS types the test you've got would work fine.  The problem is the way you're using Records. Unlike Map, List etc the constructorRecord(...) doesn't return a new object, it returns a constructor which can then be used to create new objects.  From the docs (https://facebook.github.io/immutable-js/docs/#/Record):

[Record] Creates a new Class which produces Record instances. A record is similar to a JS object, but enforce a specific set of allowed string keys, and have default values.

If you want to user Record then you can write your test like this:

import { Record, List, is } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {
        const gameState = Record({});
        const gameRecord = Record({
            id: 1,
            gameState: new gameState()
        });

        const foo = List([
            new gameRecord()
        ]);

        const expected = List([
            new gameRecord()
        ]);
        expect(foo.equals(expected)).toBe(true);
    })
});

Compare this to using a Map instead of a Record. The test below using jest's toEqual function passes as expected:

import { Map, List, is } from 'immutable'

describe('test', () => {
    it('that foo equals expected', () => {

        const foo = List([
            Map({
                id: 1,
                gameState: Map({})
            })
        ]);

        const expected = List([
            Map({
                id: 1,
                gameState: Map({})
            })
        ])
        expect(foo).toEqual(expected);
    })
});


问:
Compare list of strings in two different files vb.net
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

```<code>  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()
</code>```

答:
Instead of needing to sort them, you can use .Contains to see if they match, and if they do. Match them.

A small example, using your code:

```<code>  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String)
  For Each person as string In RqstDescription
     dim desc as String = ReadAllDescrpt.FirstOrDefault(Function(x)x.Contains(person))
if desc <> "" Then Console.WriteLine(person & " > " & desc)
  Next
</code>```

I haven't tested this, but this is how it should work. This uses LINQ too. :)

Body:
I have two different .txt files (requested_description.txt and all_description.txt).

In all_description.txt I have a list of strings, something like this:

all_description.txt

John is a policeman

  Mike is a doctor

  Barbara is a model

  etc...

In other file (requested_description.txt) I will search names from the first file (all_description.txt)

requested_description.txt

John

  Michael

  Ivan

  Donald

  Barbara

  etc...

I want to find if the strings (names) from requested_description.txt are the same in all_description.txt

Then I want to show results in output, for example:

John > John is a policeman

Barbara > Barbara is a model

For now I have only this sort of code, I want to use sort method, first to sort ascending then use for each... so I'm a little stuck here:

  Dim i As Integer = 0
  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String())
  allDescrpt.Sort()
  For Each descrpt In ReadAllDescrpt
     Console.WriteLine(ReadAllDescrpt)
  Next
  Console.WriteLine()

Body:
Instead of needing to sort them, you can use .Contains to see if they match, and if they do. Match them.

A small example, using your code:

  Dim ReadAllDescrpt As String() =File.ReadAllLines("all_description.txt")
  Dim RqstDescription As String()= File.ReadAllLines("rqst_description.txt")

  Dim allDescrpt As New List(Of String)
  For Each person as string In RqstDescription
     dim desc as String = ReadAllDescrpt.FirstOrDefault(Function(x)x.Contains(person))
if desc <> "" Then Console.WriteLine(person & " > " & desc)
  Next

I haven't tested this, but this is how it should work. This uses LINQ too. :)


问:
How to use NSDL PAN(Permanent Account Number) number verification API in php
NSDL APIS has Java sample code.

https://onlineservices.tin.egov-nsdl.com/TIN/JSP/security/DownloadCodesForOPV.jsp

答:
This API is compatible only for RBL
Bank’s internal business use.</p>


答:
The answer is in the gcc manual:

The format attribute specifies that a function takes printf, scanf,
  strftime or strfmon style arguments which should be type-checked
  against a format string.

format (archetype, string-index, first-to-check)

The parameter archetype determines how the format string is
  interpreted, and should be printf, scanf, strftime or strfmon. (You
  can also use printf, scanf, strftime or strfmon.) The
  parameter string-index specifies which argument is the format string
  argument (starting from 1), while first-to-check is the number of the
  first argument to check against the format string. For functions where
  the arguments are not available to be checked (such as vprintf),
  specify the third parameter as zero. In this case the compiler only
  checks the format string for consistency. For strftime formats, the
  third parameter is required to be zero. Since non-static C++ methods
  have an implicit this argument, the arguments of such methods should
  be counted from two, not one, when giving values for string-index and
  first-to-check.

Title: Trouble understanding __attribute__ tag


答:
Just to add to @ammportal good answer, also the last part can be done without a loop with the use of linear indices. For that, sub2ind is useful. So adopting the last part of the previous answer, this can be done:

```<code>% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
% convert the locations to linear indices
ind = sub2ind(size(B),oddRow,J(oddRow));
B(ind) = abs(B(ind)- 1);
</code>```

Title: Vectorizing a code that requires to complement some elements of a binary array

Body:
Just to add to @ammportal good answer, also the last part can be done without a loop with the use of linear indices. For that, sub2ind is useful. So adopting the last part of the previous answer, this can be done:

% Find all rows in B with an odd sum
oddRow = find(mod(sum(B, 2), 2) ~= 0);
% convert the locations to linear indices
ind = sub2ind(size(B),oddRow,J(oddRow));
B(ind) = abs(B(ind)- 1);


问:
Angular 2 JWT x-access-token
I'm having a problem setting my JWT in the header for my requests. Here's how I'm building the request:

```<code>const headers = { 'x-access-token' : this.token };
const config = { headers: headers };
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));
</code>```

When I step through this looks perfect but it's coming through the server with the token. On the server the headers look like this:

-= Edit =-

To answer some questions, I actually started out using the Headers and RequestOptions classes and that was giving me strange results so I switched to using object literals to try to simplify. This is what I had:

```<code>let headers = new Headers();
headers.append('x-access-token', this.token);
let config = new RequestOptions({ headers: headers });
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));
</code>```

But when I append the token to the header it just repeats the key in the value. Here's a screen shot of the debug window.

As you can see, even thought I set the key as x-access-token and the value as the token (which I inspected to verify that it's actually the token) the header has x-access-token as both the key and the value.

I can verify that the token is the correct token by inspecting it as well. Here's a screenshot of that:

--== More Information ==--

If I send the request from Postman it works. Here's the request from Postman:

And here's what comes through Node:

Here's my request in Angular:

And here's what comes through Node:

答:
For those who stumble upon this (most likely including myself in another six months) here is what the problem was:

Because I was adding custom headers to the request the browser first sent a CORS OPTIONS request to see if the server would be willing to accept a GET request. I wasn't doing anything special with that request and the browser didn't know how to interpret the response so it didn't send the actual GET request. This is why I saw my headers in the access-control-request-headers field. The browser was trying to ask the server if those headers were ok before it sent any actual data. I fixed it by handling CORS in my server with this code:

```<code>const cors = require('cors');
app.use(cors({ origin: '*', optionsSuccessStatus: 200 }));
</code>```

Title: Angular 2 JWT x-access-token

Body:
I'm having a problem setting my JWT in the header for my requests. Here's how I'm building the request:

const headers = { 'x-access-token' : this.token };
const config = { headers: headers };
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));

When I step through this looks perfect but it's coming through the server with the token. On the server the headers look like this:

-= Edit =-

To answer some questions, I actually started out using the Headers and RequestOptions classes and that was giving me strange results so I switched to using object literals to try to simplify. This is what I had:

let headers = new Headers();
headers.append('x-access-token', this.token);
let config = new RequestOptions({ headers: headers });
return this.http.get(this.allStudentsUrl, config)
    .toPromise()
    .catch((error) => this.handleError(error))
    .then((response) => this.handleStudents(response));

But when I append the token to the header it just repeats the key in the value. Here's a screen shot of the debug window.

As you can see, even thought I set the key as x-access-token and the value as the token (which I inspected to verify that it's actually the token) the header has x-access-token as both the key and the value.

I can verify that the token is the correct token by inspecting it as well. Here's a screenshot of that:

--== More Information ==--

If I send the request from Postman it works. Here's the request from Postman:

And here's what comes through Node:

Here's my request in Angular:

And here's what comes through Node:

Body:
For those who stumble upon this (most likely including myself in another six months) here is what the problem was:

Because I was adding custom headers to the request the browser first sent a CORS OPTIONS request to see if the server would be willing to accept a GET request. I wasn't doing anything special with that request and the browser didn't know how to interpret the response so it didn't send the actual GET request. This is why I saw my headers in the access-control-request-headers field. The browser was trying to ask the server if those headers were ok before it sent any actual data. I fixed it by handling CORS in my server with this code:

const cors = require('cors');
app.use(cors({ origin: '*', optionsSuccessStatus: 200 }));


问:
How do I change the pitch of an audio WAV file in Node?
I would like to know how I can change the audio pitch from male to female sounding within a Node application. Thanks!</p>

答: As a start point, check "How to decrease pitch of audio file in nodejs server side?" and npm/audio-decode. </p>


问:
Undefined method error with Rails has_one association (Rails 5)
I am attempting to access the methods of an associated model in the view, but getting an undefined method error

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

.  Thanks for your help!

index view:

```<code><% @actuals.each do |actual| %>
  <% if actual.procedures.present? %>
    <% actual.procedures.each do |procedure| %>
     <tr>
       <td><%= procedure.cpt_code.id %></td>
       <td><%= procedure.description %></td>
     </tr>
    <% end %>
  <% end %>
<% end %>
</code>```

Controller:

```<code>  def index
    @actuals = Actual.all
  end
</code>```

Models:

```<code>class Actual < ApplicationRecord
  has_many :actual_procedures, :dependent => :destroy
  has_many :procedures, through: :actual_procedures

class ActualProcedure < ApplicationRecord
  belongs_to :procedure
  belongs_to :actual
end

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
end

class CptCode < ApplicationRecord
  has_one :procedure
</code>```

Procedures in schema:

```<code>  create_table "procedures", force: :cascade do |t|
    t.bigint "cpt_code_id"
    t.string "code"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cpt_code_id"], name: "index_procedures_on_cpt_code_id"
  end
</code>```

答:
undefined method `cpt_code' for Procedure:0x007fe7b55518e8

<s>You don't have cpt_code in procedures table. Perhaps you meant cpt_code_id.</s>

Update:

Actual reason is you didn't defined association for cpt_code in Procedure model

```<code>class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
  belongs_to :cpt_code # you should have this
end
</code>```

Body:
I am attempting to access the methods of an associated model in the view, but getting an undefined method error

undefined method `cpt_code' for Procedure:0x007fe7b55518e8

.  Thanks for your help!

index view:

<% @actuals.each do |actual| %>
  <% if actual.procedures.present? %>
    <% actual.procedures.each do |procedure| %>

       <%= procedure.cpt_code.id %>
       <%= procedure.description %>

    <% end %>
  <% end %>
<% end %>

Controller:

  def index
    @actuals = Actual.all
  end

Models:

class Actual < ApplicationRecord
  has_many :actual_procedures, :dependent => :destroy
  has_many :procedures, through: :actual_procedures

class ActualProcedure < ApplicationRecord
  belongs_to :procedure
  belongs_to :actual
end

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
end

class CptCode < ApplicationRecord
  has_one :procedure

Procedures in schema:

  create_table "procedures", force: :cascade do |t|
    t.bigint "cpt_code_id"
    t.string "code"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["cpt_code_id"], name: "index_procedures_on_cpt_code_id"
  end

Body:
undefined method `cpt_code' for Procedure:0x007fe7b55518e8

<s>You don't have cpt_code in procedures table. Perhaps you meant cpt_code_id.</s>

Update:

Actual reason is you didn't defined association for cpt_code in Procedure model

class Procedure < ApplicationRecord
  has_many :actual_procedures
  has_many :actuals, through: :actual_procedures
  belongs_to :cpt_code # you should have this
end


问:
How to include virtual fields in find with CakePHP 3?
I am trying to add an isOnline field for users which does not exists in the database. Is there a way In can return isOnline as a virtual field? I have tried adding this to the User entity:

```<code>protected function _getIsOnline() {
    return true;
}
</code>```

But when I do a $user->find('all', []) the field is not included. Any ideas on how to accomplish this?

答: You cannot use use virtual fields within the query object. Any filtering would have to take place after retrieving the data from the query. Virtual fields are lazy loaded, so they do not exist until required.</p>

Body:
I am trying to add an isOnline field for users which does not exists in the database. Is there a way In can return isOnline as a virtual field? I have tried adding this to the User entity:

protected function _getIsOnline() {
    return true;
}

But when I do a $user->find('all', []) the field is not included. Any ideas on how to accomplish this?


问:
SSRS Report Colours change when exporting to excel
When we export an SSRS 2008 report to excel and then copy a range from that file to another excel file, the colours used in the report are changed to something that is totally different, very annoying when we use 'Conditonal Formatting' to colour some of these cells a specific colour. Any ideas why?</p>

答:
This Worked for me.

```<code>=IIF(sum(Fields!TotalHours.Value) <> "", "White","Pink")
</code>```

in other words make sure you define the colors for both conditions.
Then on the Tablix1 Properties page under the Background fill color remove the "Automatic" and choose No color

Body:
This Worked for me.

=IIF(sum(Fields!TotalHours.Value) <> "", "White","Pink")

in other words make sure you define the colors for both conditions.
Then on the Tablix1 Properties page under the Background fill color remove the "Automatic" and choose No color