问:
PopupWindow out of screen when size is unspecified
Most examples out there specify exactly the width and height of the popup window. I want them to be WRAP_CONTENT - since the content is dinamically determined, so in the constructor I set -2 for both width and height and show it via showAsDropDown(View anchor)

Doing this, the popup is always drawn below the anchor view, which means it can be drawn offscreen. The following snippet demonstrates the problem. Try clicking on the last TextView and you won't see any PopupWindow, since it's shown outside of the windows bounds. Why doesn't it work? I remark that specifying dimension explicitly (for example 200, 100) doesn't trigger the problem. Try it yourself

```<code>package com.zybnet.example.popupdemo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PopupDemoActivity extends Activity implements OnClickListener {
    private PopupWindow popup;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // -2 means WRAP_CONTENT THIS TRIGGERS THE PROBLEM
        popup = new PopupWindow(getPopupContent(), -2, -2);
        // When you specify the dimensions everything goes fine
        //popup = new PopupWindow(getPopupContent(), 200, 100);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        // FILL_PARENT  and same layout weight for all children
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1, 1);
        for (int i = 0; i < 10; i++) {
            TextView tv = new TextView(this);
            tv.setText("Click to show popup");
            tv.setOnClickListener(this);
            layout.addView(tv, params);
        }
        setContentView(layout);
    }

    @Override
    public void onClick(View view) {
        popup.dismiss();
        popup.showAsDropDown(view);
    }

    private View getPopupContent() {
        TextView popupContent = new TextView(this);
        popupContent.setText("Some text here");
        popupContent.setTextColor(Color.parseColor("#5000ae"));
        popupContent.setBackgroundColor(Color.parseColor("#ff00ff"));
        popupContent.setPadding(10, 20, 20, 10);
        return popupContent;
    }
}
</code>```

答:
I solved this problem by calling measure() method in a popup content view:

```<code>View content = getPopupContent();

content.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int measuredHeight = content.getMeasuredHeight();

popup = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT, measuredHeight);
</code>```

Body:
Most examples out there specify exactly the width and height of the popup window. I want them to be WRAP_CONTENT - since the content is dinamically determined, so in the constructor I set -2 for both width and height and show it via showAsDropDown(View anchor)

Doing this, the popup is always drawn below the anchor view, which means it can be drawn offscreen. The following snippet demonstrates the problem. Try clicking on the last TextView and you won't see any PopupWindow, since it's shown outside of the windows bounds. Why doesn't it work? I remark that specifying dimension explicitly (for example 200, 100) doesn't trigger the problem. Try it yourself

package com.zybnet.example.popupdemo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

public class PopupDemoActivity extends Activity implements OnClickListener {
    private PopupWindow popup;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // -2 means WRAP_CONTENT THIS TRIGGERS THE PROBLEM
        popup = new PopupWindow(getPopupContent(), -2, -2);
        // When you specify the dimensions everything goes fine
        //popup = new PopupWindow(getPopupContent(), 200, 100);

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        // FILL_PARENT  and same layout weight for all children
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -1, 1);
        for (int i = 0; i < 10; i++) {
            TextView tv = new TextView(this);
            tv.setText("Click to show popup");
            tv.setOnClickListener(this);
            layout.addView(tv, params);
        }
        setContentView(layout);
    }

    @Override
    public void onClick(View view) {
        popup.dismiss();
        popup.showAsDropDown(view);
    }

    private View getPopupContent() {
        TextView popupContent = new TextView(this);
        popupContent.setText("Some text here");
        popupContent.setTextColor(Color.parseColor("#5000ae"));
        popupContent.setBackgroundColor(Color.parseColor("#ff00ff"));
        popupContent.setPadding(10, 20, 20, 10);
        return popupContent;
    }
}

Body:
I solved this problem by calling measure() method in a popup content view:

View content = getPopupContent();

content.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
int measuredHeight = content.getMeasuredHeight();

popup = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT, measuredHeight);


来源: stackexchange

问:
Checking for Power Saver Mode programmatically
I have written an app (AutoWifiSwitch) and one of the features I plan to add is automatically disabling the wifi scanning service in my app if power saving mode is enabled.

I know Android L is supposed to have Battery Saving implemented (previously HTC and Samsung would add the features themselves to the software). Presumably this now means Google will have added some sort of API for it. Ideally there would be a new action added so I could listen for that.

I would also like to know if the above is possible with HTC/Samsung APIs and if so, how do I use them.

I've been searching everywhere for the above questions but had absolutely no luck, the app SecureSettings (an addon for Tasker) is able to hook into the HTC/Samsung APIs to enable the power saver anyway, I'm not quite sure how they do it.

Edit: The power saver value can be gotten from the PowerManager in Android L, not sure if there is an Action for it though.

答:
```<code>PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
boolean powerSaveMode = powerManager.isPowerSaveMode();
</code>```

Docs: developer.android.com/.../PowerManager#isPowerSaveMode()

Added in API level 21 (Android 5.0)

ContentLicense: CC BY-SA 3.0

Body:
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
boolean powerSaveMode = powerManager.isPowerSaveMode();

Docs: developer.android.com/.../PowerManager#isPowerSaveMode()

Added in API level 21 (Android 5.0)

ContentLicense: CC BY-SA 4.0


问:
Run a VBA macro on every word in Word-File

I've adapted this other answer to my needs. My changes look through the populated array and matches the selected text to the Header text instead of the Header number, as well as other some minor changes.

```<code>     Sub InsertCrossRef()
        'thank you stackoverflow:
       https://stackoverflow.com/questions/47559316/macro-to-insert-a-cross-
       reference-based-on-selection
            Dim RefList As Variant 'list of all available headings and
            numbered items available
            Dim LookUp As String 'string to be lookedup
            Dim Ref As String 'reference string in which there is to be searched
            Dim s As Integer, t As Integer 'calculated variabels for the string changes
            Dim i As Integer 'looping integer

            On Error GoTo ErrExit
            With Selection.Range

                ' discard leading blank spaces
                Do While (Asc(.Text) = 32) And (.End > .Start)
                    .MoveStart wdCharacter
                Loop
                ' discard trailing blank spaces, full stops, etc
                Do While ((Asc(Right(.Text, 1)) = 46) Or _
                          (Asc(Right(.Text, 1)) = 32) Or _
                          (Asc(Right(.Text, 1)) = 11) Or _
                          (Asc(Right(.Text, 1)) = 13)) And _
                          (.End > .Start)
                    .MoveEnd wdCharacter, -1
                Loop

        ' error protection

           ErrExit:
                If Len(.Text) = 0 Then
                    MsgBox "Please select a reference.", _
                           vbExclamation, "Invalid selection"
                    Exit Sub
                End If

                LookUp = .Text

            End With
            On Error GoTo 0

            With ActiveDocument
                ' Use WdRefTypeHeading to retrieve Headings
                RefList = .GetCrossReferenceItems(wdRefTypeNumberedItem)
                For i = UBound(RefList) To 1 Step -1
                    Ref = Trim(RefList(i))

                    If InStr(1, Ref, LookUp, vbTextCompare) = 13 Or InStr(1,                                   Ref, LookUp, vbTextCompare) = 12 Then
                        s = InStr(2, Ref, " ") 'set S = xValue when position 2 returns a Space
                        t = InStr(2, Ref, Chr(9)) 'set T = 1 when position 2 returns a Tab
                        If (s = 0) Or (t = 0) Then
                            s = IIf(s > 0, s, t)
                        Else
                            s = IIf(s < t, s, t)
                        End If

                        If LookUp = Right(Ref, Len(Ref) - s) Then Exit For

                        'If LookUp = Left(Ref, s - 1) Then Exit For
                    End If
                Next i

        ' create the cross reference, add a space when acidently a space was selected
                If i Then

                If Right(Selection.Range, 1) = " " Then

                    Selection.InsertCrossReference ReferenceType:="Numbered item", _
                                                   ReferenceKind:=wdContentText, _
                                                   ReferenceItem:=CStr(i), _
                                                   InsertAsHyperlink:=True, _
                                                   IncludePosition:=False, _
                                                   SeparateNumbers:=False, _
                                                   SeparatorString:=" "
                    Selection.InsertAfter " "

                Else
                    Selection.InsertCrossReference ReferenceType:="Numbered item", _
                                                   ReferenceKind:=wdContentText, _
                                                   ReferenceItem:=CStr(i), _
                                                   InsertAsHyperlink:=True, _
                                                   IncludePosition:=False, _
                                                   SeparateNumbers:=False, _
                                                   SeparatorString:=" "
                End If

                Else
                    MsgBox "A cross reference to """ & LookUp & """ couldn't be set" & vbCr & _
                           "because a paragraph with that number couldn't" & vbCr & _
                           "be found in the document.", _
                           vbInformation, "Invalid cross reference"
                End If
            End With
        End Sub
</code>```

