问:
Use Spring Security with JPA
I am new to Spring.

We are using spring security feature.
Database connectivity: eclipselink implementation of JPA.
Database: MySql

While using spring security, Configuration of  authentication provider is as follows,-

```<code><authentication-provider>

    <jdbc-user-service id="userDetailsService" data-source-ref="Datasource" />

    </authentication-provider>
</code>```

But in JPA we do not define datasource, we use Persistence unit with provider jpa.PersistenceProvider.

So how do we configure authentication provider so as to use JPA for database connectivity?

What exactly should data-source-ref field contain to use database for authentication?

Thank you in advance.

答:
An easier way for authentication in your case is to get one of your service layer classes implement org.springframework.security.core.userdetails.UserDetailsService interface. This interface contain only one method UserDetails loadUserByUsername(String username). You have to make sure that you return a UserDetails instance for a given username.

```<code>public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {
    // load and return user using your regular JPA techniques here
        ...
    }
</code>```

Once you have implemented this method in your service class, you will simply need to add its reference your spring configuration file:

```<code><authentication-manager>
     <authentication-provider user-service-ref="myServiceLayerClassInstance">
     </authentication-provider>
</authentication-manager>
</code>```

Title: Use Spring Security with JPA

Body:
I am new to Spring.

We are using spring security feature.
Database connectivity: eclipselink implementation of JPA.
Database: MySql

While using spring security, Configuration of  authentication provider is as follows,-

<authentication-provider>

    <jdbc-user-service id="userDetailsService" data-source-ref="Datasource" />

    </authentication-provider>

But in JPA we do not define datasource, we use Persistence unit with provider jpa.PersistenceProvider.

So how do we configure authentication provider so as to use JPA for database connectivity?

What exactly should data-source-ref field contain to use database for authentication?

Thank you in advance.

Body:
An easier way for authentication in your case is to get one of your service layer classes implement org.springframework.security.core.userdetails.UserDetailsService interface. This interface contain only one method UserDetails loadUserByUsername(String username). You have to make sure that you return a UserDetails instance for a given username.

public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {
    // load and return user using your regular JPA techniques here
        ...
    }

Once you have implemented this method in your service class, you will simply need to add its reference your spring configuration file:

<authentication-manager>
     <authentication-provider user-service-ref="myServiceLayerClassInstance">
     </authentication-provider>
</authentication-manager>


来源: stackexchange

问:
Erros with AVCaptureSession to UIImage in Swift 3
Here's my setup:

```<code>let captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSessionPresetPhoto

let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

do {
    let input = try AVCaptureDeviceInput(device: backCamera)
    captureSession.addInput(input)
} catch {
    print("can't access camera")
    return
}

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer!)

let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "sample buffer delegate", attributes: .concurrent))

captureSession.addOutput(videoOutput)
captureSession.startRunning()

let pixelBuffer = CMSampleBufferGetImageBuffer(CMSampleBuffer)
let cameraImage = CIImage(cvImageBuffer: pixelBuffer!)

let comicEffect = CIFilter(name: "CIComicEffect")

comicEffect!.setValue(cameraImage, forKey: kCIInputImageKey)

let filteredImage = UIImage(ciImage: comicEffect!.value(forKey: kCIOutputImageKey) as! CIImage!)

DispatchQueue.main.async() {
    let image_view = UIImageView(image: filteredImage)
    self.view = image_view
}
</code>```

I'm getting two errors. The first error is with setSampleBufferDelegate():

```<code>Cannot convert value of type 'ViewController' to expected argument type 'AVCaptureVideoDataOutputSampleBufferDelegate!'
</code>```

The second error is with CMSampleBufferGetImageBuffer():

```<code>Cannot convert value of type '(CMSampleBuffer).Type' (aka 'CMSampleBuffer.Type') to expected argument type 'CMSampleBuffer'
</code>```

Dose anyone know what I could be doing wrong?

答:
For first error:

Implement AVCaptureVideoDataOutputSampleBufferDelegate delegate which will give you AVCaptureOutput and CMSampleBuffer for current session.

class YourClass : AVCaptureVideoDataOutputSampleBufferDelegate {}

public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!){        print("DidDropSampleBuffer")
//use this CMSampleBuffer to get Image
}

For second error ,
replace this :

let pixelBuffer = CMSampleBufferGetImageBuffer(CMSampleBuffer)

With :

```<code>`func ciimageFromSampleBuffer(sampleBuffer : CMSampleBuffer) -> CIImage
  {
    let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    let cameraImage = CIImage(cvImageBuffer: pixelBuffer!)
    return cameraImage
  }`
</code>```

this will give you CIImage.

ContentLicense: CC BY-SA 3.0

Body:
Here's my setup:

let captureSession = AVCaptureSession()
captureSession.sessionPreset = AVCaptureSessionPresetPhoto

let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

do {
    let input = try AVCaptureDeviceInput(device: backCamera)
    captureSession.addInput(input)
} catch {
    print("can't access camera")
    return
}

let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
self.view.layer.addSublayer(previewLayer!)

let videoOutput = AVCaptureVideoDataOutput()
videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "sample buffer delegate", attributes: .concurrent))

captureSession.addOutput(videoOutput)
captureSession.startRunning()

let pixelBuffer = CMSampleBufferGetImageBuffer(CMSampleBuffer)
let cameraImage = CIImage(cvImageBuffer: pixelBuffer!)

let comicEffect = CIFilter(name: "CIComicEffect")

comicEffect!.setValue(cameraImage, forKey: kCIInputImageKey)

let filteredImage = UIImage(ciImage: comicEffect!.value(forKey: kCIOutputImageKey) as! CIImage!)

DispatchQueue.main.async() {
    let image_view = UIImageView(image: filteredImage)
    self.view = image_view
}

I'm getting two errors. The first error is with setSampleBufferDelegate():

Cannot convert value of type 'ViewController' to expected argument type 'AVCaptureVideoDataOutputSampleBufferDelegate!'

The second error is with CMSampleBufferGetImageBuffer():

Cannot convert value of type '(CMSampleBuffer).Type' (aka 'CMSampleBuffer.Type') to expected argument type 'CMSampleBuffer'

Dose anyone know what I could be doing wrong?

Body:
For first error:

Implement AVCaptureVideoDataOutputSampleBufferDelegate delegate which will give you AVCaptureOutput and CMSampleBuffer for current session.

class YourClass : AVCaptureVideoDataOutputSampleBufferDelegate {}

public func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!){        print("DidDropSampleBuffer")
//use this CMSampleBuffer to get Image
}

For second error ,
replace this :

let pixelBuffer = CMSampleBufferGetImageBuffer(CMSampleBuffer)

With :

`func ciimageFromSampleBuffer(sampleBuffer : CMSampleBuffer) -> CIImage
  {
    let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    let cameraImage = CIImage(cvImageBuffer: pixelBuffer!)
    return cameraImage
  }`

this will give you CIImage.


问:
Calling a function on user complete enter the text
I'm purposely to implementing an auto-complete dropdown using ng2-autocomplete. But my data source is on remote and I query the data source using a server in my Angular 2 service application.

Component View

```<code><ng2-completer
      [(ngModel)]="searchStr"
      [datasource]="dataService"
      [minSearchLength]="0"
      (change)='findAddress($event)'>
</ng2-completer>
</code>```

Component

```<code>findAddress($event){
      this.addressCrawlerService.findMap($event.target.value)
          .subscribe(
              res => {
                  let resultArray = res["result"];
                  this.searchData = resultArray;
                  this.dataService = this.completerService.local(this.searchData, 'streetAddress', 'streetAddress');
              },
              error => {
                  console.log(error.json);
              }
          );
}
</code>```

Here the values are not fired when the value changed. What's wrong on my code to fix this error.

答:
I think you need to delay the service call until the user stops typing.

For that you have two options:

Use the Angular way like described here https://angular.io/guide/http#1-wait-for-the-user-to-stop-typing

Use the 'javascript' way... see this plunker example:

https://embed.plnkr.co/9VYmoGxKO3buc4DmVQgl/

The principle for both ways is the same. For each character typed both set a timer to wait for i.e. 400 ms. If the user types the next character within the 400ms the already set timer is stopped and a new timer starts. If the 400ms go by without typing the code gets executed.

Body:
I'm purposely to implementing an auto-complete dropdown using ng2-autocomplete. But my data source is on remote and I query the data source using a server in my Angular 2 service application.

Component View

<ng2-completer
      [(ngModel)]="searchStr"
      [datasource]="dataService"
      [minSearchLength]="0"
      (change)='findAddress($event)'>
</ng2-completer>

Component

findAddress($event){
      this.addressCrawlerService.findMap($event.target.value)
          .subscribe(
              res => {
                  let resultArray = res["result"];
                  this.searchData = resultArray;
                  this.dataService = this.completerService.local(this.searchData, 'streetAddress', 'streetAddress');
              },
              error => {
                  console.log(error.json);
              }
          );
}

Here the values are not fired when the value changed. What's wrong on my code to fix this error.


问:
Unable to apply CSS in Angular using ng-class
I am stuck at it for a long long time now and I really need help. I have a div section which I want to display on the click of a button. For which I use CSS classes.

Here is the DIV section

```<code>    <div class="elen-main--left-menu--collapsed " ng-class="collapsedMenuAvailable">
    <div class="icon-propal icon_active">
        <img src="content/img/icon_propal_white.svg" alt="" width="18" />
    </div>

    <div class="icon-contrat">
        <img src="content/img/icon_contrat_grey.svg" alt="" width="18" />
    </div>
    <div class="left--menu--expand" ng-click="vm.showVerticalBanner">
        <img src="content/img/arrow-expandMenu-grey.svg" alt="" width="13">
    </div>
</div>
</code>```

collapsedMenuAvailable is changed to the value from my controller.
CONTROLLER

```<code>vm.hideVerticalBanner = function () {
                $scope.collapsedMenuAvailable = 'expandCollapsedMenu';
                $('.elen-main--left-menu').addClass('collapseLeftMenu');
                $('.elen-main--left-menu').css('overflow', 'hidden');
                setTimeout(function () {
                    // $('.elen-main--left-menu--collapsed').addClass('expandCollapsedMenu');
                    $('.elen-main--content').css('width', 'calc(100% - 6rem)');
                }, 200);

                $('.elen-main--left-menu').removeClass('expandLeftMenu');
                $('.elen-main--left-menu--collapsed').removeClass('collapseCollapsedMenu');
            }
</code>```

