问:
I am getting a syntax Error near and keyword
```<code>SELECT   wrhwr.bl_id,
         Count(wrhwr.wr_id) AS ct_wr_id
FROM     (
                SELECT wrhwr.bl_id,
                       wrhwr.wr_id,
                       wrhwr.site_id,
                       wrhwr.date_requested
                FROM   wrhwr
                WHERE
                And    (
                              wrhwr.bl_id LIKE 'F0006440-B0001%')
                AND    wrhwr.bl_id IN
                       (
                                SELECT TOP 10
                                         q.bl_id
                                FROM     (
                                                  SELECT   bl_id,
                                                           Count(wr_id) AS wrcnt
                                                  FROM     afm.wrhwr
                                                  GROUP BY bl_id) AS q
                                WHERE    wrhwr.[status] IN ('Com',
                                                            'I',
                                                            'HL',
                                                            'HP',
                                                            'S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE    ((
                  And      (
                                    wrhwr.bl_id LIKE 'F0006440-B0001%') ))
AND      (
                  wrhwr.site_id IN
                  (
                         SELECT site_id
                         FROM   site
                         WHERE  state_id = 'JHB')
         OR       wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC
</code>```

答:
This is at least readable...

```<code>SELECT wrhwr.bl_id,
       Count(wrhwr.wr_id) AS ct_wr_id
FROM ( SELECT wrhwr.bl_id,
              wrhwr.wr_id,
              wrhwr.site_id,
              wrhwr.date_requested
        FROM   wrhwr
        WHERE AND ( wrhwr.bl_id LIKE 'F0006440-B0001%')
          AND wrhwr.bl_id IN  ( SELECT TOP 10 q.bl_id
                                FROM ( SELECT bl_id,
                                              Count(wr_id) AS wrcnt
                                       FROM afm.wrhwr
                                       GROUP BY bl_id) AS q
                                WHERE wrhwr.[status] IN ('Com','I','HL','HP','S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE ((And(wrhwr.bl_id LIKE 'F0006440-B0001%') ))
  AND ( wrhwr.site_id IN ( SELECT site_id
                               FROM [site]
                               WHERE  state_id = 'JHB')
   OR wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC;
</code>```

And then, because it's readable you can easily see where the problems are (which I have commented out).

```<code>SELECT wrhwr.bl_id,
       Count(wrhwr.wr_id) AS ct_wr_id
FROM ( SELECT wrhwr.bl_id,
              wrhwr.wr_id,
              wrhwr.site_id,
              wrhwr.date_requested
        FROM   wrhwr
        WHERE /*AND ( */wrhwr.bl_id LIKE 'F0006440-B0001%'/*) */
          AND wrhwr.bl_id IN  ( SELECT TOP 10 q.bl_id
                                FROM ( SELECT bl_id,
                                              Count(wr_id) AS wrcnt
                                       FROM afm.wrhwr
                                       GROUP BY bl_id) AS q
                                WHERE wrhwr.[status] IN ('Com','I','HL','HP','S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE /*((And(*/wrhwr.bl_id LIKE 'F0006440-B0001%'/*) )) */
  AND /*( */wrhwr.site_id IN ( SELECT site_id
                               FROM [site]
                               WHERE  state_id = 'JHB')
   OR wrhwr.site_id IS NULL/*)*/
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC;
</code>```

But, I'll be honest, that query is still awful, but after my SQL OCD kicked in to at least fix the "look" of the query, I have no interest in making it usable. :)

Body:
This is at least readable...

SELECT wrhwr.bl_id,
       Count(wrhwr.wr_id) AS ct_wr_id
FROM ( SELECT wrhwr.bl_id,
              wrhwr.wr_id,
              wrhwr.site_id,
              wrhwr.date_requested
        FROM   wrhwr
        WHERE AND ( wrhwr.bl_id LIKE 'F0006440-B0001%')
          AND wrhwr.bl_id IN  ( SELECT TOP 10 q.bl_id
                                FROM ( SELECT bl_id,
                                              Count(wr_id) AS wrcnt
                                       FROM afm.wrhwr
                                       GROUP BY bl_id) AS q
                                WHERE wrhwr.[status] IN ('Com','I','HL','HP','S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE ((And(wrhwr.bl_id LIKE 'F0006440-B0001%') ))
  AND ( wrhwr.site_id IN ( SELECT site_id
                               FROM [site]
                               WHERE  state_id = 'JHB')
   OR wrhwr.site_id IS NULL)
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC;

And then, because it's readable you can easily see where the problems are (which I have commented out).

SELECT wrhwr.bl_id,
       Count(wrhwr.wr_id) AS ct_wr_id
FROM ( SELECT wrhwr.bl_id,
              wrhwr.wr_id,
              wrhwr.site_id,
              wrhwr.date_requested
        FROM   wrhwr
        WHERE /*AND ( */wrhwr.bl_id LIKE 'F0006440-B0001%'/*) */
          AND wrhwr.bl_id IN  ( SELECT TOP 10 q.bl_id
                                FROM ( SELECT bl_id,
                                              Count(wr_id) AS wrcnt
                                       FROM afm.wrhwr
                                       GROUP BY bl_id) AS q
                                WHERE wrhwr.[status] IN ('Com','I','HL','HP','S')
                                ORDER BY q.wrcnt DESC))wrhwr
WHERE /*((And(*/wrhwr.bl_id LIKE 'F0006440-B0001%'/*) )) */
  AND /*( */wrhwr.site_id IN ( SELECT site_id
                               FROM [site]
                               WHERE  state_id = 'JHB')
   OR wrhwr.site_id IS NULL/*)*/
GROUP BY wrhwr.bl_id
ORDER BY wrhwr.bl_id DESC;

But, I'll be honest, that query is still awful, but after my SQL OCD kicked in to at least fix the "look" of the query, I have no interest in making it usable. :)


来源: stackexchange

问:
Uncaught TypeError in getting json value
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});
```

<p>This is the JSON:</p>

```{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}
```

答:
Another approach could be something like this.

```<code>function nameSearchIdx(jsonData, idx, checkValue) {
    if (jsonData.nameSearch[idx].searchname === checkValue) {
        var linkname = jsonData.nameSearch[idx].namelink;
        alert(linkname);
    }
}
var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  Object.getOwnPropertyNames(jsonData.nameSearch).forEach(function (val, idx, array) {
     if(!isNaN(val)) {
         nameSearchIdx(jsonData, idx, selectedVal);
     }
   });
});
</code>```

var jsonData = {
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
};
function nameSearchIdx(jsonData, idx, checkValue) {
if (jsonData.nameSearch[idx].searchname === checkValue) {
      var linkname = jsonData.nameSearch[idx].namelink;
      alert(linkname);
}
}
Object.getOwnPropertyNames(jsonData.nameSearch).forEach(
  function (val, idx, array) {
      if(!isNaN(val)) {
          nameSearchIdx(jsonData, idx, "calendar");
    }
  }
);```

ContentLicense: CC BY-SA 3.0

Body:
Below the code is working but I am getting

Uncaught TypeError: Cannot read property 'searchname' of undefined

Why am I getting this error message? I do not know how to resolve this issue.

var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  for (var j = 0; j <= jsonData.nameSearch.length; j++) {
    if (jsonData.nameSearch[j].searchname == selectedVal) {
      var linkname = jsonData.nameSearch[j].namelink;
      alert(linkname);
    }
  }
});

This is the JSON:

{
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
}

Body:
Another approach could be something like this.

function nameSearchIdx(jsonData, idx, checkValue) {
    if (jsonData.nameSearch[idx].searchname === checkValue) {
        var linkname = jsonData.nameSearch[idx].namelink;
        alert(linkname);
    }
}
var selectedVal = "calendar";
$.getJSON("/js/datas.json", function(jsonData) {
  Object.getOwnPropertyNames(jsonData.nameSearch).forEach(function (val, idx, array) {
     if(!isNaN(val)) {
         nameSearchIdx(jsonData, idx, selectedVal);
     }
   });
});

var jsonData = {
  "nameSearch": [{
    "searchname": "calendar",
    "namelink": "holidays"
  }, {
    "searchname": "date",
    "namelink": "kilo"
  }]
};
function nameSearchIdx(jsonData, idx, checkValue) {
if (jsonData.nameSearch[idx].searchname === checkValue) {
      var linkname = jsonData.nameSearch[idx].namelink;
      alert(linkname);
}
}
Object.getOwnPropertyNames(jsonData.nameSearch).forEach(
  function (val, idx, array) {
      if(!isNaN(val)) {
          nameSearchIdx(jsonData, idx, "calendar");
    }
  }
);


问:
How to use multiple response in ng-repeat angularjs?
```<code>$http({
                method: 'GET',
                url: '/api/getnewgroup'
            })
            .then(function (response) {
                $scope.groups = response.data;
            }, function (response) {
                window.location.href = '/';
            });

        $http({
            method: 'GET',
            url: '/api/getnewgroupforprofsms'
        })
        .then(function (response) {
            $scope.profsmsgroups.groups = response.data;
        }, function (response) {
            window.location.href = '/';
        });
</code>```

I got two various response in $scope.groups and $scope.profsmsgroups.groups two multiple scopes.

```<code>tr(ng-repeat='group in profsmsgroups.groups')
   td
   input(type = 'checkbox', ng-model='group.select')
   td {{group.groupname}}
   td {{group.contactsCount}}
</code>```

I have groupname in $scope.profsmsgroups.groups scope, so td {{group.groupname}} is displaying correctly

but i have contactsCount in $scope.groups

So how to use multiple ng-repeat response?

my $scope.profsms.groups json:

