问:
CoordinatorLayout element isn't declared
I'm a bit new to programming so bear with me. I'm trying to create a FAB menu by following ResoCoder's tutorial on youtube, but there's an issue with the CoordinatorLayout element being declared.

It throws this warning:

The 'android.support.design.widget.CoordinatorLayout' is not declared.

Here's the AXML file.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Hello FAB menu!"
    android:textSize="24sp"/>

  <View
    android:id="@+id/bg_fab_menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#48000000"
    android:alpha="0"
    android:visibility="gone"/>

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_airballoon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_23"
    android:visibility="gone"
    android:rotation="90"
    app:fabSize="mini"
    app:srcCompat="@drawable/ic_airballoon"/>

</android.support.design.widget.CoordinatorLayout>
</code>```

And here is an image of the warning.

Warning

edit:

This is now showing on the 'Designer' tab

Error on designer tab

答:
Short Answer :

It's just a warning and not an error, you could compile your project without any problem.

Long Answer :

The problem is that the Intellisense could not pick the attributes you type although those attributes did exists in android SDK. So the Visual Studio shows that :

```<code>The 'android.support.design.widget.CoordinatorLayout' is not declared.
</code>```

To solve this problem, you should enable Intellisense in Android .axml files. But a little difference with the document, you could download android-layout-xml.xsd and schemas.android.com.apk.res.android.xsd file from the following link :

https://github.com/atsushieno/monodroid-schema-gen/blob/master/android-layout-xml.xsd

https://github.com/atsushieno/monodroid-schema-gen/blob/master/schemas.android.com.apk.res.android.xsd

Download the file and  edit the android-layout-xml.xsd and add the  ConstraintLayout element. Then move these file manually to :

```<code>C:\Program Files (x86)\Microsoft Visual Studio 14.0\XML\Schemas\1033
</code>```

Or simply just add these schemas within Visual Studio. Restart your VS, this warning will be gone

Suggestion :

It is recommend that ignoring the warning, you could compile your project  without any problem.

Update :

Otherwise, after compiling I get errors like: 'Error: No resource found that matches the given name (at 'layout_margin' with value '@dimen/standard_23').' Which I assume are because of the CoordinatorLayout not being declared.

The dimen attribute need you create on yourself, make sure you copied the dimens.xml file too. You need create the dimens.xml in Resource\values\dimens.xml, define the standard_23 size in this file. Then the compile could find the standard_23 size.

dimen.xml :

```<code><?xml version="1.0" encoding="utf-8" ?>
<resources>
  <dimen name="action_button_min_width">56dp</dimen>
  <dimen name="indeterminate_progress_size">32dp</dimen>
  <dimen name="standard_23">23dp</dimen>

</resources>
</code>```

Body:
I'm a bit new to programming so bear with me. I'm trying to create a FAB menu by following ResoCoder's tutorial on youtube, but there's an issue with the CoordinatorLayout element being declared.

It throws this warning:

The 'android.support.design.widget.CoordinatorLayout' is not declared.

Here's the AXML file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Hello FAB menu!"
    android:textSize="24sp"/>

  <View
    android:id="@+id/bg_fab_menu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#48000000"
    android:alpha="0"
    android:visibility="gone"/>

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/fab_airballoon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/standard_23"
    android:visibility="gone"
    android:rotation="90"
    app:fabSize="mini"
    app:srcCompat="@drawable/ic_airballoon"/>

</android.support.design.widget.CoordinatorLayout>

And here is an image of the warning.

Warning

edit:

This is now showing on the 'Designer' tab

Error on designer tab

Body:
Short Answer :

It's just a warning and not an error, you could compile your project without any problem.

Long Answer :

The problem is that the Intellisense could not pick the attributes you type although those attributes did exists in android SDK. So the Visual Studio shows that :

The 'android.support.design.widget.CoordinatorLayout' is not declared.

To solve this problem, you should enable Intellisense in Android .axml files. But a little difference with the document, you could download android-layout-xml.xsd and schemas.android.com.apk.res.android.xsd file from the following link :

https://github.com/atsushieno/monodroid-schema-gen/blob/master/android-layout-xml.xsd

https://github.com/atsushieno/monodroid-schema-gen/blob/master/schemas.android.com.apk.res.android.xsd

Download the file and  edit the android-layout-xml.xsd and add the  ConstraintLayout element. Then move these file manually to :

C:\Program Files (x86)\Microsoft Visual Studio 14.0\XML\Schemas\1033

Or simply just add these schemas within Visual Studio. Restart your VS, this warning will be gone

Suggestion :

It is recommend that ignoring the warning, you could compile your project  without any problem.

Update :

Otherwise, after compiling I get errors like: 'Error: No resource found that matches the given name (at 'layout_margin' with value '@dimen/standard_23').' Which I assume are because of the CoordinatorLayout not being declared.

The dimen attribute need you create on yourself, make sure you copied the dimens.xml file too. You need create the dimens.xml in Resource\values\dimens.xml, define the standard_23 size in this file. Then the compile could find the standard_23 size.

dimen.xml :

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <dimen name="action_button_min_width">56dp</dimen>
  <dimen name="indeterminate_progress_size">32dp</dimen>
  <dimen name="standard_23">23dp</dimen>

</resources>


来源: stackexchange

问:
Android built in Camera encoder VS FFMPEG --- Speed
How does recording a 1080P, H264 encoded video in android camera application is realtime fast but encoding  a video in android using FFMPEG is slow at the same video size?

I know FFMPEG is a software level encoder and it wont support any hardware features.

I know camera applications directly get buffer data from camera driver.

But actually where the difference happens??

Why camera application is Realtime fast???

Does it use GPU and OpenGL features of the phone to encode the video so that its so realtime fast??

Because both Camera Application and FFMPEG runs on same mobile but still camera encodes H264 realtime ???

答:
I also met this problem,Bothering me for a long time.I solved the problem through this:

```<code>AVDictionary *param = 0;
//H.264
if (pCodecCtx->codec_id == AV_CODEC_ID_H264) {
//        av_dict_set(&param, "preset", "slow", 0);
    /**
    *
    * ultrafast,superfast, veryfast, faster, fast, medium
    * slow, slower, veryslow, placebo.　This is x264 encoding speed parameter
    */
    av_dict_set(&param, "preset", "superfast", 0);
    av_dict_set(&param, "tune", "zerolatency", 0);
}

if (avcodec_open2(pCodecCtx, pCodec, &param) < 0) {
    loge("Failed to open encoder!\n");
    return -1;
}
</code>```

you need set preset superfast or ultrafast

ContentLicense: CC BY-SA 3.0

Body:
I also met this problem,Bothering me for a long time.I solved the problem through this:

AVDictionary *param = 0;
//H.264
if (pCodecCtx->codec_id == AV_CODEC_ID_H264) {
//        av_dict_set(&param, "preset", "slow", 0);
    /**
    *
    * ultrafast,superfast, veryfast, faster, fast, medium
    * slow, slower, veryslow, placebo.　This is x264 encoding speed parameter
    */
    av_dict_set(&param, "preset", "superfast", 0);
    av_dict_set(&param, "tune", "zerolatency", 0);
}

if (avcodec_open2(pCodecCtx, pCodec, &param) < 0) {
    loge("Failed to open encoder!\n");
    return -1;
}

you need set preset superfast or ultrafast


问:
Angular 4 add click event on button dynamically
Here is the code of button displayed from loop.

```<code>for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "<tr>";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "<td>" + this.newTmpArr[k][key2] + "</td>";
        }

    }
    myTable += "</tr>";
}

test(){
  alert("Working!");
}
</code>```

Here is the screenshot of the page look like after dynamic data rendered.

答:
As said above you can use the *ngFor in your table row in your component.html file.
Then in the button tag handle the click event as you would normally do.

```<code><td> <button (click)="clickEvent()"> Click </button> </td>
</code>```

Then in your component.ts file define the on click event

```<code>clickEvent(){console.log("click event triggered")}
</code>```

Body:
Here is the code of button displayed from loop.

for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "
";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "" + this.newTmpArr[k][key2] + "	";
        }

    }
    myTable += "
";
}

test(){
  alert("Working!");
}

Here is the screenshot of the page look like after dynamic data rendered.

Body:
As said above you can use the *ngFor in your table row in your component.html file.
Then in the button tag handle the click event as you would normally do.

<td> <button (click)="clickEvent()"> Click </button> </td>

Then in your component.ts file define the on click event

clickEvent(){console.log("click event triggered")}


问:
Get count of orders that is closed in less than 30 minutes
The below query returns the following output

Output

```<code>OutletID    Avg Receive  Avg Ready  Avg Dispatch   Avg Close       Customers           Orders
32            58           29           0             200              6               6
23            27           1            0              3               7               3
</code>```

The Query

```<code>SELECT
  Outlets.OutletID,
  AVG(DATEDIFF(mi, Orders.OrderDate, ReceivedOrders.ReceivingDate)) AS [Avg Receive],
  AVG(DATEDIFF(mi, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)) AS [Avg Ready],
  AVG(DATEDIFF(mi, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)) AS [Avg Dispatch],
  AVG(DATEDIFF(mi, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)) AS [Avg Close],
  Count (dbo.Orders.CustomerID) as Customers,
  Count (dbo.Orders.OrderID)  as Orders
FROM dbo.Orders
INNER JOIN dbo.Outlets
  ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Brands
  ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.ReceivedOrders
  ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
LEFT JOIN dbo.ReadyOrders
  ON dbo.Orders.OrderID = dbo.ReadyOrders.OrderID
LEFT JOIN dbo.DispatchedOrders
  ON dbo.Orders.OrderID = dbo.DispatchedOrders.OrderID
LEFT JOIN dbo.ClosedOrders
  ON dbo.Orders.OrderID = dbo.ClosedOrders.OrderID
WHERE Orders.OrderDate BETWEEN '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
and dbo.Orders.OrderID not in (select OrderID from [dbo].[CanceledOrders])
GROUP BY Outlets.OutletID,
         Brands.BrandName,
         dbo.Outlets.OutletName
ORDER BY dbo.Outlets.OutletName, Brands.BrandName
</code>```

what i am looking for is to get count of orders that is closed under 30 minutes for each outlet so the output should be like below.

Desired Output

```<code>OutletID    Avg Receive  Avg Ready  Avg Dispatch   Avg Close       Customers           Orders   lessthan30
32            58           29           0             200              6               6           4
23            27           1            0              3               7               3           2
</code>```

The query to get the difference between closing time and order time

```<code>    SELECT
  COUNT(Orders.OrderID) AS [less30]
FROM [dbo].[Orders]
INNER JOIN dbo.ClosedOrders
  ON dbo.ClosedOrders.[OrderID] = Orders.OrderID
WHERE [OrderStatus] = 'Closed'
AND DATEDIFF(mi, Orders.OrderDate, ClosedOrders.ClosingDate) < 30
AND Orders.OrderDate BETWEEN  '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
</code>```

So how can i combine the tow queries into one query

答:
I dont have the exact schema but I think this should work </p>

```<code>SELECT
  Outlets.OutletID,
  AVG(DATEDIFF(mi, Orders.OrderDate, ReceivedOrders.ReceivingDate)) AS [Avg Receive],
  AVG(DATEDIFF(mi, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)) AS [Avg Ready],
  AVG(DATEDIFF(mi, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)) AS [Avg Dispatch],
  AVG(DATEDIFF(mi, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)) AS [Avg Close],
  Count (dbo.Orders.CustomerID) as Customers,
  Count (dbo.Orders.OrderID)  as Orders,
  count less30 as Closedin30