But still it doesn't apply the CSS. However if I put the classname which is 'expandCollapsedMenu' in the div section, the CSS is applied.

what is possibly wrong ?

答:
ng-class is used as

ng-class="{'classname' : 'angular expression'}"

e.g.

ng-class="{'collapsedMenuAvailable' : true }"

and your function call vm.showVerticalBanner needs parenthesis.

Use your controller to change the class names, which will be applied based on the expression. On ng-click call vm.toggleClasses function.

i.e if you want to apply collapsedMenuAvailable class then do something as

```<code>ng-class="{'collapsedMenuAvailable' : $scope.shouldApplyCollapsedMenuAvailable,
'collapseCollapsedMenu' : $scope.shouldApplycollapseCollapsedMenu}"
</code>```

and in controller:

```<code>vm.toggleClasses = function () {
$scope.shouldApplycollapseCollapsedMenu = !$scope.shouldApplycollapseCollapsedMenu;
$scope.shouldApplyCollapsedMenuAvailable = !$scope.shouldApplyCollapsedMenuAvailable;

}
</code>```

Body:
I am stuck at it for a long long time now and I really need help. I have a div section which I want to display on the click of a button. For which I use CSS classes.

Here is the DIV section

collapsedMenuAvailable is changed to the value from my controller.
CONTROLLER

vm.hideVerticalBanner = function () {
                $scope.collapsedMenuAvailable = 'expandCollapsedMenu';
                $('.elen-main--left-menu').addClass('collapseLeftMenu');
                $('.elen-main--left-menu').css('overflow', 'hidden');
                setTimeout(function () {
                    // $('.elen-main--left-menu--collapsed').addClass('expandCollapsedMenu');
                    $('.elen-main--content').css('width', 'calc(100% - 6rem)');
                }, 200);

                $('.elen-main--left-menu').removeClass('expandLeftMenu');
                $('.elen-main--left-menu--collapsed').removeClass('collapseCollapsedMenu');
            }

But still it doesn't apply the CSS. However if I put the classname which is 'expandCollapsedMenu' in the div section, the CSS is applied.

what is possibly wrong ?

Body:
ng-class is used as

ng-class="{'classname' : 'angular expression'}"

e.g.

ng-class="{'collapsedMenuAvailable' : true }"

and your function call vm.showVerticalBanner needs parenthesis.

Use your controller to change the class names, which will be applied based on the expression. On ng-click call vm.toggleClasses function.

i.e if you want to apply collapsedMenuAvailable class then do something as

ng-class="{'collapsedMenuAvailable' : $scope.shouldApplyCollapsedMenuAvailable,
'collapseCollapsedMenu' : $scope.shouldApplycollapseCollapsedMenu}"

and in controller:

vm.toggleClasses = function () {
$scope.shouldApplycollapseCollapsedMenu = !$scope.shouldApplycollapseCollapsedMenu;
$scope.shouldApplyCollapsedMenuAvailable = !$scope.shouldApplyCollapsedMenuAvailable;

}


问:
How to integrate ESLint with Visual Stusio 2013?
I need to configure ESLint in my Visual Studio 2013 angular js SPA application.
Please help me on this.</p>

答:
Web Essentials extends Visual Studio with a lot of new features that web developers have been missing for many years.

If you ever write CSS, HTML, JavaScript, TypeScript, CoffeeScript or LESS, then you will find many useful features that make your life as a developer easier.

This is for all Web developers using Visual Studio.


问:
How to call Blob Images as Rest Services
i have my Blob Images store in Oracle Database. i want to create a Get Methode to retrieve it as JSON Format.

That is the Structure of my DB

答: it working fine now. i Just write it as sql Query and create the Rest


问:
Subform calulation error when pasting multiple records in subform
I do a calculation on all three Events on a subform to update the main form:

```<code>Private Sub Form_AfterDelConfirm(Status As Integer)
  Me.Parent.UpdateStunden
End Sub

Private Sub Form_AfterInsert()
  Me.Parent.UpdateStunden
End Sub

Private Sub Form_AfterUpdate()
  Me.Parent.UpdateStunden
End Sub

Public Sub UpdateStunden(Optional BeforeUpdateEvent As Boolean = False)
On Error GoTo ErrorHandler
Dim rst As Recordset
Dim sql As String
Dim NewStunden As Variant

    If Me.NewRecord Then Exit Sub

    sql = _
    "SELECT Sum(Stunden) AS SumStunden " & _
    "FROM Tätigkeiten " & _
    "WHERE Tätigkeitsdatum = #" & Format(Me!Tätigkeitsdatum, "yyyy-mm-dd") & "#;"

    Set rst = CurrentDb().OpenRecordset(sql, dbOpenSnapshot)

    If Not rst.EOF Or Not rst.BOF Then
        NewStunden = rst!SumStunden
        If Nz(NewStunden) <> Nz(Me.Stunden) Or IsNull(Me.Stunden) Then
            Me.Stunden = NewStunden
        End If
    End If

ExitPoint:
    On Error Resume Next
    If Me.Dirty And Not BeforeUpdateEvent Then Me.Dirty = False
    rst.Close
    Set rst = Nothing
    Exit Sub

ErrorHandler:
    Select Case Err
        Case Else:  LogNTEvent Now & "Error: " & Err & ": " & Err.Description & ": UpdateStunden", EVENTLOG_ERROR_TYPE, 1000, "Error: " & Err.Number
    End Select
    Resume ExitPoint
End Sub
</code>```

This normally works fine.

But there is a bug if I copy and paste more than one record into the subform. When I copy and paste multiple records from one subform to the same subform but on another main-form record the calculation is wrong.

This should work as Standard because I use it everywhere.

We Need an After Paste Event!

Does anyone know how to do this?

Regards Richard

答:
Just set the Control-Source of the Textbox-Control on the main form to this:

=DomSumme("Stunden";"Tätigkeiten";"Tätigkeitsdatum = #" & Format([Tätigkeitsdatum];"jjjj-mm-tt") & "#")
```

<p>And then requery after all three Events:</p>

<pre class="lang-vb prettyprint-override"><code>Private Sub Form_AfterDelConfirm(Status As Integer)
    Me.Parent!Test.Requery
End Sub

Private Sub Form_AfterInsert()
    Me.Parent!Test.Requery
End Sub

Private Sub Form_AfterUpdate()
    Me.Parent!Test.Requery
End Sub
</code>```

N.B. German Office 2010

Body:
I do a calculation on all three Events on a subform to update the main form:

Private Sub Form_AfterDelConfirm(Status As Integer)
  Me.Parent.UpdateStunden
End Sub

Private Sub Form_AfterInsert()
  Me.Parent.UpdateStunden
End Sub

Private Sub Form_AfterUpdate()
  Me.Parent.UpdateStunden
End Sub

Public Sub UpdateStunden(Optional BeforeUpdateEvent As Boolean = False)
On Error GoTo ErrorHandler
Dim rst As Recordset
Dim sql As String
Dim NewStunden As Variant

    If Me.NewRecord Then Exit Sub

    sql = _
    "SELECT Sum(Stunden) AS SumStunden " & _
    "FROM Tätigkeiten " & _
    "WHERE Tätigkeitsdatum = #" & Format(Me!Tätigkeitsdatum, "yyyy-mm-dd") & "#;"

    Set rst = CurrentDb().OpenRecordset(sql, dbOpenSnapshot)

    If Not rst.EOF Or Not rst.BOF Then
        NewStunden = rst!SumStunden
        If Nz(NewStunden) <> Nz(Me.Stunden) Or IsNull(Me.Stunden) Then
            Me.Stunden = NewStunden
        End If
    End If

ExitPoint:
    On Error Resume Next
    If Me.Dirty And Not BeforeUpdateEvent Then Me.Dirty = False
    rst.Close
    Set rst = Nothing
    Exit Sub

ErrorHandler:
    Select Case Err
        Case Else:  LogNTEvent Now & "Error: " & Err & ": " & Err.Description & ": UpdateStunden", EVENTLOG_ERROR_TYPE, 1000, "Error: " & Err.Number
    End Select
    Resume ExitPoint
End Sub

This normally works fine.

But there is a bug if I copy and paste more than one record into the subform. When I copy and paste multiple records from one subform to the same subform but on another main-form record the calculation is wrong.

This should work as Standard because I use it everywhere.

We Need an After Paste Event!

Does anyone know how to do this?

Regards Richard

Body:
Just set the Control-Source of the Textbox-Control on the main form to this:

=DomSumme("Stunden";"Tätigkeiten";"Tätigkeitsdatum = #" & Format([Tätigkeitsdatum];"jjjj-mm-tt") & "#")

And then requery after all three Events:

Private Sub Form_AfterDelConfirm(Status As Integer)
    Me.Parent!Test.Requery
End Sub

Private Sub Form_AfterInsert()
    Me.Parent!Test.Requery
End Sub

Private Sub Form_AfterUpdate()
    Me.Parent!Test.Requery
End Sub

N.B. German Office 2010


问:
How do I turn off PHP Notices?
```<code>Notice: Constant DIR_FS_CATALOG already defined
</code>```

I've already commented out display_errors in php.ini, but is not working.

How do I make PHP to not output such things to browsers?

UPDATE

I put display_errors = Off there but it's still reporting such notices,

Is this an issue with PHP 5.3?

Reporting numerous Call Stack too..

答:
As mentioned by some and if you are the code author, you should correct all those errors, notices, etc. because it will cause more problems for you long terms than not fixing them (especially when you upgrade your OS). For your server, you should have errors displayed in your logs only, not the client's screen.

So to avoid the errors in your browser you use the display_errors flag as you already found:

```<code>display_errors = Off
</code>```

Now the real problem is when you are running someone else code. In that case, modifying the code is likely to get overwritten each time you upgrade that code. It makes it tedious to maintain that code.