```<code>[
    {
        "id": 7,
        "groupname": "Angular",
        "createdAt": "2017-12-07T10:49:31.000Z",
        "updatedAt": "2017-12-07T10:49:31.000Z",
        "contactgroups": [
            {
                "id": 7,
                "contact": {
                    "gsm": "4779306474"
                }
            }
        ]
    },
    {
        "id": 3,
        "groupname": "Vue",
        "createdAt": "2017-12-05T09:36:15.000Z",
        "updatedAt": "2017-12-05T09:36:15.000Z",
        "contactgroups": []
    },
    {
        "id": 5,
        "groupname": "React",
        "createdAt": "2017-12-05T09:36:29.000Z",
        "updatedAt": "2017-12-07T10:46:28.000Z",
        "contactgroups": []
    },
    {
        "id": 6,
        "groupname": "Node",
        "createdAt": "2017-12-06T09:47:24.000Z",
        "updatedAt": "2017-12-07T10:46:35.000Z",
        "contactgroups": []
    }
]
</code>```

my $scope.groups response

```<code>[
    {
        "id": 3,
        "groupname": "Vue",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 5,
        "groupname": "React",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 6,
        "groupname": "Node",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 7,
        "groupname": "Angular",
        "contactsCount": 1,
        "contactgroups": [
            {
                "id": 7
            }
        ]
    }
]
</code>```

答:
I assume you have comment id between the two than you can achieve it like:-

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.groups=[
{
    "id": 3,
    "groupname": "Vue",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 5,
    "groupname": "React",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 6,
    "groupname": "Node",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 7,
    "groupname": "Angular",
    "contactsCount": 1,
    "contactgroups": [
        {
            "id": 7
        }
    ]
}
];
$scope.pGroups=[
{
    "id": 7,
    "groupname": "Angular",
    "createdAt": "2017-12-07T10:49:31.000Z",
    "updatedAt": "2017-12-07T10:49:31.000Z",
    "contactgroups": [
        {
            "id": 7,
            "contact": {
                "gsm": "4779306474"
            }
        }
    ]
},
{
    "id": 3,
    "groupname": "Vue",
    "createdAt": "2017-12-05T09:36:15.000Z",
    "updatedAt": "2017-12-05T09:36:15.000Z",
    "contactgroups": []
},
{
    "id": 5,
    "groupname": "React",
    "createdAt": "2017-12-05T09:36:29.000Z",
    "updatedAt": "2017-12-07T10:46:28.000Z",
    "contactgroups": []
},
{
    "id": 6,
    "groupname": "Node",
    "createdAt": "2017-12-06T09:47:24.000Z",
    "updatedAt": "2017-12-07T10:46:35.000Z",
    "contactgroups": []
}
];
$scope.getContactCount=function(group){
var match=$scope.groups.find(function(d){return d.id==group.id})
if(match){
return match.contactsCount
}
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table  style="width:100%">
<tr>
<th>name</th>
  <th>count</th>
</tr>
<tr ng-repeat="g in pGroups">
  <td style="text-align: center;">{{g.groupname}}</td>
  <td style="text-align: center;">{{getContactCount(g)}}</td>
</tr>
</table>
</div></code>```

Body:
$http({
                method: 'GET',
                url: '/api/getnewgroup'
            })
            .then(function (response) {
                $scope.groups = response.data;
            }, function (response) {
                window.location.href = '/';
            });

        $http({
            method: 'GET',
            url: '/api/getnewgroupforprofsms'
        })
        .then(function (response) {
            $scope.profsmsgroups.groups = response.data;
        }, function (response) {
            window.location.href = '/';
        });

I got two various response in $scope.groups and $scope.profsmsgroups.groups two multiple scopes.

tr(ng-repeat='group in profsmsgroups.groups')
   td
   input(type = 'checkbox', ng-model='group.select')
   td {{group.groupname}}
   td {{group.contactsCount}}

I have groupname in $scope.profsmsgroups.groups scope, so td {{group.groupname}} is displaying correctly

but i have contactsCount in $scope.groups

So how to use multiple ng-repeat response?

my $scope.profsms.groups json:

[
    {
        "id": 7,
        "groupname": "Angular",
        "createdAt": "2017-12-07T10:49:31.000Z",
        "updatedAt": "2017-12-07T10:49:31.000Z",
        "contactgroups": [
            {
                "id": 7,
                "contact": {
                    "gsm": "4779306474"
                }
            }
        ]
    },
    {
        "id": 3,
        "groupname": "Vue",
        "createdAt": "2017-12-05T09:36:15.000Z",
        "updatedAt": "2017-12-05T09:36:15.000Z",
        "contactgroups": []
    },
    {
        "id": 5,
        "groupname": "React",
        "createdAt": "2017-12-05T09:36:29.000Z",
        "updatedAt": "2017-12-07T10:46:28.000Z",
        "contactgroups": []
    },
    {
        "id": 6,
        "groupname": "Node",
        "createdAt": "2017-12-06T09:47:24.000Z",
        "updatedAt": "2017-12-07T10:46:35.000Z",
        "contactgroups": []
    }
]

my $scope.groups response

[
    {
        "id": 3,
        "groupname": "Vue",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 5,
        "groupname": "React",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 6,
        "groupname": "Node",
        "contactsCount": 0,
        "contactgroups": []
    },
    {
        "id": 7,
        "groupname": "Angular",
        "contactsCount": 1,
        "contactgroups": [
            {
                "id": 7
            }
        ]
    }
]

Body:
I assume you have comment id between the two than you can achieve it like:-

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.groups=[
{
    "id": 3,
    "groupname": "Vue",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 5,
    "groupname": "React",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 6,
    "groupname": "Node",
    "contactsCount": 0,
    "contactgroups": []
},
{
    "id": 7,
    "groupname": "Angular",
    "contactsCount": 1,
    "contactgroups": [
        {
            "id": 7
        }
    ]
}
];
$scope.pGroups=[
{
    "id": 7,
    "groupname": "Angular",
    "createdAt": "2017-12-07T10:49:31.000Z",
    "updatedAt": "2017-12-07T10:49:31.000Z",
    "contactgroups": [
        {
            "id": 7,
            "contact": {
                "gsm": "4779306474"
            }
        }
    ]
},
{
    "id": 3,
    "groupname": "Vue",
    "createdAt": "2017-12-05T09:36:15.000Z",
    "updatedAt": "2017-12-05T09:36:15.000Z",
    "contactgroups": []
},
{
    "id": 5,
    "groupname": "React",
    "createdAt": "2017-12-05T09:36:29.000Z",
    "updatedAt": "2017-12-07T10:46:28.000Z",
    "contactgroups": []
},
{
    "id": 6,
    "groupname": "Node",
    "createdAt": "2017-12-06T09:47:24.000Z",
    "updatedAt": "2017-12-07T10:46:35.000Z",
    "contactgroups": []
}
];
$scope.getContactCount=function(group){
var match=$scope.groups.find(function(d){return d.id==group.id})
if(match){
return match.contactsCount
}
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table  style="width:100%">
<tr>
<th>name</th>
  <th>count</th>
</tr>
<tr ng-repeat="g in pGroups">
  <td style="text-align: center;">{{g.groupname}}</td>
  <td style="text-align: center;">{{getContactCount(g)}}</td>
</tr>
</table>
</div>


问:
How to ignore or remove null element from an array inside collection
```<code>Collection {#363 ▼
  #items: array:3 [▼
    0 => Tag {#376 ▶}
    1 => null
    2 => Tag {#374 ▶}
  ]
}
</code>```

I want to remove the second key/pair element from this collection. How can I achieve this?

答:
Additionally, Collection@filter will remove the nulls without having to use any closure to do the checking. Similar to how array_filter will remove the nulls.

```<code>$filtered = $collection->filter();
// nulls will be removed
</code>```

To supplement the previous answer using Collection@filter

ContentLicense: CC BY-SA 4.0

Body:
Collection {#363 ▼
  #items: array:3 [▼
    0 => Tag {#376 ▶}
    1 => null
    2 => Tag {#374 ▶}
  ]
}

I want to remove the second key/pair element from this collection. How can I achieve this?

Body:
Additionally, Collection@filter will remove the nulls without having to use any closure to do the checking. Similar to how array_filter will remove the nulls.

$filtered = $collection->filter();
// nulls will be removed

To supplement the previous answer using Collection@filter


问:
Android O Error in use of IMPORTANCE_UNSPECIFIED with notification channel in service
I want to display notification from my service for android O but i got this crash and i want's to use IMPORTANCE_UNSPECIFIED with notification channel

```<code> java.lang.IllegalArgumentException: Invalid importance level
</code>```

here is my code.

```<code> if (android.os.Build.VERSION.SDK_INT >= 26) {
            try {

                  // Create the channel for the notification
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_UNSPECIFIED);

                    // Set the Notification Channel for the Notification Manager.
                    mNotificationManager.createNotificationChannel(mChannel);

                    Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                            .setSmallIcon(R.mipmap.instant_app_icon)
                            .setContentTitle(getString(R.string.app_name))
                            //  .setContentText("Instant Service")
                            .setAutoCancel(true);

                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

                    builder.setContentIntent(contentIntent);

                    Notification notification = builder.build();
                    startForeground(1, notification);

                }

                catch (Exception ex){
                    ex.printStackTrace();
                }
            }
</code>```

答:
According to API Docs

added in API level 24 int IMPORTANCE_UNSPECIFIED Value signifying that the user has not expressed an importance. This value is for persisting preferences, and should never be associated with an actual notification.

You should use NotificationManager.IMPORTANCE_DEFAULT..
Something like this

```<code>NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);