FROM dbo.Orders
INNER JOIN dbo.Outlets
  ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Brands
  ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.ReceivedOrders
  ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
LEFT JOIN dbo.ReadyOrders
  ON dbo.Orders.OrderID = dbo.ReadyOrders.OrderID
LEFT JOIN dbo.DispatchedOrders
  ON dbo.Orders.OrderID = dbo.DispatchedOrders.OrderID
LEFT JOIN dbo.ClosedOrders
  ON dbo.Orders.OrderID = dbo.ClosedOrders.OrderID
  left join
  (
    SELECT
    Orders.OrderID as less30
    FROM [dbo].[Orders]
        INNER JOIN dbo.ClosedOrders
    ON dbo.ClosedOrders.[OrderID] = Orders.OrderID
        WHERE [OrderStatus] = 'Closed'
    AND DATEDIFF(mi, Orders.OrderDate, ClosedOrders.ClosingDate) < 30
    AND Orders.OrderDate BETWEEN  '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
  ) closedIntime
  on
  (
  dbo.Orders.OrderID = closedIntime.less30
  )
WHERE Orders.OrderDate BETWEEN '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
and dbo.Orders.OrderID not in (select OrderID from [dbo].[CanceledOrders])
GROUP BY Outlets.OutletID,
         Brands.BrandName,
         dbo.Outlets.OutletName
ORDER BY dbo.Outlets.OutletName, Brands.BrandName
</code>```

Body:
The below query returns the following output

Output

OutletID    Avg Receive  Avg Ready  Avg Dispatch   Avg Close       Customers           Orders
32            58           29           0             200              6               6
23            27           1            0              3               7               3

The Query

SELECT
  Outlets.OutletID,
  AVG(DATEDIFF(mi, Orders.OrderDate, ReceivedOrders.ReceivingDate)) AS [Avg Receive],
  AVG(DATEDIFF(mi, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)) AS [Avg Ready],
  AVG(DATEDIFF(mi, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)) AS [Avg Dispatch],
  AVG(DATEDIFF(mi, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)) AS [Avg Close],
  Count (dbo.Orders.CustomerID) as Customers,
  Count (dbo.Orders.OrderID)  as Orders
FROM dbo.Orders
INNER JOIN dbo.Outlets
  ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Brands
  ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.ReceivedOrders
  ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
LEFT JOIN dbo.ReadyOrders
  ON dbo.Orders.OrderID = dbo.ReadyOrders.OrderID
LEFT JOIN dbo.DispatchedOrders
  ON dbo.Orders.OrderID = dbo.DispatchedOrders.OrderID
LEFT JOIN dbo.ClosedOrders
  ON dbo.Orders.OrderID = dbo.ClosedOrders.OrderID
WHERE Orders.OrderDate BETWEEN '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
and dbo.Orders.OrderID not in (select OrderID from [dbo].[CanceledOrders])
GROUP BY Outlets.OutletID,
         Brands.BrandName,
         dbo.Outlets.OutletName
ORDER BY dbo.Outlets.OutletName, Brands.BrandName

what i am looking for is to get count of orders that is closed under 30 minutes for each outlet so the output should be like below.

Desired Output

OutletID    Avg Receive  Avg Ready  Avg Dispatch   Avg Close       Customers           Orders   lessthan30
32            58           29           0             200              6               6           4
23            27           1            0              3               7               3           2

The query to get the difference between closing time and order time

    SELECT
  COUNT(Orders.OrderID) AS [less30]
FROM [dbo].[Orders]
INNER JOIN dbo.ClosedOrders
  ON dbo.ClosedOrders.[OrderID] = Orders.OrderID
WHERE [OrderStatus] = 'Closed'
AND DATEDIFF(mi, Orders.OrderDate, ClosedOrders.ClosingDate) < 30
AND Orders.OrderDate BETWEEN  '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'

So how can i combine the tow queries into one query

Body:
I dont have the exact schema but I think this should work

SELECT
  Outlets.OutletID,
  AVG(DATEDIFF(mi, Orders.OrderDate, ReceivedOrders.ReceivingDate)) AS [Avg Receive],
  AVG(DATEDIFF(mi, ReceivedOrders.ReceivingDate, ReadyOrders.ReadyDate)) AS [Avg Ready],
  AVG(DATEDIFF(mi, ReadyOrders.ReadyDate, DispatchedOrders.DispatchedDate)) AS [Avg Dispatch],
  AVG(DATEDIFF(mi, DispatchedOrders.DispatchedDate, ClosedOrders.ClosingDate)) AS [Avg Close],
  Count (dbo.Orders.CustomerID) as Customers,
  Count (dbo.Orders.OrderID)  as Orders,
  count less30 as Closedin30
FROM dbo.Orders
INNER JOIN dbo.Outlets
  ON dbo.Orders.OutletID = dbo.Outlets.OutletID
INNER JOIN dbo.Brands
  ON dbo.Brands.BrandID = dbo.Outlets.BrandID
INNER JOIN dbo.ReceivedOrders
  ON dbo.Orders.OrderID = dbo.ReceivedOrders.OrderID
LEFT JOIN dbo.ReadyOrders
  ON dbo.Orders.OrderID = dbo.ReadyOrders.OrderID
LEFT JOIN dbo.DispatchedOrders
  ON dbo.Orders.OrderID = dbo.DispatchedOrders.OrderID
LEFT JOIN dbo.ClosedOrders
  ON dbo.Orders.OrderID = dbo.ClosedOrders.OrderID
  left join
  (
    SELECT
    Orders.OrderID as less30
    FROM [dbo].[Orders]
        INNER JOIN dbo.ClosedOrders
    ON dbo.ClosedOrders.[OrderID] = Orders.OrderID
        WHERE [OrderStatus] = 'Closed'
    AND DATEDIFF(mi, Orders.OrderDate, ClosedOrders.ClosingDate) < 30
    AND Orders.OrderDate BETWEEN  '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
  ) closedIntime
  on
  (
  dbo.Orders.OrderID = closedIntime.less30
  )
WHERE Orders.OrderDate BETWEEN '01/Dec/2017 10:00 AM' AND '05/Dec/2017 12:00 am'
and dbo.Orders.OrderID not in (select OrderID from [dbo].[CanceledOrders])
GROUP BY Outlets.OutletID,
         Brands.BrandName,
         dbo.Outlets.OutletName
ORDER BY dbo.Outlets.OutletName, Brands.BrandName


问:
Validation only working for the first input field of loop
I have created a dynamic form using Angular that allows users to input email addresses. The user should not be allowed to add another empty field until the previous field is completed. Currently my code validates the first field correctly but will add a new field if the second, third, etc. is blank even though it will still fire the error alert.

Here is the HTML:

```<code><ion-item id="row" *ngFor="let emailinput of emailinputs ; let i = index">
  <ion-label fixed id="label">
    Email
  </ion-label>
  <ion-input type="email" id="email" placeholder="jdoe@gmail.com" [(ngModel)]="emailinputs[i].email"></ion-input>
</ion-item>

<div padding>
  <button (click) = "addnewemail(emailinputs)" ion-button full color="nudgetprim" block>Add</button>
  <button (click) = "sendinvite(emailinputs.email)" ion-button full color="nudgetprim" block>Invite</button>
</div>
</code>```

Here is the TS:

```<code>addnewemail() {
  console.log(this.emailinputs)
  for(var a in this.emailinputs){
    if (this.emailinputs[a].email==null || this.emailinputs[a].email=="" || !this.emailinputs[a].email.includes("@") || !this.emailinputs[a].email.includes("."))
    {
      let alert = this.alerCtrl.create({
        title: 'Error!',
        message: 'There was an error with an email address you entered.',
        buttons: ['Ok']
      });
      alert.present()
    }
    else {
      var newItem = this.emailinputs.length;
      this.emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem, 'email': ''});
    }
  }
}
</code>```

How can I make this work for every input, not just the first?

答:
You are now iterating the whole array, which means, if the code hits an item in your array that actually has values, it will add a new item in the array. What you want to check, is that the last item in your array does not have an empty (or invalid) email value:

addnewemail() {
  // get last item!
  let item = this.emailinputs[this.emailinputs.length-1];
    if (item.email == null ||
        item.email == "" ||
        !item.email.includes("@") ||
        !item.email.includes(".")) {
      // alert
    }
    else {
      // add new item
    }
}
```

StackBlitz

You could also try and use actual email validation, preferably making a reactive form (like suggested in comment) with Validators.email.

Body:
I have created a dynamic form using Angular that allows users to input email addresses. The user should not be allowed to add another empty field until the previous field is completed. Currently my code validates the first field correctly but will add a new field if the second, third, etc. is blank even though it will still fire the error alert.

Here is the HTML:

<ion-item id="row" *ngFor="let emailinput of emailinputs ; let i = index">
  <ion-label fixed id="label">
    Email
  </ion-label>
  <ion-input type="email" id="email" placeholder="jdoe@gmail.com" [(ngModel)]="emailinputs[i].email"></ion-input>
</ion-item>

  <button (click) = "addnewemail(emailinputs)" ion-button full color="nudgetprim" block>Add</button>
  <button (click) = "sendinvite(emailinputs.email)" ion-button full color="nudgetprim" block>Invite</button>

Here is the TS:

addnewemail() {
  console.log(this.emailinputs)
  for(var a in this.emailinputs){
    if (this.emailinputs[a].email==null || this.emailinputs[a].email=="" || !this.emailinputs[a].email.includes("@") || !this.emailinputs[a].email.includes("."))
    {
      let alert = this.alerCtrl.create({
        title: 'Error!',
        message: 'There was an error with an email address you entered.',
        buttons: ['Ok']
      });
      alert.present()
    }
    else {
      var newItem = this.emailinputs.length;
      this.emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem, 'email': ''});
    }
  }
}

How can I make this work for every input, not just the first?

Body:
You are now iterating the whole array, which means, if the code hits an item in your array that actually has values, it will add a new item in the array. What you want to check, is that the last item in your array does not have an empty (or invalid) email value:

addnewemail() {
  // get last item!
  let item = this.emailinputs[this.emailinputs.length-1];
    if (item.email == null ||
        item.email == "" ||
        !item.email.includes("@") ||
        !item.email.includes(".")) {
      // alert
    }
    else {
      // add new item
    }
}

StackBlitz

You could also try and use actual email validation, preferably making a reactive form (like suggested in comment) with Validators.email.


问:
How can i pass the parameter “username” to "/" router with express?

I have a db operation in login post router, when db operation callback success, I got a username value, and how I can pass this username to the "/" router?
</p>

```<code>router.post('/login', (req, res)=> {
    var username = req.body.username;
    var password = common.md5(req.body.password + common.MD5_SUFFIX);
    db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data)=> {
        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {
            if (data.length == 0) {
                res.status(404).send('no this admin').end();
            } else {
                if (data[0].password == password) {
                    req.session['admin_id']=data[0].ID;
                    res.redirect('/');

                } else {
                    res.status(404).send('This password is not incorrect!').end();
                }
            }
        }
    });
});
router.get('/login',(req,res)=>{
    res.render('admin/login.ejs',{layout:'/admin/layout.ejs',title:'Login'});
});
router.get('/',(req,res)=>{
    res.render('admin/index.ejs',{layout:'/admin/layout.ejs',title:'Index',username:username});
});
</code>```