In my case, I am running PHP with crontab to have the wp-cron.php script running once in a while. I was getting errors sent to my emails, which becomes tedious when you get one email every 10 minutes! In that case, though, the Wordpress system has a configuration file includes a WP_DEBUG and they call the error_reporting() function so trying to change the error_reporting variable on the command line won't work. Instead you have to edit the wp-config.php file in the root folder and make sure that the WP_DEBUG is set to false. Otherwise you will get all those warnings and notices all the time.

Title: How do I turn off PHP Notices?

Body:
Notice: Constant DIR_FS_CATALOG already defined

I've already commented out display_errors in php.ini, but is not working.

How do I make PHP to not output such things to browsers?

UPDATE

I put display_errors = Off there but it's still reporting such notices,

Is this an issue with PHP 5.3?

Reporting numerous Call Stack too..

Body:
As mentioned by some and if you are the code author, you should correct all those errors, notices, etc. because it will cause more problems for you long terms than not fixing them (especially when you upgrade your OS). For your server, you should have errors displayed in your logs only, not the client's screen.

So to avoid the errors in your browser you use the display_errors flag as you already found:

display_errors = Off

Now the real problem is when you are running someone else code. In that case, modifying the code is likely to get overwritten each time you upgrade that code. It makes it tedious to maintain that code.

In my case, I am running PHP with crontab to have the wp-cron.php script running once in a while. I was getting errors sent to my emails, which becomes tedious when you get one email every 10 minutes! In that case, though, the Wordpress system has a configuration file includes a WP_DEBUG and they call the error_reporting() function so trying to change the error_reporting variable on the command line won't work. Instead you have to edit the wp-config.php file in the root folder and make sure that the WP_DEBUG is set to false. Otherwise you will get all those warnings and notices all the time.


问:
PSQL [error] - value being recognized as a column
I just started learning database a couple of days ago.
I'm running into this problem where my value is being recognized as a column, and it's spitting out an error.

This is my News table:

```<code>id | bodyText | url |  createdAt | updatedAt
----+----------+-----+-----------+-----------
</code>```

this is the command I ran in psql:

```<code>INSERT INTO "News" ("bodyText") VALUES ("this is a test");
</code>```

and this is the error I'm getting:

ERROR:  column "this is a test" does not exist
LINE 1: INSERT INTO "News" ("bodyText") VALUES ("this is a ...
```

I've tried removing the double quotes, adding it, doing it line by line, and so far I haven't come across an answer. Does anyone have an answer to this? Thanks in advance.

答:
Try this:</p>

```<code>INSERT INTO "Notifications" ("bodyText") VALUES ('this is a test');
</code>```

Body:
I just started learning database a couple of days ago.
I'm running into this problem where my value is being recognized as a column, and it's spitting out an error.

This is my News table:

id | bodyText | url |  createdAt | updatedAt
----+----------+-----+-----------+-----------

this is the command I ran in psql:

INSERT INTO "News" ("bodyText") VALUES ("this is a test");

and this is the error I'm getting:

ERROR:  column "this is a test" does not exist
LINE 1: INSERT INTO "News" ("bodyText") VALUES ("this is a ...

I've tried removing the double quotes, adding it, doing it line by line, and so far I haven't come across an answer. Does anyone have an answer to this? Thanks in advance.

Body:
Try this:

INSERT INTO "Notifications" ("bodyText") VALUES ('this is a test');


问:
After rake db:migrate my 'structure.sql' became different from the git version
Differences are of two kinds:

resource_id character varying NOT NULL  instead of resource_id character varying(255) NOT NULL

created_at timestamp without time zone instead of created_at timestamp without time zone NOT NULL

Rails 4.2, PostgreSQL Version 9.4.4.1

What should I do in this situation?

答: Yes, the reason: different PostgreSQL versions. </p>


问:
list of entity, max date, max row_id
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

```<code>entity        date_value       row_id
50            30/06/2017       3000<br>
75            30/04/2017       2900<br>
50            30/06/2017       2890<br>
50            30/05/2017       2500<br>
50            30/06/2017       2100<br>
75            30/03/2017       2000<br>
</code>```

here I need to take only 2 rows:

```<code> 50            30/06/2017       3000<br>
 75            30/04/2017       2900<br>
</code>```

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

答:
You can use LINQ like below:</p>

```<code>var res = from t in listName
                          group t by t.entity
                          into g
                          select new
                          {
                              entity = g.Key,
                              date_value = (from t2 in g select t2.date_value).Max(),
                              row_id = (from t3 in g select t3.row_id).Max(),
                          };
</code>```

Title: list of entity, max date, max row_id

Body:
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

entity        date_value       row_id
50            30/06/2017       3000

75            30/04/2017       2900

50            30/06/2017       2890

50            30/05/2017       2500

50            30/06/2017       2100

75            30/03/2017       2000

here I need to take only 2 rows:

 50            30/06/2017       3000

 75            30/04/2017       2900

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

Body:
You can use LINQ like below:

var res = from t in listName
                          group t by t.entity
                          into g
                          select new
                          {
                              entity = g.Key,
                              date_value = (from t2 in g select t2.date_value).Max(),
                              row_id = (from t3 in g select t3.row_id).Max(),
                          };


问:
DropDown List selections in asp mvc
I am using a loop to create multi DropDownList in the same view. As a result of the loop, two lists are created. However the problem is when user select an item from one list, the other list will change its selection to be the same selection from the other one.

So, how do I avoid that, and make selection process separated from a list to another?

Here is the code generate the list

```<code>@Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })
</code>```

EDIT:

The ListItem Code is this

```<code>List<SelectListItem> listItems = new List<SelectListItem>();

listItems.Add(new SelectListItem
{

    Text = "1 day",
    Value = "1"
});
listItems.Add(new SelectListItem
{

    Text = "3 days",
    Value = "3"
});
listItems.Add(new SelectListItem
{
    Selected = true,
    Text = "7 days",
    Value = "7"
});
listItems.Add(new SelectListItem
{

    Text = "15 days",
    Value = "15"
});
listItems.Add(new SelectListItem
{

    Text = "30 days",
    Value = "30"
});
</code>```

and This is the loop

```<code>@{
foreach (var item in companyList)
{
<div class="panel-body">

                                            <form class="form-horizontal" role="form" action="/Admin/Telecom" method="post">
                                                <div class="form-group">
                                                    <label class="col-sm-2 control-label">Payment View</label>
                                                    <div class="col-sm-6">

                                                        @Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })
                                                    </div>

                                                    <div class="col-sm-3">
                                                        <button type="submit" name="btnView" value="@item.TelecomCompanyName" class="btn btn-primary btn-rounded w-md waves-effect waves-light m-b-5">change</button>
                                                    </div>
                                                </div>
                                            </form>

                                    </div>
}
</code>```

答: You shouldn't reuse listItems between DropDownLists. After selecting a value on one list, element will be Selected on all of them. Create separate lists for each DropDownList.

Title: DropDown List selections in asp mvc

Body:
I am using a loop to create multi DropDownList in the same view. As a result of the loop, two lists are created. However the problem is when user select an item from one list, the other list will change its selection to be the same selection from the other one.

So, how do I avoid that, and make selection process separated from a list to another?

Here is the code generate the list

@Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })

EDIT:

The ListItem Code is this

List<SelectListItem> listItems = new List<SelectListItem>();

listItems.Add(new SelectListItem
{

    Text = "1 day",
    Value = "1"
});
listItems.Add(new SelectListItem
{

    Text = "3 days",
    Value = "3"
});
listItems.Add(new SelectListItem
{
    Selected = true,
    Text = "7 days",
    Value = "7"
});
listItems.Add(new SelectListItem
{

    Text = "15 days",
    Value = "15"
});
listItems.Add(new SelectListItem
{

    Text = "30 days",
    Value = "30"
});

and This is the loop

@{
foreach (var item in companyList)
{

                                            <form class="form-horizontal" role="form" action="/Admin/Telecom" method="post">

                                                    Payment View

                                                        @Html.DropDownList("selectedDays", listItems, new { @class = "form-control", id="Day"+item.id })

                                                        <button type="submit" name="btnView" value="@item.TelecomCompanyName" class="btn btn-primary btn-rounded w-md waves-effect waves-light m-b-5">change</button>

                                            </form>

}


问:
how to retrieve the type of value which is there more number of times in a column in a table and count of it?
```<code>s.no    Name       type of vehicle allotted

1      ram             bus
2      krish           car

3      raj             bus

4      albert          car

5      johnson         bike

6      raghu           car
</code>```

consider this is a table now i want to retrieve the type of vehicle which is there more number of times in the table and count of it. is there any particular method(query).

答:
You have to use COUNT and GROUP BY.
Count will give you the number of rows grouped by type field.

```<code>SELECT COUNT(id) as count, type FROM table_name GROUP BY type
</code>```

The output should be like this:

```<code>count  |  type

2      |  bus
3      |  car
1      |  Bike
</code>```

If you need just the highest one, append to the query:

```<code>ORDER BY count DESC LIMIT 1
</code>```

Body:
s.no    Name       type of vehicle allotted

1      ram             bus
2      krish           car

3      raj             bus

4      albert          car

5      johnson         bike

6      raghu           car

consider this is a table now i want to retrieve the type of vehicle which is there more number of times in the table and count of it. is there any particular method(query).

Body:
You have to use COUNT and GROUP BY.
Count will give you the number of rows grouped by type field.

SELECT COUNT(id) as count, type FROM table_name GROUP BY type

The output should be like this:

count  |  type

2      |  bus
3      |  car
1      |  Bike

If you need just the highest one, append to the query:

ORDER BY count DESC LIMIT 1


问:
Why do I get Unexpected Token , error?
I am developing application for mobile device on Ionic framework. So I have just got 'Ionic white screen of death' on my android. I get unexpected token , error. Ok, I opened inspector in Google Chrome and there is what I got

Picture 1

As you can see, there is an error in main.js file. I've found this file. It is in www/build folder. So this Main.js is required for building application for android.
Ok, so I can't edit this file because when I try to build app again all my edits get undo. I can see origin file without my edits. Why is this happening?

!! I use libary for image editing LowPoly -> Link

triangle.html

```<code><ion-header>

    <ion-navbar>
    <ion-title>Trianglify</ion-title>
    </ion-navbar>

</ion-header>