// Set the Notification Channel for the Notification Manager.
mNotificationManager.createNotificationChannel(mChannel);
</code>```

You can set lockscreen visibility with notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);

Body:
I want to display notification from my service for android O but i got this crash and i want's to use IMPORTANCE_UNSPECIFIED with notification channel

 java.lang.IllegalArgumentException: Invalid importance level

here is my code.

 if (android.os.Build.VERSION.SDK_INT >= 26) {
            try {

                  // Create the channel for the notification
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_UNSPECIFIED);

                    // Set the Notification Channel for the Notification Manager.
                    mNotificationManager.createNotificationChannel(mChannel);

                    Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                            .setSmallIcon(R.mipmap.instant_app_icon)
                            .setContentTitle(getString(R.string.app_name))
                            //  .setContentText("Instant Service")
                            .setAutoCancel(true);

                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

                    builder.setContentIntent(contentIntent);

                    Notification notification = builder.build();
                    startForeground(1, notification);

                }

                catch (Exception ex){
                    ex.printStackTrace();
                }
            }

Body:
According to API Docs

added in API level 24 int IMPORTANCE_UNSPECIFIED Value signifying that the user has not expressed an importance. This value is for persisting preferences, and should never be associated with an actual notification.

You should use NotificationManager.IMPORTANCE_DEFAULT..
Something like this

NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);

// Set the Notification Channel for the Notification Manager.
mNotificationManager.createNotificationChannel(mChannel);

You can set lockscreen visibility with notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);


问:
Sum all the child level data
I have a requirement where I need to sum up all the child of a node.

And the Output should be

```<code>D023343 120
D022959 120
D023375 50
D035738 10
D024481 0
</code>```

I tried using diff queries but it is not getting the required . Kindly help

```<code>SELECT * FROM (SELECT a.child achild,b.child bchild,a.parent aparent,b.parent bparent,a.sales,b.sales
 FROM TEST a,TEST b
WHERE a.CHILD='D023375')
where aparent!=bchild
and achild=bparent
</code>```

Kindly help.

Thanks

答:
Use a hierarchical query to traverse the hierarchy and CONNECT_BY_ROOT() to reference the top of the hierarchy - you can then use that to group the query to get the totals of the descendants.

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE your_table( parent, child, sales ) AS
SELECT 'D023343', 'D022959',  0 FROM DUAL UNION ALL
SELECT 'D022959', 'D023375', 60 FROM DUAL UNION ALL
SELECT 'D023375', 'D035738', 50 FROM DUAL UNION ALL
SELECT 'D035738', 'D024481', 10 FROM DUAL;
</code>```

Query 1:

```<code>SELECT root,
       SUM( sales ) AS total_sales
FROM   (
  SELECT CONNECT_BY_ROOT( parent ) AS root,
         sales
  FROM   your_table
  CONNECT BY PRIOR child = parent
)
GROUP BY root
</code>```

Results:

```<code>|    ROOT | TOTAL_SALES |
|---------|-------------|
| D023375 |          60 |
| D035738 |          10 |
| D023343 |         120 |
| D022959 |         120 |
</code>```

If you want the leaf children that have no sales then you will need to do something like appending

```<code>UNION ALL
SELECT child, 0 FROM your_table
</code>```

to the inner query.

Title: Sum all the child level data

Body:
I have a requirement where I need to sum up all the child of a node.

And the Output should be

D023343 120
D022959 120
D023375 50
D035738 10
D024481 0

I tried using diff queries but it is not getting the required . Kindly help

SELECT * FROM (SELECT a.child achild,b.child bchild,a.parent aparent,b.parent bparent,a.sales,b.sales
 FROM TEST a,TEST b
WHERE a.CHILD='D023375')
where aparent!=bchild
and achild=bparent

Kindly help.

Thanks

Body:
Use a hierarchical query to traverse the hierarchy and CONNECT_BY_ROOT() to reference the top of the hierarchy - you can then use that to group the query to get the totals of the descendants.

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE your_table( parent, child, sales ) AS
SELECT 'D023343', 'D022959',  0 FROM DUAL UNION ALL
SELECT 'D022959', 'D023375', 60 FROM DUAL UNION ALL
SELECT 'D023375', 'D035738', 50 FROM DUAL UNION ALL
SELECT 'D035738', 'D024481', 10 FROM DUAL;

Query 1:

SELECT root,
       SUM( sales ) AS total_sales
FROM   (
  SELECT CONNECT_BY_ROOT( parent ) AS root,
         sales
  FROM   your_table
  CONNECT BY PRIOR child = parent
)
GROUP BY root

Results:

|    ROOT | TOTAL_SALES |
|---------|-------------|
| D023375 |          60 |
| D035738 |          10 |
| D023343 |         120 |
| D022959 |         120 |

If you want the leaf children that have no sales then you will need to do something like appending

UNION ALL
SELECT child, 0 FROM your_table

to the inner query.


问:
How do I allow HTTPS for Apache on localhost?
I was asked to set up HTTPS with a self-signed cert on Apache on localhost, but how do I actually do that? I have no idea at all.</p>

答:
For those using macOS this is a great guide https://getgrav.org/blog/macos-sierra-apache-multiple-php-versions to set up your local web dev environment. In its 3rd part https://getgrav.org/blog/macos-sierra-apache-ssl  Andy Miller explains how to set up apache with a self-signed certificate:

This is the key command:

```<code>openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
</code>```

But there are a few steps you need to follow, so check that out and good luck! ;)

Body:
For those using macOS this is a great guide https://getgrav.org/blog/macos-sierra-apache-multiple-php-versions to set up your local web dev environment. In its 3rd part https://getgrav.org/blog/macos-sierra-apache-ssl  Andy Miller explains how to set up apache with a self-signed certificate:

This is the key command:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout server.key -out server.crt

But there are a few steps you need to follow, so check that out and good luck! ;)


问:
Remove Rows based on values in 2 columns unless another column has a specific text character
So I have a sheet with 6 columns, and it has headers. In column F there are dates in mm - dd - yy format. In Column B there are numbers referencing the priority of the order, ranging from -999,999 to 473,700. In Column A there are Workcenter numbers in the form of numbers, 4005, 7009, etc. Some SPECIAL workcenters have names that end in R. I need to DELETE all rows that follow these criteria:
 - Greater than 0 in Column B
 - Assigned today's date in column F
 - DO NOT have an R at the end of the workcenter in column A

Here is what I have so far, but it is still deleting R workcenters (like 1027R)

I have looked at many different articles on this site, some using the AutoFilter tool, some using if value is this, then increment this var and add all vars together to check if the row should be deleted, but this is the cleanest I have gotten the code so far, and it is not working correctly. Also there are lots of articles about removing duplicates, but that is not my problem here.

```<code>Sub CleanData()
Dim lr As Long, i As Long
With Sheet3
    lr = Application.Max(.Cells(Rows.Count, 1).End(xlUp).Row, _
      .Cells(Rows.Count, 2).End(xlUp).Row, _
      .Cells(Rows.Count, 6).End(xlUp).Row)
    For i = lr To 1 Step -1
        If Not InStr(1, ActiveSheet.Cells(i, 2).Value, "R") > 0 And _
            .Cells(i, 2).Value > 0 And _
            .Cells(i, 6).Value = Date Then
            .Rows(i).EntireRow.Delete
        End If
    Next i
End With
</code>```

End Sub

答:
```<code>Sub CleanData()
Dim lr As Long, i As Long
With Sheet3
    lr = Application.Max(.Cells(Rows.Count, 1).End(xlUp).Row, _
      .Cells(Rows.Count, 2).End(xlUp).Row, _
      .Cells(Rows.Count, 6).End(xlUp).Row)
    For i = lr To 1 Step -1
        If Not Application.Right(.Cells(i, 1).Value, 1) = "R" Then
            If .Cells(i, 2).Value > 0 And .Cells(i, 6).Value = Date Then
                .Rows(i).EntireRow.Delete
            End If
        End If
    Next i
End With
</code>```

Your issue appears to have been If Not InStr(1, ActiveSheet.Cells(i, 2).Value, "R") where InStr is evaluating column B. I only changed to a nested if for my sanity as it reads easier... If you have any more issues I would think it may be with the format of Date.

Body:
So I have a sheet with 6 columns, and it has headers. In column F there are dates in mm - dd - yy format. In Column B there are numbers referencing the priority of the order, ranging from -999,999 to 473,700. In Column A there are Workcenter numbers in the form of numbers, 4005, 7009, etc. Some SPECIAL workcenters have names that end in R. I need to DELETE all rows that follow these criteria:
 - Greater than 0 in Column B
 - Assigned today's date in column F
 - DO NOT have an R at the end of the workcenter in column A

Here is what I have so far, but it is still deleting R workcenters (like 1027R)

I have looked at many different articles on this site, some using the AutoFilter tool, some using if value is this, then increment this var and add all vars together to check if the row should be deleted, but this is the cleanest I have gotten the code so far, and it is not working correctly. Also there are lots of articles about removing duplicates, but that is not my problem here.

Sub CleanData()
Dim lr As Long, i As Long
With Sheet3
    lr = Application.Max(.Cells(Rows.Count, 1).End(xlUp).Row, _
      .Cells(Rows.Count, 2).End(xlUp).Row, _
      .Cells(Rows.Count, 6).End(xlUp).Row)
    For i = lr To 1 Step -1
        If Not InStr(1, ActiveSheet.Cells(i, 2).Value, "R") > 0 And _
            .Cells(i, 2).Value > 0 And _
            .Cells(i, 6).Value = Date Then
            .Rows(i).EntireRow.Delete
        End If
    Next i
End With

End Sub