<p>
Such as in post login router, I got a username is "ollie", when db operation is ending, the router redirect "/", I can got the username "ollie" in the "/" router .
</p>

答:
The simplest way is to use a session. E.g. where you configure the express app, use this:

```<code>if (data[0].password == password) {
    req.session['admin_id']=data[0].ID;
    req.session.username = data.username;
    res.redirect('/');
}
</code>```

Then later you can access that, e.g.

```<code>router.get('/route', (req, res) => {
    console.log(req.session && req.session.username);
    res.end(`Hi ${req.session && req.session.username}`)
});
</code>```

And please, please, please do not use md5 in any authentication schemes, even example code.

Body:
I have a db operation in login post router, when db operation callback success, I got a username value, and how I can pass this username to the "/" router?

router.post('/login', (req, res)=> {
    var username = req.body.username;
    var password = common.md5(req.body.password + common.MD5_SUFFIX);
    db.query(`SELECT * FROM admin_table WHERE username='${username}'`, (err, data)=> {
        if (err) {
            console.log(err);
            res.status(500).send('database error').end();
        } else {
            if (data.length == 0) {
                res.status(404).send('no this admin').end();
            } else {
                if (data[0].password == password) {
                    req.session['admin_id']=data[0].ID;
                    res.redirect('/');

                } else {
                    res.status(404).send('This password is not incorrect!').end();
                }
            }
        }
    });
});
router.get('/login',(req,res)=>{
    res.render('admin/login.ejs',{layout:'/admin/layout.ejs',title:'Login'});
});
router.get('/',(req,res)=>{
    res.render('admin/index.ejs',{layout:'/admin/layout.ejs',title:'Index',username:username});
});

Such as in post login router, I got a username is "ollie", when db operation is ending, the router redirect "/", I can got the username "ollie" in the "/" router .

Body:
The simplest way is to use a session. E.g. where you configure the express app, use this:

if (data[0].password == password) {
    req.session['admin_id']=data[0].ID;
    req.session.username = data.username;
    res.redirect('/');
}

Then later you can access that, e.g.

router.get('/route', (req, res) => {
    console.log(req.session && req.session.username);
    res.end(`Hi ${req.session && req.session.username}`)
});

And please, please, please do not use md5 in any authentication schemes, even example code.


问:
Is SQL the assembly for databases?
Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.

I think is soon to assert this, but I guess can be true on a near future, not sure.

UPDATE: The analogy I was referring means SQL is to assembly what ORM is to C/Java/C#. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only ORM (or ORM like) instead of SQL.

答: RPG is the assembly language of databases. :-)</p>

OwnerDisplayName: FerranB

ContentLicense: CC BY-SA 2.5

Title: Is SQL the assembly for databases?

LastEditorDisplayName: FerranB

OwnerDisplayName: stesch


问:
C++ - #include "filename"
At this tutorial it mentions the following about #include "filename":

#include "filename" tells the compiler to look for the file in
  directory containing the source file
  doing the #include. If that fails,
  it will act identically to the angled
  brackets case.

What is meant by the bolded font sentence?

Thanks.

答:
The bold bit simply means that, if the file specified inside quotes cannot be located using the " method, it will revert to the <> method.

I should mention that the bit about where it looks for the include files is actually incorrect. In both cases (quotes and angle brackets), the search locations are implementation defined.

From the lex.header section:

The sequences in both forms of header-names are mapped in an implementation-defined manner to headers or to external source file names as specified in 16.2.

The 16.2 section follows:

A #include directive shall identify a header or source file that can be processed by the implementation.

A preprocessing directive of the form

```<code># include < h-char-sequence> new-line
</code>```

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

```<code># include " q-char-sequence" new-line
</code>```

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

```<code># include < h-char-sequence> new-line
</code>```

with the identical contained sequence (including > characters, if any) from the original directive.

So the statement "... tells the compiler to look for the file in directory containing the source file doing the #include ..." is wrong. It's totally up to the implementation how it finds the files, in both cases.

Having said that, the rest is correct. If the method used by the " type does not locate the header, the method used by the <> type is then used. That's really all the bold bit means.

You just have to read the documentation for your particular implementation to see what those methods are.

Title: C++ - #include "filename"

Body:
The bold bit simply means that, if the file specified inside quotes cannot be located using the " method, it will revert to the <> method.

I should mention that the bit about where it looks for the include files is actually incorrect. In both cases (quotes and angle brackets), the search locations are implementation defined.

From the lex.header section:

The sequences in both forms of header-names are mapped in an implementation-defined manner to headers or to external source file names as specified in 16.2.

The 16.2 section follows:

A #include directive shall identify a header or source file that can be processed by the implementation.

A preprocessing directive of the form

# include < h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

# include " q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

# include < h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So the statement "... tells the compiler to look for the file in directory containing the source file doing the #include ..." is wrong. It's totally up to the implementation how it finds the files, in both cases.

Having said that, the rest is correct. If the method used by the " type does not locate the header, the method used by the <> type is then used. That's really all the bold bit means.

You just have to read the documentation for your particular implementation to see what those methods are.


问:
Exception handler doesn't return correct response
I have controller method with following signature:

```<code>@PostMapping("/rest_upload")
public DeferredResult<ResponseEntity> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
</code>```

And I have following exception handler:

```<code>@ExceptionHandler(MultipartException.class)
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
@ResponseBody
public String handleMaxUploadSizeExceededException(MultipartException e) {
    logger.warn("MultipartException occurred", e);
    String rootCauseMessage = ExceptionUtils.getRootCauseMessage(e);
    return rootCauseMessage.substring(rootCauseMessage.indexOf(":") + 1);
}
</code>```

This handler invokes when I send file with size(120MB) more than configurable maximum(100MB) But in browser I see following:

and details:

How can I fix this issue?

答:
this bean fixed my problem:</p>

```<code>@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        // configure maxSwallowSize
        if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
            // -1 means unlimited, accept bytes
            ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
    });
    return tomcat;
}
</code>```

Body:
I have controller method with following signature:

@PostMapping("/rest_upload")
public DeferredResult<ResponseEntity> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {

And I have following exception handler:

@ExceptionHandler(MultipartException.class)
@ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
@ResponseBody
public String handleMaxUploadSizeExceededException(MultipartException e) {
    logger.warn("MultipartException occurred", e);
    String rootCauseMessage = ExceptionUtils.getRootCauseMessage(e);
    return rootCauseMessage.substring(rootCauseMessage.indexOf(":") + 1);
}

This handler invokes when I send file with size(120MB) more than configurable maximum(100MB) But in browser I see following:

and details:

How can I fix this issue?

Body:
this bean fixed my problem:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
    TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
    tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
        // configure maxSwallowSize
        if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
            // -1 means unlimited, accept bytes
            ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
        }
    });
    return tomcat;
}


问:
Pass Dynamic values to the rules in ANTLR4 grammar
I am newbie to ANTLR4
I want to write a grammar that would parse the syntax using the values which it reads dynamically.
Say  my grammar is as follows in image

I need help such the HANDLERID not only takes the values mentioned,but a list of values based on a function call,dynamic values. For example a function return list containing {'ACD','GHY','XYZ' ..}. Not to confuse with identifier,these values are names of some defined set of objects, so writing a grammar for IDENTIFIER is not solution.

Any help is appeciated.

答:
Maybe actions are a viable solution? These are written in the target language and allow to do all kind of processing. Formulated as a predicate (appending a ? to the action block) they can even be used to guide the parser what path to take.

Here's a typical form:

```<code>decl: type ID ';' { System.out.println("found a decl"); };
</code>```

or as a predicate:

```<code>HANDLERID: ID { isSpecialWord($ID.text) }?;
</code>```

which will only be matched for IDs that your internal function isSpecialWord is returning true for. So essentially, you are not passing the lexer rule some values, but you do the evaluation in internal code.

Body:
Maybe actions are a viable solution? These are written in the target language and allow to do all kind of processing. Formulated as a predicate (appending a ? to the action block) they can even be used to guide the parser what path to take.

Here's a typical form:

decl: type ID ';' { System.out.println("found a decl"); };

or as a predicate:

HANDLERID: ID { isSpecialWord($ID.text) }?;

which will only be matched for IDs that your internal function isSpecialWord is returning true for. So essentially, you are not passing the lexer rule some values, but you do the evaluation in internal code.


问:
is there any wordpress plugin for MCQ questions not quiz?
I have an website stuffarrow.com in wordpress. I have to post some Multiple choice questions(MCQ). I searched the wordpress plugin directory with "mcq" there are hardly 2 plugins and they are not relevant.

Can someone please help me to find out any plugin for MCQ in plugin. there are lot of quiz plugins available, but not able to find the MCQ plugin.

Thanks

答: Thanks Stackoverflow for your support. I got this plugin wp-showhide. this  plugin solved my purpose.</p>


问:
Skipping headers and parsing xml to convert to json
I have a xml file like this:

```<code>  "HTTP/1.1 100 Continue
   HTTP/1.1 200 OK
   Expires: 0
   Buffer: false
   Pragma: No-cache
   Cache-Control: no-cache
   Server: Transaction_Server/4.1.0(zOS)
   Connection: close
   Content-Type: text/html
   Content-Length: 33842
   Date: Sat, 02 Aug 2014 09:27:02 GMT

 <?xml version=""1.0"" encoding=""UTF-8""?>
 <creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

 <document>response</document>
 <version>2.9</version>
 <transactionControl><userRefNumber>Credit Report Example</userRefNumber>
 <subscriber><industryCode>Z</industryCode></subscriber></transactionControl>
</code>```

This is just a part of the entire document. I want to convert this into json.
The problem is how to skip or delete the header part and start parsing from the real xml as in, starting from the <document> tag.

There are more than a million such files. I can't do it manually. How can I do it? Any help appreciated.

答:
You could use regex to select only the xml part
Something like: /<document>(.*)/gs or /"">(.*)/gs

but how are you fetching that website? This looks similar to something I've been doing with curl, but you should be able to get only body out from curl.

Then you use some library to convert xml to json.

For that part you can use something like Converting XML to JSON using Python?