<ion-content class="triangle" text-center>

<button ion-button block outline (click)="takePicture()">Take a picture</button><br>
<button ion-button color="secondary" block outline style="position: absolute; bottom: 5px;" (click)="transformPHToTriangle(base64Image);">Transform</button>

<img [src]="base64Image" *ngIf="base64Image">
</ion-content>
</code>```

Triangle.ts

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import  LowPoly from 'lowpoly';

@IonicPage()

@Component({
    selector: 'page-triangle',
    templateUrl: 'triangle.html',
})

export class TrianglePage {

    public base64Image: string = './home_img/portrait.jpg';

    constructor(private camera: Camera, public navCtrl: NavController,         public navParams: NavParams) {}

    ionViewDidLoad() {
        console.log('ionViewDidLoad TrianglePage');
    }

    takePicture() {
        this.camera.getPicture({
        destinationType: this.camera.DestinationType.DATA_URL,
        targetWidth: 1000,
        targetHeight: 1000
        }).then((imageData) => {
        this.base64Image = "data:image/jpeg;base64," + imageData;
        }, (err) => {
        console.log(err);
        });
    }

transformPHToTriangle(photo) {
    new LowPoly(photo, {EDGE_DETECT_VALUE:80,
    POINT_RATE:0.075,
    POINT_MAX_NUM:3500,
    BLUR_SIZE:2,
    EDGE_SIZE:8,
    PIXEL_LIMIT: 350000}).init().then((data) => {
    this.base64Image = data;
    });
    }
}
</code>```

答:
The library expects you to pass it through babel. See docs : https://github.com/jrainlau/LowPolifier#usage

Fix

Use babel-loader.

More

https://github.com/babel/babel-loader

Title: Why do I get Unexpected Token , error?

Body:
I am developing application for mobile device on Ionic framework. So I have just got 'Ionic white screen of death' on my android. I get unexpected token , error. Ok, I opened inspector in Google Chrome and there is what I got

Picture 1

As you can see, there is an error in main.js file. I've found this file. It is in www/build folder. So this Main.js is required for building application for android.
Ok, so I can't edit this file because when I try to build app again all my edits get undo. I can see origin file without my edits. Why is this happening?

!! I use libary for image editing LowPoly -> Link

triangle.html

<ion-header>

    <ion-navbar>
    <ion-title>Trianglify</ion-title>
    </ion-navbar>

</ion-header>

<ion-content class="triangle" text-center>

<button ion-button block outline (click)="takePicture()">Take a picture</button>

<button ion-button color="secondary" block outline style="position: absolute; bottom: 5px;" (click)="transformPHToTriangle(base64Image);">Transform</button>

</ion-content>

Triangle.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import  LowPoly from 'lowpoly';

@IonicPage()

@Component({
    selector: 'page-triangle',
    templateUrl: 'triangle.html',
})

export class TrianglePage {

    public base64Image: string = './home_img/portrait.jpg';

    constructor(private camera: Camera, public navCtrl: NavController,         public navParams: NavParams) {}

    ionViewDidLoad() {
        console.log('ionViewDidLoad TrianglePage');
    }

    takePicture() {
        this.camera.getPicture({
        destinationType: this.camera.DestinationType.DATA_URL,
        targetWidth: 1000,
        targetHeight: 1000
        }).then((imageData) => {
        this.base64Image = "data:image/jpeg;base64," + imageData;
        }, (err) => {
        console.log(err);
        });
    }

transformPHToTriangle(photo) {
    new LowPoly(photo, {EDGE_DETECT_VALUE:80,
    POINT_RATE:0.075,
    POINT_MAX_NUM:3500,
    BLUR_SIZE:2,
    EDGE_SIZE:8,
    PIXEL_LIMIT: 350000}).init().then((data) => {
    this.base64Image = data;
    });
    }
}


问:
Error on import matplotlib.pyplot (on Anaconda3 for Windows 10 Home 64-bit PC)
I recently installed "Anaconda3 for Windows v2.4.0" on my Windows 10 Home (64 bit) machine.