Body:
Sub CleanData()
Dim lr As Long, i As Long
With Sheet3
    lr = Application.Max(.Cells(Rows.Count, 1).End(xlUp).Row, _
      .Cells(Rows.Count, 2).End(xlUp).Row, _
      .Cells(Rows.Count, 6).End(xlUp).Row)
    For i = lr To 1 Step -1
        If Not Application.Right(.Cells(i, 1).Value, 1) = "R" Then
            If .Cells(i, 2).Value > 0 And .Cells(i, 6).Value = Date Then
                .Rows(i).EntireRow.Delete
            End If
        End If
    Next i
End With

Your issue appears to have been If Not InStr(1, ActiveSheet.Cells(i, 2).Value, "R") where InStr is evaluating column B. I only changed to a nested if for my sanity as it reads easier... If you have any more issues I would think it may be with the format of Date.


问:
Split txt file with bat every x pipes
I have a txt file with the following type of string:

A|B|B|CC|R|TRR|Y|D|S|S|S|G|Q|G|...

There is someone that can help me to create a .bat file that take this file and create a new one with the following result?

A|B|B|CC|

R|TRR|Y|D|

S|S|S|G|

In other words I need to split the string every 4 | going in a new line every 4th pipe.

Thanks in advance.

答:
I adapted a script for you to use from here.

It adds a word-wrap every 8 symbols and saves it to a new file.

```<code>@echo off & setlocal
set "in=C:\insert.txt"
set "out=C:\output.txt"

set S8=%temp%\Split8.vbs
echo Set fso=CreateObject("Scripting.FileSystemObject"):Text=fso.OpenTextFile("%in%",1).ReadAll>%S8%
echo Set out=fso.OpenTextFile("%out%",2,True):For i=1 To Len(Text) Step 8:out.WriteLine Mid(Text,i,8):Next:out.Close>>%S8%
cscript //nologo %S8%
del %S8%
</code>```

Title: Split txt file with bat every x pipes

Body:
I adapted a script for you to use from here.

It adds a word-wrap every 8 symbols and saves it to a new file.

@echo off & setlocal
set "in=C:\insert.txt"
set "out=C:\output.txt"

set S8=%temp%\Split8.vbs
echo Set fso=CreateObject("Scripting.FileSystemObject"):Text=fso.OpenTextFile("%in%",1).ReadAll>%S8%
echo Set out=fso.OpenTextFile("%out%",2,True):For i=1 To Len(Text) Step 8:out.WriteLine Mid(Text,i,8):Next:out.Close>>%S8%
cscript //nologo %S8%
del %S8%


问:
Why are the result of preg_match not displayed?
I can't see the results of preg_match by regex! Where is the problem?

```<code>preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from: <p id='long'>{$matches[0]}\n</p>";
}
</code>```

Output:

```<code>from:
</code>```

答:
```<code>echo parse_url($urls['url'], PHP_URL_HOST);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I can't see the results of preg_match by regex! Where is the problem?

preg_match('@^(?:http://)?([^/]+)@i',"'".$urls['url']."'", $matches);
    $host = $matches[1];
    preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "from:
{$matches[0]}\n
";
}

Output:

from:


问:
Android - Using Custom Font
I applied a custom font to a TextView, but it doesn't seems to change the typeface.

Here is my code:

```<code>    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);
</code>```

Can anyone please get me out of this issue?

答:
With Android 8.0 using Custom Fonts in Application became easy with downloadable fonts.
We can add fonts directly to the res/font/ folder in the project folder, and in doing so, the fonts become automatically available in Android Studio.

Now set fontFamily attribute to list of fonts or click on more and select font of your choice. This will add tools:fontFamily="@font/your_font_file" line to your TextView.

This will Automatically generate few files.

1. In values folder it will create fonts_certs.xml.

2. In Manifest it will add this lines:

```<code>  <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
</code>```

3.
preloaded_fonts.xml

```<code><resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/open_sans_regular</item>
        <item>@font/open_sans_semibold</item>
    </array>
</resources>
</code>```

Title: Android - Using Custom Font

Body:
I applied a custom font to a TextView, but it doesn't seems to change the typeface.

Here is my code:

    Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
    TextView myTextView = (TextView)findViewById(R.id.myTextView);
    myTextView.setTypeface(myTypeface);

Can anyone please get me out of this issue?

Body:
With Android 8.0 using Custom Fonts in Application became easy with downloadable fonts.
We can add fonts directly to the res/font/ folder in the project folder, and in doing so, the fonts become automatically available in Android Studio.

Now set fontFamily attribute to list of fonts or click on more and select font of your choice. This will add tools:fontFamily="@font/your_font_file" line to your TextView.

This will Automatically generate few files.

1. In values folder it will create fonts_certs.xml.

2. In Manifest it will add this lines:

  <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />

3.
preloaded_fonts.xml

<resources>
    <array name="preloaded_fonts" translatable="false">
        <item>@font/open_sans_regular</item>
        <item>@font/open_sans_semibold</item>
    </array>
</resources>


问:
How to add a constraint to my optimization?
I am working on formulating an optimization problem where I have a 2-D matrix A.

```<code>           A= [0 f1 0 f2]
              [f3 f3 0 0]
              .........
</code>```

And I have another 2-D matrix B that I should fill. B has the same size of A. I need b_ij (element of B) to be zero if a_ij=0 (element of A) and I need b_ij to be greater than zero and less than or equal to a_ij if a_ij is not zero.

How can I represent this in my formulation? I have added this constraint/condition:

```<code>            b_ij<=a_ij
</code>```

But this does not satisfy the condition that states that b_ij is not equal zero when a_ij is not equal zero. Any help?

答:
If all elements are positive, keep the smallest element of each matrix by doing an element by element comparison :

```<code>B2 = min(A,B)
</code>```

Alternatively, create a logical matrix indicating if a condition is answered and multiply element by element with the matrix B , only elements who satisfy the condition remain, others are set to zero:

```<code>B = B.*(A~=0)
</code>```

Then keep elements of B that are smaller or equal to elements of A, and replace them by the value of A otherwise.

```<code>B = B.*(B<=A) + A.*(B>A) )
</code>```

This option lets you generalize your constraint.

You indicate needing elements of b_ij to be greater than zero if elements of a_ij are greater than zero. An option  is to use the function max to ensure that all elements of B are  positive.

```<code>B = max(1e-2,B); % exact value is yours to set.
</code>```

This step is up to you and depend on your problem.

Body:
I am working on formulating an optimization problem where I have a 2-D matrix A.

           A= [0 f1 0 f2]
              [f3 f3 0 0]
              .........

And I have another 2-D matrix B that I should fill. B has the same size of A. I need b_ij (element of B) to be zero if a_ij=0 (element of A) and I need b_ij to be greater than zero and less than or equal to a_ij if a_ij is not zero.

How can I represent this in my formulation? I have added this constraint/condition:

            b_ij<=a_ij

But this does not satisfy the condition that states that b_ij is not equal zero when a_ij is not equal zero. Any help?

Body:
If all elements are positive, keep the smallest element of each matrix by doing an element by element comparison :

B2 = min(A,B)

Alternatively, create a logical matrix indicating if a condition is answered and multiply element by element with the matrix B , only elements who satisfy the condition remain, others are set to zero:

B = B.*(A~=0)

Then keep elements of B that are smaller or equal to elements of A, and replace them by the value of A otherwise.

B = B.*(B<=A) + A.*(B>A) )

This option lets you generalize your constraint.

You indicate needing elements of b_ij to be greater than zero if elements of a_ij are greater than zero. An option  is to use the function max to ensure that all elements of B are  positive.

B = max(1e-2,B); % exact value is yours to set.

This step is up to you and depend on your problem.


问:
TRACKER : error TRK0005: Failed to locate: "CL.exe"
I feel like I've tried everything.

I have installed and uninstalled every single version of Visual
studio (from 2010 - 2017)

I have attempted to install the build tools used for windows c++

I have uninstalled node.js and reinstalled.

BUT NO matter what I do I still get the error:

```<code>TRACKER : error TRK0005: Failed to locate: "CL.exe".
</code>```

I have attempted every "solution" i could find on google that discusses or descripe this issue.

When i run npm install

I get the following error:

```<code>    TRACKER : error TRK0005: Failed to locate: "CL.exe". file not found

gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\xampp\htdocs\myproject\src\node_modules\node-expat
gyp ERR! node -v v6.11.1
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
learningbank@1.0.0 C:\xampp\htdocs\myproject\src
`-- (empty)
</code>```

Can anyone tell me how I can fix this issue?

My operation system is "Windows 10 pro".

答: I tried to install Visual Studio 2015. Still, I see this error. Later on I found that I must choose Custom Install, Select Visual C++ during the installation.</p>

Body:
I feel like I've tried everything.

I have installed and uninstalled every single version of Visual
studio (from 2010 - 2017)

I have attempted to install the build tools used for windows c++

I have uninstalled node.js and reinstalled.

BUT NO matter what I do I still get the error:

TRACKER : error TRK0005: Failed to locate: "CL.exe".

I have attempted every "solution" i could find on google that discusses or descripe this issue.

When i run npm install

I get the following error:

    TRACKER : error TRK0005: Failed to locate: "CL.exe". file not found

gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack     at emitTwo (events.js:106:13)
gyp ERR! stack     at ChildProcess.emit (events.js:191:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:215:12)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\xampp\htdocs\myproject\src\node_modules\node-expat
gyp ERR! node -v v6.11.1
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
learningbank@1.0.0 C:\xampp\htdocs\myproject\src
`-- (empty)

Can anyone tell me how I can fix this issue?

My operation system is "Windows 10 pro".


问:
convert maven pom to gradle build
I am converting one of my maven project into gradle. For doing this I am runngin following command where pom.xml is located

```<code>gradle init --type pom
</code>```

But it is giving me java.lang.NullPointerException

```<code>  FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':init'.
> Could not convert Maven POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml to a Gradle build.
> Unable to create Maven project model using POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml.
  > java.lang.NullPointerException (no error message)