What I want to achieve is to run this code on every word in my document:

```<code>For Each sentence In ActiveDocument.StoryRanges
   For Each w In sentence.Words

    'above code should run

   Next
</code>```

What I expected was that the macro would run through every word in my document, see if it matches any of the headers and apply the crossreference maacro hereabove.

答:
1. Make you main subroutine parametrized in this way:

```<code>Sub InsertCrossRef(rngWord as Range)
    ...
End Sub
</code>```

2. Next, inside InsertCrossRef you need to identify and change all references which should point to Word Object (rngWord). Example for you:

```<code>With Selection.Range '<< this should be changed into...
With rngWord '<<...this
</code>```

And I could see one or more other to change in this way.

3. Finally, to call it for each word complete your loops in this way:

```<code>For Each sentence In ActiveDocument.StoryRanges
   For Each w In sentence.Words

      InsertCrossRef w

   Next
Next
</code>```

Body:
I've adapted this other answer to my needs. My changes look through the populated array and matches the selected text to the Header text instead of the Header number, as well as other some minor changes.

     Sub InsertCrossRef()
        'thank you stackoverflow:
       https://stackoverflow.com/questions/47559316/macro-to-insert-a-cross-
       reference-based-on-selection
            Dim RefList As Variant 'list of all available headings and
            numbered items available
            Dim LookUp As String 'string to be lookedup
            Dim Ref As String 'reference string in which there is to be searched
            Dim s As Integer, t As Integer 'calculated variabels for the string changes
            Dim i As Integer 'looping integer

            On Error GoTo ErrExit
            With Selection.Range

                ' discard leading blank spaces
                Do While (Asc(.Text) = 32) And (.End > .Start)
                    .MoveStart wdCharacter
                Loop
                ' discard trailing blank spaces, full stops, etc
                Do While ((Asc(Right(.Text, 1)) = 46) Or _
                          (Asc(Right(.Text, 1)) = 32) Or _
                          (Asc(Right(.Text, 1)) = 11) Or _
                          (Asc(Right(.Text, 1)) = 13)) And _
                          (.End > .Start)
                    .MoveEnd wdCharacter, -1
                Loop

        ' error protection

           ErrExit:
                If Len(.Text) = 0 Then
                    MsgBox "Please select a reference.", _
                           vbExclamation, "Invalid selection"
                    Exit Sub
                End If

                LookUp = .Text

            End With
            On Error GoTo 0

            With ActiveDocument
                ' Use WdRefTypeHeading to retrieve Headings
                RefList = .GetCrossReferenceItems(wdRefTypeNumberedItem)
                For i = UBound(RefList) To 1 Step -1
                    Ref = Trim(RefList(i))

                    If InStr(1, Ref, LookUp, vbTextCompare) = 13 Or InStr(1,                                   Ref, LookUp, vbTextCompare) = 12 Then
                        s = InStr(2, Ref, " ") 'set S = xValue when position 2 returns a Space
                        t = InStr(2, Ref, Chr(9)) 'set T = 1 when position 2 returns a Tab
                        If (s = 0) Or (t = 0) Then
                            s = IIf(s > 0, s, t)
                        Else
                            s = IIf(s < t, s, t)
                        End If

                        If LookUp = Right(Ref, Len(Ref) - s) Then Exit For

                        'If LookUp = Left(Ref, s - 1) Then Exit For
                    End If
                Next i

        ' create the cross reference, add a space when acidently a space was selected
                If i Then

                If Right(Selection.Range, 1) = " " Then

                    Selection.InsertCrossReference ReferenceType:="Numbered item", _
                                                   ReferenceKind:=wdContentText, _
                                                   ReferenceItem:=CStr(i), _
                                                   InsertAsHyperlink:=True, _
                                                   IncludePosition:=False, _
                                                   SeparateNumbers:=False, _
                                                   SeparatorString:=" "
                    Selection.InsertAfter " "

                Else
                    Selection.InsertCrossReference ReferenceType:="Numbered item", _
                                                   ReferenceKind:=wdContentText, _
                                                   ReferenceItem:=CStr(i), _
                                                   InsertAsHyperlink:=True, _
                                                   IncludePosition:=False, _
                                                   SeparateNumbers:=False, _
                                                   SeparatorString:=" "
                End If

                Else
                    MsgBox "A cross reference to """ & LookUp & """ couldn't be set" & vbCr & _
                           "because a paragraph with that number couldn't" & vbCr & _
                           "be found in the document.", _
                           vbInformation, "Invalid cross reference"
                End If
            End With
        End Sub

What I want to achieve is to run this code on every word in my document:

For Each sentence In ActiveDocument.StoryRanges
   For Each w In sentence.Words

    'above code should run

   Next

What I expected was that the macro would run through every word in my document, see if it matches any of the headers and apply the crossreference maacro hereabove.

Body:
1. Make you main subroutine parametrized in this way:

Sub InsertCrossRef(rngWord as Range)
    ...
End Sub

2. Next, inside InsertCrossRef you need to identify and change all references which should point to Word Object (rngWord). Example for you:

With Selection.Range '<< this should be changed into...
With rngWord '<<...this

And I could see one or more other to change in this way.

3. Finally, to call it for each word complete your loops in this way:

For Each sentence In ActiveDocument.StoryRanges
   For Each w In sentence.Words

      InsertCrossRef w

   Next
Next


问:
Uncaught Error: class 'OTPHP\\TOTP' MAMP (MySQL /w Apache PHP on MacOS X)
it is my first practice of php(MAMP stack) and I want login 'MFA' feature

I install otphp

and follow tutorial in README.md

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>1aefwefawef</h1>
<?php
use OTPHP\TOTP;

$otp = new TOTP;
echo $otp;
?>
</body>
</html>
</code>```

but there's no change in 127.0.0.1:8080/number.php

so I check the error.log

```<code>Tue Dec 05 18:35:11.950337 2017] [php7:error] [pid 98137] [client 127.0.0.1:60727] PHP Fatal error:  Uncaught Error: Class 'OTPHP\\TOTP' not found in /Applications/mampstack-7.1.11-0/apache2/htdocs/number.php:12\nStack trace:\n#0 {main}\n  thrown in /Applications/mampstack-7.1.11-0/apache2/htdocs/number.php on line 12
</code>```

I think it is import error but I can't find where is correct location

In number.php

/Applications/mampstack-7.1.11-0/apache2/htdocs

location of otphp

/Applications/mampstack-7.1.11-0/apache2/htdocs/vendor/spomky-labs/otphp

location of TOTP.php

/Applications/mampstack-7.1.11-0/apache2/htdocs/vendor/spomky-labs/otphp/src

答:
Maybe you should try to load your dependencies ?

Take a look at Autoloading or Composer if you have many dependencies...

Hope it helps

Body:
it is my first practice of php(MAMP stack) and I want login 'MFA' feature

I install otphp

and follow tutorial in README.md

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

1aefwefawef

<?php
use OTPHP\TOTP;

$otp = new TOTP;
echo $otp;
?>

but there's no change in 127.0.0.1:8080/number.php

so I check the error.log

Tue Dec 05 18:35:11.950337 2017] [php7:error] [pid 98137] [client 127.0.0.1:60727] PHP Fatal error:  Uncaught Error: Class 'OTPHP\\TOTP' not found in /Applications/mampstack-7.1.11-0/apache2/htdocs/number.php:12\nStack trace:\n#0 {main}\n  thrown in /Applications/mampstack-7.1.11-0/apache2/htdocs/number.php on line 12

I think it is import error but I can't find where is correct location

In number.php

/Applications/mampstack-7.1.11-0/apache2/htdocs

location of otphp

/Applications/mampstack-7.1.11-0/apache2/htdocs/vendor/spomky-labs/otphp

location of TOTP.php

/Applications/mampstack-7.1.11-0/apache2/htdocs/vendor/spomky-labs/otphp/src


问:
Cardboard Mockup Scene for Hololens Look and Fell
I didn't know which forum to ask about this is the most fitting, but I think this is the best:

Our designers want to check their stuff on the hololens. For example to check if their gui is right and how the depth effect is. But we dont have that many hololenses and the developer don't have the time to load up the designers' projects for checking.

So my question is:
Is there an plugin or Scene, in which they can load their stuff and export/build it for vr (cardboard or at least htc vive) and have the same look and feel like the holo lens (just with a 3d world?). It's mostly for some fancy 3D iron man Style ui (for now).

A concrete Problem:

They have a animated loading Circle(s). They want to check if you look straight on it at the holo lens or if you have a to big perspective distortion or occlusion. Also it would be nice if the small FOV would be simulated.

I'm kinda searching a hololens vr simulator for unity scene/script

答:
Sry for the long silence (had other Stuff to do):

The other answering Persons have good Solutions, but i just want to make an Overview of things that helped me on the way. When I asked the questions i had the Hololens like 3 Days and no Idea of it:

Checking Clipping/Lost of sight:
Set the Camera FOV to 55 the aspect ratio to 16:9. Also if you import the Camera from the Toolkit you can change the eye from the Settings. Also set the Clipping Plane to 0.75. Objects closer than this will only be shown on one eye.

As Dtb49 said: "use he Holographic Remoting App on your HoloLens.  Once you do that in the Unity editor you can go to Window->Holographic Emulation->Remote To Device and type in the IP address displayed when you launch the app from your HoloLens." The Problem is you need the Fall Creators Update for that (and your Admin won't let you update). And it's very laggy (in my case)

Or use the emulator as Gambolati said.

Last but not least my favorite way now: Use the "Manual Gaze Control" Script from the Toolkit and attach to the cam and use the "Input Manager Prefab". The EditorHandsInput is needed. No you can emulate interactions in the Playmode.

PS: To check the 3D Experience Cardboard is not usefull. It's just another experience.


问:
Angular 4, convert from component to module
I have a component DfqComponent that I want to turn into a module, but it should keep its routing behavoir. These are the routes I want to keep, defined in the module ProductionLineRoutingModule, that has its own outlet:

```<code>const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  children: [
    { path: 'dfq', component: DfqComponent },
    // other modules planed
    { path: '', pathMatch: 'full', redirectTo: 'dfq' }
  ]
}];
</code>```

To turn DfqComponent to DfqModule and call it as before, I used the following routing in DfqRoutingModule:

```<code>const routes: Routes = [
  { path: 'line/:name/dfq', component: DfqComponent }
];
</code>```

This showed me the desired html (actually only simply the word DFQ), but in my opinion there are two drawbacks:

1. The outlet now is the primary outlet of the AppComponent.

2. The route definition is coupled with the ProductionLineModule ('line/:name/dfq' instead of 'dfq').

So how can I achieve this?

The project actually looks like this:

答:
OK, thanks to elasticrash it now works and the code files look clearly.

To remove the children[] array in ProductionLineRoutingModule and by adding multiple path definitions with the  loadChildren property did the trick. DfqModule and DfqRoutingModule already were ok.

```<code>const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../masterdata/masterdata.module#MasterdataModule'
  },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../order/order.module#OrderModule'
  },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../dfq/dfq.module#DfqModule'
  }
];
</code>```

There's on thing missing: How can I now set a default route, like 'dfq'?

Thanks!

Body:
I have a component DfqComponent that I want to turn into a module, but it should keep its routing behavoir. These are the routes I want to keep, defined in the module ProductionLineRoutingModule, that has its own outlet:

const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  children: [
    { path: 'dfq', component: DfqComponent },
    // other modules planed
    { path: '', pathMatch: 'full', redirectTo: 'dfq' }
  ]
}];

To turn DfqComponent to DfqModule and call it as before, I used the following routing in DfqRoutingModule:

const routes: Routes = [
  { path: 'line/:name/dfq', component: DfqComponent }
];

This showed me the desired html (actually only simply the word DFQ), but in my opinion there are two drawbacks:

1. The outlet now is the primary outlet of the AppComponent.

2. The route definition is coupled with the ProductionLineModule ('line/:name/dfq' instead of 'dfq').

So how can I achieve this?

The project actually looks like this:

Body:
OK, thanks to elasticrash it now works and the code files look clearly.

To remove the children[] array in ProductionLineRoutingModule and by adding multiple path definitions with the  loadChildren property did the trick. DfqModule and DfqRoutingModule already were ok.

const routes: Routes = [
  { path: 'line', component: ProductionLineListComponent },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../masterdata/masterdata.module#MasterdataModule'
  },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../order/order.module#OrderModule'
  },
  { path: 'line/:name', component: ProductionLineDetailsComponent,
  loadChildren: '../dfq/dfq.module#DfqModule'
  }
];

There's on thing missing: How can I now set a default route, like 'dfq'?

Thanks!


问:
Why doesn't Grails notify me of error at domain object saving?
I'm just starting with Grails, and here is the first issue.

I spent several hours to find out that domain object cannot be inserted in DB, until all its properties are populated.

```<code>class Item {
  String title
  String link
}

class ItemController {
  def fetch = {
    def item = new Item()
    item.title = "blabla"
    // no value for "link"
    item.save()
  }
}
</code>```

Looks logical, but why is it skipped so silently? Can I configure something to get exceptions in such cases?

Thanks

答:
No exception is thrown by default .

The save() method injected to Domain classes returns false if an error has occured during the validation phase.
A classic code sample for checking save/update of a domain class is :

```<code>if (!myDomainObj.save()) {
   log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of  org.springframework.validation.FieldError
}
</code>```

If you need to have an exception for a particular domain class, use:

```<code>myDomainObj.save(failOnError: true)
</code>```

and exceptions for validation failures will be thrown.

If you want to throw an exception for EVERY domain classes, then simply set grails.gorm.failOnError to true in grails-app/conf/Config.groovy

Be carefull : all domain properties have an implicit nullable: false constraint.

I recommend you reading this article.

ContentLicense: CC BY-SA 2.5

Body:
I'm just starting with Grails, and here is the first issue.

I spent several hours to find out that domain object cannot be inserted in DB, until all its properties are populated.

class Item {
  String title
  String link
}

class ItemController {
  def fetch = {
    def item = new Item()
    item.title = "blabla"
    // no value for "link"
    item.save()
  }
}

Looks logical, but why is it skipped so silently? Can I configure something to get exceptions in such cases?

Thanks

Body:
No exception is thrown by default .

The save() method injected to Domain classes returns false if an error has occured during the validation phase.
A classic code sample for checking save/update of a domain class is :

if (!myDomainObj.save()) {
   log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of  org.springframework.validation.FieldError
}

If you need to have an exception for a particular domain class, use:

myDomainObj.save(failOnError: true)

and exceptions for validation failures will be thrown.

If you want to throw an exception for EVERY domain classes, then simply set grails.gorm.failOnError to true in grails-app/conf/Config.groovy

Be carefull : all domain properties have an implicit nullable: false constraint.

I recommend you reading this article.


问:
Junit test case for PreparedStatementCallback coverage
```<code>@Transactional
    public Boolean save(final StudentLogEntry studentLogEntry) throws SQLException,DaoException{
        boolean returnFlag = true;
        String sqlInsert = "insert into STUDENT_DETAILS (INSERT_DATE,STUDENT_NAME,STUDENT_ID) values(SYSDATE,?,?)";
        returnFlag = jdbcTemplate.execute(
            sqlInsert,
            new PreparedStatementCallback<Boolean>() {
                Boolean b=false;
                @Override
                public Boolean doInPreparedStatement(PreparedStatement pst) {
                    try {
                        pst.setString(2, studentLogEntry.getStuName());
                        pst.setString(3, studentLogEntry.getStuId());
                        b=pst.execute();
                    } catch (SQLException e) {
                        clicklogger.info("SQLException has occurred while inserting studentlog ",e);
                    } catch (DataAccessException e) {
                        clicklogger.info("DataAccessException has occurred while inserting studentlog ",e);
                    }
                    return b;
                }
            }
        );
        return returnFlag;
    }
</code>```

I am using Spring framework for my project, I have written Junit test case for the above code. But I am not able to cover the PreparedStatementCallback. My test case is as below:

```<code>@Test
public void testSave() throws DaoException, SQLException {
    studentDao.setJdbcTemplate(jdbcTemplate);
    studentDao.setTransactionManager(transactionManager);
    StudentLogEntry studentLogEntry = new StudentLogEntry();
    studentLogEntry.getStuName("ABC");
    studentLogEntry.getStuId("1234");
    assertEquals("true",studentDao.save(studentLogEntry));
}
</code>```

答:
The method is doing to much to make it easily and clearly testable.

1) I would move the new PreparedStatementCallback to a specialized class:

```<code>public class MyPreparedStatementCallback implements PreparedStatementCallback<Boolean>{

  @Override
  public Boolean doInPreparedStatement(PreparedStatement pst) {
    ....
}
</code>```

I would test the doInPreparedStatement method in separation here. It should not be related to the former test at all.

2) Use the new class in the original method and test whether proper instance has been passed (you would need Mockito here):

```<code>returnFlag = jdbcTemplate.execute(sqlInsert,new MyPreparedStatementCallback());
</code>```

and the test:

```<code>@InjectMocks
StudentDao studentDao;

@Mock
JdbcTemplate jdbcTemplateMock;

@Captor
ArgumentCaptor argCaptor;

@Before
public void init(){
     MockitoAnnotations.initMocks(this);
}

@Test
public void shouldSaveWithCallback(){
     // Act
     // set up
     studentDao.save(studentLogEntry);
     myClass.userPressedButton();

    Mockito.verify(jdbcTemplateMock).execute(Mockito.anyString(), argCaptor.capture());

    // Assert
    assertTrue(argCaptor.getValue() instance of MyPreparedStatementCallback);
}
</code>```

The bottom line is that you should not test the implementation of that callback withing your original test method. That is too much and your test would be to coarse and hard to maintain.

Body:
@Transactional
    public Boolean save(final StudentLogEntry studentLogEntry) throws SQLException,DaoException{
        boolean returnFlag = true;
        String sqlInsert = "insert into STUDENT_DETAILS (INSERT_DATE,STUDENT_NAME,STUDENT_ID) values(SYSDATE,?,?)";
        returnFlag = jdbcTemplate.execute(
            sqlInsert,
            new PreparedStatementCallback<Boolean>() {
                Boolean b=false;
                @Override
                public Boolean doInPreparedStatement(PreparedStatement pst) {
                    try {
                        pst.setString(2, studentLogEntry.getStuName());
                        pst.setString(3, studentLogEntry.getStuId());
                        b=pst.execute();
                    } catch (SQLException e) {
                        clicklogger.info("SQLException has occurred while inserting studentlog ",e);
                    } catch (DataAccessException e) {
                        clicklogger.info("DataAccessException has occurred while inserting studentlog ",e);
                    }
                    return b;
                }
            }
        );
        return returnFlag;
    }

I am using Spring framework for my project, I have written Junit test case for the above code. But I am not able to cover the PreparedStatementCallback. My test case is as below:

@Test
public void testSave() throws DaoException, SQLException {
    studentDao.setJdbcTemplate(jdbcTemplate);
    studentDao.setTransactionManager(transactionManager);
    StudentLogEntry studentLogEntry = new StudentLogEntry();
    studentLogEntry.getStuName("ABC");
    studentLogEntry.getStuId("1234");
    assertEquals("true",studentDao.save(studentLogEntry));
}

Body:
The method is doing to much to make it easily and clearly testable.

1) I would move the new PreparedStatementCallback to a specialized class:

public class MyPreparedStatementCallback implements PreparedStatementCallback<Boolean>{

  @Override
  public Boolean doInPreparedStatement(PreparedStatement pst) {
    ....
}

I would test the doInPreparedStatement method in separation here. It should not be related to the former test at all.

2) Use the new class in the original method and test whether proper instance has been passed (you would need Mockito here):

returnFlag = jdbcTemplate.execute(sqlInsert,new MyPreparedStatementCallback());

and the test:

@InjectMocks
StudentDao studentDao;

@Mock
JdbcTemplate jdbcTemplateMock;

@Captor
ArgumentCaptor argCaptor;

@Before
public void init(){
     MockitoAnnotations.initMocks(this);
}

@Test
public void shouldSaveWithCallback(){
     // Act
     // set up
     studentDao.save(studentLogEntry);
     myClass.userPressedButton();

    Mockito.verify(jdbcTemplateMock).execute(Mockito.anyString(), argCaptor.capture());

    // Assert
    assertTrue(argCaptor.getValue() instance of MyPreparedStatementCallback);
}

The bottom line is that you should not test the implementation of that callback withing your original test method. That is too much and your test would be to coarse and hard to maintain.


问:
rejuggle 1D array into multidimensional fields in python
Dears,

I want to do the below in python but found no refs on how to generate data_rejuggled from data (except this for matlab):

```<code>from collections import namedtuple

data=[1,2,2,2,3,4,5,5,5,5]
dims=[1,3,1,1,4]

data_rejuggled=somefunction(data,dims) #<--THIS is what I want to know

print data_rejuggled
  [1,[2,2,2],3,4,[5,5,5,5]]

names=["a","b","c","d","e"]

recID ='r'+str(1) #define a rec id
s = namedtuple(recID, names, verbose=False) #create tuple
s=s(*data_rejuggled) #fill tuple

print s
  r1(a=1, b=[2, 2, 2], c=3, d=4, e=[5, 5, 5, 5])
</code>```

Backgrounds:

data is decoded from a binary file

data can be potentially very large

Thank you for reading,

F#

答:
Just in case someone ever bothers, here is how I finally solved this:</p>

```<code>def somefunction(data,dims):
  ls2=np.add.accumulate(np.array(dims)) #gets indices for last members of each field
  ls=np.roll(ls2,1)                     #gets indices for first members of each field
  ls[0]=0                               #set index of first field to zero
  return [data[i:j] for i,j in zip(ls,ls2)] #return members of of each field as arrays
</code>```

Body:
Dears,

I want to do the below in python but found no refs on how to generate data_rejuggled from data (except this for matlab):

from collections import namedtuple

data=[1,2,2,2,3,4,5,5,5,5]
dims=[1,3,1,1,4]

data_rejuggled=somefunction(data,dims) #<--THIS is what I want to know

print data_rejuggled
  [1,[2,2,2],3,4,[5,5,5,5]]

names=["a","b","c","d","e"]

recID ='r'+str(1) #define a rec id
s = namedtuple(recID, names, verbose=False) #create tuple
s=s(*data_rejuggled) #fill tuple

print s
  r1(a=1, b=[2, 2, 2], c=3, d=4, e=[5, 5, 5, 5])

Backgrounds:

data is decoded from a binary file

data can be potentially very large

Thank you for reading,

F#

Body:
Just in case someone ever bothers, here is how I finally solved this:

def somefunction(data,dims):
  ls2=np.add.accumulate(np.array(dims)) #gets indices for last members of each field
  ls=np.roll(ls2,1)                     #gets indices for first members of each field
  ls[0]=0                               #set index of first field to zero
  return [data[i:j] for i,j in zip(ls,ls2)] #return members of of each field as arrays


问:
Rhapsody for DO-178 avionics environment?
Has anyone successfully used Rhapsody in a DO-178 avionics environment? That is, working with the FAA/DER process to provide artifacts to them and have them approved.  Since it is my understanding that Rhapsody isn't a certifiable MDD tool, I was curious if there were other mitigating factors.

If you were successful so, what steps did you take in order to be able to accomplish this?

Thanks for any feedback and insights.

答:
Rhapsody is being used in our Level A/C/D project with Arinc 653. Since Output of Rhapsody(Auto code generators) are being verified.

Hence, Qualifying Rhapsody is not necessary. Rhapsody gives advantages in Traceability and generation or modifying Test Scripts by updating just "Tags" field.

So the entire Test script or traces in Test script need not to be modified.


问:
JavaScript slideshow not working (images are static)
I am quite new to JavaScript and I am trying to implement a slider. Below is the javascript code that I am trying to solve.

    <title> Home Page </title>

```

It is not working and the images are static. Any idea why? Thanks for helping in advance.

答:
You need to use jquery in order to be able to use that plugin.

```<code><html>
  <head>
    <title>
      Home Page
    </title>
    <!-- here -->
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript">
      $("#slideshow > div:gt(0)").hide();

      setInterval(function() {
        $('#slideshow > div:first')
          .fadeOut(1000)
          .next()
          .fadeIn(1000)
          .end()
          .appendTo('#slideshow');
      }, 3000);
    </script>
  </head>
  <body>
    <div id="slideshow">
      <div>
        <img src="http://vectorlogofree.com/wp-content/uploads/2014/04/23656-apple-logo-icon-vector-icon-vector-eps.png">
      </div>
      <div>
        <img src="http://vignette4.wikia.nocookie.net/memoryalpha/images/0/02/Linux_icon.png/revision/latest?cb=20141003183250&path-prefix=en">
      </div>
      <div>
      </div>
    </div>
  </body>
</html>
</code>```

Check out the @Jiib answer to fix your style issue and you'll be done.

Body:
I am quite new to JavaScript and I am trying to implement a slider. Below is the javascript code that I am trying to solve.

    <title> Home Page </title>

It is not working and the images are static. Any idea why? Thanks for helping in advance.

Body:
You need to use jquery in order to be able to use that plugin.

<html>
  <head>
    <title>
      Home Page
    </title>
    <!-- here -->
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script type="text/javascript">
      $("#slideshow > div:gt(0)").hide();

      setInterval(function() {
        $('#slideshow > div:first')
          .fadeOut(1000)
          .next()
          .fadeIn(1000)
          .end()
          .appendTo('#slideshow');
      }, 3000);
    </script>
  </head>
  <body>
    <div id="slideshow">
      <div>
        <img src="http://vectorlogofree.com/wp-content/uploads/2014/04/23656-apple-logo-icon-vector-icon-vector-eps.png">
      </div>
      <div>
        <img src="http://vignette4.wikia.nocookie.net/memoryalpha/images/0/02/Linux_icon.png/revision/latest?cb=20141003183250&path-prefix=en">
      </div>
      <div>
      </div>
    </div>
  </body>
</html>

Check out the @Jiib answer to fix your style issue and you'll be done.


问:
Partial specialization for pointers, c++
How to make partial specialization of the class GList so that it is possible to store pointers of I (i.e I*) ?</p>

```<code>template <class I>
struct TIList
{
    typedef std::vector <I> Type;
};

template <class I>
class GList
{
      private:
            typename TIList <I>::Type objects;
};
</code>```

答:
Previous post states that you don't NEED to specialize for pointer types, but you might.

Consider the following:

```<code>struct Bar {
    void bar(void) { /* do work */ }
};

template <class T> struct Foo {
    T t;

    void foo(void)
    {
        t.bar(); // If T is a pointer, we should have used operator -> right?
    }
};

int main(int argc, char * argv[])
{
    Foo<Bar *> t;

    t.foo();
}
</code>```

This won't compile. Because in Foo::foo we have a pointer yet we use it as variable.

If you add the following, it will use the specialization and compile fine:

```<code>// This is a pointer to T specialization!
template <class T> class Foo<T *> {
    T * t;
public:
    void foo(void)
    {
        t->bar();
    }
};
</code>```

Body:
How to make partial specialization of the class GList so that it is possible to store pointers of I (i.e I*) ?

template <class I>
struct TIList
{
    typedef std::vector  Type;
};

template <class I>
class GList
{
      private:
            typename TIList ::Type objects;
};

Body:
Previous post states that you don't NEED to specialize for pointer types, but you might.

Consider the following:

struct Bar {
    void bar(void) { /* do work */ }
};

template <class T> struct Foo {
    T t;

    void foo(void)
    {
        t.bar(); // If T is a pointer, we should have used operator -> right?
    }
};

int main(int argc, char * argv[])
{
    Foo<Bar *> t;

    t.foo();
}

This won't compile. Because in Foo::foo we have a pointer yet we use it as variable.

If you add the following, it will use the specialization and compile fine:

// This is a pointer to T specialization!
template <class T> class Foo<T *> {
    T * t;
public:
    void foo(void)
    {
        t->bar();
    }
};


问:
Geocode in Twitter API doesn't work
Can somebody tell me about Twitter Search API with geolocation filter?

I'm trying to use

```<code>GET https://api.twitter.com/1.1/search/tweets.json?oauth_consumer_key=*************&oauth_token=************-**********************&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1502873578&oauth_nonce=*****&oauth_version=1.0&oauth_signature=%****************%3D&q=ffdp&geocode=45.458626,9.181872999999996,150mi
</code>```

45.458626,9.181872999999996 - Milan, Italy

And I have no statuses, but if I try this query, using advanced search:

https://twitter.com/search?l=&q=ffdp%20near%3A%22Milan%2C%20Lombardy%22%20within%3A15mi&src=typd&lang=en

I have some statuses.

Can somebody describe me, please, does it work? Or, maybe there are some mistake in my request?

答:
Try setting up your retrieval parameters like this
["geocode" => "Lon,Lat,Radius"]

for example

```<code>["geocode" => "37.781157,-122.398720,1mi"]
</code>```

Title: Geocode in Twitter API doesn't work

Body:
Can somebody tell me about Twitter Search API with geolocation filter?

I'm trying to use

GET https://api.twitter.com/1.1/search/tweets.json?oauth_consumer_key=*************&oauth_token=************-**********************&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1502873578&oauth_nonce=*****&oauth_version=1.0&oauth_signature=%****************%3D&q=ffdp&geocode=45.458626,9.181872999999996,150mi

45.458626,9.181872999999996 - Milan, Italy

And I have no statuses, but if I try this query, using advanced search:

https://twitter.com/search?l=&q=ffdp%20near%3A%22Milan%2C%20Lombardy%22%20within%3A15mi&src=typd&lang=en

I have some statuses.

Can somebody describe me, please, does it work? Or, maybe there are some mistake in my request?

Body:
Try setting up your retrieval parameters like this
["geocode" => "Lon,Lat,Radius"]

for example

["geocode" => "37.781157,-122.398720,1mi"]


问:
Importing data from excelsheet file into the mysql database C#
I have the following lines of code:

```<code>     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}
</code>```

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

答:
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this</p>

```<code>string file_name = Path.GetFileName(FileUpload1.FileName);
    string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();
    FileUpload1.SaveAs(Excel_path);
    OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended

Properties=Excel 8.0;Persist Security Info=False");
        OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
        if(dtExceldata.Rows.Count>0)
        {
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
            {
                //assign value to variable
                //like below
                //string ex_uid = dtExceldata.Rows[i]["columnName"];
                //then insert operation here

            }
    }
</code>```

Body:
I have the following lines of code:

     protected void btnUpload_Click(object sender, EventArgs e)
{

        MySqlTransaction transaction;

        string ex_id = "";

        string file_name = Path.GetFileName(FileUpload1.FileName);
        string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();//just added
    FileUpload1.SaveAs(Excel_path);

        OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
    my_con.Open();
    OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
    if (dtExceldata.Rows.Count > 0)
    {
        //foreach (DataRow row in dtExceldata.Rows)
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)

        {

                string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
                //string ex_dir = row["website_a"].ToString();

                string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
                // string ex_email = row["email_id"].ToString();

                string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
                //string ex_email1 = row["email_id2"].ToString();

                string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
                //string ex_email2 = row["email_id3"].ToString();

                string ex_company = dtExceldata.Rows[i]["company"].ToString();
                //string ex_company = row["company"].ToString();

                string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
                //string ex_contact = row["contact_name"].ToString();

                string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
                // string ex_proposal = row["proposal_status"].ToString();

                string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
                //string ex_reason = row["reason"].ToString();

        int chk = 0;
            int type = 0;
            int dup = 0;
            int dir = 0;

            if (ddlwebsites.SelectedIndex != 0)
            {
                dir = Convert.ToInt32(ddlwebsites.SelectedValue);
                if (dir == 8)
                {
                    type = 1;
                }

            }

            foreach (ListItem lstAssign in ddlevents.Items)
            {
                if (lstAssign.Selected == true)
                {
                    chk = 1;
                }
            }

            if (type == 1 && chk == 0)
            {
                evyerror.Text = "Please Select the Event!!";
                return;

            }

            else
            {
                string querycomp = "", compID = "";
                querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
                string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                connect = new MySqlConnection(connStr);
                connect.Open();
                transaction = connect.BeginTransaction();
                try
                {
                    ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
                    DataTable dt = clsDtResult.GetDataTable(querycomp);
                    if (dt.Rows.Count > 0)
                    {
                        compID = dt.Rows[0]["comp_id"].ToString();
                        ViewState["comp_id"] = compID;
                        if (type == 1)
                        {
                            dup = checkforDuplicates(Convert.ToInt32(compID));
                            if (dup == 1)
                            {
                                //Confirm_MP.Show();
                                // ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
                            }

                        }
                        //return;
                    }
                    else
                    {

                        string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
                        MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
                        cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?website", ex_dir);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = "Select LAST_INSERT_ID()";
                        compID = cmd.ExecuteScalar().ToString();
                        transaction.Commit();
                        connect.Close();

                    }
                }
                catch
                {
                    transaction.Rollback();
                }

                if (dup == 0)
                {
                    // create a connection string with your sql database
                    string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
                    connect = new MySqlConnection(connStr1);
                    connect.Open();
                    DateTime date = new DateTime();
                    date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
                    string SentDateString = date.ToString("yyyy/MM/dd");
                    //DateTime date = new DateTime();
                    //if (!string.IsNullOrEmpty(ex_date))
                    // {
                    //DateTime date = new DateTime();//added by chetan
                    //ex_date = ex_date.Split(' ')[0];//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
                    //string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
                    //DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
                    //// DateTime date = DateTime.Parse(ex_date);//added by chetan

                    // }
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
                    //date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
                    // string SentDateString = date.ToString("yyyy/MM/dd");
                    transaction = connect.BeginTransaction();
                    try
                    {

                        string ex_uid = Session["session_barterUser_id"].ToString();

                        MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);

                        cmd.Parameters.AddWithValue("?uid", ex_uid);
                        cmd.Parameters.AddWithValue("?comp", compID);

                        cmd.Parameters.AddWithValue("?sentdate", SentDateString);
                        // command.Parameters.AddWithValue("?event", eventname);
                        cmd.Parameters.AddWithValue("?dir", dir);
                        // command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
                        // command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
                        //cmd.Parameters.AddWithValue("?comp", ex_company);
                        cmd.Parameters.AddWithValue("?cont_name", ex_contact);
                        cmd.Parameters.AddWithValue("?email", ex_email);
                        cmd.Parameters.AddWithValue("?email2", ex_email1);
                        cmd.Parameters.AddWithValue("?email3", ex_email2);
                        cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
                        cmd.Parameters.AddWithValue("?reason", ex_reason);
                        cmd.Parameters.AddWithValue("?type", type);
                        // command.Parameters.AddWithValue("?type", type);

                        cmd.ExecuteNonQuery();
                        if (type == 1)
                        {

                            cmd.CommandText = "Select LAST_INSERT_ID()";
                            Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
                            int eventAssignID;
                            string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";

                            foreach (ListItem lstAssign in ddlevents.Items)
                            {
                                if (lstAssign.Selected == true)
                                {
                                    cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
                                    cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
                                    eventAssignID = Convert.ToInt32(lstAssign.Value);
                                    cmd.Parameters.AddWithValue("?event_id", eventAssignID);
                                    cmd.ExecuteNonQuery();

                                }
                            }

                        }//end of if
                        transaction.Commit();
                        connect.Close();
                        Response.Write("");
                    }//end of try
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Response.Write("");
                    }
                    finally
                    {
                        connect.Close();

                    }

                }//ifdupzero
            }//else
        }//for//foreach
      }//while //if

   // dr.Close();//commented by chetan

    my_con.Close();
    if (System.IO.File.Exists(Excel_path))
    {
        System.IO.File.Delete(Excel_path);
    }

}

suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.

Body:
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this

string file_name = Path.GetFileName(FileUpload1.FileName);
    string Excel_path = Server.MapPath("~/Excel/" + file_name);
    DataTable dtExceldata = new DataTable();
    FileUpload1.SaveAs(Excel_path);
    OleDbConnection my_con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended

Properties=Excel 8.0;Persist Security Info=False");
        OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
        da.Fill(dtExceldata);
        if(dtExceldata.Rows.Count>0)
        {
            for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
            {
                //assign value to variable
                //like below
                //string ex_uid = dtExceldata.Rows[i]["columnName"];
                //then insert operation here

            }
    }


问:
How to send binary data from a Node.js socket.io (v2.0.x) server to a browser client?

Engine.io send function do send binary data as binary, it can be seen
in as binary in DevTools.

Socket.io handles it as json ans sends it
as text.

May be somehow Engine.io send function can be accessed via Socket.io instance?

May be I need to re-implement custom encoder/decoder for this?

答:
Answering my own question because may be it will save some time for someone.

Found out that binary data in format of Uint8Array cannot be sended properly, it is just needed to be converted to regular Buffer with new Buffer(...) and it will be transported by wire as binary


问:
Python: OSError: [Errno 22] Invalid argument: '*.txt'
I have a script that I want to use in order to enumerate all file types in a folder:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import argparse
import magic
import os

# Argparse starts here
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None)
args = parser.parse_args()

for files in args.input:
    if magic.from_file(files,mime=True) == "text/plain":
        print (files, "=" , magic.from_file(files,mime=True) )
</code>```

it works pretty well when I input a file:

even when I input two files:

but not when I input ALL files:

The error says:

```<code>Traceback (most recent call last):
  File "Test.py", line 15, in <module>
    if magic.from_file(files,mime=True) == "text/plain":
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 135, in from_file
    return m.from_file(filename)
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 85, in from_file
    with open(filename):
OSError: [Errno 22] Invalid argument: '*.txt'
</code>```

But *.txt is exactly what I want to input; I also would like to input whatever file *.*

Is this a problem related to python-magic or caused by the way I input the files?

答:
trying to open a file called *.txt makes no sense. open doesn't support opening multiple files with a wildcard.

If you want to loop on every file, you have to perform multiple opens for that, using glob.glob to return the matching filenames

```<code>import glob
for fexp in glob.glob(filename):
    with open(fexp) as f:
      # do something with the opened file
      pass
</code>```

note that if the directory is wrong, glob.glob returns an empty list.

Body:
I have a script that I want to use in order to enumerate all file types in a folder:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import argparse
import magic
import os

# Argparse starts here
parser = argparse.ArgumentParser()
parser.add_argument('-input', dest='input',help="input one or more files",nargs='+',metavar=None)
args = parser.parse_args()

for files in args.input:
    if magic.from_file(files,mime=True) == "text/plain":
        print (files, "=" , magic.from_file(files,mime=True) )

it works pretty well when I input a file:

even when I input two files:

but not when I input ALL files:

The error says:

Traceback (most recent call last):
  File "Test.py", line 15, in <module>
    if magic.from_file(files,mime=True) == "text/plain":
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 135, in from_file
    return m.from_file(filename)
  File "C:\Users\FrancescoM\AppData\Local\Programs\Python\Python36-32\lib\site-packages\magic\magic.py", line 85, in from_file
    with open(filename):
OSError: [Errno 22] Invalid argument: '*.txt'

But *.txt is exactly what I want to input; I also would like to input whatever file *.*

Is this a problem related to python-magic or caused by the way I input the files?

Body:
trying to open a file called *.txt makes no sense. open doesn't support opening multiple files with a wildcard.

If you want to loop on every file, you have to perform multiple opens for that, using glob.glob to return the matching filenames

import glob
for fexp in glob.glob(filename):
    with open(fexp) as f:
      # do something with the opened file
      pass

note that if the directory is wrong, glob.glob returns an empty list.


问:
NodeJS - infinite call on promise functions
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

```<code>const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);
</code>```

Failing code

```<code>const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);
</code>```

答:
Rewrite your saveLtcPrice to resolve after the insert was done: </p>

```<code>// get current litecoin price from Bitfinex
function getLtcPrice(){
   return new Promise(function(resolve, reject){
       request.get(ltc_url, function (error, response, body) {
           if (error) reject(error)

           var rep = JSON.parse(body);
           var ltc_price = rep.ask;
           resolve (ltc_price)
       });
   })
}

//save current litecoin price to the database
function saveLtcPrice (ltc_price){
    return new Promise(function(resolve, reject){
        db_name.insert({
            _id: nonce,
            currency:"Litecoin",
            price: ltc_price
        }, function(error, body) {
            if(error) reject(error)

            console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
            resolve(body)
      })
  });
}

Promise.resolve().then(function resolver() {
    return getLtcPrice().then(function(ltcPrice){
        return saveLtcPrice(ltcPrice);
    }).then(resolver)// both functions ended, call them again
}).catch((error) => {
    console.log("Error: " + error);
});
</code>```

Body:
I'm looking for a way to call infinitely a functions with promises.
I tried 2 scenarios, one works the other don't.
The aim of the code that doesn't works is to: get data from an API and then store it into a database.

I'm learning promises, can someone explain me why one is working and the other don't ?
Below my codes

Working code
The function is called only once, I'm looking to get it called infinitly

const request = require('request') //node to facilitate http request
var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
var db_name  = nano.db.use('bitfinex'); //couchdb database name
var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
var nonce = new Date().toISOString()  //gives a unique id
                      .replace(/T/, ' ')    // replace T with a space
                      .replace(/\..+/, '')     // delete the dot and everything after

let cleanTheRoom = function() {
      return new Promise(function(resolve, reject) {
        resolve('Cleaned the Room, ');
      });
    };

  let removedTheGarbage = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg + 'removed the garbage, ');
    });
  };

  let getIcecream = function(msg) {
    return new Promise(function(resolve, reject) {
      resolve(msg +'got icecream.');
    });
  };

setInterval(function(){
  cleanTheRoom()
    .then(removedTheGarbage)
    .then(getIcecream)
    .then(function(msg) {
    console.log(msg );
  });
}, 2000);

Failing code

const request = require('request') //node to facilitate http request
    var nano    = require('nano')('http://admin:12345@localhost:5984'); //connect to couchdb using id and password
    var db_name  = nano.db.use('bitfinex'); //couchdb database name
    var ltc_url = 'https://api.bitfinex.com/v1/pubticker/ltcusd' //entry point
    var nonce = new Date().toISOString()  //gives a unique id
                          .replace(/T/, ' ')    // replace T with a space
                          .replace(/\..+/, '')     // delete the dot and everything after

// get current litecoin price from Bitfinex

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url,
        function (error, response, body) {
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
          resolve (ltc_price)
        if (error){
          reject(ltc_price)
          }
      });
    })
  }

//save current litecoin price to the database

function saveLtcPrice (ltc_price){
      return new Promise(function(resolve, reject){
        resolve(
        db_name.insert({ _id: nonce, currency:"Litecoin", price: ltc_price},
           function(err, body) {
             if (!err)
             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
          })
          )
      });
    }

setInterval(function(){
  getLtcPrice()
    .then(function(ltcPrice){
      saveLtcPrice(ltcPrice);
    });
}, 2000);

Body:
Rewrite your saveLtcPrice to resolve after the insert was done:

// get current litecoin price from Bitfinex
function getLtcPrice(){
   return new Promise(function(resolve, reject){
       request.get(ltc_url, function (error, response, body) {
           if (error) reject(error)

           var rep = JSON.parse(body);
           var ltc_price = rep.ask;
           resolve (ltc_price)
       });
   })
}

//save current litecoin price to the database
function saveLtcPrice (ltc_price){
    return new Promise(function(resolve, reject){
        db_name.insert({
            _id: nonce,
            currency:"Litecoin",
            price: ltc_price
        }, function(error, body) {
            if(error) reject(error)

            console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
            resolve(body)
      })
  });
}

Promise.resolve().then(function resolver() {
    return getLtcPrice().then(function(ltcPrice){
        return saveLtcPrice(ltcPrice);
    }).then(resolver)// both functions ended, call them again
}).catch((error) => {
    console.log("Error: " + error);
});


问:
is this Laravel Relationship error undefined variable $task
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

```<code>@foreach($task->files as $file) //line 14
                <div>
                    <div><i class="fa fa-check-square-o"></i>
                        <span>

                            <a href="{{ $file->file_url }}" target="_blank">{{ $file->file_name }}</a>

                   </span>
                    </div>
                </div>
</code>```

and My FileController is this

```<code>use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);
</code>```

and route is this

```<code>Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);
</code>```

but got this error

```<code>ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)
</code>```

how can fix this problem?

file Model

```<code>use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}
</code>```

答:
You have to pass the $task collection to your blade view as shown below</p>

```<code>$task = Task::all() //collect task collection as per your logic
return view('files.form', compact('task'));
</code>```

Body:
I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file

@foreach($task->files as $file) //line 14

                            file_url }}" target="_blank">{{ $file->file_name }}

and My FileController is this

use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
    {
         $this->validate($request, [
            'file_name'     => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
        ]);

        $filename     = $request->file('file_name')->getRealPath();

        Cloudder::upload($filename, null);
        list($width, $height) = getimagesize($filename);

$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
        $this->saveUploads($request, $fileUrl, $id,$taskId);

and route is this

Route::post('projects/{projects}/tasks/{tasks}/', [
     'uses' => 'FilesController@uploadAttachments',
     'as'   => 'projects.files',
     'middleware' => ['auth']
]);

but got this error

ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)

how can fix this problem?

file Model

use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    public function scopeProject($query, $id)
    {
        return $query->where('project_id', $id);
    }

    public function scopeTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    public function task(){
    return $this->belongsTo(Task::class);
}

Body:
You have to pass the $task collection to your blade view as shown below

$task = Task::all() //collect task collection as per your logic
return view('files.form', compact('task'));


问:
To insert a single quotes in a table using query
I want to insert single quotes with the data in which I am trying to insert it in a mysql table
Example    id    column
           1     data='rose'

data='rose' should be saved under column
 My Actual query is UPDATE test SET ItemType ='doctype="\'text'\"'WHERE ITEMINDEX='221'

答:
Thanks.The following code solved my issue
UPDATE test SET ItemType ='doctype=''text''' WHERE ITEMINDEX='221'</p>


问:
How to prevent page from refreshing on selection of First Drop Down List value
I have Two 'DropDownLists' which I want to Fill with the help of first 'DropDownList'. I have successfully filled both 'DropDownLists' but when I select the value from the first 'DropDownList', my page refreshes every time. Please help me. What should I do or how to prevent page form refreshing?</p>

答:
Use Ajax update panel for unwanted refreshing the page
the scriptmanager use in body tag.

```<code><asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</code>```

and then use following code .

```<code><asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server>
    </asp:DropDownList>
  </ContentTemplate>
</asp:UpdatePanel>
</code>```

Body:
Use Ajax update panel for unwanted refreshing the page
the scriptmanager use in body tag.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

and then use following code .

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>
    <asp:DropDownList ID="DropDownList1" runat="server>
    </asp:DropDownList>
  </ContentTemplate>
</asp:UpdatePanel>


问:
How to encrypt a field in a custom table / DAC
I have a custom table where I'd like to make sure that the data for a specific field are encrypted.  This means that if a query is run on that table, the data for that field would show up as an encrypted string, and only the UI would show its true value.

I've noticed someone else submitted the following case on October 18th, but no one has answered this:
Encrypt Fields in a Custom Table

Is there any documented (or undocumented) process to do this?

答:
In short - You should use PXRSACryptStringAttribute. In the App_Data\CodeRepository\PX.Objects folder you can find examples of PXRSACryptStringAttribute usage.

To learn more about encryption - see "Managing Data Encryption" on help.acumatica.com.


问:
Getting value from associated model
My setup: Rails 2.3.10, Ruby 1.8.7

Here are my models

```<code>class User
 has_many :user_projects
end

class Project
 has_many :user_projects
 #has a column named "project_type"
end

class UserProject
 belongs_to :user
 belongs_to :project
 #fields: project_id, user_id
end
</code>```

When I return a JSON string of a user and his related user_projects records, I also want to include in the user_project record the project.project_type column. Note: I don't want to also include the entire project record in the results. A possible solution is dup the project_type field in user_projects but I prefer not to do that if possible, is there another way to accomplish this during the find/read action?

Just to be clear, here's the JSON output I'm looking for

```<code>{
  "user": {
    "username": "bob",
    "id": 1,
    "email": "bob@blah.com"
    "user_projects": [
      {
            "id": 15,
            "user_id": 1,
            "project_id": 10,
            "project_type": "marketing"
      }
      {
            "id": 22,
            "user_id": 1,
            "project_id": 11,
            "project_type": "sales"
      }
     ]
}
</code>```

答:
You could try using the :only key in a nested include:

```<code>user.to_json(:include => {:user_projects => {:include => {:project => {:only => :type}}}})
</code>```

But I would add has_many :projects, :through => :user_projects to User so you can do the simpler:

```<code>user.to_json(:include => {:projects => {:only => [:id, :type]}})
</code>```

Also, an off-topic cautionary note: never use 'type' as a column name in Rails unless you are using STI (ie. the project types are ruby subclasses of Project).

-

Edit

Here's a way to add project_type to UserProject like you want

```<code>class UserProject
  belongs_to :user
  belongs_to :project
  delegate :type, :to => :project, :prefix => true
end

user.to_json(:include => {:user_projects => {:methods => :project_type}})
</code>```

Title: Getting value from associated model

Body:
My setup: Rails 2.3.10, Ruby 1.8.7

Here are my models

class User
 has_many :user_projects
end

class Project
 has_many :user_projects
 #has a column named "project_type"
end

class UserProject
 belongs_to :user
 belongs_to :project
 #fields: project_id, user_id
end

When I return a JSON string of a user and his related user_projects records, I also want to include in the user_project record the project.project_type column. Note: I don't want to also include the entire project record in the results. A possible solution is dup the project_type field in user_projects but I prefer not to do that if possible, is there another way to accomplish this during the find/read action?

Just to be clear, here's the JSON output I'm looking for

{
  "user": {
    "username": "bob",
    "id": 1,
    "email": "bob@blah.com"
    "user_projects": [
      {
            "id": 15,
            "user_id": 1,
            "project_id": 10,
            "project_type": "marketing"
      }
      {
            "id": 22,
            "user_id": 1,
            "project_id": 11,
            "project_type": "sales"
      }
     ]
}

Body:
You could try using the :only key in a nested include:

user.to_json(:include => {:user_projects => {:include => {:project => {:only => :type}}}})

But I would add has_many :projects, :through => :user_projects to User so you can do the simpler:

user.to_json(:include => {:projects => {:only => [:id, :type]}})

Also, an off-topic cautionary note: never use 'type' as a column name in Rails unless you are using STI (ie. the project types are ruby subclasses of Project).

-

Edit

Here's a way to add project_type to UserProject like you want

class UserProject
  belongs_to :user
  belongs_to :project
  delegate :type, :to => :project, :prefix => true
end

user.to_json(:include => {:user_projects => {:methods => :project_type}})


问:
How can I use Jest to spy on a method call?
I recently wanted to test that some custom method gets conditionally called in the componentDidMount method of a React component.

```<code>componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}
</code>```

I'm using Jest as my testing framework, which includes jest.fn() for mocks/spies.  I've read that this would be fairly trivial to test with Sinon, by doing something like the following:

```<code>sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
</code>```

I'm trying to recreate this with Jest like so:

```<code>Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
</code>```

This code fails and throws the following error:

```<code>jest.fn() value must be a mock function or spy.
Received:
  function: [Function bound mockConstructor]
</code>```

Is it possible to test this functionality with Jest? And if so, how?

答:
I know its a bit late, but I came across this and would suggest that to test componentDidMount initiates the call to your nested method that your test should look something like:

Module

```<code>componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}
</code>```

Test - Good

```<code>it('should call methodName during componentDidMount', () => {
    const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
    const wrapper = mount(<MyComponent {...props} />);
    expect(methodNameFake).toHaveBeenCalledTimes(1);
});
</code>```

If you call componentDidMount then the assertion that methodName was called via componentDidMount is more valid.

Test - Bad

```<code>it('should call methodName during componentDidMount', () => {
    const spy = jest.spyOn(Component.prototype, 'methodName');
    const wrapper = mount(<Component {...props} />);
    wrapper.instance().methodName();
    expect(spy).toHaveBeenCalled();
}
</code>```

By writing the test like this - you call the method and then assert that it was called. Which of course it will have given you just called it.

Body:
I recently wanted to test that some custom method gets conditionally called in the componentDidMount method of a React component.

componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}

I'm using Jest as my testing framework, which includes jest.fn() for mocks/spies.  I've read that this would be fairly trivial to test with Sinon, by doing something like the following:

sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();

I'm trying to recreate this with Jest like so:

Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();

This code fails and throws the following error:

jest.fn() value must be a mock function or spy.
Received:
  function: [Function bound mockConstructor]

Is it possible to test this functionality with Jest? And if so, how?

Body:
I know its a bit late, but I came across this and would suggest that to test componentDidMount initiates the call to your nested method that your test should look something like:

Module

componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}

Test - Good

it('should call methodName during componentDidMount', () => {
    const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
    const wrapper = mount(<MyComponent {...props} />);
    expect(methodNameFake).toHaveBeenCalledTimes(1);
});

If you call componentDidMount then the assertion that methodName was called via componentDidMount is more valid.

Test - Bad

it('should call methodName during componentDidMount', () => {
    const spy = jest.spyOn(Component.prototype, 'methodName');
    const wrapper = mount(<Component {...props} />);
    wrapper.instance().methodName();
    expect(spy).toHaveBeenCalled();
}

By writing the test like this - you call the method and then assert that it was called. Which of course it will have given you just called it.


问:
Horizontal swipe in mobile web view using combination of appium and watir
I am using  combination of appium-android and watir-cucumber in our automation  framework.

In mobile emulator i am opening one site in chrome browser.

I want to do horizontal swipe for one of the slider images.

Let me know if anyone know any idea to swipe image from left to right or vice a versa?

I have tried Appium's touch action but no luck so far.

答:
Take a look for https://github.com/Ricardonacif/touch_action
Touch action is what you should use for swiping</p>