(I downloaded the Windows 64-bit Graphical Installer "Anaconda3-2.4.0-Windows-x86_64.exe" (392 MB) from https://www.continuum.io/downloads.)

In a Command Prompt window, I did the conda "Test Drive", including "conda update conda", etc. In the end, I see the following:

```<code>C:\Users\Anshul\Downloads\Python>conda update conda
Fetching package metadata: ....
# All requested packages already installed.
# packages in environment at C:\Anaconda3:
#
conda                     3.18.6                   py35_0    defaults

C:\Users\Anshul\Downloads\Python>conda list matplotlib
# packages in environment at C:\Anaconda3:
#
matplotlib                1.5.0               np110py35_0    defaults
</code>```

The installation seems to have been successful - for example:

```<code>C:\Users\Anshul\Downloads\Python>python
Python 3.5.0 |Anaconda 2.4.0 (64-bit)| (default, Nov  7 2015, 13:15:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>> import os
>>> os.getcwd()
'C:\\Users\\Anshul\\Downloads\\Python'
>>> import matplotlib as mpl
>>> print(mpl.__version__)
1.5.0
>>>
</code>```

Note that matplotlib was imported fine above.  However, I get an error message when I try to import "matplotlib.pyplot" as shown below:

```<code>>>> import matplotlib.pyplot as pp
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1412, in <module>
    fontManager = pickle_load(_fmcache)
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 963, in pickle_load
    with open(filename, 'rb') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Anshul\\.matplotlib\\fontList.py3k.cache'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
    import matplotlib.colorbar
  File "C:\Anaconda3\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
    import matplotlib.collections as collections
  File "C:\Anaconda3\lib\site-packages\matplotlib\collections.py", line 27, in <module>
    import matplotlib.backend_bases as backend_bases
  File "C:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
    import matplotlib.textpath as textpath
  File "C:\Anaconda3\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
    import matplotlib.font_manager as font_manager
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1420, in <module>
    _rebuild()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1405, in _rebuild
    fontManager = FontManager()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1043, in __init__
    self.ttffiles = findSystemFonts(paths) + findSystemFonts()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 312, in findSystemFonts
    for f in win32InstalledFonts(fontdir):
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
    direc = os.path.abspath(direc).lower()
  File "C:\Anaconda3\lib\ntpath.py", line 535, in abspath
    path = _getfullpathname(path)
ValueError: _getfullpathname: embedded null character
>>>
</code>```

I opened "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py" in a text editor and tried to look for the source of the error. I think this is where things are going wrong:

```<code>>>> mpl.get_cachedir()
'C:\\Users\\Anshul\\.matplotlib'
>>> mpl.get_configdir()
'C:\\Users\\Anshul\\.matplotlib'
>>>
</code>```

In Windows Explorer, I see that the "C:\Users\Anshul.matplotlib" folder is empty, hence the FileNotFoundError for the "fontList.py3k.cache" file (which I don't see anywhere in the "C:\Anaconda3" directory either).  It seems to be a problem with the installer (I think), but I don't know how to fix it. I'd appreciate any help or pointers.

(BTW, I've already tried googling this issue.  The one that came closest was reported back in 2013: fail to import matplotlib.pyplot #2320.  It involved a WinPython-64bit-3.3.2.2 installation on a Windows 7 64-bit machine.  The thread was closed with the comment: "Closing. Already fixed in master.", but it appears the issue has resurfaced. I hope there is a simple fix or workaround.)

Thanks,

Anshul

答:
I'm using Python 3.5.2. When I tried @simonzack solution, I still got an error. I narrowed down the exception to the <python>/Lib/ntpath.py file. Look for the definition of the abspath() function around line 530.

I added @simonzack's solution to a ValueError exception handler. Insert the following code after line 537:

```<code>    530:    def abspath(path):
    531:    """Return the absolute version of a path."""

    533:    if path: # Empty path must return current working directory.
    534:        try:
    535:            path = _getfullpathname(path)
    536:        except OSError:
    537:            pass # Bad path - return unchanged.
    NEW:        except ValueError:
    NEW:            path = path.split('\0', 1)[0]
    NEW:            path = _getfullpathname(path)
    538:    elif isinstance(path, bytes):
    539:        path = os.getcwdb()
    540:    else:
    541:        path = os.getcwd()
    542:    return normpath(path)
</code>```

That fixed the error for me.

For a little history on the cause of this issue take a look at: Python Issue 25778. It's a bit long but the final conclusion is that the fix didn't make it into 2.7.14, 3.5.3 or 3.6.0. So it appears this hack is going to be our only solution for older versions of Python.

Body:
I recently installed "Anaconda3 for Windows v2.4.0" on my Windows 10 Home (64 bit) machine.

(I downloaded the Windows 64-bit Graphical Installer "Anaconda3-2.4.0-Windows-x86_64.exe" (392 MB) from https://www.continuum.io/downloads.)

In a Command Prompt window, I did the conda "Test Drive", including "conda update conda", etc. In the end, I see the following:

C:\Users\Anshul\Downloads\Python>conda update conda
Fetching package metadata: ....
# All requested packages already installed.
# packages in environment at C:\Anaconda3:
#
conda                     3.18.6                   py35_0    defaults

C:\Users\Anshul\Downloads\Python>conda list matplotlib
# packages in environment at C:\Anaconda3:
#
matplotlib                1.5.0               np110py35_0    defaults

The installation seems to have been successful - for example:

C:\Users\Anshul\Downloads\Python>python
Python 3.5.0 |Anaconda 2.4.0 (64-bit)| (default, Nov  7 2015, 13:15:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>> import os
>>> os.getcwd()
'C:\\Users\\Anshul\\Downloads\\Python'
>>> import matplotlib as mpl
>>> print(mpl.__version__)
1.5.0
>>>

Note that matplotlib was imported fine above.  However, I get an error message when I try to import "matplotlib.pyplot" as shown below:

>>> import matplotlib.pyplot as pp
Traceback (most recent call last):
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1412, in <module>
    fontManager = pickle_load(_fmcache)
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 963, in pickle_load
    with open(filename, 'rb') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Anshul\\.matplotlib\\fontList.py3k.cache'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 29, in <module>
    import matplotlib.colorbar
  File "C:\Anaconda3\lib\site-packages\matplotlib\colorbar.py", line 34, in <module>
    import matplotlib.collections as collections
  File "C:\Anaconda3\lib\site-packages\matplotlib\collections.py", line 27, in <module>
    import matplotlib.backend_bases as backend_bases
  File "C:\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 62, in <module>
    import matplotlib.textpath as textpath
  File "C:\Anaconda3\lib\site-packages\matplotlib\textpath.py", line 15, in <module>
    import matplotlib.font_manager as font_manager
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1420, in <module>
    _rebuild()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1405, in _rebuild
    fontManager = FontManager()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 1043, in __init__
    self.ttffiles = findSystemFonts(paths) + findSystemFonts()
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 312, in findSystemFonts
    for f in win32InstalledFonts(fontdir):
  File "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py", line 231, in win32InstalledFonts
    direc = os.path.abspath(direc).lower()
  File "C:\Anaconda3\lib\ntpath.py", line 535, in abspath
    path = _getfullpathname(path)
ValueError: _getfullpathname: embedded null character
>>>

I opened "C:\Anaconda3\lib\site-packages\matplotlib\font_manager.py" in a text editor and tried to look for the source of the error. I think this is where things are going wrong:

>>> mpl.get_cachedir()
'C:\\Users\\Anshul\\.matplotlib'
>>> mpl.get_configdir()
'C:\\Users\\Anshul\\.matplotlib'
>>>

In Windows Explorer, I see that the "C:\Users\Anshul.matplotlib" folder is empty, hence the FileNotFoundError for the "fontList.py3k.cache" file (which I don't see anywhere in the "C:\Anaconda3" directory either).  It seems to be a problem with the installer (I think), but I don't know how to fix it. I'd appreciate any help or pointers.

(BTW, I've already tried googling this issue.  The one that came closest was reported back in 2013: fail to import matplotlib.pyplot #2320.  It involved a WinPython-64bit-3.3.2.2 installation on a Windows 7 64-bit machine.  The thread was closed with the comment: "Closing. Already fixed in master.", but it appears the issue has resurfaced. I hope there is a simple fix or workaround.)

Thanks,

Anshul

Body:
I'm using Python 3.5.2. When I tried @simonzack solution, I still got an error. I narrowed down the exception to the <python>/Lib/ntpath.py file. Look for the definition of the abspath() function around line 530.

I added @simonzack's solution to a ValueError exception handler. Insert the following code after line 537:

    530:    def abspath(path):
    531:    """Return the absolute version of a path."""

    533:    if path: # Empty path must return current working directory.
    534:        try:
    535:            path = _getfullpathname(path)
    536:        except OSError:
    537:            pass # Bad path - return unchanged.
    NEW:        except ValueError:
    NEW:            path = path.split('\0', 1)[0]
    NEW:            path = _getfullpathname(path)
    538:    elif isinstance(path, bytes):
    539:        path = os.getcwdb()
    540:    else:
    541:        path = os.getcwd()
    542:    return normpath(path)

That fixed the error for me.

For a little history on the cause of this issue take a look at: Python Issue 25778. It's a bit long but the final conclusion is that the fix didn't make it into 2.7.14, 3.5.3 or 3.6.0. So it appears this hack is going to be our only solution for older versions of Python.


问:
Cannot implicitly convert type 'double' to 'long'
In this code i got the above error in lines i commented.

```<code>public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter < i.Length; counter++)
    {
        nums[counter] = Convert.ToInt32(i[counter]);
    }

    u = nums[0];
    int firstdigits = Convert.ToInt32(Math.Floor(Math.Log10(u) + 1));
    v = nums[1];
    int seconddigits = Convert.ToInt32(Math.Floor(Math.Log10(v) + 1));
    if (firstdigits >= seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}
</code>```

Whats is the problem? Thanks!

答:
Math.Pow returns a double. You could explicitly cast to long, for example

```<code>x = u % (long)Math.Pow(10, m);
</code>```

although that is likely not the correct solution. Are you certain that the results that you are after can be properly expressed as a double? If not then change the variables to be declared as doubles rather than longs.

ContentLicense: CC BY-SA 2.5

Body:
In this code i got the above error in lines i commented.

public double bigzarb(long u, long v)
{
    double n;
    long x;
    long y;
    long w;
    long z;
    string[] i = textBox7.Text.Split(',');
    long[] nums = new long[i.Length];
    for (int counter = 0; counter = seconddigits)
    {
        n = firstdigits;

    }
    else
    {
        n = seconddigits;
    }
    if (u == 0 || v == 0)
    {
        MessageBox.Show("the Multiply is 0");
    }

    int intn = Convert.ToInt32(n);
    if (intn <= 3)
    {
        long uv = u * v;
        string struv = uv.ToString();
        MessageBox.Show(struv);
        return uv;
    }
    else
    {
        int m =Convert.ToInt32(Math.Floor(n / 2));

        x = u % Math.Pow(10, m); // here
        y = u / Math.Pow(10, m); // here
        w = v % Math.Pow(10, m); // here
        z = v / Math.Pow(10, m); // here

        long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
        textBox1.Text = result.ToString();
        return result;
    }
}

Whats is the problem? Thanks!

Body:
Math.Pow returns a double. You could explicitly cast to long, for example

x = u % (long)Math.Pow(10, m);

although that is likely not the correct solution. Are you certain that the results that you are after can be properly expressed as a double? If not then change the variables to be declared as doubles rather than longs.


问:
how to return as array in php function
im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

```<code> public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}
</code>```

答:
```<code>public function upload(Request $request) {
    $answer=array();
    $array = $request->file('image');
    $count = count($array);
    $answer=array();
    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[$i] = $rnd;
    }
//here print $answer and check
//you can also check $answer with function var_dump();
    echo json_encode($answer);
    die;
}
</code>```

Decode this array like

```<code>json_decode($json_array,true);
</code>```

Title: how to return as array in php function

Body:
im using laravel 5.4 and intervention plugin to upload images as ajax

i will upload images in php controller and it will return a response (file name).

and the returned variables from php is an array but in javascript it going to string and i cant iterate that

 public function upload(Request $request)
{
    $array = $request->file('image');
    $count = count($array);

    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[] = $rnd;
    }
    return $answer;
}

Body:
public function upload(Request $request) {
    $answer=array();
    $array = $request->file('image');
    $count = count($array);
    $answer=array();
    for ($i=0 ; $i<$count; $i++)
    {
        $img = Image::make($request->file('image')[$i]);
        $img->widen(800);
        $img->fit(800,600);
        $rnd = rand(10,10000);
        $location = 'images/carimages/c'.$rnd.'.jpg';
        $img->save($location);
        $answer[$i] = $rnd;
    }
//here print $answer and check
//you can also check $answer with function var_dump();
    echo json_encode($answer);
    die;
}

Decode this array like

json_decode($json_array,true);


问:
Generate date for selected comments
I will try to describe briefly the problem, namely: I have a page where there are about 1000 profiles. Each profile has its own comments with different dates.

What I would like to do is write a code that would take from each profile 3 last comments, but only the ones whose last comment was no later than 2016 and add them + 6 months, and skips those profiles that have comments from 2017.

I made sample code to add those 6 months:

```<code>UPDATE `sktest`.`wp_comment`
SET `time` = DATE_ADD(`time`, INTERVAL 6 MONTH)
WHERE date(`wp_comment`.`time`) BETWEEN "2015-05-01" AND "2016-06-01"
</code>```

Unfortunately, I have no idea how to get only those profiles with 3 last comments that have a date before 2017. Does anyone have any suggestions? Ideas?

Comments I keep in the wp_comment table, which looks like this:

The column "whom" is ID of the user profile (in wp_users).

EDIT:
Ok I did this and seems working. I'm getting 3 last comments from all profiles:

```<code>$infor=$wpdb->get_results('SELECT a.*, count(*) as row_number FROM wp_comment a JOIN wp_comment b ON a.whom = b.whom AND a.id <= b.id GROUP BY a.whom, a.id ORDER BY a.time DESC');

    foreach ($infor as $info_resr) {
        $id             = $info_resr->id;
        $active         = $info_resr->whom;
        $time       = $info_resr->time;
        $row_num        = $info_resr->row_number;
        }
       if ($row_num>3) {
           continue;
       }
        echo ''.$active.', '.$time.', '.$row_num.' <br>';
    }
</code>```

Now, how can I skip those profiles that already have comments from 2017?

答:
Use date( )  for wp_comment.time

```<code>  UPDATE `sktest`.`wp_comment`
  SET `time` = DATE_ADD(`time`, INTERVAL 6 MONTH)
  WHERE date(`wp_comment`.`time`)  BETWEEN '2015-05-01' AND '2016-06-01'
</code>```

Title: Generate date for selected comments

Body:
I will try to describe briefly the problem, namely: I have a page where there are about 1000 profiles. Each profile has its own comments with different dates.

What I would like to do is write a code that would take from each profile 3 last comments, but only the ones whose last comment was no later than 2016 and add them + 6 months, and skips those profiles that have comments from 2017.

I made sample code to add those 6 months:

UPDATE `sktest`.`wp_comment`
SET `time` = DATE_ADD(`time`, INTERVAL 6 MONTH)
WHERE date(`wp_comment`.`time`) BETWEEN "2015-05-01" AND "2016-06-01"

Unfortunately, I have no idea how to get only those profiles with 3 last comments that have a date before 2017. Does anyone have any suggestions? Ideas?

Comments I keep in the wp_comment table, which looks like this:

The column "whom" is ID of the user profile (in wp_users).

EDIT:
Ok I did this and seems working. I'm getting 3 last comments from all profiles:

$infor=$wpdb->get_results('SELECT a.*, count(*) as row_number FROM wp_comment a JOIN wp_comment b ON a.whom = b.whom AND a.id <= b.id GROUP BY a.whom, a.id ORDER BY a.time DESC');

    foreach ($infor as $info_resr) {
        $id             = $info_resr->id;
        $active         = $info_resr->whom;
        $time       = $info_resr->time;
        $row_num        = $info_resr->row_number;
        }
       if ($row_num>3) {
           continue;
       }
        echo ''.$active.', '.$time.', '.$row_num.'
';
    }

Now, how can I skip those profiles that already have comments from 2017?

Body:
Use date( )  for wp_comment.time

  UPDATE `sktest`.`wp_comment`
  SET `time` = DATE_ADD(`time`, INTERVAL 6 MONTH)
  WHERE date(`wp_comment`.`time`)  BETWEEN '2015-05-01' AND '2016-06-01'


问:
Check if image and thumbnail exist in directory or not
In this code I check if the image and its thumbnail are present in the directory using file_exists() function. With this code I don't get the thumbnail of the image which is not present in the directory, but I get the images which are not in it. How do I get the thumbnails of images which are not present in the directory? $abc and $pqr are the names of the arrays.

What should I do to get the image name and thumbnail which are not in the directory using file_exists()?

```<code>$vin1 = array();
$q1 = mysql_query("SELECT * FROM rr2s4_cma_images");
while ($q2=mysql_fetch_array($q1)) {
    $abc = $q2['image_name'];
    $pqr = $q2['type'];
    // $xyz[] = $abc."".$pqr;
    echo "```";
    if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc.$pqr) && ($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc."_thumb".$pqr)) {
        // ...
    } else  {
        // echo $abc."_thumb".$pqr. " The file doesn't exists";
        $img = $abc.$pqr;
        $thumb = $abc."_thumb".$pqr;
        $img1[] = $img;
        $thumb1[] = $thumb;
    }
}
echo "
";
print_r($img1);
print_r($thumb1);
```

答:
Your mistake is in you if condition. file_exists function is not properly used.

Remember your file extension variable $pqr is contain .(dot).

See e.g.,

```<code>if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc.$pqr)){
   // Do if origional image is exists.
}
else{
    // Do if origional image is not exists.
}
if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc."_thumb".$pqr)){
    // Do if thumbnail image is exists.
}
else{
    // Do if thumbnail image is not exists.
}
</code>```

Body:
In this code I check if the image and its thumbnail are present in the directory using file_exists() function. With this code I don't get the thumbnail of the image which is not present in the directory, but I get the images which are not in it. How do I get the thumbnails of images which are not present in the directory? $abc and $pqr are the names of the arrays.

What should I do to get the image name and thumbnail which are not in the directory using file_exists()?

$vin1 = array();
$q1 = mysql_query("SELECT * FROM rr2s4_cma_images");
while ($q2=mysql_fetch_array($q1)) {
    $abc = $q2['image_name'];
    $pqr = $q2['type'];
    // $xyz[] = $abc."".$pqr;
    echo "
";
    if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc.$pqr) && ($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc."_thumb".$pqr)) {
        // ...
    } else  {
        // echo $abc."_thumb".$pqr. " The file doesn't exists";
        $img = $abc.$pqr;
        $thumb = $abc."_thumb".$pqr;
        $img1[] = $img;
        $thumb1[] = $thumb;
    }
}
echo "
";
print_r($img1);
print_r($thumb1);

Body:
Your mistake is in you if condition. file_exists function is not properly used.

Remember your file extension variable $pqr is contain .(dot).

See e.g.,

if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc.$pqr)){
   // Do if origional image is exists.
}
else{
    // Do if origional image is not exists.
}
if(file_exists($_SERVER['DOCUMENT_ROOT']."/cribsuite/images/shortlistings/".$abc."_thumb".$pqr)){
    // Do if thumbnail image is exists.
}
else{
    // Do if thumbnail image is not exists.
}


问:
Firebase observeEventType:FIRDataEventTypeChildChanged callback never called
I want to to get real time updated database object. Whenever a new message added in chat list.

If I Use

```<code>observeSingleEventOfType:FIRDataEventTypeValue
</code>```

it works and respond well. But ofcourse it will give me results once.

If I call the below method:

```<code>observeEventType:FIRDataEventTypeChildChanged
</code>```

as of my knowledge It will give results first time and every time when the child is changed. (new message added)

but this never called back. Not first time not if I add some new message in database.

This is how I m calling these methods:

In my.h file

```<code>@property (strong, nonatomic) FIRDatabaseReference *ref;
</code>```

In viewDidLoad

```<code>_ref = [[FIRDatabase database] reference];
[self getChats];
</code>```

and finally:

```<code>-(void) getChats {

//  this is working
[[[_ref child:@"chat_rooms"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    NSDictionary *dict = snapshot.value;
    NSLog(@"%@",dict);

}];

// this is not working / Never calling
[[[_ref child:@"chat_rooms"] child:userID] observeEventType:FIRDataEventTypeChildChanged
 withBlock:^ (FIRDataSnapshot * _Nonnull snapshot) {

     NSDictionary *dict = snapshot.value;
     NSLog(@"%@",dict);

 }];

 // this is not working / Never calling too
[[[_ref child:@"chat_rooms"] child:userID] observeEventType:FIRDataEventTypeChildAdded
 withBlock:^ (FIRDataSnapshot * _Nonnull snapshot) {

     NSDictionary *dict = snapshot.value;
     NSLog(@"%@",dict);

 }];

}

//this is how I m sending message to database.
//and this is working good. message added in node. verified at firebase console
- (void)sendMessage : (NSDictionary*) dict
{
    [[[[_ref child:@"chat_rooms"] child:userID] childByAutoId] setValue:dict];
}
</code>```

Guide me where I m wrong, OR what should I have to use to get (real time) updated chats.

答:
I have Figured out the solution,

For the first time If we don't have the Child Node created under firebase database. In my case it is chat_room with userID

So the observer observeEventType:FIRDataEventTypeChildChanged will never called because observer did not find which child it has to observe. And I guess it is not even registered to observe.

So when I have added first message in chat_room. Node is created for that user. Then I have to get all the records with observeSingleEventOfType:FIRDataEventTypeValue

Then registered the Child Changed observer and finally on every change observeEventType:FIRDataEventTypeChildChanged is working as expected.

Body:
I want to to get real time updated database object. Whenever a new message added in chat list.

If I Use

observeSingleEventOfType:FIRDataEventTypeValue

it works and respond well. But ofcourse it will give me results once.

If I call the below method:

observeEventType:FIRDataEventTypeChildChanged

as of my knowledge It will give results first time and every time when the child is changed. (new message added)

but this never called back. Not first time not if I add some new message in database.

This is how I m calling these methods:

In my.h file

@property (strong, nonatomic) FIRDatabaseReference *ref;

In viewDidLoad

_ref = [[FIRDatabase database] reference];
[self getChats];

and finally:

-(void) getChats {

//  this is working
[[[_ref child:@"chat_rooms"] child:userID] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    NSDictionary *dict = snapshot.value;
    NSLog(@"%@",dict);

}];

// this is not working / Never calling
[[[_ref child:@"chat_rooms"] child:userID] observeEventType:FIRDataEventTypeChildChanged
 withBlock:^ (FIRDataSnapshot * _Nonnull snapshot) {

     NSDictionary *dict = snapshot.value;
     NSLog(@"%@",dict);

 }];

 // this is not working / Never calling too
[[[_ref child:@"chat_rooms"] child:userID] observeEventType:FIRDataEventTypeChildAdded
 withBlock:^ (FIRDataSnapshot * _Nonnull snapshot) {

     NSDictionary *dict = snapshot.value;
     NSLog(@"%@",dict);

 }];

}

//this is how I m sending message to database.
//and this is working good. message added in node. verified at firebase console
- (void)sendMessage : (NSDictionary*) dict
{
    [[[[_ref child:@"chat_rooms"] child:userID] childByAutoId] setValue:dict];
}

Guide me where I m wrong, OR what should I have to use to get (real time) updated chats.


问:
MS SQL apotrophe in prompt in WHERE clause
I am trying to deal with an apostrophe in a prompt field in my SQL statement.  Example below :

```<code>WHERE propertyfieldintable=@promptfromuser
</code>```

The problem is that there are addresses with an ' eg. Wood's therefore the SQL works for all other addresses except those with an '.

I have tried to use replace(@promptfromuser,"'","''") but keep getting an error (missing right ').  The propertyfieldintable is a text field so am assuming it needs a text input from the prompt.

I would appreciate any straightforward suggestions as the query is not in the database itself but sits within a reporting tool so can't take functions.

答:
Try the following replace statement

```<code>replace (@promptfromuser,'''', '''''')
</code>```

Forget using " in databasecontext for ever. Microsoft has [] syntax to denote identifiers containing special characters.

Body:
I am trying to deal with an apostrophe in a prompt field in my SQL statement.  Example below :

WHERE propertyfieldintable=@promptfromuser

The problem is that there are addresses with an ' eg. Wood's therefore the SQL works for all other addresses except those with an '.

I have tried to use replace(@promptfromuser,"'","''") but keep getting an error (missing right ').  The propertyfieldintable is a text field so am assuming it needs a text input from the prompt.

I would appreciate any straightforward suggestions as the query is not in the database itself but sits within a reporting tool so can't take functions.

Body:
Try the following replace statement

replace (@promptfromuser,'''', '''''')

Forget using " in databasecontext for ever. Microsoft has [] syntax to denote identifiers containing special characters.


问:
JPA how to avoid updating associated entity in @ManyToOne or @OneToOne
I have two entities like this:

```<code>@Entity
@Table(name = "article")
@EntityListeners({AuditingEntityListener.class})
public class Notification implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Integer id;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationLang> langs;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationTarget> targets;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

}

@Entity
@Table(name = "article_count")
@EntityListeners({AuditingEntityListener.class})
public class NotificationTarget implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer id;

    @Column(name = "user_id")
    private String userId;

    @ManyToOne(optional = false)
    @JoinColumn(name = "notification_id")
    private Notification notification;
}
</code>```

Notification and NotificationTarget are associated, If I update NotificationTarget:

```<code>NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
        notificationId, userId);
notificationTarget.setUserId(userId);
notificationTargetRepository.save(notificationTarget);
</code>```

hibernate will update Notification too.
I have checked update Notification because Notification has EntityListener,  AuditingEntityListener will change updatedAt field when DefaultFlushEntityEventListener invoke Interceptor. But in this business case, I don't want to change Notification when updating NotificationTarget, is there some advice?

Sorry, I think the problem describe is wrong.

I debugged and found that update both because of NotificationLang list is check as dirty in CollectionType.isEqual. But I don't know why it is dirty??

答: You can add insertable = false, updatable = false attributes in the mapping annotation in NotificationTarget

Body:
I have two entities like this:

@Entity
@Table(name = "article")
@EntityListeners({AuditingEntityListener.class})
public class Notification implements Serializable {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Integer id;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationLang> langs;

    @OneToMany(mappedBy = "notification", cascade = {CascadeType.PERSIST})
    private List<NotificationTarget> targets;

    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated_at")
    private Date updatedAt;

    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at")
    private Date createdAt;

}

@Entity
@Table(name = "article_count")
@EntityListeners({AuditingEntityListener.class})
public class NotificationTarget implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonIgnore
    private Integer id;

    @Column(name = "user_id")
    private String userId;

    @ManyToOne(optional = false)
    @JoinColumn(name = "notification_id")
    private Notification notification;
}

Notification and NotificationTarget are associated, If I update NotificationTarget:

NotificationTarget notificationTarget = notificationTargetRepository.findByNotificationIdAndUserId(
        notificationId, userId);
notificationTarget.setUserId(userId);
notificationTargetRepository.save(notificationTarget);

hibernate will update Notification too.
I have checked update Notification because Notification has EntityListener,  AuditingEntityListener will change updatedAt field when DefaultFlushEntityEventListener invoke Interceptor. But in this business case, I don't want to change Notification when updating NotificationTarget, is there some advice?

Sorry, I think the problem describe is wrong.

I debugged and found that update both because of NotificationLang list is check as dirty in CollectionType.isEqual. But I don't know why it is dirty??


问:
Getting an "UNABLE_TO_GET_ISSUER_CERT_LOCALLY" while using "tsd" command
I'm trying to use the below tsd command to install angular type definition files in my project.

tsd install angular --resolve --save

TypeScript Version:  2.3.4

However when I try to do that, I'm getting the below error.

```<code>[ERR!] node : v7.8.0
[ERR!] tsd  : 0.6.5
[ERR!] Error: unable to get local issuer certificate
[ERR!] CODE : UNABLE_TO_GET_ISSUER_CERT_LOCALLY
[ERR!] unable to get local issuer certificate
</code>```

I've tried setting the strict-ssl to false using npm and even tried executing npm cache clean command, But no luck though.

Can someone help?

答:
Please don't use tsd anymore. The project is deprecated and not maintained. Just use npm install @types/angular.

More

https://github.com/DefinitelyTyped/tsd/issues/149

Body:
I'm trying to use the below tsd command to install angular type definition files in my project.

tsd install angular --resolve --save

TypeScript Version:  2.3.4

However when I try to do that, I'm getting the below error.

[ERR!] node : v7.8.0
[ERR!] tsd  : 0.6.5
[ERR!] Error: unable to get local issuer certificate
[ERR!] CODE : UNABLE_TO_GET_ISSUER_CERT_LOCALLY
[ERR!] unable to get local issuer certificate

I've tried setting the strict-ssl to false using npm and even tried executing npm cache clean command, But no luck though.

Can someone help?


问:
Sending mail using Laravel 4.2 and Mailgun
i'm little bit new to this.

I had read the documentation of Laravel 4 and some of the Mailgun, I had tested some mail and worked but just in route like this:

```<code>Route::get('send_test_email', function(){
    Mail::send('emails.registro', array('key' => 'value'), function($message)
    {
        $message->subject('Bienvenido a la gran experiencia');
        $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));
        $message->to('luis02lopez@hotmail.com');
    });
});
</code>```

I went to myapp/send_test_email in the browser and get an email.

But now I want to send an email at registration, I created the route:

```<code>Route::get('mail', ['uses' => 'MailController@send', 'as' => 'send']);
</code>```

The controller:

```<code><?php

class MailController extends \BaseController {

    public function index()
    {
        return View::make('signup');
    }

    public function send() {

        Mail::send('emails.registro', $data, function($message) use
           {

           $message->subject('Bienvenido a la gran experiencia');

           $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

           $message->to($user->email, $user->firstname);

           });
    }
</code>```

And added a form to the signup form like this:

```<code>    {{ Form::open(['route' => 'send', 'method' => 'get']) }}

    <div class="form-group">
        {{ Form::label('username', 'Usuario', ['class' => 'sr-only']) }}
        {{ Form::text('username', null, ['placeholder' => 'Usuario', 'required', 'minlength' => 6, 'class' => 'form-control', ]) }}
        @foreach($errors->get('username', '<span class=error>:message</span>') as $message)
            {{$message}}
        @endforeach
    </div>
    <div class="form-group">
        {{ Form::label('password', 'Contraseña', ['class' => 'sr-only']) }}
        {{ Form::password('password', ['placeholder' => 'Contraseña', 'required', 'minlength' => 8, 'class' => 'form-control']) }}
        @foreach($errors->get('password', '<span class=error>:message</span>') as $message)
            {{$message}}
        @endforeach
    </div>
    <div class="form-group">
        {{ Form::label('password_confirm', 'Confirmar Contraseña', ['class' => 'sr-only']) }}
        {{ Form::password('password_confirmation', ['placeholder' => 'Confirmar Contraseña', 'required', 'minlength' => 8, 'class' => 'form-control']) }}
        @foreach($errors->get('password_confirmation', '<span class=error>:message</span>') as $message)
            {{$message}}
        @endforeach
    </div>
    <div class="form-group">
        {{ Form::label('email', 'Email', ['class' => 'sr-only']) }}
        {{ Form::email('email', null, ['placeholder' => 'Email', 'required', 'class' => 'form-control']) }}
        @foreach($errors->get('email', '<span  class=error>:message</span>') as $message)
            {{$message}}
        @endforeach
    </div>
    <div class="form-group">
        {{ Form::label('firstname', 'Nombres', ['class' => 'sr-only']) }}
        {{ Form::text('firstname', null, ['placeholder' => 'Nombres', 'required', 'class' => 'form-control']) }}
    </div>
    <div class="form-group">
        {{ Form::label('lastname', 'Apellidos', ['class' => 'sr-only']) }}
        {{ Form::text('lastname', null, ['placeholder' => 'Apellidos', 'required', 'class' => 'form-control']) }}
    </div>

    <div class="form-group">
        {{ Form::submit('Registrar', ['class' => 'btn btn-lg btn-block btn-kinbu'])}}
    </div>
    {{ Form::close() }}
</code>```

And I got a Parse error: syntax error, unexpected 'Mail' (T_STRING) in the controller, why?

答:
Here I have errors:

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

    Mail::send('emails.registro', $data, function($message) use
       {

       $message->subject('Bienvenido a la gran experiencia');

       $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

       $message->to($user->email, $user->firstname);

       });
}
</code>```

I'm using the $user var, but I'm not passing it with the closure "user" so I have to do:

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

    Mail::send('emails.registro', array('key' => 'value'), function($message) use ($user)
       {

       $message->subject('Bienvenido a la gran experiencia');

       $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

       $message->to($user->email, $user->firstname);

       });
}
</code>```

Body:
i'm little bit new to this.

I had read the documentation of Laravel 4 and some of the Mailgun, I had tested some mail and worked but just in route like this:

Route::get('send_test_email', function(){
    Mail::send('emails.registro', array('key' => 'value'), function($message)
    {
        $message->subject('Bienvenido a la gran experiencia');
        $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));
        $message->to('luis02lopez@hotmail.com');
    });
});

I went to myapp/send_test_email in the browser and get an email.

But now I want to send an email at registration, I created the route:

Route::get('mail', ['uses' => 'MailController@send', 'as' => 'send']);

The controller:

<?php

class MailController extends \BaseController {

    public function index()
    {
        return View::make('signup');
    }

    public function send() {

        Mail::send('emails.registro', $data, function($message) use
           {

           $message->subject('Bienvenido a la gran experiencia');

           $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

           $message->to($user->email, $user->firstname);

           });
    }

And added a form to the signup form like this:

    {{ Form::open(['route' => 'send', 'method' => 'get']) }}

        {{ Form::label('username', 'Usuario', ['class' => 'sr-only']) }}
        {{ Form::text('username', null, ['placeholder' => 'Usuario', 'required', 'minlength' => 6, 'class' => 'form-control', ]) }}
        @foreach($errors->get('username', ':message') as $message)
            {{$message}}
        @endforeach

        {{ Form::label('password', 'Contraseña', ['class' => 'sr-only']) }}
        {{ Form::password('password', ['placeholder' => 'Contraseña', 'required', 'minlength' => 8, 'class' => 'form-control']) }}
        @foreach($errors->get('password', ':message') as $message)
            {{$message}}
        @endforeach

        {{ Form::label('password_confirm', 'Confirmar Contraseña', ['class' => 'sr-only']) }}
        {{ Form::password('password_confirmation', ['placeholder' => 'Confirmar Contraseña', 'required', 'minlength' => 8, 'class' => 'form-control']) }}
        @foreach($errors->get('password_confirmation', ':message') as $message)
            {{$message}}
        @endforeach

        {{ Form::label('email', 'Email', ['class' => 'sr-only']) }}
        {{ Form::email('email', null, ['placeholder' => 'Email', 'required', 'class' => 'form-control']) }}
        @foreach($errors->get('email', ':message') as $message)
            {{$message}}
        @endforeach

        {{ Form::label('firstname', 'Nombres', ['class' => 'sr-only']) }}
        {{ Form::text('firstname', null, ['placeholder' => 'Nombres', 'required', 'class' => 'form-control']) }}

        {{ Form::label('lastname', 'Apellidos', ['class' => 'sr-only']) }}
        {{ Form::text('lastname', null, ['placeholder' => 'Apellidos', 'required', 'class' => 'form-control']) }}

        {{ Form::submit('Registrar', ['class' => 'btn btn-lg btn-block btn-kinbu'])}}

    {{ Form::close() }}

And I got a Parse error: syntax error, unexpected 'Mail' (T_STRING) in the controller, why?

Body:
Here I have errors:

    public function send() {

    Mail::send('emails.registro', $data, function($message) use
       {

       $message->subject('Bienvenido a la gran experiencia');

       $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

       $message->to($user->email, $user->firstname);

       });
}

I'm using the $user var, but I'm not passing it with the closure "user" so I have to do:

    public function send() {

    Mail::send('emails.registro', array('key' => 'value'), function($message) use ($user)
       {

       $message->subject('Bienvenido a la gran experiencia');

       $message->from(env('CONTACT_MAIL'), env('CONTACT_NAME'));

       $message->to($user->email, $user->firstname);

       });
}


问:
Countdown timer in Python (Raspberry Pi for motor RPM)
I am trying to get a reasonable RPM for a motor. I have a photo-interrupter that sends 0 or 1 if it detects a slit that passes by. My code is as following, what I simply need is to time 0-60 seconds, and add the number of times 1 was detected and then divide it by 60, thus RPM.

I don't want to complicate my code, also keep in mind this is running on the Raspberry Pi with many other scripts and webservers running behind it. So not a bad code like "sleep" that would hog down the entire cpu.

I'm not looking for a crazy accurate measurement, just a reasonable idea of how fast the motor is spinning. Also does the slit size make a difference?

```<code>import RPi.GPIO as GPIO
import time
signal = 21

from time import sleep     # this lets us have a time delay (see line 15)
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
GPIO.setup(signal, GPIO.IN)    # set GPIO21 as input (signal)
GPIO.add_event_detect(signal,GPIO.BOTH)

try:
    while True:            # this will carry on until you hit CTRL+C
        if GPIO.event_detected(signal): # if port 21 == 1
            print "Port 21 is 1/HIGH/True - LED ON"
            slit=slit+1       # Counts every time slit passes

        else:
            print "Port 21 is 0/LOW/False - LED OFF"
        rpm = slit/60         # Calculates the RPM
        sleep(0.0001)         # wait 0.0001 seconds

finally:                   # this block will run no matter how the try block exits
    GPIO.cleanup()         # clean up after yourself
</code>```

答:
With the reservation that I have never programmed an RPi using Python, this is how I would try to tackle this task:

```<code>import RPi.GPIO as GPIO
import threading

signal = 21
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
GPIO.setup(signal, GPIO.IN)    # set GPIO21 as input (signal)

slit = 0
rpm = 0

def increment():
    global slit
    print("Port 21 is 1/HIGH/True - LED ON")
    slit += 1

def count_complete():
    global slit
    global rpm
    rpm = slit/60
    print ("RPM = {}".format(rpm))
    # reset and restart timer
    slit = 0
    t = threading.Timer(60, count_complete)

# Bounce will prevent double detection of the same rising edge (for 1 ms)
GPIO.add_event_detect(signal, GPIO.RISING, callback=increment, bounce=1)

t = threading.Timer(60, count_complete)
try:
    while True:            # this will carry on until you hit CTRL+C
        pass               # Do nothing but wait for callbacks and timer
finally:                   # this block will run no matter how the try block exits
    t.cancel()             # stop the timer
    GPIO.cleanup()         # clean up after yourself
</code>```

As can be seen, I have added a callback function that will be called as soon as a rising edge is detected on the input. Here the clit counter is incremented. The bounce parameter is a protection that will stop the program from counting the same slit double.

Setting at 1 ms means that the RPM needs to be (well) below 1,000 or some slits will be missed. It is possible to experiment by removing this. I don't know if it is possible to give a fractional bounce time. That may be another option.

The main program then, stats a timer, that lets the increment run for 1 minute, after which the RPM is calculated and the system reset and a new count is initiated. (There is a risk of a race condition here, where a slit interrupt may happen while doing the calculation. This could be missed in these cases.)

Then in the main loop, nothing happens, except for the program waiting for interrupts (slit, timer or ctrl-c). This is a busy wait, since it will continuously run the pass statement, doing nothing. Maybe there is a way to improve performance and make the program completely event driven, freeing up the CPU in the mean time, but that is a bigger task than I am attempting here.

Body:
I am trying to get a reasonable RPM for a motor. I have a photo-interrupter that sends 0 or 1 if it detects a slit that passes by. My code is as following, what I simply need is to time 0-60 seconds, and add the number of times 1 was detected and then divide it by 60, thus RPM.

I don't want to complicate my code, also keep in mind this is running on the Raspberry Pi with many other scripts and webservers running behind it. So not a bad code like "sleep" that would hog down the entire cpu.

I'm not looking for a crazy accurate measurement, just a reasonable idea of how fast the motor is spinning. Also does the slit size make a difference?

import RPi.GPIO as GPIO
import time
signal = 21

from time import sleep     # this lets us have a time delay (see line 15)
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
GPIO.setup(signal, GPIO.IN)    # set GPIO21 as input (signal)
GPIO.add_event_detect(signal,GPIO.BOTH)

try:
    while True:            # this will carry on until you hit CTRL+C
        if GPIO.event_detected(signal): # if port 21 == 1
            print "Port 21 is 1/HIGH/True - LED ON"
            slit=slit+1       # Counts every time slit passes

        else:
            print "Port 21 is 0/LOW/False - LED OFF"
        rpm = slit/60         # Calculates the RPM
        sleep(0.0001)         # wait 0.0001 seconds

finally:                   # this block will run no matter how the try block exits
    GPIO.cleanup()         # clean up after yourself

Body:
With the reservation that I have never programmed an RPi using Python, this is how I would try to tackle this task:

import RPi.GPIO as GPIO
import threading

signal = 21
GPIO.setmode(GPIO.BCM)     # set up BCM GPIO numbering
GPIO.setup(signal, GPIO.IN)    # set GPIO21 as input (signal)

slit = 0
rpm = 0

def increment():
    global slit
    print("Port 21 is 1/HIGH/True - LED ON")
    slit += 1

def count_complete():
    global slit
    global rpm
    rpm = slit/60
    print ("RPM = {}".format(rpm))
    # reset and restart timer
    slit = 0
    t = threading.Timer(60, count_complete)

# Bounce will prevent double detection of the same rising edge (for 1 ms)
GPIO.add_event_detect(signal, GPIO.RISING, callback=increment, bounce=1)

t = threading.Timer(60, count_complete)
try:
    while True:            # this will carry on until you hit CTRL+C
        pass               # Do nothing but wait for callbacks and timer
finally:                   # this block will run no matter how the try block exits
    t.cancel()             # stop the timer
    GPIO.cleanup()         # clean up after yourself

As can be seen, I have added a callback function that will be called as soon as a rising edge is detected on the input. Here the clit counter is incremented. The bounce parameter is a protection that will stop the program from counting the same slit double.

Setting at 1 ms means that the RPM needs to be (well) below 1,000 or some slits will be missed. It is possible to experiment by removing this. I don't know if it is possible to give a fractional bounce time. That may be another option.

The main program then, stats a timer, that lets the increment run for 1 minute, after which the RPM is calculated and the system reset and a new count is initiated. (There is a risk of a race condition here, where a slit interrupt may happen while doing the calculation. This could be missed in these cases.)

Then in the main loop, nothing happens, except for the program waiting for interrupts (slit, timer or ctrl-c). This is a busy wait, since it will continuously run the pass statement, doing nothing. Maybe there is a way to improve performance and make the program completely event driven, freeing up the CPU in the mean time, but that is a bigger task than I am attempting here.


问:
drop down list appears in front of my calender in asp.net
Drop Down list comes in front of all the controls. I have a calander extender for the text box which is right above(top) the drop down. when the calender pop's out it goes under i.e behind the drop down. Any solution friends.</p>

答: How about posting some code/markup?</p>

Body: How about posting some code/markup?


问:
Form control valueChanges gives the previous value
I have a form control with name 'question1' within the form object parentForm and I have subscribed to it in the following way.

Its a radio button with two options Yes and No, when I select No I get Yes and when I select Yes its a No.

```<code>this.parentForm.controls['question1'].valueChanges.subscribe(
  (selectedValue) => {
    // If option `No is selected`
    console.log(selectedValue);  // displays No. OK
    console.log(this.parentForm.value['question1']);  // displays Yes. Problem is here
  }
);
</code>```

selectedValue variable has the correct value but if I do console.log(this.parentForm.value['question1'] it gives the previous value.

I tried to put a setTimeout() before retrieving value from this.parentForm.value['question1'], It just works fine.

```<code>setTimeout(() => {
  console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);
</code>```

But my question is why parentForm is not updated when its control's value changes and that too I am retrieving its value only after value was changed.

Note: I don't want to observe for parentForm.valueChanges, not my requirement.

答:
The valueChanges event is fired after the new value is updated to the FormControl value, and before the change is bubbled up to its parent and ancestors. Therefore, you will have to access the value of the FormControl itself (which has just been patched), not a field of the FormGroup value object (which is untouched during the event).

In light of that, use this.parentForm.get('question1').value instead:

```<code>this.parentForm.controls['question1'].valueChanges.subscribe(
    (selectedValue) => {
      console.log(selectedValue);
      console.log(this.parentForm.get('question1').value);
    }
);
</code>```

Body:
I have a form control with name 'question1' within the form object parentForm and I have subscribed to it in the following way.

Its a radio button with two options Yes and No, when I select No I get Yes and when I select Yes its a No.

this.parentForm.controls['question1'].valueChanges.subscribe(
  (selectedValue) => {
    // If option `No is selected`
    console.log(selectedValue);  // displays No. OK
    console.log(this.parentForm.value['question1']);  // displays Yes. Problem is here
  }
);

selectedValue variable has the correct value but if I do console.log(this.parentForm.value['question1'] it gives the previous value.

I tried to put a setTimeout() before retrieving value from this.parentForm.value['question1'], It just works fine.

setTimeout(() => {
  console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);

But my question is why parentForm is not updated when its control's value changes and that too I am retrieving its value only after value was changed.

Note: I don't want to observe for parentForm.valueChanges, not my requirement.

Body:
The valueChanges event is fired after the new value is updated to the FormControl value, and before the change is bubbled up to its parent and ancestors. Therefore, you will have to access the value of the FormControl itself (which has just been patched), not a field of the FormGroup value object (which is untouched during the event).

In light of that, use this.parentForm.get('question1').value instead:

this.parentForm.controls['question1'].valueChanges.subscribe(
    (selectedValue) => {
      console.log(selectedValue);
      console.log(this.parentForm.get('question1').value);
    }
);