</code>```

is there anything to perform with init or anything else i am missing?

This is my pom.xml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.test</groupId>
<artifactId>ui</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>ui</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-parent</artifactId>
            <version>1.0.1.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <wro4j.version>1.7.6</wro4j.version>
    <java.version>1.7</java.version>
</properties>

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
        </resource>
        <resource>
            <directory>${project.build.directory}/generated-resources</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
                <execution>
                    <!-- Serves *only* to filter the wro.xml so it can get an absolute
                        path for the project -->
                    <id>copy-resources</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/target/wro</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/wro</directory>
                                <filtering>true</filtering>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>ro.isdc.wro4j</groupId>
            <artifactId>wro4j-maven-plugin</artifactId>
            <version>${wro4j.version}</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
                <cssDestinationFolder>${project.build.directory}/generated-resources/static/css</cssDestinationFolder>
                <jsDestinationFolder>${project.build.directory}/generated-resources/static/js</jsDestinationFolder>
                <wroFile>${project.build.directory}/wro/wro.xml</wroFile>
                <extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
                <contextFolder>${basedir}/src/main/wro</contextFolder>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                    <version>2.1.1</version>
                </dependency>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>angularjs</artifactId>
                    <version>1.3.8</version>
                </dependency>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>bootstrap</artifactId>
                    <version>3.2.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>http://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
</code>```

答:
Not only will the Gradle init task allow you to create a new skeleton project, but it will also automatically convert an existing Maven one to Gradle. All you have to do is run the command

$ gradle init

Title: convert maven pom to gradle build

Body:
I am converting one of my maven project into gradle. For doing this I am runngin following command where pom.xml is located

gradle init --type pom

But it is giving me java.lang.NullPointerException

  FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':init'.
> Could not convert Maven POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml to a Gradle build.
> Unable to create Maven project model using POM /Users/myname/Documents/oAuth+Angular/workspace/feature-oauth_and_security_69/ui/pom.xml.
  > java.lang.NullPointerException (no error message)

is there anything to perform with init or anything else i am missing?

This is my pom.xml :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.test</groupId>
<artifactId>ui</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>ui</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
    <relativePath />
</parent>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-parent</artifactId>
            <version>1.0.1.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <wro4j.version>1.7.6</wro4j.version>
    <java.version>1.7</java.version>
</properties>

<build>
    <resources>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
        </resource>
        <resource>
            <directory>${project.build.directory}/generated-resources</directory>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
                <execution>

                    <id>copy-resources</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/target/wro</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/wro</directory>
                                <filtering>true</filtering>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>ro.isdc.wro4j</groupId>
            <artifactId>wro4j-maven-plugin</artifactId>
            <version>${wro4j.version}</version>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
                <cssDestinationFolder>${project.build.directory}/generated-resources/static/css</cssDestinationFolder>
                <jsDestinationFolder>${project.build.directory}/generated-resources/static/js</jsDestinationFolder>
                <wroFile>${project.build.directory}/wro/wro.xml</wroFile>
                <extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
                <contextFolder>${basedir}/src/main/wro</contextFolder>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>jquery</artifactId>
                    <version>2.1.1</version>
                </dependency>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>angularjs</artifactId>
                    <version>1.3.8</version>
                </dependency>
                <dependency>
                    <groupId>org.webjars</groupId>
                    <artifactId>bootstrap</artifactId>
                    <version>3.2.0</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>http://repo.spring.io/libs-snapshot-local</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/libs-milestone-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-releases</id>
        <name>Spring Releases</name>
        <url>http://repo.spring.io/libs-release-local</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>


问:
Fetching Single Client Data - Laravel
In my code below,

I request for the ids of selected products (by checking a checkbox).

Now, i find the clients of whom the products belong to. Then i get the name and phone number of the clients.

Now the query string below is an API to send messages to these clients.

but When i send a message, i am not able to seperate the product numbers for the respective clients.

For instance, if Mark and Bill are the clients, the message should be like

Dear Customer, your products with number #343fr3 has been shipped - For Mark`

Dear Customer, your products with number #22543 has been shipped - For Bill

But what happens with mine is, one clients (Mark or Bill) gets the product number of another in the message.

What am i doing wrong or could it be from how the api is structured?

```<code> public function sendAll(Request $request)
 {
     $ids      = $request->ids;
     $split    = explode(",",$ids);
     $shipment = Shipment::findOrFail($split);

     if(request()->ajax()) {
         $clients = Client::whereHas('products', function($find_clients)use($split)
        {
            $find_clients->whereIn('id',$split);
        })->get();

        foreach($shipment as $check_shipment)
        {
            if($check_shipment->status == 0 )
            {
                //do something
            }
            else
            {
                $get_client_name  = [];
                $get_client_phone = [];

                foreach($clients as $key => $client)
                {
                    $get_client_name[]  = $client->name;
                    $get_client_phone[] = $client->phone;
                }

                $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";
           }
       }
   }
}
</code>```

答:
i would go moreless this way:

```<code>public function sendAll(Request $request)
{
 $ids = $request->ids;
 $split = explode(",",$ids);
 $shipment = Shipment::where('status', '>', 0)->whereIn('id', $split);

 if(request()->ajax()) {

    foreach($shipment->get() as $check_shipment)
    {

            $query = "?key=something&to=".implode(',',$check_shipment->client->phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";

     }
  }
}
</code>```

I assume shipment belongs to client

Title: Fetching Single Client Data - Laravel

Body:
In my code below,

I request for the ids of selected products (by checking a checkbox).

Now, i find the clients of whom the products belong to. Then i get the name and phone number of the clients.

Now the query string below is an API to send messages to these clients.

but When i send a message, i am not able to seperate the product numbers for the respective clients.

For instance, if Mark and Bill are the clients, the message should be like

Dear Customer, your products with number #343fr3 has been shipped - For Mark`

Dear Customer, your products with number #22543 has been shipped - For Bill

But what happens with mine is, one clients (Mark or Bill) gets the product number of another in the message.