P.S. (I know this would be better as a comment, but i don't have enough reputation so putting it here.)

Body:
I have a xml file like this:

  "HTTP/1.1 100 Continue
   HTTP/1.1 200 OK
   Expires: 0
   Buffer: false
   Pragma: No-cache
   Cache-Control: no-cache
   Server: Transaction_Server/4.1.0(zOS)
   Connection: close
   Content-Type: text/html
   Content-Length: 33842
   Date: Sat, 02 Aug 2014 09:27:02 GMT

 <?xml version=""1.0"" encoding=""UTF-8""?>
 <creditBureau xmlns=""http://www.transunion.com/namespace"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">

 <document>response</document>
 <version>2.9</version>
 <transactionControl><userRefNumber>Credit Report Example</userRefNumber>
 <subscriber><industryCode>Z</industryCode></subscriber></transactionControl>

This is just a part of the entire document. I want to convert this into json.
The problem is how to skip or delete the header part and start parsing from the real xml as in, starting from the <document> tag.

There are more than a million such files. I can't do it manually. How can I do it? Any help appreciated.


问:
set output path for cmake generated files
My question is the following:
Is there a way to tell CMakeFiles where to generate it's makefiles, such as cmake_install.cmake, CMakeCache.txt etc.?

More specifically, is there a way to set some commands in the CMakeFiles that specifies where to output these generated files? I have tried to search around the web to find some answers, and most people say there's no explicit way of doing this, while others say I might be able to, using custom commands. Sadly, I'm not very strong in cmake, so I couldn't figure this out.

I'm currently using the CLion IDE and there you can specifically set the output path through the settings, but for flexibility reasons I would like as much as possible to be done through the CMakeFiles such that compiling from different computers isn't that big of a hassle.

I would also like to avoid explicitly adding additional command line arguments etc.

I hope someone might have an answer for me, thanks in advance!

答:
You can't (easily) do this and you shouldn't try to do it.

The build tree is CMake's territory. It allows you some tiny amount of customization there (for instance you can specify where the final build artifacts will be placed through the *_OUTPUT_DIRECTORY target properties), but it does not give you any direct control over where intermediate files, like object files or internal make scripts used for bookkeeping are being placed.

This is a feature. You have no idea how all the build systems supported by CMake work internally. Maybe you can move that internal file to a different location in your build process, which is based on Unix Makefiles. But maybe that will also horribly break my build process, which is using Visual Studio. The bottom line is: You shouldn't have to care about this. CMake should take care of it, and by taking some freedom away from you, it ensures that it can actually do that job on all supported build toolchains.

But this might still be an unsatisfactory answer to you. You're the developer, shouldn't you be in full control of the results produced by your build? Of course you should, which is why CMake again grants you full control over what goes into the install tree. That is, whatever ends up in the install directory when you call make install (or whatever is the equivalent of installing in your build toolchain) is again under your control.

So you do control everything that matters: The source tree, the install tree, and that tiny portion of the build tree where the final build artifacts go. The rest of the build tree is off-limits for you and for good reasons.


问:
Trying to position a div below a button, but having trouble aligning it to the right side of the button
I'm using react, and I have a row of buttons, and one of these buttons should open a div that contains some information on click.

I'm having some trouble with the css though.  Here's an example fiddle: https://jsfiddle.net/4ovxw4eg/1/

And the snippet:

.container {
  display: flex;
  flex-direction: row;
}

.openItem {
  height: 200px;
  width: 200px;
  border: 1px solid black;
  position: absolute;
  right: 0;
}

.test {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button class="test">
    The Button
  </button>
</div>

<div class="openItem">
  This should be below and to the right edge of The Button
</div></code>```

How should I approach this issue?  I'm using a flex box for the row of buttons.

My react code has a check where if someProp is true, then show this box.  ie.  showPopup && renderPopup

答:
.container {
  display: inline-flex;
  flex-direction: row;
  position: relative;
}

.openItem {
  height: 200px;
  width: 200px;
  border: 1px solid black;
  position: absolute;
  right: 0;
  bottom: 0px;
}

.test {
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button class="test">
    The Button
  </button>
  <div class="openItem">
    This should be below and to the right edge of The Button
  </div>
</div></code>```

Body:
I'm using react, and I have a row of buttons, and one of these buttons should open a div that contains some information on click.

I'm having some trouble with the css though.  Here's an example fiddle: https://jsfiddle.net/4ovxw4eg/1/

And the snippet:

.container {
  display: flex;
  flex-direction: row;
}

.openItem {
  height: 200px;
  width: 200px;
  border: 1px solid black;
  position: absolute;
  right: 0;
}

.test {
  position: relative;
}

  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button class="test">
    The Button
  </button>

  This should be below and to the right edge of The Button

How should I approach this issue?  I'm using a flex box for the row of buttons.

My react code has a check where if someProp is true, then show this box.  ie.  showPopup && renderPopup

Body:
.container {
  display: inline-flex;
  flex-direction: row;
  position: relative;
}

.openItem {
  height: 200px;
  width: 200px;
  border: 1px solid black;
  position: absolute;
  right: 0;
  bottom: 0px;
}

.test {
  position: relative;
}

<div class="container">
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button>
    some button
  </button>
  <button class="test">
    The Button
  </button>
  <div class="openItem">
    This should be below and to the right edge of The Button
  </div>
</div>


问:
shiny app works locally, but not on shinyapps.io
i have created this app with sql server connection and its worked correctly on my device but after publishing it i get this error The application failed to start and this is what i get in this error page:

```<code>    Attaching package: ‘rsconnect’

The following object is masked from ‘package:shiny’:

    serverInfo

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

Attaching package: ‘RODBCext’

The following objects are masked from ‘package:RODBC’:

    odbcFetchRows, sqlFetchMore

Attaching package: ‘shinydashboard’

The following object is masked from ‘package:graphics’:

    box

Warning in odbcDriverConnect("driver={SQL Server};server=************;database=*******;uid=****;pwd=*****") :
  [RODBC] ERROR: state IM002, code 0, message [unixODBC][Driver Manager]Data source name not found, and no default driver specified
Warning in odbcDriverConnect("driver={SQL Server};server=************\\.,1435;database=************;uid=****;pwd=****") :
  ODBC connection failed
Error in value[[3L]](cond) : first argument is not an open RODBC channel
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
</code>```

my code will be here:
my app code

答: I solved this problem by using dbConnect & DBI libraries instead of RODBC and using RSQLServer::SQLServer() to open the connection on the sql server. and i thanks @PorkChop for give me a help in that.

ContentLicense: CC BY-SA 4.0

Body:
i have created this app with sql server connection and its worked correctly on my device but after publishing it i get this error The application failed to start and this is what i get in this error page:

    Attaching package: ‘rsconnect’

The following object is masked from ‘package:shiny’:

    serverInfo

Attaching package: ‘dplyr’

The following objects are masked from ‘package:stats’:

    filter, lag

The following objects are masked from ‘package:base’:

    intersect, setdiff, setequal, union

Attaching package: ‘RODBCext’

The following objects are masked from ‘package:RODBC’:

    odbcFetchRows, sqlFetchMore

Attaching package: ‘shinydashboard’

The following object is masked from ‘package:graphics’:

    box

Warning in odbcDriverConnect("driver={SQL Server};server=************;database=*******;uid=****;pwd=*****") :
  [RODBC] ERROR: state IM002, code 0, message [unixODBC][Driver Manager]Data source name not found, and no default driver specified
Warning in odbcDriverConnect("driver={SQL Server};server=************\\.,1435;database=************;uid=****;pwd=****") :
  ODBC connection failed
Error in value[[3L]](cond) : first argument is not an open RODBC channel
Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted

my code will be here:
my app code


问:
Scripts or commands for Moving files from a directory if it stays there for more than 30 min
I need to write a script which will move files that will stay in that directory for more than 30 min.
For example there is a dir called /var/test/ inside it there are some files coming in.
These files move to another directory for getting processed by another script ok.
So what happens is some of the files they don't get processed and stay in /var/test/ dir which i don't want.

I am using hp-unix and i tried this command:

```<code>find /var/home/dacorftp/prt_output/SAP-PO/input_special -maxdepth 1 -mmin -30 -type f -exec mv "{}" /var/home/dacorftp/prt_output/SAP-PO/ErrorFilesDir \;
</code>```

ErrorFilesDir is the directory where i want the moved files to get stored.

but the command doesn't work as maxdepth and mmin don't work on hp-unix.

Also can i add a utility which will mail me and tell that the file has been moved and you should start working on the  errors?

答:
On Linux you can do

find /path/to/search -type f -mmin +30 | xargs -I mv {} /destination/path

But for more complex logic (like check if the files have been moved and reload the source path file list) I would recommend using Golang application.

Body:
I need to write a script which will move files that will stay in that directory for more than 30 min.
For example there is a dir called /var/test/ inside it there are some files coming in.
These files move to another directory for getting processed by another script ok.
So what happens is some of the files they don't get processed and stay in /var/test/ dir which i don't want.

I am using hp-unix and i tried this command:

find /var/home/dacorftp/prt_output/SAP-PO/input_special -maxdepth 1 -mmin -30 -type f -exec mv "{}" /var/home/dacorftp/prt_output/SAP-PO/ErrorFilesDir \;

ErrorFilesDir is the directory where i want the moved files to get stored.

but the command doesn't work as maxdepth and mmin don't work on hp-unix.

Also can i add a utility which will mail me and tell that the file has been moved and you should start working on the  errors?


问:
MATLAB Environment Tweaks
How have you tweaked the MATLAB environment to better suit your needs?  One tweak per answer.</p>

答:
send the outputs to your email esp when the running is long
http://www.mathworks.com/matlabcentral/fileexchange/29183-sending-reports-and-timestamped-file-by-emailing

create a result collector for archiving and sending
http://www.mathworks.com/matlabcentral/fileexchange/29255-track-collect-and-tar-inputs-and-outputs

a patch to line up the file within a directory in proper order
http://www.mathworks.com/matlabcentral/fileexchange/29033-file-ordering-patch-utility-for-matlab

Title: MATLAB Environment Tweaks


问:
R: Error in bestglm - Error in if (any(Column1Test)) stop("Column of 1's can't be used! Intercept always included.")
I am trying to run the bestglm command but am getting the error message

Error in if (any(Column1Test)) stop("Column of 1's can't be used! Intercept always included.") : missing value where TRUE/FALSE needed

Below is the source code for the error message for the bestglm function:

```<code>#Test if there is a column of 1's in X.
#Only do this test if:
#1) X contains at least one column corresponding to a quantitative variable
#2) IncludeInterceptQ (intercept is included already)
if (!all(FactorsQ)&& IncludeInterceptQ){
    X2<-X[,!FactorsQ,drop=FALSE] #removing factor variables
    p2<-ncol(X2)
    Column1Test<-apply(X2-matrix(rep(1,n*p2),ncol=p2), MARGIN=2, function(x) 0==sum(abs(x)))
    if (any(Column1Test))
      stop("Column of 1's can't be used! Intercept always included.")
}
</code>```

I don't have a column of 1s in my data and I am at a loss as to what that means. Below is the code I am using. Can anyone help please?

```<code>#Lables all variables in the data file
allVars<- c('Full_ID','cen','fam','id','group','groupControlPersistPreterm','excludePersis','sefosgroup','sefosexclude','Conners_Parent',   'age','sex','IQ','ga','bw','sib','DIVA_Parent_score','Reasons_for_exclusion_CPT','exclude', 'Persistent_remitted_parent','Previous_ADHD_Status1','inattention','hypimp','subtype','BFISparent','adhdinptBFIS','adhd_parent','exclude_nogo15','exclude_cnv15','exclude_go15','N2inc_latencyFz','N2inc_ampFz','N2cong_latencyFz','N2cong_ampFz','N2inc_latencyFCz','N2inc_ampFCz','N2cong_latencyFCz','N2cong_ampFCz','Pe_latencyCz','Pe_ampCz',  'Pe_latencyCPz','Pe_ampCPz','PNe_latencyFz','PNe_ampFz','PNe_latencyFCz','PNe_ampFCz','ERN_latencyFz','ERN_ampFz','ERN_latencyFCz','ERN_ampFCz','cnv','cuep3_amp','Gop3_amp','Nogo_p3_amp','cue_p3_lat','Gop3_lat','Nogo_p3_lat','excluded_cuep3','excluded_go','excluded_nogo','excluded_cnv','CPT_OE','CPT_MRT',  'CPT_RTV','CPT_FalseAlarm','CPT_OnotX','PersistRemitControl_CPT','PersistRemit_CPT','exclude_background','exclude_GA','alphalg1','alphalg2','betalg1','betalg2','thetalg1','thetalg2','deltalg1','deltalg2','nogop3_czlat','nogop3_czamp','nogop3_czlat_BC','nogop3_czamp_BC','nogop3_fczlat','nogop3_fczamp','nogop3_fczlat_BC',   'nogop3_fczamp_BC', 'nogon2_fzlat', 'nogon2_fzamp', 'nogon2_fzlat_BC','nogon2_fzamp_BC','gop3_pzlat','gop3_pzamp','gop3_pzlat_BC','gop3_pzamp_BC','gop3_cpzlat','gop3_cpzamp','gop3_cpzlat_BC','gop3_cpzamp_BC','CNVcz','CNVcz_BC','CNVcpz','CNVcpz_BC','cuep3_pzlat','cuep3_pzamp','cuep3_pzlat_BC','cuep3_pzamp_BC','excludeGOseg','excludeNOGOseg','excludeCUEseg','segcue','segCNV','seggo','segnogo','CNV','excludeIQ','excludeGA','excludeADHDga','excludePTga','excludeCTga','excludeADHDrating','N2cong_latency_BC_Fz','N2cong_amp_BC_Fz','N2cong_latency_BC_FCz','N2cong_amp_BC_FCz','N2incong_latency_BC_Fz','N2incong_amp_BC_Fz','N2incong_latency_BC_FCz','N2incong_amp_BC_FCz',    'ERN_latency_BC_Fz','ERN_amp_BC_Fz',    'ERN_latency_BC_FCz','ERN_amp_BC_FCz','PNe_latency_BC_Fz','PNe_amp_BC_Fz','PNe_latency_BC_FCz','PNe_amp_BC_FCz','Pe_latency_BC_Cz','Pe_amp_BC_Cz','Pe_latency_BC_CPz','Pe_amp_BC_CPz','spin3_fam','spin3_sample','spin3_allgroups','spin3_preterm','spin3_gestationalage','spin3_ft_bcp3_pz_base','spin3_ft_bcp3_pz_fast','spin3_ft_cnv_cz_base','spin3_ft_cnv_cz_fast','spin3_ft_mrt_base','spin3_ft_mrt_fast','spin3_ft_rtv_base','spin3_ft_rtv_fast','CNSLS5yrs','CNSLS1mnth')

# Read data from CSV file, with '.' as missing values
EL <- read.csv ('EL analysis_Aug 2017_ADHD_exclusion applied.csv', header=T, na.strings=".", col.names=allVars)

## Prepare data by setting those variables to NULL that are not required in the analysis
ELdata <- within(EL, {
    Full_ID <- NULL        # Delete
    cen <- NULL
    fam <- NULL
    id <- NULL
    groupControlPersistPreterm <- NULL
    excludePersis <- NULL
    sefosgroup <- NULL
    sefosexclude <- NULL
    sib <- NULL
    DIVA_Parent_score <- NULL
    Reasons_for_exclusion_CPT <- NULL
    exclude <- NULL
    Persistent_remitted_parent <- NULL
    Previous_ADHD_Status1 <- NULL
    inattention <- NULL
    hypimp <- NULL
    subtype <- NULL
    BFISparent <- NULL
    adhdinptBFIS <- NULL
    adhd_parent <- NULL
    exclude_nogo15 <- NULL
    exclude_cnv15 <- NULL
    exclude_go15 <- NULL
    cnv <- NULL
    excluded_cuep3 <- NULL
    excluded_go <- NULL
    excluded_nogo <- NULL
    excluded_cnv <- NULL
    PersistRemitControl_CPT <- NULL
    PersistRemit_CPT <- NULL
    exclude_background <- NULL
    exclude_GA <- NULL
    excludeCUEseg <- NULL
    segcue <- NULL
    segCNV <- NULL
    seggo <- NULL
    segnogo <- NULL
    CNV <- NULL
    excludeIQ <- NULL
    excludeGA <- NULL
    excludeADHDga <- NULL
    excludePTga <- NULL
    excludeCTga <- NULL
    excludeADHDrating <- NULL
    spin3_fam <- NULL
    spin3_sample <- NULL
    spin3_allgroups <- NULL
    spin3_preterm <- NULL
    spin3_gestationalage <- NULL
    y <- CNSLS5yrs #EL variable is DV
})

## Reorder variables
ELdata <-ELdata[,c('Conners_Parent','age','sex','group','IQ','ga','bw','N2inc_latencyFz','N2inc_ampFz','N2cong_latencyFz','N2cong_ampFz','N2inc_latencyFCz','N2inc_ampFCz','N2cong_latencyFCz','N2cong_ampFCz','Pe_latencyCz','Pe_ampCz','Pe_latencyCPz','Pe_ampCPz','PNe_latencyFz','PNe_ampFz','PNe_latencyFCz','PNe_ampFCz','ERN_latencyFz','ERN_ampFz','ERN_latencyFCz','ERN_ampFCz','cuep3_amp','Gop3_amp','Nogo_p3_amp','cue_p3_lat','Gop3_lat','Nogo_p3_lat','CPT_OE','CPT_MRT','CPT_RTV','CPT_FalseAlarm','CPT_OnotX','alphalg1','alphalg2','betalg1','betalg2','thetalg1','thetalg2','deltalg1','deltalg2','nogop3_czlat','nogop3_czamp','nogop3_czlat_BC','nogop3_czamp_BC','nogop3_fczlat','nogop3_fczamp','nogop3_fczlat_BC','nogop3_fczamp_BC','nogon2_fzlat','nogon2_fzamp','nogon2_fzlat_BC','nogon2_fzamp_BC','gop3_pzlat','gop3_pzamp','gop3_pzlat_BC','gop3_pzamp_BC','gop3_cpzlat','gop3_cpzamp','gop3_cpzlat_BC','gop3_cpzamp_BC','CNVcz','CNVcz_BC','CNVcpz','CNVcpz_BC','cuep3_pzlat','cuep3_pzamp','cuep3_pzlat_BC','cuep3_pzamp_BC','N2cong_latency_BC_Fz','N2cong_amp_BC_Fz','N2cong_latency_BC_FCz','N2cong_amp_BC_FCz','N2incong_latency_BC_Fz','N2incong_amp_BC_Fz','N2incong_latency_BC_FCz','N2incong_amp_BC_FCz','ERN_latency_BC_Fz','ERN_amp_BC_Fz','ERN_latency_BC_FCz','ERN_amp_BC_FCz','PNe_latency_BC_Fz','PNe_amp_BC_Fz','PNe_latency_BC_FCz','PNe_amp_BC_FCz','Pe_latency_BC_Cz','Pe_amp_BC_Cz','Pe_latency_BC_CPz','Pe_amp_BC_CPz','spin3_ft_bcp3_pz_base','spin3_ft_bcp3_pz_fast','spin3_ft_cnv_cz_base','spin3_ft_cnv_cz_fast','spin3_ft_mrt_base','spin3_ft_mrt_fast','spin3_ft_rtv_base','spin3_ft_rtv_fast','CNSLS1mnth','y')]

dim(ELdata)
describe(ELdata)

res.EL <-
    bestglm(ELdata)

res.EL$BestModels
</code>```

答:
I came across the same error and it was solved by removing NAs in those variables included into the bestglm command. You can get rid of NAs from the original data-frame DF like this:

```<code>df <- DF[is.na(DF$foo)==F & is.na(DF$bar)==F,]
</code>```

If you add those columns that have NAs between the square brackets above, you can then run bestglm on the new data-frame df

Body:
I am trying to run the bestglm command but am getting the error message

Error in if (any(Column1Test)) stop("Column of 1's can't be used! Intercept always included.") : missing value where TRUE/FALSE needed

Below is the source code for the error message for the bestglm function:

#Test if there is a column of 1's in X.
#Only do this test if:
#1) X contains at least one column corresponding to a quantitative variable
#2) IncludeInterceptQ (intercept is included already)
if (!all(FactorsQ)&& IncludeInterceptQ){
    X2<-X[,!FactorsQ,drop=FALSE] #removing factor variables
    p2<-ncol(X2)
    Column1Test<-apply(X2-matrix(rep(1,n*p2),ncol=p2), MARGIN=2, function(x) 0==sum(abs(x)))
    if (any(Column1Test))
      stop("Column of 1's can't be used! Intercept always included.")
}

I don't have a column of 1s in my data and I am at a loss as to what that means. Below is the code I am using. Can anyone help please?

#Lables all variables in the data file
allVars<- c('Full_ID','cen','fam','id','group','groupControlPersistPreterm','excludePersis','sefosgroup','sefosexclude','Conners_Parent',   'age','sex','IQ','ga','bw','sib','DIVA_Parent_score','Reasons_for_exclusion_CPT','exclude', 'Persistent_remitted_parent','Previous_ADHD_Status1','inattention','hypimp','subtype','BFISparent','adhdinptBFIS','adhd_parent','exclude_nogo15','exclude_cnv15','exclude_go15','N2inc_latencyFz','N2inc_ampFz','N2cong_latencyFz','N2cong_ampFz','N2inc_latencyFCz','N2inc_ampFCz','N2cong_latencyFCz','N2cong_ampFCz','Pe_latencyCz','Pe_ampCz',  'Pe_latencyCPz','Pe_ampCPz','PNe_latencyFz','PNe_ampFz','PNe_latencyFCz','PNe_ampFCz','ERN_latencyFz','ERN_ampFz','ERN_latencyFCz','ERN_ampFCz','cnv','cuep3_amp','Gop3_amp','Nogo_p3_amp','cue_p3_lat','Gop3_lat','Nogo_p3_lat','excluded_cuep3','excluded_go','excluded_nogo','excluded_cnv','CPT_OE','CPT_MRT',  'CPT_RTV','CPT_FalseAlarm','CPT_OnotX','PersistRemitControl_CPT','PersistRemit_CPT','exclude_background','exclude_GA','alphalg1','alphalg2','betalg1','betalg2','thetalg1','thetalg2','deltalg1','deltalg2','nogop3_czlat','nogop3_czamp','nogop3_czlat_BC','nogop3_czamp_BC','nogop3_fczlat','nogop3_fczamp','nogop3_fczlat_BC',   'nogop3_fczamp_BC', 'nogon2_fzlat', 'nogon2_fzamp', 'nogon2_fzlat_BC','nogon2_fzamp_BC','gop3_pzlat','gop3_pzamp','gop3_pzlat_BC','gop3_pzamp_BC','gop3_cpzlat','gop3_cpzamp','gop3_cpzlat_BC','gop3_cpzamp_BC','CNVcz','CNVcz_BC','CNVcpz','CNVcpz_BC','cuep3_pzlat','cuep3_pzamp','cuep3_pzlat_BC','cuep3_pzamp_BC','excludeGOseg','excludeNOGOseg','excludeCUEseg','segcue','segCNV','seggo','segnogo','CNV','excludeIQ','excludeGA','excludeADHDga','excludePTga','excludeCTga','excludeADHDrating','N2cong_latency_BC_Fz','N2cong_amp_BC_Fz','N2cong_latency_BC_FCz','N2cong_amp_BC_FCz','N2incong_latency_BC_Fz','N2incong_amp_BC_Fz','N2incong_latency_BC_FCz','N2incong_amp_BC_FCz',    'ERN_latency_BC_Fz','ERN_amp_BC_Fz',    'ERN_latency_BC_FCz','ERN_amp_BC_FCz','PNe_latency_BC_Fz','PNe_amp_BC_Fz','PNe_latency_BC_FCz','PNe_amp_BC_FCz','Pe_latency_BC_Cz','Pe_amp_BC_Cz','Pe_latency_BC_CPz','Pe_amp_BC_CPz','spin3_fam','spin3_sample','spin3_allgroups','spin3_preterm','spin3_gestationalage','spin3_ft_bcp3_pz_base','spin3_ft_bcp3_pz_fast','spin3_ft_cnv_cz_base','spin3_ft_cnv_cz_fast','spin3_ft_mrt_base','spin3_ft_mrt_fast','spin3_ft_rtv_base','spin3_ft_rtv_fast','CNSLS5yrs','CNSLS1mnth')

# Read data from CSV file, with '.' as missing values
EL <- read.csv ('EL analysis_Aug 2017_ADHD_exclusion applied.csv', header=T, na.strings=".", col.names=allVars)

## Prepare data by setting those variables to NULL that are not required in the analysis
ELdata <- within(EL, {
    Full_ID <- NULL        # Delete
    cen <- NULL
    fam <- NULL
    id <- NULL
    groupControlPersistPreterm <- NULL
    excludePersis <- NULL
    sefosgroup <- NULL
    sefosexclude <- NULL
    sib <- NULL
    DIVA_Parent_score <- NULL
    Reasons_for_exclusion_CPT <- NULL
    exclude <- NULL
    Persistent_remitted_parent <- NULL
    Previous_ADHD_Status1 <- NULL
    inattention <- NULL
    hypimp <- NULL
    subtype <- NULL
    BFISparent <- NULL
    adhdinptBFIS <- NULL
    adhd_parent <- NULL
    exclude_nogo15 <- NULL
    exclude_cnv15 <- NULL
    exclude_go15 <- NULL
    cnv <- NULL
    excluded_cuep3 <- NULL
    excluded_go <- NULL
    excluded_nogo <- NULL
    excluded_cnv <- NULL
    PersistRemitControl_CPT <- NULL
    PersistRemit_CPT <- NULL
    exclude_background <- NULL
    exclude_GA <- NULL
    excludeCUEseg <- NULL
    segcue <- NULL
    segCNV <- NULL
    seggo <- NULL
    segnogo <- NULL
    CNV <- NULL
    excludeIQ <- NULL
    excludeGA <- NULL
    excludeADHDga <- NULL
    excludePTga <- NULL
    excludeCTga <- NULL
    excludeADHDrating <- NULL
    spin3_fam <- NULL
    spin3_sample <- NULL
    spin3_allgroups <- NULL
    spin3_preterm <- NULL
    spin3_gestationalage <- NULL
    y <- CNSLS5yrs #EL variable is DV
})

## Reorder variables
ELdata <-ELdata[,c('Conners_Parent','age','sex','group','IQ','ga','bw','N2inc_latencyFz','N2inc_ampFz','N2cong_latencyFz','N2cong_ampFz','N2inc_latencyFCz','N2inc_ampFCz','N2cong_latencyFCz','N2cong_ampFCz','Pe_latencyCz','Pe_ampCz','Pe_latencyCPz','Pe_ampCPz','PNe_latencyFz','PNe_ampFz','PNe_latencyFCz','PNe_ampFCz','ERN_latencyFz','ERN_ampFz','ERN_latencyFCz','ERN_ampFCz','cuep3_amp','Gop3_amp','Nogo_p3_amp','cue_p3_lat','Gop3_lat','Nogo_p3_lat','CPT_OE','CPT_MRT','CPT_RTV','CPT_FalseAlarm','CPT_OnotX','alphalg1','alphalg2','betalg1','betalg2','thetalg1','thetalg2','deltalg1','deltalg2','nogop3_czlat','nogop3_czamp','nogop3_czlat_BC','nogop3_czamp_BC','nogop3_fczlat','nogop3_fczamp','nogop3_fczlat_BC','nogop3_fczamp_BC','nogon2_fzlat','nogon2_fzamp','nogon2_fzlat_BC','nogon2_fzamp_BC','gop3_pzlat','gop3_pzamp','gop3_pzlat_BC','gop3_pzamp_BC','gop3_cpzlat','gop3_cpzamp','gop3_cpzlat_BC','gop3_cpzamp_BC','CNVcz','CNVcz_BC','CNVcpz','CNVcpz_BC','cuep3_pzlat','cuep3_pzamp','cuep3_pzlat_BC','cuep3_pzamp_BC','N2cong_latency_BC_Fz','N2cong_amp_BC_Fz','N2cong_latency_BC_FCz','N2cong_amp_BC_FCz','N2incong_latency_BC_Fz','N2incong_amp_BC_Fz','N2incong_latency_BC_FCz','N2incong_amp_BC_FCz','ERN_latency_BC_Fz','ERN_amp_BC_Fz','ERN_latency_BC_FCz','ERN_amp_BC_FCz','PNe_latency_BC_Fz','PNe_amp_BC_Fz','PNe_latency_BC_FCz','PNe_amp_BC_FCz','Pe_latency_BC_Cz','Pe_amp_BC_Cz','Pe_latency_BC_CPz','Pe_amp_BC_CPz','spin3_ft_bcp3_pz_base','spin3_ft_bcp3_pz_fast','spin3_ft_cnv_cz_base','spin3_ft_cnv_cz_fast','spin3_ft_mrt_base','spin3_ft_mrt_fast','spin3_ft_rtv_base','spin3_ft_rtv_fast','CNSLS1mnth','y')]

dim(ELdata)
describe(ELdata)

res.EL <-
    bestglm(ELdata)

res.EL$BestModels

Body:
I came across the same error and it was solved by removing NAs in those variables included into the bestglm command. You can get rid of NAs from the original data-frame DF like this:

df <- DF[is.na(DF$foo)==F & is.na(DF$bar)==F,]

If you add those columns that have NAs between the square brackets above, you can then run bestglm on the new data-frame df


问:
Windows 10: What is a real path to smartphone in file manager?
Windows 10 (64 bit).

When I connect(via microUSB) smartphone Nokia to my computer, the Windows 10 is success detect device. And as result I can copy file to/from smartphone.

Here result:

nokia_path

But as you can see the File Manager show in address that path:

```<code>This PC\Nokia C5-00.2\Memory card (MY PHONE)\Backup
</code>```

But when I try to go to this path from console I get error:

d:\TEMP\test>cd This PC\Nokia C5-00.2\Memory card (MY PHONE)\Backup

```<code>The system cannot find the path specified.
</code>```

Is this a real path to smartpnone?

答:
Probably because the console can't find This PC\Nokia C5-00.2\Memory card (MY PHONE)\Backup in D:\TEMP\test.

Most likely your Windows is installed on C:/ thus you should replace This PCwith C:/.

No it's not the 'real' path to the smartphone.

Body:
Windows 10 (64 bit).

When I connect(via microUSB) smartphone Nokia to my computer, the Windows 10 is success detect device. And as result I can copy file to/from smartphone.

Here result:

nokia_path

But as you can see the File Manager show in address that path:

This PC\Nokia C5-00.2\Memory card (MY PHONE)\Backup

But when I try to go to this path from console I get error:

d:\TEMP\test>cd This PC\Nokia C5-00.2\Memory card (MY PHONE)\Backup

The system cannot find the path specified.

Is this a real path to smartpnone?


问:
What template system uses <?r ... ?>
I saw this strange looking template code, and want to know which templating system it belongs to:

```<code>        <?r currencies.each do |currency| ?>
        <tr>
            <td colspan="5">#{currency} Summary:</td>
            <td class="total">#{f.text summary[:total][currency]}</td>
            <td></td>
        </tr>
        <?r end ?>
</code>```

The inline language is certainly Ruby, but <?r ... ?> is not ERB's <% ... %> that I am familiar with.

答:
The code's author, Samuel Williams also created a templating system called Trenni which uses the syntax:

```<code><?r expression ?>
</code>```

to evaluate the given expression in Ruby.

According to Trenni's README, it was influenced / inspired by the template engines ezamar and nagoro by Michael Fellinger.

Title: What template system uses <?r ... ?>

Body:
I saw this strange looking template code, and want to know which templating system it belongs to:

        <?r currencies.each do |currency| ?>

            #{currency} Summary:
            #{f.text summary[:total][currency]}

        <?r end ?>

The inline language is certainly Ruby, but <?r ... ?> is not ERB's <% ... %> that I am familiar with.

Body:
The code's author, Samuel Williams also created a templating system called Trenni which uses the syntax:

<?r expression ?>

to evaluate the given expression in Ruby.

According to Trenni's README, it was influenced / inspired by the template engines ezamar and nagoro by Michael Fellinger.


问:
Googleapis: "failed to load external entity"
Since 2 days we have problems with Google API Maps Geocode.
We don't have response with this PHP call:

```<code>$base_url="https://maps.googleapis.com/maps/api/geocode/xml?latlng=48.000,2.0000&key=MyServerKey";
$xml = simplexml_load_file($base_url);
</code>```

Response:

PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "https://maps.googleapis.com/maps/api/geocode/xml?latlng=....

The call works when we call it from another IP.
We don't have made change on the PHP code since a lot of month...

Have you an idea from the problem?
Can Google blacklist IPs? There is no indication in Google Cloud Platform about a problem.

Thanks a lot.

答:
I'm in discussion with Google support....
It seems to be an IPV6 problem.

When i made a "wget" to maps.googleapis.com, i have a timout but if I have to use an ip v4, it works.

I will put the result when I have the solution...

Body:
Since 2 days we have problems with Google API Maps Geocode.
We don't have response with this PHP call:

$base_url="https://maps.googleapis.com/maps/api/geocode/xml?latlng=48.000,2.0000&key=MyServerKey";
$xml = simplexml_load_file($base_url);

Response:

PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "https://maps.googleapis.com/maps/api/geocode/xml?latlng=....

The call works when we call it from another IP.
We don't have made change on the PHP code since a lot of month...

Have you an idea from the problem?
Can Google blacklist IPs? There is no indication in Google Cloud Platform about a problem.

Thanks a lot.


问:
Generate dynamic table with div based on ngFor loop
The code below is in a view of main-category.component

```<code><div>
  <div *ngFor="let category of categories;">
      <app-subcategory>
        [name]="category.name">
      </app-subcategory>
  </div>
</div>
</code>```

I'd like generate a table with 4 columns and x rows depending the number of items in categories. Each cell contain the component app-subcategory.

I don't see the right way to do this. Do you have idea ?

Thanks,

答:
```<code>@Pipe({ name: columns })
export class ColumnsPipe implements PipeTransform {
  transform(data, numColumns) {
    if(!data || data.length == 0) {
      return data;
    }

    var i,j,temparray,chunk = 10;
    result = [];
    for (i=0,j=data.length; i<j; i+=chunk) {
        result.pop(array.slice(i,i+chunk));
    }
    return result;
  }
}
</code>```

see also https://stackoverflow.com/a/8495740/217408

```<code><div>
  <div *ngFor="let row of categories | columns:4">
    <div *ngFor="let category of row">
      <app-subcategory>
        [name]="category.name">
      </app-subcategory>
    </div>
  </div>
</div>
</code>```

You might want to change the divs into
 and  to get real rows and columns.

Body:
The code below is in a view of main-category.component

      <app-subcategory>
        [name]="category.name">
      </app-subcategory>

I'd like generate a table with 4 columns and x rows depending the number of items in categories. Each cell contain the component app-subcategory.

I don't see the right way to do this. Do you have idea ?

Thanks,

Body:
@Pipe({ name: columns })
export class ColumnsPipe implements PipeTransform {
  transform(data, numColumns) {
    if(!data || data.length == 0) {
      return data;
    }

    var i,j,temparray,chunk = 10;
    result = [];
    for (i=0,j=data.length; i<j; i+=chunk) {
        result.pop(array.slice(i,i+chunk));
    }
    return result;
  }
}

see also https://stackoverflow.com/a/8495740/217408

<div>
  <div *ngFor="let row of categories | columns:4">
    <div *ngFor="let category of row">
      <app-subcategory>
        [name]="category.name">
      </app-subcategory>
    </div>
  </div>
</div>

You might want to change the divs into <tr> and <td> to get real rows and columns.


问:
C++ - Macro defines directive
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

It mentions a directive called "Macro defines". What do we mean when we say "Macro"?

Thanks.

答:
A macro is a preprocessor directive that defines a name that is to be replaced (or removed) by the preprocessor right before compilation.

Example:

```<code>#define MY_MACRO1 somevalue
#define MY_MACRO2
#define SUM(a, b) (a + b)
</code>```

then if anywhere in the code (except in the string literals) there is a mention of MY_MACRO1 or MY_MACRO2 the preprocessor replaces this with whatever comes after the name in the #define line.

There can also be macros with parameters (like the SUM). In that case the preprocessor recognizes the arguments, example:

```<code>int x = 1, y = 2;
int z = SUM(x, y);
</code>```

preprocessor replaces like this:

```<code>int x = 1, y = 2;
int z = (x + y);
</code>```

only after this replacement the compiler gets to compile the resulting code.

Title: C++ - Macro defines directive

Body:
A macro is a preprocessor directive that defines a name that is to be replaced (or removed) by the preprocessor right before compilation.

Example:

#define MY_MACRO1 somevalue
#define MY_MACRO2
#define SUM(a, b) (a + b)

then if anywhere in the code (except in the string literals) there is a mention of MY_MACRO1 or MY_MACRO2 the preprocessor replaces this with whatever comes after the name in the #define line.

There can also be macros with parameters (like the SUM). In that case the preprocessor recognizes the arguments, example:

int x = 1, y = 2;
int z = SUM(x, y);

preprocessor replaces like this:

int x = 1, y = 2;
int z = (x + y);

only after this replacement the compiler gets to compile the resulting code.


问:
Selective role based module loading
I wanted to know if there is any way to selectively load module based on roles.

e.g:-
There are three groups of users namely- admin, biller and end-user. Based on their role, they will be authorized to use certain feature. The app is split into three modules based on same user groups with one common module shared by all of them.
Based on login, is it possible to selectively load only the module required for that particular user?

Note:- routing path is same for all, like /home, /dashboard, /sales etc

Adding a point:
In the above scenario, assume, I have generated four files- admin.chunk.js, biller.chunk.js, end-user.chunk.js and common module will be eagerly loaded with app js.
Based on the user logging in, from the backend, I am selectively sending the js suitable for that logged in user. Now paths for all the components are same, except the part that admin will have access to couple of modules more than end-user. How to manage routing in this case...?

答:
Yes you can do this I have done a similar thing in my project. It was based on the kind of environment. You must have seen environment file and each .ts file represent one of the environment based on the environment loaded I setup my providers,

```<code>providers: environment.production?[MyService1]:[MyService1, MyService2],
</code>```

in the example above I will be loading my service in module.ts based on my environment if it is not production this ternary operator will load two of my service in the provider else it will just inject one.

environment.production is a boolean variable.

Same can be applied to imports and other property of @ngmodule, that way we can configure single module with multiple behavior.

check this out,

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule, HttpClient, HttpParams } from '@angular/common/http';
import {DatePipe} from '@angular/common';

import { AppComponent } from './app.component';
import { MYInterceptor} from '../mocks/my-interceptor';

import { MyNameServiceService } from '../services/my-name-service.service';
import { MyNameComponent } from './display-name/my-name.component';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    DisplayNameComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: environment.production?[MyNameServiceService, DatePipe]:[DatePipe,MyNameServiceService, {provide: HTTP_INTERCEPTORS,useClass: MYInterceptor,multi: true}],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Title: Selective role based module loading

Body:
Yes you can do this I have done a similar thing in my project. It was based on the kind of environment. You must have seen environment file and each .ts file represent one of the environment based on the environment loaded I setup my providers,

providers: environment.production?[MyService1]:[MyService1, MyService2],

in the example above I will be loading my service in module.ts based on my environment if it is not production this ternary operator will load two of my service in the provider else it will just inject one.

environment.production is a boolean variable.

Same can be applied to imports and other property of @ngmodule, that way we can configure single module with multiple behavior.

check this out,

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule, HttpClient, HttpParams } from '@angular/common/http';
import {DatePipe} from '@angular/common';