What am i doing wrong or could it be from how the api is structured?

 public function sendAll(Request $request)
 {
     $ids      = $request->ids;
     $split    = explode(",",$ids);
     $shipment = Shipment::findOrFail($split);

     if(request()->ajax()) {
         $clients = Client::whereHas('products', function($find_clients)use($split)
        {
            $find_clients->whereIn('id',$split);
        })->get();

        foreach($shipment as $check_shipment)
        {
            if($check_shipment->status == 0 )
            {
                //do something
            }
            else
            {
                $get_client_name  = [];
                $get_client_phone = [];

                foreach($clients as $key => $client)
                {
                    $get_client_name[]  = $client->name;
                    $get_client_phone[] = $client->phone;
                }

                $query = "?key=something&to=".implode(',',$get_client_phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";
           }
       }
   }
}

Body:
i would go moreless this way:

public function sendAll(Request $request)
{
 $ids = $request->ids;
 $split = explode(",",$ids);
 $shipment = Shipment::where('status', '>', 0)->whereIn('id', $split);

 if(request()->ajax()) {

    foreach($shipment->get() as $check_shipment)
    {

            $query = "?key=something&to=".implode(',',$check_shipment->client->phone)."&msg=Dear Customer, your products with  number ".$check_shipment->id." has been shipped.";

     }
  }
}

I assume shipment belongs to client


问:
Convert array to conditional php
I have and array, and I want to convert it into an if conditional.

```<code>$array = ['check 1', 'check 2', 'check 3'];
</code>```

I want the final result to work like this:

```<code>if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}
</code>```

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

答:
Loop through array and check in_array like this:

```<code>$array = ( 'check 1', 'check 2', 'check 3' );

    foreach($array as $k => $v)
    {
        $flag = "false";
        if(in_array($v,$array))
        {
            $flag = "true";
        }
    }
</code>```

So from above code, is any of the value exist in array, the variable $flag will have string value "true".

Title: Convert array to conditional php

Body:
I have and array, and I want to convert it into an if conditional.

$array = ['check 1', 'check 2', 'check 3'];

I want the final result to work like this:

if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

Body:
Loop through array and check in_array like this:

$array = ( 'check 1', 'check 2', 'check 3' );

    foreach($array as $k => $v)
    {
        $flag = "false";
        if(in_array($v,$array))
        {
            $flag = "true";
        }
    }

So from above code, is any of the value exist in array, the variable $flag will have string value "true".


问:
How to extract a vector in a tibble column to multiple columns in the same tibble?
The following code produces a vector of length 6 in the last column, from that column I would like to extract 6 new columns in my tibble.

```<code>require(tidyverse)
require(purrrlyr)
# this function will return a vector of the same length (6) for each group
fun=function(X,Y){
   mycut<-cut(X,breaks=seq(50,350,by=50),right=FALSE)
   v<-tapply(Y,mycut,sum)
   return(v)
}
# use the previous function to count gears per class of hp
mtcars %>%
    group_by(cyl)  %>%
    by_slice(~fun(.x$hp,.x$gear)) %>%
    rename(cut=.out)
</code>```

Here I have a vector in my column cut

```<code># tibble [3 x 2]
     cyl       cut
  <fctr>    <list>
1      4 <dbl [6]>
2      6 <dbl [6]>
3      8 <dbl [6]>
</code>```

What command do I need to pass from this vector to a table like?

```<code>cyl  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
   4     36         9        NA        NA        NA        NA
   ...
</code>```

unnest does not work. Do I have to work with by_row or is there a more straightforward answer?

答:
I would suggest another approach. Instead of using the deprecated by_slice() function (that now recides in the purrrlyr package), you can use this code:

```<code>mtcars %>%
  split(.$cyl) %>%
  map(~fun(.x$hp,.x$gear)) %>%
  do.call(rbind, .)
</code>```

Which gives the following output

```<code>  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
4       36         9        NA        NA        NA        NA
6       NA        22         5        NA        NA        NA
8       NA        NA        21        15         5         5
</code>```

Body:
The following code produces a vector of length 6 in the last column, from that column I would like to extract 6 new columns in my tibble.

require(tidyverse)
require(purrrlyr)
# this function will return a vector of the same length (6) for each group
fun=function(X,Y){
   mycut<-cut(X,breaks=seq(50,350,by=50),right=FALSE)
   v<-tapply(Y,mycut,sum)
   return(v)
}
# use the previous function to count gears per class of hp
mtcars %>%
    group_by(cyl)  %>%
    by_slice(~fun(.x$hp,.x$gear)) %>%
    rename(cut=.out)

Here I have a vector in my column cut

# tibble [3 x 2]
     cyl       cut
  <fctr>    <list>
1      4 <dbl [6]>
2      6 <dbl [6]>
3      8 <dbl [6]>

What command do I need to pass from this vector to a table like?

cyl  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
   4     36         9        NA        NA        NA        NA
   ...

unnest does not work. Do I have to work with by_row or is there a more straightforward answer?

Body:
I would suggest another approach. Instead of using the deprecated by_slice() function (that now recides in the purrrlyr package), you can use this code:

mtcars %>%
  split(.$cyl) %>%
  map(~fun(.x$hp,.x$gear)) %>%
  do.call(rbind, .)

Which gives the following output

  [50,100) [100,150) [150,200) [200,250) [250,300) [300,350)
4       36         9        NA        NA        NA        NA
6       NA        22         5        NA        NA        NA
8       NA        NA        21        15         5         5


问:
Getting an default namespace for nested XML element by (LINQ to XML)

Im trying to get default namespace for nested element. Part of my XML file is:

```<code><Node xmlns="http://namespace-root/">
 <Node1>
  <Node2 xmlns="http://namespace-element">Value</Node2>
 </Node1>
</Node>
</code>```

Part of my query code is
  (namespaces 'namespaceNode' and 'namespaceElement' are XNamespace objects:

```<code>    from node in xDoc.Elements(namespaceNode+ "Node")
    select new DataObject
    {
        Xmlns = node.Element(namespaceNode+ "Node1").Element(namespaceElement+ "Node2").GetDefaultNamespace(),
        Value = (string)node.Element(namespaceNode+ "Node1").Element(namespaceElement+ "Node2")
    }
</code>```

Value property gets the value of the element, but how can I read the namespace of this node to Xmlns property?

答:
This is how I normally do it</p>

```<code>            XDocument doc = XDocument.Load(FILENAME);
            XElement node = doc.Root;
            XNamespace xNs = node.GetDefaultNamespace();

            XElement node2 = doc.Descendants().Where(x => x.Name.LocalName == "Node2").FirstOrDefault();
            XNamespace x2Ns = node2.GetDefaultNamespace();
</code>```

Body:
Im trying to get default namespace for nested element. Part of my XML file is:

<Node xmlns="http://namespace-root/">
 <Node1>
  <Node2 xmlns="http://namespace-element">Value</Node2>
 </Node1>
</Node>

Part of my query code is
  (namespaces 'namespaceNode' and 'namespaceElement' are XNamespace objects:

    from node in xDoc.Elements(namespaceNode+ "Node")
    select new DataObject
    {
        Xmlns = node.Element(namespaceNode+ "Node1").Element(namespaceElement+ "Node2").GetDefaultNamespace(),
        Value = (string)node.Element(namespaceNode+ "Node1").Element(namespaceElement+ "Node2")
    }

Value property gets the value of the element, but how can I read the namespace of this node to Xmlns property?

Body:
This is how I normally do it

            XDocument doc = XDocument.Load(FILENAME);
            XElement node = doc.Root;
            XNamespace xNs = node.GetDefaultNamespace();

            XElement node2 = doc.Descendants().Where(x => x.Name.LocalName == "Node2").FirstOrDefault();
            XNamespace x2Ns = node2.GetDefaultNamespace();


问:
angularjs ng-paste not updating model value
I have used ng-paste for textarea while pasting the link in textarea, i am calling a custom function to store that value. Please refer following code

```<code><textarea rows="1" ng-model="myObj.content"
              ng-paste="getContent(myObj)">
 </textarea>

$scope.getContent = function(a){
    console.log(a.content);
}
</code>```

But in console always I am getting undefined value. How can I get my object value?

答:
Simply use $timeout to call your paste callback after the model has been updated.

```<code>$scope.getContent = function(a){
   $timeout(function () {console.log(a.content)});
}
</code>```

Body:
I have used ng-paste for textarea while pasting the link in textarea, i am calling a custom function to store that value. Please refer following code

<textarea rows="1" ng-model="myObj.content"
              ng-paste="getContent(myObj)">
 </textarea>

$scope.getContent = function(a){
    console.log(a.content);
}

But in console always I am getting undefined value. How can I get my object value?

Body:
Simply use $timeout to call your paste callback after the model has been updated.

$scope.getContent = function(a){
   $timeout(function () {console.log(a.content)});
}


问:
What does 'Refused to get unsafe header "X-Bandwidth-Est 3"' error mean?
I have a problem with every website that I am working on currently. And the error is this:

Refused to get unsafe header "X-Bandwidth-Est 3" in base.js.
Base.js is youtube file. I searched a lot and I couldn't find this error. Anyone have idea what this error is?

And this is image of this error:

答: All points for a chrome issue, specially because if you go to the youtube.com page and open any video, you will get the same error.</p>


问:
Return words before specific character from wordpress the_title();
I am trying to get words before specific character in WordPress the_title().

My WordPress post titles always looks something like this "How To - Make Things Happen".

How can I return all the words before the "-" in PHP, for example get "How To" from "How To - Make Things"

I am trying to use all words before "-" and a keyword within the post page.

I have seen a similar solution here: Get first word in string php the_title WordPress but it doesn't  fit perfectly as I am trying to get all words before a specific character

答:
You can do it this way:

```<code>$title = get_the_title();
$substring = substr($title, 0, strpos($string, '-'));
</code>```

or

```<code>$title = current(explode('-', get_the_title()));

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

Body:
You can do it this way:

$title = get_the_title();
$substring = substr($title, 0, strpos($string, '-'));

or

$title = current(explode('-', get_the_title()));

echo $title['0'];


问:
systemd[1]: Failed to start LSB: Apache2 web server
I have an Apache Web (version 2.4.10) server running on Debian 8 (Jessie). It is mainly  used as a SVN repository server.
It was working well since a few weeks, and suddenly, I got an internal error when attempting to list the SVN repos from a Web Browser as can be seen below:

Apache Internal Error & Authentication

As you can see, authentication is still working fine.

I ran the 2 following commands:
systemctl status apache2.service
and
journalctl -xn

commands

But that doesn't help me much, maybe I'm missing something?
I did NOT modify any configuration file recently related to Apache (or even anything else for that matter): neither the main apache conf file nor any vHost conf file.
I tried restarting Apache, it does restart but the Web Server still encounters an internal error.

error.log:

```<code>[Sun Jan 31 18:36:17.372502 2016] [core:notice] [pid 27449:tid 140087289513856] AH00094: Command line: '/usr/sbin/apache2'
[Sun Jan 31 18:37:07.641329 2016] [mpm_event:notice] [pid 27449:tid 140087289513856] AH00491: caught SIGTERM, shutting down
[Sun Jan 31 18:38:31.156131 2016] [wsgi:warn] [pid 1049:tid 140557851056000] mod_wsgi: Compiled for Python/2.7.8.
[Sun Jan 31 18:38:31.156330 2016] [wsgi:warn] [pid 1049:tid 140557851056000] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 18:38:31.157222 2016] [mpm_event:notice] [pid 1049:tid 140557851056000] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 18:38:31.157241 2016] [core:notice] [pid 1049:tid 140557851056000] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:21:39.401930 2016] [mpm_event:notice] [pid 1049:tid 140557851056000] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:22:35.038612 2016] [wsgi:warn] [pid 1313:tid 139813423814528] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:22:35.038672 2016] [wsgi:warn] [pid 1313:tid 139813423814528] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:22:35.039592 2016] [mpm_event:notice] [pid 1313:tid 139813423814528] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:22:35.039611 2016] [core:notice] [pid 1313:tid 139813423814528] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:24:57.303622 2016] [mpm_event:notice] [pid 1313:tid 139813423814528] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:26:20.336578 2016] [wsgi:warn] [pid 1050:tid 140178825381760] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:26:20.336805 2016] [wsgi:warn] [pid 1050:tid 140178825381760] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:26:20.337601 2016] [mpm_event:notice] [pid 1050:tid 140178825381760] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:26:20.337617 2016] [core:notice] [pid 1050:tid 140178825381760] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:31:24.663351 2016] [mpm_event:notice] [pid 1050:tid 140178825381760] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:31:25.827873 2016] [wsgi:warn] [pid 1208:tid 139958437914496] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:31:25.827919 2016] [wsgi:warn] [pid 1208:tid 139958437914496] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:31:25.828655 2016] [mpm_event:notice] [pid 1208:tid 139958437914496] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:31:25.828679 2016] [core:notice] [pid 1208:tid 139958437914496] AH00094: Command line: '/usr/sbin/apache2'
</code>```

Could that come from the Python version that mod_wsgi is running which differs from what mod_wsgi is apparently expecting?

答:
try two commands blow:

```<code>sudo apt-get purge apache2

sudo apt-get install apache2
</code>```

after that use systemctl status apache2 to check you apache's status

Body:
I have an Apache Web (version 2.4.10) server running on Debian 8 (Jessie). It is mainly  used as a SVN repository server.
It was working well since a few weeks, and suddenly, I got an internal error when attempting to list the SVN repos from a Web Browser as can be seen below:

Apache Internal Error & Authentication

As you can see, authentication is still working fine.

I ran the 2 following commands:
systemctl status apache2.service
and
journalctl -xn

commands

But that doesn't help me much, maybe I'm missing something?
I did NOT modify any configuration file recently related to Apache (or even anything else for that matter): neither the main apache conf file nor any vHost conf file.
I tried restarting Apache, it does restart but the Web Server still encounters an internal error.

error.log:

[Sun Jan 31 18:36:17.372502 2016] [core:notice] [pid 27449:tid 140087289513856] AH00094: Command line: '/usr/sbin/apache2'
[Sun Jan 31 18:37:07.641329 2016] [mpm_event:notice] [pid 27449:tid 140087289513856] AH00491: caught SIGTERM, shutting down
[Sun Jan 31 18:38:31.156131 2016] [wsgi:warn] [pid 1049:tid 140557851056000] mod_wsgi: Compiled for Python/2.7.8.
[Sun Jan 31 18:38:31.156330 2016] [wsgi:warn] [pid 1049:tid 140557851056000] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 18:38:31.157222 2016] [mpm_event:notice] [pid 1049:tid 140557851056000] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 18:38:31.157241 2016] [core:notice] [pid 1049:tid 140557851056000] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:21:39.401930 2016] [mpm_event:notice] [pid 1049:tid 140557851056000] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:22:35.038612 2016] [wsgi:warn] [pid 1313:tid 139813423814528] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:22:35.038672 2016] [wsgi:warn] [pid 1313:tid 139813423814528] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:22:35.039592 2016] [mpm_event:notice] [pid 1313:tid 139813423814528] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:22:35.039611 2016] [core:notice] [pid 1313:tid 139813423814528] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:24:57.303622 2016] [mpm_event:notice] [pid 1313:tid 139813423814528] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:26:20.336578 2016] [wsgi:warn] [pid 1050:tid 140178825381760] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:26:20.336805 2016] [wsgi:warn] [pid 1050:tid 140178825381760] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:26:20.337601 2016] [mpm_event:notice] [pid 1050:tid 140178825381760] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:26:20.337617 2016] [core:notice] [pid 1050:tid 140178825381760] AH00094: Command line: '/usr/sbin/apache2'

[Sun Jan 31 19:31:24.663351 2016] [mpm_event:notice] [pid 1050:tid 140178825381760] AH00491: caught SIGTERM, shutting down

[Sun Jan 31 19:31:25.827873 2016] [wsgi:warn] [pid 1208:tid 139958437914496] mod_wsgi: Compiled for Python/2.7.8.

[Sun Jan 31 19:31:25.827919 2016] [wsgi:warn] [pid 1208:tid 139958437914496] mod_wsgi: Runtime using Python/2.7.9.

[Sun Jan 31 19:31:25.828655 2016] [mpm_event:notice] [pid 1208:tid 139958437914496] AH00489: Apache/2.4.10 (Debian) SVN/1.8.10 OpenSSL/1.0.1k mod_wsgi/4.3.0 Python/2.7.9 configured -- resuming normal operations

[Sun Jan 31 19:31:25.828679 2016] [core:notice] [pid 1208:tid 139958437914496] AH00094: Command line: '/usr/sbin/apache2'

Could that come from the Python version that mod_wsgi is running which differs from what mod_wsgi is apparently expecting?

Body:
try two commands blow:

sudo apt-get purge apache2

sudo apt-get install apache2

after that use systemctl status apache2 to check you apache's status


问:
What is the best way to avoid getting "Emacs Pinky"?
I just started using GNU Emacs as my text editor and I am concerned about getting afflicted with "Emacs Pinky" by having to constantly press the control key with my pinky finger as is required when using Emacs. How can I avoid potentially getting this type of repetitive strain injury?</p>

答:
One more approach: if you want to avoid getting "emacs pinky" simply do not use pinky to press control key.

If it is necessary remap keys on your keyboard to go in the following order:

[Ctrl][Alt][  Space  ][Alt][Ctrl]

On any standard keyboard (which symmetrically positions modifier keys, e.g. any MS keyboard) now you can press Ctrl key with ring finger and Alt key with middle finger on both hands. These fingers are much stronger than pinky and can endure frequent use.

Great tool for easily remapping keyboard keys on windows is AutoHotKey

On Ubuntu I managed to do it using: Keyboard Preferences / Layouts/ Other options

OwnerDisplayName: Ray Vega

OwnerDisplayName: boskom


问:
get list of sub-set dict from existing list of dict in python
There is a list of dict like below, with each dict contains two keys.

```<code>original_list = [
    {
        'label': 'First Name',
        'value': 'Leo',
    },
    {
        'label': 'Last Name',
        'value': 'Lee',
    },
    {
        'label': 'Gender',
        'value': 'Male',
    },
    {
        'label': 'Age',
        'value': 35,
    },
    {
        'label': 'Telephone',
        'value': '13788995566',
    }
]
</code>```

I want to get a new list of dict with only one key('label') in the dict.

```<code># expecting output like below
new_list =  [
    {
        'label': 'First Name'
    },
    {
        'label': 'Last Name'
    },
    {
        'label': 'Gender'
    },
    {
        'label': 'Age'
    },
    {
        'label': 'Telephone'
    }
]
</code>```

I know one way to get around.

```<code>new_list = [{'label': d['label']} for d in original_list]
print(new_list)
</code>```

Is there any method more convenient?

If the original_list data is in one pandas DataFrame, how to get the same result?

答:
If input is DataFrame select columns for output by subset [[]] and call to_dict with parameter orient='records':

```<code>df = pd.DataFrame(original_list)
print (df)
        label        value
0  First Name          Leo
1   Last Name          Lee
2      Gender         Male
3         Age           35
4   Telephone  13788995566

print (df[['label']].to_dict(orient='records'))
[{'label': 'First Name'},
 {'label': 'Last Name'},
 {'label': 'Gender'},
 {'label': 'Age'},
 {'label': 'Telephone'}]
</code>```

Body:
There is a list of dict like below, with each dict contains two keys.

original_list = [
    {
        'label': 'First Name',
        'value': 'Leo',
    },
    {
        'label': 'Last Name',
        'value': 'Lee',
    },
    {
        'label': 'Gender',
        'value': 'Male',
    },
    {
        'label': 'Age',
        'value': 35,
    },
    {
        'label': 'Telephone',
        'value': '13788995566',
    }
]

I want to get a new list of dict with only one key('label') in the dict.

# expecting output like below
new_list =  [
    {
        'label': 'First Name'
    },
    {
        'label': 'Last Name'
    },
    {
        'label': 'Gender'
    },
    {
        'label': 'Age'
    },
    {
        'label': 'Telephone'
    }
]

I know one way to get around.

new_list = [{'label': d['label']} for d in original_list]
print(new_list)

Is there any method more convenient?

If the original_list data is in one pandas DataFrame, how to get the same result?

Body:
If input is DataFrame select columns for output by subset [[]] and call to_dict with parameter orient='records':

df = pd.DataFrame(original_list)
print (df)
        label        value
0  First Name          Leo
1   Last Name          Lee
2      Gender         Male
3         Age           35
4   Telephone  13788995566

print (df[['label']].to_dict(orient='records'))
[{'label': 'First Name'},
 {'label': 'Last Name'},
 {'label': 'Gender'},
 {'label': 'Age'},
 {'label': 'Telephone'}]


问:
How to Dispose VlcControl for wpf
I am using Vlc.DotNet.Wpf for playing video

creating VlcControl object

`

```<code>private void CreateVlcObject1()
{
   myControl1 = new VlcControl();
   myControl1.MediaPlayer.VlcLibDirectoryNeeded+=MediaPlayer_VlcLibDirectoryNeeded;
   myControl1.MediaPlayer.EndReached += MediaPlayer_EndReached1;
   myControl1.MediaPlayer.EndInit(); myControl1.MediaPlayer.Play(newUri(@"C:\Users\Public\videos\45.mp4"));
   MainGrid.Children.Add(myControl1);
}
</code>```

`

Dispose Method of VlcControl object

`

```<code>  private void DisposeObject1()
  {
    myControl1.MediaPlayer.VlcLibDirectoryNeeded -=   MediaPlayer_VlcLibDirectoryNeeded1;
    myControl1.MediaPlayer.EndReached -= MediaPlayer_EndReached1;

    if (!myControl1.MediaPlayer.IsDisposed)
    {
       myControl1.MediaPlayer.Stop();
       myControl1.MediaPlayer.Dispose();
    }
       myControl1 = null;
       MainGrid.Children.Remove(myControl1);
 }
</code>```

`

the program get stuck at stop method in Dispose method however if i comment stop method it will stuck at the dispose method.
Without Disposing this object i can't proceed further as it eats 100 MB in 1 min.

When I break it shows like this:

My Question is how to Dispose this VlcControl object
Edited
I am disposing vlc object in every 15 seconds

答:
Vlc.DotNet is currently very sensitive when using callbacks : you need to make sure that you are calling Dispose() and other Vlc-related methods from the same thread that was creating the control.

If you are using Timers to Dispose the control, as you said in your question, chances are that there are more than one thread involved.

In Wpf, I'd say a good choice is using Dispatcher.InvokeAsync(() => {...});

Thanks for using Vlc.DotNet

Title: How to Dispose VlcControl for wpf

Body:
I am using Vlc.DotNet.Wpf for playing video

creating VlcControl object

`