import { AppComponent } from './app.component';
import { MYInterceptor} from '../mocks/my-interceptor';

import { MyNameServiceService } from '../services/my-name-service.service';
import { MyNameComponent } from './display-name/my-name.component';
import { environment } from '../environments/environment';

@NgModule({
  declarations: [
    AppComponent,
    DisplayNameComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: environment.production?[MyNameServiceService, DatePipe]:[DatePipe,MyNameServiceService, {provide: HTTP_INTERCEPTORS,useClass: MYInterceptor,multi: true}],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Why doesn't this code work? Combination of for and if for a "test" login page
I'm trying to make some kind of login page (I don't care about security or some sort. This is a test, and I'm not even that advanced of a coder. And I'm struggling with the coding. I want to make it as:

```<code>    If the username was filled in as "Ardent" and the password as "1",
        Say something like "Welcome!"
    If the username or(and) the password are(is) incorrect,
        alert("The username and password is incorrect.");
and make it loop, leading to asking for username and password again.
</code>```

So, this is what I coded (I could not find out how this can work, so I don't even have the basic structure of it).

```<code>for([id == prompt("What is your ID?"), password == prompt("What is your password?")];
     id == "Ardent" || password == "1" ;) {

    prompt("What is your ID?");
    prompt("What is your password?");
    if(id == "Ardent" || password == "1") {
        alert("Welcome back!");
    }
}
</code>```

Thank you!
Sorry if it is actually a complete mess :(
I'm so bad at coding and I'm just a beginner.

答:
Me too:-

```<code>do {
    var id = prompt("What is your ID?");
    var password = prompt("What is your password?");
} while (id != "Ardent" && password != "1");
alert("Welcome back");
</code>```

If you are on Firefox press Ctrl+Shift+I to open the Developer Console and see syntax errors in your javascript code.

More on do..while loops

Body:
I'm trying to make some kind of login page (I don't care about security or some sort. This is a test, and I'm not even that advanced of a coder. And I'm struggling with the coding. I want to make it as:

    If the username was filled in as "Ardent" and the password as "1",
        Say something like "Welcome!"
    If the username or(and) the password are(is) incorrect,
        alert("The username and password is incorrect.");
and make it loop, leading to asking for username and password again.

So, this is what I coded (I could not find out how this can work, so I don't even have the basic structure of it).

for([id == prompt("What is your ID?"), password == prompt("What is your password?")];
     id == "Ardent" || password == "1" ;) {

    prompt("What is your ID?");
    prompt("What is your password?");
    if(id == "Ardent" || password == "1") {
        alert("Welcome back!");
    }
}

Thank you!
Sorry if it is actually a complete mess :(
I'm so bad at coding and I'm just a beginner.

Body:
Me too:-

do {
    var id = prompt("What is your ID?");
    var password = prompt("What is your password?");
} while (id != "Ardent" && password != "1");
alert("Welcome back");

If you are on Firefox press Ctrl+Shift+I to open the Developer Console and see syntax errors in your javascript code.

More on do..while loops


问:
CMD: Can't add 1 to 08 using += operator
I am using CMD commands to work on some variables. I can add 1 to a variable but if that variable is 08 or 09, the result comes out to be 1,rather than 9 or 10. Here's the code:

```<code>setlocal EnableDelayedExpansion
set day=08
echo Day:%day%
set /a day+=1
echo Day:% day%
</code>```

This works for numbers 1-7, and after 10. I need to add a leading zero to digits less than 10 because otherwise somehow the variable is not written to a text file (which I perform later) despite showing the correct value in other parts of the code.

答:
```<code>Numeric values are decimal numbers, unless
prefixed by 0x for hexadecimal numbers, and 0 for octal numbers.
So 0x12 is the same as 18 is the same as 022. Please note that the octal
notation can be confusing: 08 and 09 are not valid numbers because 8 and
9 are not valid octal digits.
</code>```

From set /?.

Body:
I am using CMD commands to work on some variables. I can add 1 to a variable but if that variable is 08 or 09, the result comes out to be 1,rather than 9 or 10. Here's the code:

setlocal EnableDelayedExpansion
set day=08
echo Day:%day%
set /a day+=1
echo Day:% day%

This works for numbers 1-7, and after 10. I need to add a leading zero to digits less than 10 because otherwise somehow the variable is not written to a text file (which I perform later) despite showing the correct value in other parts of the code.

Body:
Numeric values are decimal numbers, unless
prefixed by 0x for hexadecimal numbers, and 0 for octal numbers.
So 0x12 is the same as 18 is the same as 022. Please note that the octal
notation can be confusing: 08 and 09 are not valid numbers because 8 and
9 are not valid octal digits.

From set /?.


问:
Django REST Framework: Nested Serializers not appearing
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]
</code>```

What I want it to return:

```<code>HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]
</code>```

views.py

```<code>from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer
</code>```

models.py

```<code>class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)
</code>```

serializers.py

```<code>class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')
</code>```

Any help is appreciated

答:
This might help you:

class UserSerializer(serializers.ModelSerializer):
     name = NameSerializer()
     userName = serializers.EmailField(source='email')

```<code>     class Meta:
         model = Person
         fields = ('id', 'userName', 'name')
</code>```

If the items should be a list, then only you need to pass many=True.

Body:
I am having trouble with nested serializers and the Django rest framework.
When setting serializer_class to "UserSerializer", the nested data from the "NameSerializer" class isn't appearing.
However, when I set serializer_class to "NameSerializer", the data does appear.

The API returns when using UserSerializer:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
  },
  {
    "id": 2,
    "userName": "2@admin.com"
  },
  {
    "id": 3,
    "userName": "3@admin.com"
  },
  {
    "id": 4,
    "userName": "4@admin.com"
  }
]

What I want it to return:

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
  {
    "id": 1,
    "userName": "admin@admin.com"
    "name": {
      "familyName": "Joe",
      "givenName": "admin",
      "formated": "admin Joe"
    },
  },
  {
    "id": 2,
    "userName": "jane@admin.com"
    "name": {
      "familyName": "Doe",
      "givenName": "Jane",
      "formated": "Jane Doe"
    },
  },
  {
    "id": 3,
    "userName": "Billy@admin.com"
    "name": {
      "familyName": "Idol",
      "givenName": "Billy",
      "formated": "Billy Idol"
    },
  },
  {
    "id": 4,
    "userName": "User@admin.com"
    "name": {
      "familyName": "B",
      "givenName": "User",
      "formated": "User B"
    },
  }
]

views.py

from API.models import Person
from API.serializers import *
from rest_framework import viewsets

class UserViewSet(viewsets.ModelViewSet):
   queryset = Person.objects.all()
   serializer_class = NameSerializer

models.py

class Person(AbstractBaseUser):
    email = models.EmailField(
       verbose_name='email address',
       max_length=255,
       unique=True,
       )
    first_name = models.CharField(max_length=254, blank=True)
    last_name =  models.CharField(max_length=254, blank=True)

serializers.py

class NameSerializer(serializers.ModelSerializer):

  familyName = serializers.CharField(source='last_name')
  givenName = serializers.CharField(source='first_name')
  formatted = serializers.SerializerMethodField()

  class Meta:
      model = Person
      fields = ('familyName', 'givenName', 'formatted',)

  def get_formatted(slef, obj):
      FullName = obj.first_name + '' + obj.last_name
      return FullName

class UserSerializer(serializers.ModelSerializer):

  name = NameSerializer(many=True, readonly=True)
  userName = serializers.EmailField(source='email')

  class Meta:
      model = Person
      fields = ('id', 'userName', 'name')

Any help is appreciated

Body:
This might help you:

class UserSerializer(serializers.ModelSerializer):
     name = NameSerializer()
     userName = serializers.EmailField(source='email')

     class Meta:
         model = Person
         fields = ('id', 'userName', 'name')

If the items should be a list, then only you need to pass many=True.


问:
Selecting columns based on row values in multiple columns using dplyr
I am trying to select columns where at least one row equals 1, only if the same row also has a certain value in a second column. I would prefer to achieve this using dplyr, but any computationally efficient solution is welcome.

Example:

Select columns among a1, a2, a3 containing at least one row where the value is 1 AND where column b=="B"

Example data:

```<code>rand <- function(S) {set.seed(S); sample(x = c(0,1),size = 3, replace=T)}
df <- data.frame(a1=rand(1),a2=rand(2),a3=rand(3),b=c("A","B","A"))
</code>```

Input data:

```<code>  a1 a2 a3 b
1  0  0  0 A
2  0  1  1 B
3  1  1  0 A
</code>```

Desired output:

```<code>  a2 a3
1  0  0
2  1  1
3  1  0
</code>```

I managed to obtain the correct output with the following code, however this is a very inefficient solution and I need to run it on a very large dataframe (365,000 rows X 314 columns).

```<code>df %>% select_if(function(x) any(paste0(x,.$b) == '1B'))
</code>```

答:
A solution, not using dplyr:</p>

```<code>df[sapply(df[df$b == "B",], function(x) 1 %in% x)]
</code>```

Body:
I am trying to select columns where at least one row equals 1, only if the same row also has a certain value in a second column. I would prefer to achieve this using dplyr, but any computationally efficient solution is welcome.

Example:

Select columns among a1, a2, a3 containing at least one row where the value is 1 AND where column b=="B"

Example data:

rand <- function(S) {set.seed(S); sample(x = c(0,1),size = 3, replace=T)}
df <- data.frame(a1=rand(1),a2=rand(2),a3=rand(3),b=c("A","B","A"))

Input data:

  a1 a2 a3 b
1  0  0  0 A
2  0  1  1 B
3  1  1  0 A

Desired output:

  a2 a3
1  0  0
2  1  1
3  1  0

I managed to obtain the correct output with the following code, however this is a very inefficient solution and I need to run it on a very large dataframe (365,000 rows X 314 columns).

df %>% select_if(function(x) any(paste0(x,.$b) == '1B'))

Body:
A solution, not using dplyr:

df[sapply(df[df$b == "B",], function(x) 1 %in% x)]


问:
Remove extra spaces in sp_send_dbmail
I have the following table:

```<code>CREATE TABLE [dbo].[MyTable](
    [Day_ID] [nvarchar](50) NULL,
    [SAS] [nvarchar](50) NULL,
    [STAMP] [datetime] NULL DEFAULT (getdate())
)
</code>```

which contains this data:

'2017_12_06_01','Red'

'2017_12_06_02','Yellow'

'2017_12_06_03','Green'

'2017_12_06_04','Blue'

I also have a SP which read all the data from MyTable and send it in the body of an e-mail message.

```<code>SET NOCOUNT ON;

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'MyMailProfile'
        ,@recipients = 'me@account.com'
        ,@subject = 'This is the object'
        ,@body = 'This is the body:'
        ,@body_format = 'TEXT'
        ,@query = 'SET NOCOUNT ON select [Day_ID],[SAS] from MyTable SET NOCOUNT OFF'
        ,@attach_query_result_as_file = 0
        ,@query_result_separator = '|'
        ,@exclude_query_output = 1
        ,@query_result_no_padding = 0
        ,@query_result_header = 0
        ,@append_query_error=1
</code>```

Everything works but my problem is that in the body the results appear like these:

```<code>2017_12_06_01                                   |Red
2017_12_06_02                                   |Yellow
2017_12_06_03                                   |Green
2017_12_06_04                                   |Blue
</code>```

In other words SQL Server know that the columns could be 50 characters long so they fill the space that doesn't contain characters with spaces. This is very boring if you consider that happen also if you write numeric values into a column, for example, NUMERIC.
I've tried with LTRIM and RTRIM but nothing changed.

I am using SQL Server 2005.

答:
You need to run two queries - first to compute the actual lengths, the second to retrieve the data for the email. Obviously, this can have a high cost.

Something like:

```<code>declare @maxDay int
declare @maxSAS int

select @maxDay = MAX(LEN(RTRIM(Day_ID))),@maxSAS = MAX(LEN(RTRIM(SAS))) from MyTable

declare @sql varchar(max)
set @sql = 'SET NOCOUNT ON select CONVERT(nvarchar(' + CONVERT(varchar(10),@maxDay) +
           '),[Day_ID]) as Day_ID,CONVERT(nvarchar(' + CONVERT(varchar(10),@maxSAS) +
           '),[SAS]) as SAS from MyTable SET NOCOUNT OFF'
</code>```

And then use @sql in you sp_send_dbmail call.

I've tried with LTRIM and RTRIM but nothing changed.

It wouldn't. Each column in a result set has a single fixed type. The input to your e.g. RTRIM() calls is an nvarchar(50). Without knowing the contents of all rows, what possible data type can SQL Server derive for the output from that RTRIM() using expression? It can only still be nvarchar(50) and so that's still the type of the column in the result set. For all the server nows, there could be a row containing 50 non-whitespace characters and the result still needs to show that.

Title: Remove extra spaces in sp_send_dbmail

Body:
I have the following table:

CREATE TABLE [dbo].[MyTable](
    [Day_ID] [nvarchar](50) NULL,
    [SAS] [nvarchar](50) NULL,
    [STAMP] [datetime] NULL DEFAULT (getdate())
)

which contains this data:

'2017_12_06_01','Red'

'2017_12_06_02','Yellow'

'2017_12_06_03','Green'

'2017_12_06_04','Blue'

I also have a SP which read all the data from MyTable and send it in the body of an e-mail message.

SET NOCOUNT ON;

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'MyMailProfile'
        ,@recipients = 'me@account.com'
        ,@subject = 'This is the object'
        ,@body = 'This is the body:'
        ,@body_format = 'TEXT'
        ,@query = 'SET NOCOUNT ON select [Day_ID],[SAS] from MyTable SET NOCOUNT OFF'
        ,@attach_query_result_as_file = 0
        ,@query_result_separator = '|'
        ,@exclude_query_output = 1
        ,@query_result_no_padding = 0
        ,@query_result_header = 0
        ,@append_query_error=1

Everything works but my problem is that in the body the results appear like these:

2017_12_06_01                                   |Red
2017_12_06_02                                   |Yellow
2017_12_06_03                                   |Green
2017_12_06_04                                   |Blue

In other words SQL Server know that the columns could be 50 characters long so they fill the space that doesn't contain characters with spaces. This is very boring if you consider that happen also if you write numeric values into a column, for example, NUMERIC.
I've tried with LTRIM and RTRIM but nothing changed.

I am using SQL Server 2005.

Body:
You need to run two queries - first to compute the actual lengths, the second to retrieve the data for the email. Obviously, this can have a high cost.

Something like:

declare @maxDay int
declare @maxSAS int

select @maxDay = MAX(LEN(RTRIM(Day_ID))),@maxSAS = MAX(LEN(RTRIM(SAS))) from MyTable

declare @sql varchar(max)
set @sql = 'SET NOCOUNT ON select CONVERT(nvarchar(' + CONVERT(varchar(10),@maxDay) +
           '),[Day_ID]) as Day_ID,CONVERT(nvarchar(' + CONVERT(varchar(10),@maxSAS) +
           '),[SAS]) as SAS from MyTable SET NOCOUNT OFF'

And then use @sql in you sp_send_dbmail call.

I've tried with LTRIM and RTRIM but nothing changed.

It wouldn't. Each column in a result set has a single fixed type. The input to your e.g. RTRIM() calls is an nvarchar(50). Without knowing the contents of all rows, what possible data type can SQL Server derive for the output from that RTRIM() using expression? It can only still be nvarchar(50) and so that's still the type of the column in the result set. For all the server nows, there could be a row containing 50 non-whitespace characters and the result still needs to show that.


问:
Are all the Unicode characters supported on Android
My question is simple. Are all Unicode characters available in Android?
I actually am using the soft keyboard and I want to add a few arabic letters which I can't find the codes for.</p>

答:
Android supports UTF-8 but you will not be able to use arabic, if it's not installed in your OS. There are ways to install new fonts, but some of them  needs jailbreaking your phone.

See link for installing font in Android:

https://web.archive.org/web/20091023103506/http://www.android-devs.com/?p=33


问:
how to convert HH:MM representation to minutes in oracle sql
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

```<code>HH:MM    Minutes
08:00    480
08:45    525
07:57    477
</code>```

Body:
how to convert varchar(hh:mm) to minutes in oracle sql.

For example:

HH:MM    Minutes
08:00    480
08:45    525
07:57    477

Body:
Try this

TO_NUMBER(SUBSTR('(08:00)',2,INSTR('(08:00)',':')-2))*60+TO_NUMBER(SUBSTR('(08:00)',INSTR('(08:00)',':')+1,2))