private void CreateVlcObject1()
{
   myControl1 = new VlcControl();
   myControl1.MediaPlayer.VlcLibDirectoryNeeded+=MediaPlayer_VlcLibDirectoryNeeded;
   myControl1.MediaPlayer.EndReached += MediaPlayer_EndReached1;
   myControl1.MediaPlayer.EndInit(); myControl1.MediaPlayer.Play(newUri(@"C:\Users\Public\videos\45.mp4"));
   MainGrid.Children.Add(myControl1);
}

`

Dispose Method of VlcControl object

`

  private void DisposeObject1()
  {
    myControl1.MediaPlayer.VlcLibDirectoryNeeded -=   MediaPlayer_VlcLibDirectoryNeeded1;
    myControl1.MediaPlayer.EndReached -= MediaPlayer_EndReached1;

    if (!myControl1.MediaPlayer.IsDisposed)
    {
       myControl1.MediaPlayer.Stop();
       myControl1.MediaPlayer.Dispose();
    }
       myControl1 = null;
       MainGrid.Children.Remove(myControl1);
 }

`

the program get stuck at stop method in Dispose method however if i comment stop method it will stuck at the dispose method.
Without Disposing this object i can't proceed further as it eats 100 MB in 1 min.

When I break it shows like this:

My Question is how to Dispose this VlcControl object
Edited
I am disposing vlc object in every 15 seconds


问:
When i use ado.net model in 3-tier architecture and i tries to load the data from DAL to UI it asks for connection string in UI app.config
Problem with connectiong string in 3-tier architecture using ADO.NET model.
When I try to load data from database using ADO.NET context it asks for connection string when it has already added in DAL app.config but it asks for it in UI.</p>

答: The connection string must be on the .config file on the project which will execute, for sample, windows forms, web application, wpf, wcf, web api, mobile projects. If add a connection string on a app.config file on a class library project, it will not affect your project. You have to keep it on the project which will execute the solution.


问:
CKEditor CDN and config for inline editing
So, I have a page with div's that have contenteditable=true, and I load //cdn.ckeditor.com/4.7.3/standard/ckeditor.js which makes them editable with CKEditor - but since I do not use CKEDITOR.replace() I can't send along a configuration for the editor's. How do I set the toolbar configuration for CKEditor that is being loaded for contenteditable fields?

答:
Inline editor

If you wish to have inline editor, you can use CKEDITOR.inline method to converse such div into inline editor, you can pass regular configuration as object in second argument. Example with configuration which change ui colour you can do like that (full example):

```<code>var editor = CKEDITOR.inline( 'editor', {
  uiColor: '66FFFF'
} );
</code>```

Divarea editor

Another option is to use divarea editor. In such case you use regular CKEDITOR.replace method and you have to add divarea plugin.
Example implementation below with link to codepen implementation.
https://codepen.io/msamsel/pen/YEbode As you can see css from main website are also applied inside the editor.

```<code>var editor = CKEDITOR.replace( 'editor', {
  uiColor: '66FFFF',
  extraPlugins: 'divarea'
} );
</code>```

Body:
Inline editor

If you wish to have inline editor, you can use CKEDITOR.inline method to converse such div into inline editor, you can pass regular configuration as object in second argument. Example with configuration which change ui colour you can do like that (full example):

var editor = CKEDITOR.inline( 'editor', {
  uiColor: '66FFFF'
} );

Divarea editor

Another option is to use divarea editor. In such case you use regular CKEDITOR.replace method and you have to add divarea plugin.
Example implementation below with link to codepen implementation.
https://codepen.io/msamsel/pen/YEbode As you can see css from main website are also applied inside the editor.

var editor = CKEDITOR.replace( 'editor', {
  uiColor: '66FFFF',
  extraPlugins: 'divarea'
} );


问:
How update collections using Azure functions
I want to create the azure Function which is bind to cosmos DB.

Whenever some insertion happens in "A" collection I want to update "B" collection.

"B" collection has stored procedure which I want to call after the insertion in collection "A".

I am new to Azure and cosmos-DB.

Suggest me what need to be done to accomplish the requirement.

So far I have created Azure Function

Also Updated the function.json with below code.

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "cdb-swm-dev-001_DOCUMENTDB",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "admin",
      "collectionName": "test",
      "createIfNotExists": true,
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

Also Updated the Integrate Part as below

Any Suggestion will be appreciable.

答:
I find your question not very specific, but broadly you have at least two options:

Insert to both collections from the same Azure Function

Insert to the collection 1 from the first Azure Function, then have a second Azure Function with Cosmos DB trigger listening to the changes of collection 1 and updating collection 2

I'm sure there are other options too.

Body:
I want to create the azure Function which is bind to cosmos DB.

Whenever some insertion happens in "A" collection I want to update "B" collection.

"B" collection has stored procedure which I want to call after the insertion in collection "A".

I am new to Azure and cosmos-DB.

Suggest me what need to be done to accomplish the requirement.

So far I have created Azure Function

Also Updated the function.json with below code.

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "cdb-swm-dev-001_DOCUMENTDB",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "admin",
      "collectionName": "test",
      "createIfNotExists": true,
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}

Also Updated the Integrate Part as below

Any Suggestion will be appreciable.


问:
XML deserialize to object
Hi,
I would like to deserialize (not so common) XML to object. Normal XML should looks like:

```<code><library>
<books>
 <book name="1"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
</books>
</library>
</code>```

As you can see there is 'books' branch inside which I have some 'book' elements. It is ok, easy to deserialize etc. However my XML looks different. Inside 'books' there are elements with random names. Instead of 'book' element there is element with book name itself (as element name). What is more inside these elements there are always the same elements like 'author' and 'details'.

Please have a look at this:

```<code><library>
<books>
 <1><author></author><details></details></1>
 <2><author></author><details></details></2>
 <3><author></author><details></details></3>
</books>
</library>
</code>```

Any suggestion how to create objects from the  second XML?

答:
XmlSerializer will hate that - it is used to situations where the elements are fixed. Options:

rewrite the xml completely and use XmlSerializer

use manual deserialization (like @jdweng's answer)

rewrite bits of the xml in-memory, and use XmlSerializer

For an example of the third option:

```<code>using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

static class P
{
    static void Main()
    {
        var xml = @"<library>
<books>
 <a><author>x</author><details>1</details></a>
 <b><author>y</author><details>2</details></b>
 <c><author>z</author><details>3</details></c>
</books>
</library>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var ser = new XmlSerializer(typeof(Book));

        List<Book> books = new List<Book>();
        foreach (XmlElement book in doc.SelectNodes("/library/books/*"))
        {
            var el = doc.CreateElement("book");
            el.SetAttribute("name", book.Name);
            foreach (XmlNode child in book.ChildNodes)
            {
                el.AppendChild(child.Clone());
            }

            using (var reader = new XmlNodeReader(el))
            {
                books.Add((Book)ser.Deserialize(reader));
            }
        }

        foreach(var book in books)
        {
            System.Console.WriteLine(book);
        }

    }
}
[XmlRoot("book")]
public class Book
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("author")]
    public string Author { get; set; }
    [XmlElement("details")]
    public string Details { get; set; }

    public override string ToString() => $"{Name} by {Author}: {Details}";
}
</code>```

which outputs:

```<code>a by x: 1
b by y: 2
c by z: 3
</code>```

Title: XML deserialize to object

Body:
Hi,
I would like to deserialize (not so common) XML to object. Normal XML should looks like:

<library>
<books>
 <book name="1"><author></author></book>
 <book name="2"><author></author></book>
 <book name="2"><author></author></book>
</books>
</library>

As you can see there is 'books' branch inside which I have some 'book' elements. It is ok, easy to deserialize etc. However my XML looks different. Inside 'books' there are elements with random names. Instead of 'book' element there is element with book name itself (as element name). What is more inside these elements there are always the same elements like 'author' and 'details'.

Please have a look at this:

<library>
<books>
 <1><author></author></1>
 <2><author></author></2>
 <3><author></author></3>
</books>
</library>

Any suggestion how to create objects from the  second XML?

Body:
XmlSerializer will hate that - it is used to situations where the elements are fixed. Options:

rewrite the xml completely and use XmlSerializer

use manual deserialization (like @jdweng's answer)

rewrite bits of the xml in-memory, and use XmlSerializer

For an example of the third option:

using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

static class P
{
    static void Main()
    {
        var xml = @"<library>
<books>
 <a><author>x</author><details>1</details></a>
 <b><author>y</author><details>2</details></b>
 <c><author>z</author><details>3</details></c>
</books>
</library>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var ser = new XmlSerializer(typeof(Book));

        List<Book> books = new List<Book>();
        foreach (XmlElement book in doc.SelectNodes("/library/books/*"))
        {
            var el = doc.CreateElement("book");
            el.SetAttribute("name", book.Name);
            foreach (XmlNode child in book.ChildNodes)
            {
                el.AppendChild(child.Clone());
            }

            using (var reader = new XmlNodeReader(el))
            {
                books.Add((Book)ser.Deserialize(reader));
            }
        }

        foreach(var book in books)
        {
            System.Console.WriteLine(book);
        }

    }
}
[XmlRoot("book")]
public class Book
{
    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlElement("author")]
    public string Author { get; set; }
    [XmlElement("details")]
    public string Details { get; set; }

    public override string ToString() => $"{Name} by {Author}: {Details}";
}

which outputs:

a by x: 1
b by y: 2
c by z: 3