问:
TypeError: db.collection is not a function
I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

```<code>const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

})
</code>```

db.js

```<code>module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};
</code>```

index.js

```<code>const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
    noteroutes(app,db);

};
</code>```

note_routes.js

```<code>module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};
</code>```

答:
So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn't passing in a blank reference like the accepted answer, try this solution out.

When you run..

```<code>MongoClient.connect(db.url,(err,database) =>{ }
</code>```

In mongodb version >= 3.0, That database variable is actually the parent object of the object you are trying to access with database.collection('whatever'). To access the correct object, you need to reference your database name, for me that was by doing

```<code>MongoClient.connect(db.url,(err,database) =>{
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}
</code>```

This fixed my errors when running my node.js server, hopefully this helps somebody who doesn't just want to downgrade their version.

(also, if you don't know your db name for some reason, just do a console.log(database) and you'll see it as an object attribute)

EDIT (June 2018):

According to this, the callback actually returns the connected client of the database, instead of the database itself.

Therefore, to get the database instance, we need to use this method, which takes in a dbName. In the documentation it said If not provided, use database name from connection string., as mentioned by @divillysausages in the comments below.

In short, we should call database.db().collection('theCollectionIwantToAccess'); if the dbName is provided by url, where the database is actually client for better understanding

Body:
I am trying to post data to database that I have created on mLab and I am getting this error but I don't know whats going wrong.I also have read previously asked question on this topic but I am not able to solve my error as I am new to this. So here I am posting the code which I am trying to implement and It is taken from this tutorial https://medium.freecodecamp.com/building-a-simple-node-js-api-in-under-30-minutes-a07ea9e390d2.

server.js

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');

const db = require('./config/db');

const app = express();

const port = 8000;

app.use(bodyParser.urlencoded({extened:true}));

MongoClient.connect(db.url,(err,database) =>{

    if (err) return console.log(err)
    require('./app/routes')(app,{});
    app.listen(port,() => {
        console.log("We are live on"+port);
    });

})

db.js

module.exports = {
  url : "mongodb://JayTanna:Jay12345@ds147510.mlab.com:47510/testing"
};

index.js

const noteroutes = require('./note_routes');

module.exports = function(app,db)
{
    noteroutes(app,db);

};

note_routes.js

module.exports = function(app, db) {
  app.post('/notes', (req, res) => {
    const note = { text: req.body.body, title: req.body.title };
    db.collection('notes').insert(note, (err, result) => {
      if (err) {
        res.send({ 'error': 'An error has occurred' });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

Body:
So I voted for the answer which said to just go down to mongodb 2.2.33 because I tried it and it worked, but then I felt weird about just downgrading to fix a problem so I found the solution which allows you to keep version >= 3.0. If anyone finds this issue and their problem wasn't passing in a blank reference like the accepted answer, try this solution out.

When you run..

MongoClient.connect(db.url,(err,database) =>{ }

In mongodb version >= 3.0, That database variable is actually the parent object of the object you are trying to access with database.collection('whatever'). To access the correct object, you need to reference your database name, for me that was by doing

MongoClient.connect(db.url,(err,database) =>{
  const myAwesomeDB = database.db('myDatabaseNameAsAString')
  myAwesomeDB.collection('theCollectionIwantToAccess')
}

This fixed my errors when running my node.js server, hopefully this helps somebody who doesn't just want to downgrade their version.

(also, if you don't know your db name for some reason, just do a console.log(database) and you'll see it as an object attribute)

EDIT (June 2018):

According to this, the callback actually returns the connected client of the database, instead of the database itself.

Therefore, to get the database instance, we need to use this method, which takes in a dbName. In the documentation it said If not provided, use database name from connection string., as mentioned by @divillysausages in the comments below.

In short, we should call database.db().collection('theCollectionIwantToAccess'); if the dbName is provided by url, where the database is actually client for better understanding


来源: stackexchange

问:
controller undefined angularjs
I am a beginner in angularJs. As I was trying to build a sample app, I am getting this following error

controller undefined angularjs

```<code><div ng-controller="listCtrl">
        {{2+3}}
    </div>
</code>```

It is not printing the {{2+3}} expression on browser but when I remove the ng-controller tag from the div it prints the result is 5 which is correct.

I have linked all necessary scripts in html file.

here is my controller code

```<code>(function(){

  angular.module("myApp").controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();
</code>```

答:
Most probably you are missing value of ng-app directive. like below

```<code><div ng-app="myApp">
  <div ng-controller="listCtrl">
     {{2+3}}
  </div>
</div>
</code>```

Also, please note, that if you haven't created your module (myApp) first, then you need to do that by doing this angular.module("myApp", []) before referring your controller file or within controller file.

```<code>(function(){

  angular.module("myApp", []).controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();
</code>```

ContentLicense: CC BY-SA 3.0

Title: controller undefined angularjs

Body:
I am a beginner in angularJs. As I was trying to build a sample app, I am getting this following error

controller undefined angularjs

        {{2+3}}

It is not printing the {{2+3}} expression on browser but when I remove the ng-controller tag from the div it prints the result is 5 which is correct.

I have linked all necessary scripts in html file.

here is my controller code

(function(){

  angular.module("myApp").controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();

Body:
Most probably you are missing value of ng-app directive. like below

<div ng-app="myApp">
  <div ng-controller="listCtrl">
     {{2+3}}
  </div>
</div>

Also, please note, that if you haven't created your module (myApp) first, then you need to do that by doing this angular.module("myApp", []) before referring your controller file or within controller file.

(function(){

  angular.module("myApp", []).controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();


问:
Separating words and put it to array?
User-agent: * Disallow: / kadirgamar/ Disallow: / arrow/ Disallow: / orion/ Disallow: / woolimlanka/ Disallow: / nippon/ Disallow: / luna-tower/ Disallow: / thotalagala/ Disallow: / altair/ Disallow: / arrowlibrary/ Disallow: / ashraf/ Disallow: / ashrafnew/ Disallow: / invoke/ Disallow: / lavana/ Disallow: / leia/ Disallow: / lorelle/ Disallow: / lioc/ Disallow: / liocdev/ Disallow: / lorellenew/ Disallow: / openmanthri/ Disallow: / opentapes/ Disallow: / rates/ Disallow: / rsq/ Disallow: / signature/ Disallow: / site/ Disallow: / visualretale/ Disallow: / srhr/ Disallow: / smitratest/ Disallow: / smitra/ Disallow: / lioccontent/ Disallow: / lioccopy/ Disallow: / liocold/ Disallow: / global/ Disallow: / echelon/ Disallow: / arrowlive/

this is my string. I have to separate kadirgamar, arrow etc these words. How can I separate and put it to array in php?

I tried this:-

```<code><?php
$url = 'http://www.test.oddly.co/robots.txt';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
$result = curl_exec($curl);
curl_close($curl);
echo $result.'<br>';
$arr = array("lorelle","kadirgamar","arrow","orion","woolimlanka","nippon","luna-tower","thotalagala","arrowlibrary",
    "ashrafnew","invoke","lavana","leia","lorelle","lioc","liocdev","lorellenew","openmanthri","rsq","signature",
    "site","visualretale","srhr","smitratest","smitra","lioccontent","lioccopy","liocold","global","echelon","arrowlive"
);

$str = explode('Disallow: /',$result,-1);

?>
</code>```

I have tried this but its giving error.
I want to check that two array is that equal or not? how can I do that?

答:
You can do it like below:-

```<code>$array = explode('Disallow: / ',$vstring); //explode string to array

unset($array[0]); // to remove first word User-agent: *
$array = array_values($array); // re-index array

function trim_array_element(&$item1)
{
    $item1 = preg_replace('/\//', '', $item1);
}

array_walk($array,'trim_array_element'); // apply custom function to remove / from each values of array

print_r($array);
</code>```

Output:- https://eval.in/914410

Title: Separating words and put it to array?

Body:
User-agent: * Disallow: / kadirgamar/ Disallow: / arrow/ Disallow: / orion/ Disallow: / woolimlanka/ Disallow: / nippon/ Disallow: / luna-tower/ Disallow: / thotalagala/ Disallow: / altair/ Disallow: / arrowlibrary/ Disallow: / ashraf/ Disallow: / ashrafnew/ Disallow: / invoke/ Disallow: / lavana/ Disallow: / leia/ Disallow: / lorelle/ Disallow: / lioc/ Disallow: / liocdev/ Disallow: / lorellenew/ Disallow: / openmanthri/ Disallow: / opentapes/ Disallow: / rates/ Disallow: / rsq/ Disallow: / signature/ Disallow: / site/ Disallow: / visualretale/ Disallow: / srhr/ Disallow: / smitratest/ Disallow: / smitra/ Disallow: / lioccontent/ Disallow: / lioccopy/ Disallow: / liocold/ Disallow: / global/ Disallow: / echelon/ Disallow: / arrowlive/

this is my string. I have to separate kadirgamar, arrow etc these words. How can I separate and put it to array in php?

I tried this:-

<?php
$url = 'http://www.test.oddly.co/robots.txt';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);
$result = curl_exec($curl);
curl_close($curl);
echo $result.'
';
$arr = array("lorelle","kadirgamar","arrow","orion","woolimlanka","nippon","luna-tower","thotalagala","arrowlibrary",
    "ashrafnew","invoke","lavana","leia","lorelle","lioc","liocdev","lorellenew","openmanthri","rsq","signature",
    "site","visualretale","srhr","smitratest","smitra","lioccontent","lioccopy","liocold","global","echelon","arrowlive"
);

$str = explode('Disallow: /',$result,-1);

?>

I have tried this but its giving error.
I want to check that two array is that equal or not? how can I do that?

Body:
You can do it like below:-

$array = explode('Disallow: / ',$vstring); //explode string to array

unset($array[0]); // to remove first word User-agent: *
$array = array_values($array); // re-index array

function trim_array_element(&$item1)
{
    $item1 = preg_replace('/\//', '', $item1);
}

array_walk($array,'trim_array_element'); // apply custom function to remove / from each values of array

print_r($array);

Output:- https://eval.in/914410


问:
Automatic type Conversion in C#
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

```<code>public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}
</code>```

so that I could just call them like this:

```<code>eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();
</code>```

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

```<code>eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];
</code>```

The row is a DataRow if that matters.

答:
I believe what you're looking for is implicit conversion, which is described here: http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx.

However, adding these to object would be a very bad idea, for reasons outlined on the page I've linked to.

ContentLicense: CC BY-SA 2.5

Title: Automatic type Conversion in C#

Body:
I know that you could override an object's ToString() Method, so that everytime you call an object or pass it to a function that requires a String type it will be converted to a String.

I have written several extension methods for object type 'object'

public static DateTime ToDate(this object date)
{
    return DateTime.Parse(date.ToString());
}

public static int ToInteger(this object num)
{
    return Int32.Parse(num.ToString());
}

public static long ToLong(this object num)
{
    return Int64.Parse(num.ToString());
}

so that I could just call them like this:

eventObject.Cost = row["cost"].ToString();
eventObject.EventId = row["event_id"].ToLong();

However, what I want to accomplish is to convert the row objects which is of type 'object' to its correct type based on the property types on my 'eventObject'. So, I could call it like this:

eventObject.Cost = row["cost"];
eventObject.EventId = row["event_id"];

The row is a DataRow if that matters.


问:
Do I need to check if keys exist before adding new values to it in multidimensional arrays?
I remember writing code a long time ago like seen below. Where you check each key before adding value to it in multidimensional arrays:

```<code>$transactions = [];

if (!isset($transactions[$account])) {
    $transactions[$account] = [];
}

if (!$transactions[$account]['cards'])) {
    $transactions[$account]['cards'] = [];
}

$transactions[$account]["cards"][] = $card;
</code>```

but recently I noticed that I have started writing this:

```<code>$transactions = [];

$transactions[$account]["cards"][] = $card;
</code>```

and everything seems to work just fine without declaring those arrays beforehand.

答:
You dont need to check when you create the Multi dimensional or any Array.
But you need to check, when you want to Update or Delete the array.

Examle:

```<code>$transactions[$account]["cards"][] = $card;
// you dont need to check here.

$transactions[$account]["cards"][] = 343; // This may not work
// When you want to update it, you need to check

if(isset($transactions[$account]["cards"]))
    $transactions[$account]["cards"] = 343;
// The above condition helps you in not breaking the script,
//if you want to assign to an array which is not created.
</code>```

Good Luck!

Body:
I remember writing code a long time ago like seen below. Where you check each key before adding value to it in multidimensional arrays:

$transactions = [];

if (!isset($transactions[$account])) {
    $transactions[$account] = [];
}

if (!$transactions[$account]['cards'])) {
    $transactions[$account]['cards'] = [];
}

$transactions[$account]["cards"][] = $card;

but recently I noticed that I have started writing this:

$transactions = [];

$transactions[$account]["cards"][] = $card;

and everything seems to work just fine without declaring those arrays beforehand.

Body:
You dont need to check when you create the Multi dimensional or any Array.
But you need to check, when you want to Update or Delete the array.

Examle:

$transactions[$account]["cards"][] = $card;
// you dont need to check here.

$transactions[$account]["cards"][] = 343; // This may not work
// When you want to update it, you need to check

if(isset($transactions[$account]["cards"]))
    $transactions[$account]["cards"] = 343;
// The above condition helps you in not breaking the script,
//if you want to assign to an array which is not created.

Good Luck!


问:
Location updates At Server under specific Conditions
I have implemented CLLocationManager to monitor significant location changes. So I get updates at around 500 metres or more I update it to the server. But now I need to update the location only when the user stops moving. That means if a user moves a distance 10 km and stops moving. Then it should be updated to the server, not in between.

I was able to control the location update operation at every 500 metres by checking the speed from CLLocationManager, but however for cases like if the user travels a distance of around 700 meters and getting stable at that point. The location update fails as it fails to qualify 500-meter change.

Can anyone help me with an idea so as to how to check if the user is stable at a particular point?

Thanks

答:
To register smaller movement changes, I'd refer to HealthKit instead of CLLocationManager.

For registering changes higher than that, what are you using in terms of accuracy?

You could try: self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;


问:
Is there such a thing as min-font-size and max-font-size?
I'm trying to make a font in a div responsive to the browser window. So far, it has worked perfectly, but the parent div has a max-width of 525px. Resizing the browser further will not make the font stop resizing. This has made me wonder if there is such a thing as min-font-size or max-font-size, and if such a thing does not exist, if there is a way to achieve something similar.

I thought that using percentages at font-size would work, but the bit of text won't scale accordingly to the parent div. Here's what I have:

The CSS for the parent div:

```<code>.textField{
    background-color:rgba(88, 88, 88, 0.33);

    width:40%;
    height:450px;

    min-width:200px;
    max-width:525px;

    z-index:2;
}
</code>```

The CSS for the piece of text in question:

```<code>.subText{
    position:relative;
    top:-55px;
    left:15px;

    font-family:"news_gothic";
    font-size:1.3vw;
    font-size-adjust:auto;

    width:90%;

    color:white;

    z-index:1;
}
</code>```

答:
This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

```<code>.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}
</code>```

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a font in a div responsive to the browser window. So far, it has worked perfectly, but the parent div has a max-width of 525px. Resizing the browser further will not make the font stop resizing. This has made me wonder if there is such a thing as min-font-size or max-font-size, and if such a thing does not exist, if there is a way to achieve something similar.

I thought that using percentages at font-size would work, but the bit of text won't scale accordingly to the parent div. Here's what I have:

The CSS for the parent div:

.textField{
    background-color:rgba(88, 88, 88, 0.33);

    width:40%;
    height:450px;

    min-width:200px;
    max-width:525px;

    z-index:2;
}

The CSS for the piece of text in question:

.subText{
    position:relative;
    top:-55px;
    left:15px;

    font-family:"news_gothic";
    font-size:1.3vw;
    font-size-adjust:auto;

    width:90%;

    color:white;

    z-index:1;
}

Body:
This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).


问:
JQuery How to create element in created element
There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK.
But I don't know how to create child element in the created element. I need to create

```<code><img src="path"/>
</code>```

In the div I have created earlier in script. It must be like that

```<code><div class="img-w js-popup">
    <img src="path"/>
</div>
<a href="delete.php">Delete</a>
</code>```

But only I can do is create  as next sibling to the div

```<code><div class="img-w js-popup"></div>
<img src="path"/>
<a href="delete.php">Delete</a>
</code>```

Who can help me and solve my problem?

答:
You can append img to div before you append that div to li. You can also write the same code like this Fiddle

$('
')
  .append($('
', {
    'class': 'img-w js-popup',
  }).append($('', {
    'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
  })))
  .append($('', {
    href: 'delete.php',
    text: 'Delete'
  }))
  .appendTo('ul');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <div>
      <img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
    </div>
    Delete
  </li>
</ul></code>```

Body:
There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK.
But I don't know how to create child element in the created element. I need to create

In the div I have created earlier in script. It must be like that

Delete

But only I can do is create  as next sibling to the div

Delete

Who can help me and solve my problem?

Body:
You can append img to div before you append that div to li. You can also write the same code like this Fiddle

$('<li/>')
  .append($('<div/>', {
    'class': 'img-w js-popup',
  }).append($('<img/>', {
    'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
  })))
  .append($('<a/>', {
    href: 'delete.php',
    text: 'Delete'
  }))
  .appendTo('ul');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <div>
      <img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
    </div>
    <a href="delete.php">Delete</a>
  </li>
</ul>


问:
How to Delete Kubernetes Service
The command kubectl get service returns a list of services that were created at one point in time:

```<code>NAME                     CLUSTER-IP   EXTERNAL-IP   PORT(S)                         AGE
car-example-service      10.0.0.129   <nodes>       8025:31564/TCP,1025:31764/TCP   10h
circle-example-service   10.0.0.48    <nodes>       9000:30362/TCP                  9h
demo-service             10.0.0.9     <nodes>       8025:30696/TCP,1025:32047/TCP   10h
example-servic           10.0.0.168   <nodes>       8080:30231/TCP                  1d
example-service          10.0.0.68    <nodes>       8080:32308/TCP                  1d
example-service2         10.0.0.184   <nodes>       9000:32727/TCP                  13h
example-webservice       10.0.0.35    <nodes>       9000:32256/TCP                  1d
hello-node               10.0.0.224   <pending>     8080:32393/TCP                  120d
kubernetes               10.0.0.1     <none>        443/TCP                         120d
mouse-example-service    10.0.0.40    <nodes>       9000:30189/TCP                  9h
spring-boot-web          10.0.0.171   <nodes>       8080:32311/TCP                  9h
spring-boot-web-purple   10.0.0.42    <nodes>       8080:31740/TCP                  9h
</code>```

I no longer want any of these services listed, because when I list resources:
% kubectl get rs

I am expecting that I only see the spring-boot-web resource listed.

```<code>NAME                         DESIRED   CURRENT   READY     AGE
spring-boot-web-1175758536   1         1         0         18m
</code>```

Please help clarify why I am seeing services that are listed , when the resources only show 1 resource.

答: Kubernetes objects like Service and Deployment/ReplicaSet/Pod are independent and their deletions do not cascade to each other (like it does between say Deployment/RS/Pod). You need to manage your services independently from other objects, so you just need to delete the ones that are still lingering behind.</p>

Title: How to Delete Kubernetes Service

Body:
The command kubectl get service returns a list of services that were created at one point in time:

NAME                     CLUSTER-IP   EXTERNAL-IP   PORT(S)                         AGE
car-example-service      10.0.0.129   <nodes>       8025:31564/TCP,1025:31764/TCP   10h
circle-example-service   10.0.0.48    <nodes>       9000:30362/TCP                  9h
demo-service             10.0.0.9     <nodes>       8025:30696/TCP,1025:32047/TCP   10h
example-servic           10.0.0.168   <nodes>       8080:30231/TCP                  1d
example-service          10.0.0.68    <nodes>       8080:32308/TCP                  1d
example-service2         10.0.0.184   <nodes>       9000:32727/TCP                  13h
example-webservice       10.0.0.35    <nodes>       9000:32256/TCP                  1d
hello-node               10.0.0.224   <pending>     8080:32393/TCP                  120d
kubernetes               10.0.0.1     <none>        443/TCP                         120d
mouse-example-service    10.0.0.40    <nodes>       9000:30189/TCP                  9h
spring-boot-web          10.0.0.171   <nodes>       8080:32311/TCP                  9h
spring-boot-web-purple   10.0.0.42    <nodes>       8080:31740/TCP                  9h

I no longer want any of these services listed, because when I list resources:
% kubectl get rs

I am expecting that I only see the spring-boot-web resource listed.

NAME                         DESIRED   CURRENT   READY     AGE
spring-boot-web-1175758536   1         1         0         18m

Please help clarify why I am seeing services that are listed , when the resources only show 1 resource.


问:
Regarding WPF and web development?
i don't know anything about WPF. so a question has come to my mind that when we develop apps in WPF that can be run as web application without changing code. please comment. thanks.</p>

答:
WPF is the best technology for windows development. It's very easy to learn and use. Though it's not as mature as WinForms but is surely worth trying. I am developing a register maintenance application and feel like home.
You can go through following links to quickly grab this technology

1) MSDN Documentation

2) WPF Tutorials

3) WPF Sample Applications

Best of luck and Happy Learning

Title: Regarding WPF and web development?


答:
The issue is because your append() call is on the li itself, not the div you just added. Try this:

var $div = $('
', {
  'class': 'img-w js-popup'
});
$('', {
  'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}).appendTo($div)

$('
').append($div).append($('', {
  href: 'delete.php',
  text: 'Delete'
})).appendTo('ul');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
  <li>
    <div>
      <img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
    </div>
    Delete
  </li>
</ul></code>```

With that said, you're using the most verbose method of creating HTML. As you're hard-coding all attributes, it can be simplified by just providing the plain string - or even by just cloning the previous li and appending that.

Title: JQuery How to create element in created element

Body:
The issue is because your append() call is on the li itself, not the div you just added. Try this:

var $div = $('<div/>', {
  'class': 'img-w js-popup'
});
$('<img/>', {
  'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}).appendTo($div)

$('<li/>').append($div).append($('<a/>', {
  href: 'delete.php',
  text: 'Delete'
})).appendTo('ul');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
  <li>
    <div>
      <img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
    </div>
    <a href="delete.php">Delete</a>
  </li>
</ul>

With that said, you're using the most verbose method of creating HTML. As you're hard-coding all attributes, it can be simplified by just providing the plain string - or even by just cloning the previous li and appending that.


问:
Drawable with a four-color border With Circular Shape
Is it possible to achieve the following as a drawable (for a background) using a Layer-List ???

答:
Yeah sure. Why not?

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:right="5dp">
        <shape android:shape="rectangle">
            <solid android:color="#55FF55"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"
                android:topLeftRadius="5dp"/>
        </shape>
    </item>

    <item android:left="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#FFFF00"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomRightRadius="5dp"
                android:topRightRadius="5dp"/>
        </shape>
    </item>

    <item android:top="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#555555"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp"/>
        </shape>
    </item>

    <item
        android:right="5dp"
        android:top="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#FF0000"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"/>
        </shape>
    </item>

    <!-- Look out! -->
    <item>
        <shape android:shape="oval">
            <size
                android:width="10dp"
                android:height="10dp"/>

            <stroke
                android:width="1dp"
                android:color="#000000"/>
        </shape>
    </item>

    <!-- You might wanna uncomment this ! -->
    <!--<item-->
        <!--android:gravity="center">-->
        <!--<shape android:shape="oval">-->
            <!--<size-->›
                <!--android:width="8dp"-->
                <!--android:height="8dp"/>-->

            <!--<solid android:color="#000000"/>-->
        <!--</shape>-->
    <!--</item>-->

</layer-list>
</code>```

Body:
Yeah sure. Why not?

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:right="5dp">
        <shape android:shape="rectangle">
            <solid android:color="#55FF55"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"
                android:topLeftRadius="5dp"/>
        </shape>
    </item>

    <item android:left="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#FFFF00"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomRightRadius="5dp"
                android:topRightRadius="5dp"/>
        </shape>
    </item>

    <item android:top="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#555555"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"
                android:bottomRightRadius="5dp"/>
        </shape>
    </item>

    <item
        android:right="5dp"
        android:top="5dp">
        <shape
            android:shape="rectangle">
            <solid android:color="#FF0000"/>
            <size
                android:width="5dp"
                android:height="5dp"/>
            <corners
                android:bottomLeftRadius="5dp"/>
        </shape>
    </item>

    <!-- Look out! -->
    <item>
        <shape android:shape="oval">
            <size
                android:width="10dp"
                android:height="10dp"/>

            <stroke
                android:width="1dp"
                android:color="#000000"/>
        </shape>
    </item>

    <!-- You might wanna uncomment this ! -->
    <!--<item-->
        <!--android:gravity="center">-->
        <!--<shape android:shape="oval">-->
            <!--<size-->›
                <!--android:width="8dp"-->
                <!--android:height="8dp"/>-->

            <!--<solid android:color="#000000"/>-->
        <!--</shape>-->
    <!--</item>-->

</layer-list>


答:
You have to pass an empty array as argument in angular.module()
For example-</p>

```<code>(function(){

  angular.module("myApp",[]).controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();
</code>```

Title: controller undefined angularjs

Body:
You have to pass an empty array as argument in angular.module()
For example-

(function(){

  angular.module("myApp",[]).controller("listCtrl", Listcontroller);

    function Listcontroller($scope){
      $scope.dummyData = "hello word";
    }

})();


问:
how to get specific colums from datagridview to listbox
im trying to get 3 columns instead of 15 to listbox, how do i do that?

this is the code which gets all columns.

```<code>private void testlist()
    {
        string[,] Datavalue = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                Datavalue[row.Index, col.Index] = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString();
            }
        }
        int i = 1;
        string strval = "";
        foreach (string ss in Datavalue)
        {
            strval += ss + " ";
            if (i == 15)
            {
                listBox1.Items.Add(strval);
                strval = "";
                i = 0;
            }
            i++;
        }
    }
</code>```

答:
```<code>private void testlist()
{
    string[,] Datavalue = new string[dataGridView1.Rows.Count, 3];
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        Datavalue[row.Index, 0] =
            dataGridView1.Rows[row.Index].Cells[1].Value.ToString();
        Datavalue[row.Index, 1] =
            dataGridView1.Rows[row.Index].Cells[2].Value.ToString();
        Datavalue[row.Index, 2] =
            dataGridView1.Rows[row.Index].Cells[14].Value.ToString();
    }
    int i = 1;
    string strval = "";
    foreach (string ss in Datavalue)
    {
        strval += ss + " ";
        if (i == 3)
        {
            listBox1.Items.Add(strval);
            strval = "";
            i = 0;
        }
        i++;
    }
}
</code>```

Body:
im trying to get 3 columns instead of 15 to listbox, how do i do that?

this is the code which gets all columns.

private void testlist()
    {
        string[,] Datavalue = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count];
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewColumn col in dataGridView1.Columns)
            {
                Datavalue[row.Index, col.Index] = dataGridView1.Rows[row.Index].Cells[col.Index].Value.ToString();
            }
        }
        int i = 1;
        string strval = "";
        foreach (string ss in Datavalue)
        {
            strval += ss + " ";
            if (i == 15)
            {
                listBox1.Items.Add(strval);
                strval = "";
                i = 0;
            }
            i++;
        }
    }


问:
Angular 4, angularfire2, Metadata version mismatch
I've got the following error

Metadata version mismatch for module c:/..../node_modules/angularfire2/index.d.ts, found version4, expected 3.

And if I go and check in my package.json, I have angularfire2 on version 5.0.0-rc.4, and firebase on 4.6.2.
see screenshot for details

I tried changing the version of angularfire2 and firebase to previous versions but nothing worked.

Any suggestions ?
Thank you.

```<code>{
  "name": "twitter-revamped",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "angularfire2": "^5.0.0-rc.4",
    "core-js": "^2.4.1",
    "firebase": "^4.6.2",
    "ng2-semantic-ui": "^0.9.6",
    "rxjs": "<5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.4.7",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}
</code>```

答:
I tried above solutions but it didn't solve my issue. I tried the below steps & it solved my issue.

The issue actually occurred when npm install angularfire2 firebase --save command was run. Below dependencies were added in package.json

```<code>"angularfire2": "^5.0.0-rc.4",
"firebase": "^4.7.0"
</code>```

Actual issue here is due to the version of angularfire2. We need to have angularfire2": "^5.0.0-rc.3 instead of angularfire2": "^5.0.0-rc.4. I am not aware as to why this version is having issue.

Below are the steps for resolution:

STEP 1: Uninstall angularfire2 & firebase

```<code>npm uninstall angularfire2 firebase --save
</code>```

STEP 2: Install angularfire2 5.0.0-rc.3 version

```<code>npm install angularfire2@5.0.0-rc.3 --save
</code>```

STEP 3: Install firebase

```<code>npm install firebase --save
</code>```

STEP 4: Check dependencies added in package.json

```<code>"angularfire2": "^5.0.0-rc.3",
"firebase": "^4.7.0"
</code>```

STEP 5: Execute ng serve

```<code>ng serve
</code>```

This solves the issue & application compiles successfully.

Body:
I've got the following error

Metadata version mismatch for module c:/..../node_modules/angularfire2/index.d.ts, found version4, expected 3.

And if I go and check in my package.json, I have angularfire2 on version 5.0.0-rc.4, and firebase on 4.6.2.
see screenshot for details

I tried changing the version of angularfire2 and firebase to previous versions but nothing worked.

Any suggestions ?
Thank you.

{
  "name": "twitter-revamped",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "angularfire2": "^5.0.0-rc.4",
    "core-js": "^2.4.1",
    "firebase": "^4.6.2",
    "ng2-semantic-ui": "^0.9.6",
    "rxjs": "<5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.4.7",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}

Body:
I tried above solutions but it didn't solve my issue. I tried the below steps & it solved my issue.

The issue actually occurred when npm install angularfire2 firebase --save command was run. Below dependencies were added in package.json

"angularfire2": "^5.0.0-rc.4",
"firebase": "^4.7.0"

Actual issue here is due to the version of angularfire2. We need to have angularfire2": "^5.0.0-rc.3 instead of angularfire2": "^5.0.0-rc.4. I am not aware as to why this version is having issue.

Below are the steps for resolution:

STEP 1: Uninstall angularfire2 & firebase

npm uninstall angularfire2 firebase --save

STEP 2: Install angularfire2 5.0.0-rc.3 version

npm install angularfire2@5.0.0-rc.3 --save

STEP 3: Install firebase

npm install firebase --save

STEP 4: Check dependencies added in package.json

"angularfire2": "^5.0.0-rc.3",
"firebase": "^4.7.0"

STEP 5: Execute ng serve

ng serve

This solves the issue & application compiles successfully.


问:
Add column in dataframe from list
I have a dataframe with some columns like this:

```<code>A   B   C
0
4
5
6
7
7
6
5
</code>```

The possible range of values in A are only from 0 to 7.

Also, I have a list of 8 elements like this:

```<code>List=[2,5,6,8,12,16,26,32]  //There are only 8 elements in this list
</code>```

If the element in column A is n, I need to insert the n th element from the List in a new column, say 'D'.

How can I do this in one go without looping over the whole dataframe?

The resulting dataframe would look like this:

```<code>A   B   C   D
0           2
4           12
5           16
6           26
7           32
7           32
6           26
5           16
</code>```

Note: The dataframe is huge and iteration is the last option option. But I can also arrange the elements in 'List' in any other data structure like dict if necessary.

答:
A solution improving on the great one from @sparrow.

Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

Let's suppose you want to call your new column simply, new_column

First make the list into a Series:

```<code>column_values = pd.Series(mylist)
</code>```

Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column.
In the following example we will position the new column in the first position from left (by setting loc=0)

```<code>df.insert(loc=0, column='new_column', value=column_values)
</code>```

Title: Add column in dataframe from list

Body:
I have a dataframe with some columns like this:

A   B   C
0
4
5
6
7
7
6
5

The possible range of values in A are only from 0 to 7.

Also, I have a list of 8 elements like this:

List=[2,5,6,8,12,16,26,32]  //There are only 8 elements in this list

If the element in column A is n, I need to insert the n th element from the List in a new column, say 'D'.

How can I do this in one go without looping over the whole dataframe?

The resulting dataframe would look like this:

A   B   C   D
0           2
4           12
5           16
6           26
7           32
7           32
6           26
5           16

Note: The dataframe is huge and iteration is the last option option. But I can also arrange the elements in 'List' in any other data structure like dict if necessary.

Body:
A solution improving on the great one from @sparrow.

Let df, be your dataset, and mylist the list with the values you want to add to the dataframe.

Let's suppose you want to call your new column simply, new_column

First make the list into a Series:

column_values = pd.Series(mylist)

Then use the insert function to add the column. This function has the advantage to let you choose in which position you want to place the column.
In the following example we will position the new column in the first position from left (by setting loc=0)

df.insert(loc=0, column='new_column', value=column_values)


问:
Web scraping multiple sites in python
I signed up to this website just to ask this question as I have been searching for hours over multiple days and haven't found anything.
I am trying to, within 10 seconds, scrape the 2-3 characters from 5 websites, combine them, and paste them into a box.
I have a rough idea of what I would need, but no idea how to go about this.
I believe I want to assign variables the scraped contents from a certain website, and then get it to print the combination of these variables for me to copy and paste.
I'm not an expert by any means in Python, so if possible, a copy/pasteable script would be great.
The websites are:
https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
Keeping this up now only because I cannot take it down. Thank you to those who have helped, I hope this helps someone else.
Sorry for being dumb</p>

答:
I completed the challenge, I used an excel spreadsheet with functions to get all the little code things from every clock cycle and put them together to make one code every 10 seconds. Sorry if that doesn't make sense I'm not sure how to explain it. Then I pasted this into the end of the "validation link" to replace the < clock pts > at the end of the URL. I had to do this very fast before the clock reset. Very stressful haha. Then eventually I did this in time and it gave me the code. I hope this helps.
But you'll have to figure out how to get all the codes together in under 10 seconds by yourself, otherwise this is basically cheating, right?</p>

Title: Web scraping multiple sites in python


问:
SMS BroadcastReceiver on Oreo
I have a SMS listener that works well in versions prior to Oreo (API 26) but seems to be ignored in API 26. According to documentation, SMS_RECEIVED_ACTION is exempted from the implicit broadcast limitations (link), so no changes should be needed.

Here is my listener:

```<code>public class SmsListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        (...)
    }
}
</code>```

I have this on the manifest:

```<code><receiver android:name=".communication.SmsListener"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>
</code>```

And also set the permissions

```<code><uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
</code>```

Have tried with different sample projects like this as well and the outcome is the same, no SMS is captured in API 26.

Can someone provide me a working sample or help me figure out whether I have to change something or if there is a bug in API 26?

答:
Just figured out what happened! The android:priority="1000" causes the issue.
Found this on the documentation:

The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.

Source: link

Title: SMS BroadcastReceiver on Oreo

Body:
I have a SMS listener that works well in versions prior to Oreo (API 26) but seems to be ignored in API 26. According to documentation, SMS_RECEIVED_ACTION is exempted from the implicit broadcast limitations (link), so no changes should be needed.

Here is my listener:

public class SmsListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        (...)
    }
}

I have this on the manifest:

<receiver android:name=".communication.SmsListener"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

And also set the permissions

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

Have tried with different sample projects like this as well and the outcome is the same, no SMS is captured in API 26.

Can someone provide me a working sample or help me figure out whether I have to change something or if there is a bug in API 26?


问:
Using BLE between devices with React Native
I am trying to make an app that uses Bluetooth Low Energy between two smartphones in proximity using React Native.

I am looking at react-native-ble-manager but i don't understand how to create the "server" (or in this case peripheral) part.

I understood the methods to discover and connect to a peripheral but I don't understand how to make a smartphone (with enabled bluetooth) listening incoming connections.

How can I listen incoming connections with BLE?

Thank you in advance for your answers

答:
For any BLE connection there has two part, i.e central and peripheral.

react-native-ble-manager
is a central library. You can not create peripheral using this.
Also, every smartphone does not have peripheral mode enabled. So in the situation, you can not use your application properly.


问:
Join and count number of values in each subcategory
Lets say a have a data frame that looks like this:

```<code> V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER
</code>```

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

```<code>  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3
</code>```

And so on...

答:
You can do pivot with unstack i.e

```<code>df.pivot_table(index='V290',columns='V311',aggfunc='size',fill_value=0).unstack()

V311            V290
MIDDLE HALF     AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
                POOR              4
NK-UNASCERTAIN  AVERAGE           0
                GOOD              0
                NK-UNASCERTAIN    0
                POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                NK-UNASCERTAIN    0
                POOR              1
dtype: int64
</code>```

Also :

```<code>df.groupby(['V290','V311']).size().unstack().fillna(0).unstack()
</code>```

If you want the percentage then you can divide by the sum i.e

```<code>ndf = df.pivot_table(index='V290',columns='V311',aggfunc='size',fill_value=0)
percents = (ndf/ndf.sum()*100).unstack()

V311            V290
MIDDLE HALF     AVERAGE            33.333333
                GOOD               11.111111
                NK-UNASCERTAIN     11.111111
                POOR               44.444444
NK-UNASCERTAIN  AVERAGE             0.000000
                GOOD                0.000000
                NK-UNASCERTAIN      0.000000
                POOR              100.000000
TOP QUARTER     AVERAGE            33.333333
                GOOD               33.333333
                NK-UNASCERTAIN      0.000000
                POOR               33.333333
dtype: float64
</code>```

Body:
Lets say a have a data frame that looks like this:

 V290   V311
0   GOOD    TOP QUARTER
1   NK-UNASCERTAIN  MIDDLE HALF
2   AVERAGE TOP QUARTER
3   POOR    NK-UNASCERTAIN
4   POOR    MIDDLE HALF
5   GOOD    MIDDLE HALF
6   POOR    TOP QUARTER
7   AVERAGE MIDDLE HALF
8   POOR    MIDDLE HALF
9   AVERAGE MIDDLE HALF
10  POOR    MIDDLE HALF
11  POOR    MIDDLE HALF
12  AVERAGE MIDDLE HALF
13  AVERAGE TOP QUARTER

And i want to group this data by ['V311'] and see how many GOOD or POOR would be in Every ['V311'] Subcategory.
I want to make something like this:

  Top Quarter:GOOD:12
              POOR:30
              Average:15
  Middle half:GOOD:5
              POOR:19
              Average:3

And so on...

Body:
You can do pivot with unstack i.e

df.pivot_table(index='V290',columns='V311',aggfunc='size',fill_value=0).unstack()

V311            V290
MIDDLE HALF     AVERAGE           3
                GOOD              1
                NK-UNASCERTAIN    1
                POOR              4
NK-UNASCERTAIN  AVERAGE           0
                GOOD              0
                NK-UNASCERTAIN    0
                POOR              1
TOP QUARTER     AVERAGE           2
                GOOD              1
                NK-UNASCERTAIN    0
                POOR              1
dtype: int64

Also :

df.groupby(['V290','V311']).size().unstack().fillna(0).unstack()

If you want the percentage then you can divide by the sum i.e

ndf = df.pivot_table(index='V290',columns='V311',aggfunc='size',fill_value=0)
percents = (ndf/ndf.sum()*100).unstack()

V311            V290
MIDDLE HALF     AVERAGE            33.333333
                GOOD               11.111111
                NK-UNASCERTAIN     11.111111
                POOR               44.444444
NK-UNASCERTAIN  AVERAGE             0.000000
                GOOD                0.000000
                NK-UNASCERTAIN      0.000000
                POOR              100.000000
TOP QUARTER     AVERAGE            33.333333
                GOOD               33.333333
                NK-UNASCERTAIN      0.000000
                POOR               33.333333
dtype: float64


问:
Get selected QAction text label from QActionGroup
So I am trying to create a PyQt settings tab with a list of options, where I can only choose one option of a list of options. The label of the selected option (e.g. 'A') should then be copied to the self.ID variable, so it can be used as a variable for later functions. Here is what I have written in my init function:

```<code>    self.ID = 0
    self.prevMenu = QtWidgets.QMenu('ID tag', self)
    ag = QtWidgets.QActionGroup(self.prevMenu, exclusive=True)
    self.myID = ['A','B','C','D','E']

    for i in self.myID:
        Action = ag.addAction(QtWidgets.QAction(i, self.prevMenu, checkable=True))
        self.prevMenu.addAction(Action)
        Action.setText(i)
        Action.triggered.connect(lambda item=Action.text(): self.set_ID(Action.text()))
    self.menubar.addMenu(self.prevMenu)

    def set_ID(self, ID):
       print "Which: ", ID
       self.ID = ID
       print self.ID
</code>```

Now my problem is that when I run this, no matter which label I choose, it is only the last element of the list ('E'), that is being transferred to self.ID. I know it must be something about how my variables inherits from each other, but I cannot figure out how. Can anybody help me?

答:
There are two mistakes in your code.

The triggered signal has the checked arguments, this means that the "item" argument you use will be "overwritten" by the triggered checked status.

The scope of lambda functions is not internal to the function itself, you need to have an actual reference to the value (possibly, a class attribute) or pass it as a lambda optional argument. This is very important when using for/while cycles.

You should change the last line of your for cycle to this:

```<code>Action.triggered.connect(lambda checked, item=Action: self.set_ID(item.text())
</code>```

As a personal note, if you are going to use the set_ID method only for this purpose, you might prefer to use the action as argument (and read its text from the method) or, eventually, ignore the arguments at all and use the QObject.sender() function to retrieve the action that triggered the signal.

Body:
So I am trying to create a PyQt settings tab with a list of options, where I can only choose one option of a list of options. The label of the selected option (e.g. 'A') should then be copied to the self.ID variable, so it can be used as a variable for later functions. Here is what I have written in my init function:

    self.ID = 0
    self.prevMenu = QtWidgets.QMenu('ID tag', self)
    ag = QtWidgets.QActionGroup(self.prevMenu, exclusive=True)
    self.myID = ['A','B','C','D','E']

    for i in self.myID:
        Action = ag.addAction(QtWidgets.QAction(i, self.prevMenu, checkable=True))
        self.prevMenu.addAction(Action)
        Action.setText(i)
        Action.triggered.connect(lambda item=Action.text(): self.set_ID(Action.text()))
    self.menubar.addMenu(self.prevMenu)

    def set_ID(self, ID):
       print "Which: ", ID
       self.ID = ID
       print self.ID

Now my problem is that when I run this, no matter which label I choose, it is only the last element of the list ('E'), that is being transferred to self.ID. I know it must be something about how my variables inherits from each other, but I cannot figure out how. Can anybody help me?

Body:
There are two mistakes in your code.

The triggered signal has the checked arguments, this means that the "item" argument you use will be "overwritten" by the triggered checked status.

The scope of lambda functions is not internal to the function itself, you need to have an actual reference to the value (possibly, a class attribute) or pass it as a lambda optional argument. This is very important when using for/while cycles.

You should change the last line of your for cycle to this:

Action.triggered.connect(lambda checked, item=Action: self.set_ID(item.text())

As a personal note, if you are going to use the set_ID method only for this purpose, you might prefer to use the action as argument (and read its text from the method) or, eventually, ignore the arguments at all and use the QObject.sender() function to retrieve the action that triggered the signal.


问:
What to choose to store just one integer? Sqlite? or Text file?
I've build a small web-service in PHP. I want to control the number of calls to a specific API method.

I thought at first of using a text file, because it's just an integer. But after taking a good look at SQLite it seemed much more convenient.
So the code is just: get the "counter" from SQLite and increment it when that method is called, then store it back on SQLite db.

Is this a right way of doing it? Would it be simpler and more scalable to just use a file or... maybe something else?

Thanks in advance.

答: A database would typically scale better than the filesystem, but you are going to need to be careful and use appropriate locks with either mechanism.</p>

OwnerDisplayName: rogeriopvl

OwnerDisplayName: Mitch Wheat


问:
Oracle hierarchical query - combine results
Given a table:

```<code>Old_ID  New_ID
A       B
B       C
</code>```

Multiple ID changes can form a chain A -> B -> C. I can do a hierarchical query.

```<code>SELECT Old_ID, New_ID from mytable
CONNECT BY PRIOR New_ID = Old_ID
</code>```

Since C is the valid new ID for both A and B, the result I'd like to get is:

```<code>Old_ID  New_ID
A       C
B       C
</code>```

So map all old IDs to the latest new ID in the chain.

答:
Use a combination of CONNECT_BY_ROOT( old_id ), to get the start of the hierarchy, and WHERE CONNECT_BY_ISLEAF = 1, to find the last item in the hierarchy:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE your_table( Old_ID, New_ID ) As
SELECT 'A', 'B' FROM DUAL UNION ALL
SELECT 'B', 'C' FROM DUAL;
</code>```

Query 1:

```<code>SELECT CONNECT_BY_ROOT( old_id ) AS old_id,
       new_id
FROM   your_table
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY PRIOR New_ID = Old_id
</code>```

Results:

```<code>| OLD_ID | NEW_ID |
|--------|--------|
|      A |      C |
|      B |      C |
</code>```

Body:
Given a table:

Old_ID  New_ID
A       B
B       C

Multiple ID changes can form a chain A -> B -> C. I can do a hierarchical query.

SELECT Old_ID, New_ID from mytable
CONNECT BY PRIOR New_ID = Old_ID

Since C is the valid new ID for both A and B, the result I'd like to get is:

Old_ID  New_ID
A       C
B       C

So map all old IDs to the latest new ID in the chain.

Body:
Use a combination of CONNECT_BY_ROOT( old_id ), to get the start of the hierarchy, and WHERE CONNECT_BY_ISLEAF = 1, to find the last item in the hierarchy:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE your_table( Old_ID, New_ID ) As
SELECT 'A', 'B' FROM DUAL UNION ALL
SELECT 'B', 'C' FROM DUAL;

Query 1:

SELECT CONNECT_BY_ROOT( old_id ) AS old_id,
       new_id
FROM   your_table
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY PRIOR New_ID = Old_id

Results:

| OLD_ID | NEW_ID |
|--------|--------|
|      A |      C |
|      B |      C |


问:
Jenkins Github pull Request Builder phrase update
I am using DSL script to create a Github Pull request build job. I am trying to modify phrase "retest this please" to "retest". I can find all other phrase in Plugin UI like skipphrase, Test phrase. Accept to test phrase (in manage jenkins) or job config, but not able to find this "retest this please". if you can share DSL or groovy code that would be great.</p>

答: triggerPhrase('^.retest.$') worked for me.


问:
Objective-C "<...>" notation
I'm reading through More iPhone Programming 3, and I cannot remember what the <> notation is.  I know it's to conform to Protocols for a class, but I'm not sure what it is in this example talking about NSFetchedResultsController in the Core Data section.  Here is the code:

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
</code>```

Thanks!

答:
id <NSFetchedResultsSectionInfo> sectionInfo simply means sectionInfo is some object (indicated by id) that conforms to the NSFetchedResultsSectionInfo protocol.

By declaring the variable as a type that conforms to this protocol, its numberOfObjects property is guaranteed to be available to use, unless it turns out the object doesn't conform to the protocol in which case you get a crash.

Title: Objective-C "<...>" notation

Body:
I'm reading through More iPhone Programming 3, and I cannot remember what the <> notation is.  I know it's to conform to Protocols for a class, but I'm not sure what it is in this example talking about NSFetchedResultsController in the Core Data section.  Here is the code:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];

Thanks!


问:
how to generate core file in docker container?
using ulimit command, i set core file size.

ulimit -c unlimited

and I compiled  c source code using gcc - g option.
then a.out generated.
after command

./a.out
there is runtime error .

```<code>(core dumped)
</code>```

but core file was not generated.(ex. core.294340)

how to generated core file?

答:
First make sure the container will write the cores to an existing location in the container filesystem. The core generation settings are set in the host, not in the container. Example:

```<code>echo '/cores/core.%e.%p' | sudo tee /proc/sys/kernel/core_pattern
</code>```

will generate cores in the folder /cores.

In your Dockerfile, create that folder:

```<code>RUN mkdir /cores
</code>```

You need to specify the core size limit; the ulimit shell command would not work, cause it only affects at the current shell. You need to use the docker run option --ulimit with a soft and hard limit. After building the Docker image, run the container with something like:

```<code>docker run --ulimit core=-1 --mount source=coredumps_volume,target=/cores ab3ca583c907 ./a.out
</code>```

where coredumps_volume is a volume you already created where the core will persist after the container is terminated. E.g.

```<code>docker volume create coredumps_volume
</code>```

Body:
using ulimit command, i set core file size.

ulimit -c unlimited

and I compiled  c source code using gcc - g option.
then a.out generated.
after command

./a.out
there is runtime error .

(core dumped)

but core file was not generated.(ex. core.294340)

how to generated core file?

Body:
First make sure the container will write the cores to an existing location in the container filesystem. The core generation settings are set in the host, not in the container. Example:

echo '/cores/core.%e.%p' | sudo tee /proc/sys/kernel/core_pattern

will generate cores in the folder /cores.

In your Dockerfile, create that folder:

RUN mkdir /cores

You need to specify the core size limit; the ulimit shell command would not work, cause it only affects at the current shell. You need to use the docker run option --ulimit with a soft and hard limit. After building the Docker image, run the container with something like:

docker run --ulimit core=-1 --mount source=coredumps_volume,target=/cores ab3ca583c907 ./a.out

where coredumps_volume is a volume you already created where the core will persist after the container is terminated. E.g.

docker volume create coredumps_volume


问:
Why is not updated model in ngFor after changed model?
I have an property:

```<code>public rows: any[];
</code>```

Then I fill this array in constructor:

```<code>this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});
</code>```

In template I iterate array like as:

```<code><tr *ngFor="let p of rows; let i = index;">
</code>```

So, if I remove element from array:

```<code>this.rows.splice(this.rows.length - 1, 1);
</code>```

It does not change model, I see as before one row in array.

答:
Angular doesn't recognise an array as having been changed if only it's contents have been changed. To let it know the array has changed just reassign the array object after removing an element and it should update on the DOM:</p>

```<code>this.rows.splice(this.rows.length - 1, 1);
this.rows = [...this.rows];
</code>```

Body:
I have an property:

public rows: any[];

Then I fill this array in constructor:

this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});

In template I iterate array like as:

So, if I remove element from array:

this.rows.splice(this.rows.length - 1, 1);

It does not change model, I see as before one row in array.

Body:
Angular doesn't recognise an array as having been changed if only it's contents have been changed. To let it know the array has changed just reassign the array object after removing an element and it should update on the DOM:

this.rows.splice(this.rows.length - 1, 1);
this.rows = [...this.rows];


问:
Positioning of annotations in subplots
I have to generate a plot of different sensor data. These should be printed in subplot each.  After generating the plot it should be annotated with some rectangles to highlight different features. Afterwards, these rectangles should be annotated with a text, describing the belonging class with a short word.

Surprisingly the same code is working in another script, where I don't use subplots, but only a single specgram.
I already replace the annotation(h,...) with annotation(gcf, ...), which should be the same. Adding tempplot instead of h, which makes sense to me,

```<code>Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'}
sampledExperiment = [10, 10, 0;
                 30,10, 1;
                 50,10, 0;
                 70,10, 1;
                 ]

experimentnaming = {0, 'classA';
                1, 'classB'
                }

samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
  tempplot = subplot(length(Sensorinput(1,:)),1,index);
  plot(Sensorinput(:,index));
  title(Naminginput(index));
  pos = get (tempplot, 'position')
  step = pos(3)/length(Sensorinput(:,index));

  for index=1:1:length(sampledExperiment)

    annotation(h, "rectangle",[pos(1)+step*sampledExperiment(index,1),pos(2),step*sampledExperiment(index,2),pos(4)]);
    y  = ylim;
    for namingindex=1:1:length(experimentnaming(:,1))
      if experimentnaming{namingindex,1}==sampledExperiment(index,3)
          text(sampledExperiment(index,1)/samplerate,y(2),experimentnaming(namingindex,2),'rotation',90);
      end
    end

  end

end
</code>```

I expect the boxes having the same height than the underlying subplot. Also, I am expecting the text (which is obviously printed as a stack) as an annotation to the box.
But this is the result I currently get: wrong result. Also, the boxes do not zoom correctly, when I resize the window. wrong_small_window.
This is mainly, what is working: working with single figure. Draw rectangles with the full height of the subplot and add text. This is created with the same code, but without subplots.

Hopefully you can help?

答:
I just managed to get what I want by using a direct rectangle instead of annotation rectangle. With this type, I am able to use the data space instead of figure space and everything is fine.

```<code>Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'};
sampledExperiment = [10, 10, 0;
                     30, 10, 1;
                     50, 10, 0;
                     70, 10, 1];
experimentnaming = {0, 'classA';
                    1, 'classB'};
samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
    tempplot = subplot(length(Sensorinput(1,:)),1,index);
    plot(Sensorinput(:,index));
    title(Naminginput(index));
    pos = get (tempplot, 'position')
    step = pos(3)/length(Sensorinput(:,index));

    for index=1:1:length(sampledExperiment)
        rectangle('Position',[sampledExperiment(index,1),0,sampledExperiment(index,2),1]);
        y  = ylim;
        for namingindex=1:1:length(experimentnaming(:,1))
            if experimentnaming{namingindex,1}==sampledExperiment(index,3)
                text(sampledExperiment(index,1)+0.5*sampledExperiment(index,2), y(2),experimentnaming(namingindex,2),'rotation',90);
            end
        end
    end
end
</code>```

I also mixed up the data space with the figure space while plotting the text.

Title: Positioning of annotations in subplots

Body:
I have to generate a plot of different sensor data. These should be printed in subplot each.  After generating the plot it should be annotated with some rectangles to highlight different features. Afterwards, these rectangles should be annotated with a text, describing the belonging class with a short word.

Surprisingly the same code is working in another script, where I don't use subplots, but only a single specgram.
I already replace the annotation(h,...) with annotation(gcf, ...), which should be the same. Adding tempplot instead of h, which makes sense to me,

Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'}
sampledExperiment = [10, 10, 0;
                 30,10, 1;
                 50,10, 0;
                 70,10, 1;
                 ]

experimentnaming = {0, 'classA';
                1, 'classB'
                }

samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
  tempplot = subplot(length(Sensorinput(1,:)),1,index);
  plot(Sensorinput(:,index));
  title(Naminginput(index));
  pos = get (tempplot, 'position')
  step = pos(3)/length(Sensorinput(:,index));

  for index=1:1:length(sampledExperiment)

    annotation(h, "rectangle",[pos(1)+step*sampledExperiment(index,1),pos(2),step*sampledExperiment(index,2),pos(4)]);
    y  = ylim;
    for namingindex=1:1:length(experimentnaming(:,1))
      if experimentnaming{namingindex,1}==sampledExperiment(index,3)
          text(sampledExperiment(index,1)/samplerate,y(2),experimentnaming(namingindex,2),'rotation',90);
      end
    end

  end

end

I expect the boxes having the same height than the underlying subplot. Also, I am expecting the text (which is obviously printed as a stack) as an annotation to the box.
But this is the result I currently get: wrong result. Also, the boxes do not zoom correctly, when I resize the window. wrong_small_window.
This is mainly, what is working: working with single figure. Draw rectangles with the full height of the subplot and add text. This is created with the same code, but without subplots.

Hopefully you can help?

Body:
I just managed to get what I want by using a direct rectangle instead of annotation rectangle. With this type, I am able to use the data space instead of figure space and everything is fine.

Sensorinput = rand(100,6);
Naminginput = {'a' 'b' 'c' 'd' 'e' 'f'};
sampledExperiment = [10, 10, 0;
                     30, 10, 1;
                     50, 10, 0;
                     70, 10, 1];
experimentnaming = {0, 'classA';
                    1, 'classB'};
samplerate = 10;

h = figure;
for index = 1:1:length(Sensorinput(1,:))
    tempplot = subplot(length(Sensorinput(1,:)),1,index);
    plot(Sensorinput(:,index));
    title(Naminginput(index));
    pos = get (tempplot, 'position')
    step = pos(3)/length(Sensorinput(:,index));

    for index=1:1:length(sampledExperiment)
        rectangle('Position',[sampledExperiment(index,1),0,sampledExperiment(index,2),1]);
        y  = ylim;
        for namingindex=1:1:length(experimentnaming(:,1))
            if experimentnaming{namingindex,1}==sampledExperiment(index,3)
                text(sampledExperiment(index,1)+0.5*sampledExperiment(index,2), y(2),experimentnaming(namingindex,2),'rotation',90);
            end
        end
    end
end

I also mixed up the data space with the figure space while plotting the text.


问:
handle Http Request in exception case
I have an application the backend is spring MVC and the front end is angular.the server side sends data to the client side. My question is if something wrong happens in the server side what is the best way to handle it.
I think about 2 solutions :
the first one is to create new model which contains 3 attributes like this

public class Response{
       boolean hasError;
       Object data;
       Exception ex}

and send this object to the client side then in the client side check if the hasError equals false check the data object otherwise check the exception object.
this solution grants that in all case the http response status will be 200 from the server side,

the second solution is to create custom status code for the http response then in the front end use this status code to detect exception type.

The question is what is the best practice of these 2 solutions ?
Or is there is a solution better than these 2 solutions ?

答:
TL; DR:

Use what you have out of the box with Spring and do it by REST principles.
Handle the error on the frontend with more generic messages so that there is no need for a custom model when it comes to error handling, just http status codes.

Longer version:

There is no need to reinvent the wheel and write custom http codes. There are plenty around and Spring has an excellent support for handling exceptions with @ControllerAdvice and @ExceptionHanlder annotations.
Some reference and a quick guide

Depending on your backend endpoints you can write various exception classes that correspond best to what you need. Try to follow the REST principles here, you will thank yourself later on.
Also, there is no need to propagate the error all the way to the front end. For example - If you had a NullPointerException happened in the backend, do not display Null pointer happened to the user on the frontend, this helps him nothing.

this solution grants that in all case the http response status will be 200 from the server side

Don't return 200 if there was an error, because that is confusing to the caller. If there was an error, return a 4xx or a 5xx code that corresponds to the error occurred and then handle that case on the frontend independently from the backend (e.g, database is down, you return an error 500 to the frontend and have it display a message to the user like Service temporarily down, please try again later or something like that).

Title: handle Http Request in exception case


问:
How to copy a field from a .gz file to a csv
Is there a way to copy a field, from a .gz file into a txt file without unzipping in either Windows commands or Python?

The .gz file is over 15000 lines long

If field 1="SVR" i need to output fields 2, 3, 4, 6, 7, 11, 12, 13 and 21. (if $1 = other, ignore)

Can be written to any other file type, does not have to be txt.

答:
This can be done using Python's gzip library to read the .gz file, the csv library to parse the CSV file inside and the use of operator.itemgetter() to extract the required items from each row:

```<code>from operator import itemgetter
import csv
import gzip

with gzip.open('input.gz', 'rb') as f_gz, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_gz)
    csv_output = csv.writer(f_output)
    req_cols = itemgetter(1, 2, 3, 5, 6, 10, 11, 12, 20)
    csv_output.writerow(req_cols(next(csv_input)))

    for row in csv_input:
        if row[0] == 'SVR':
            csv_output.writerow(req_cols(row))
</code>```

So if you had a CSV containing something like:

c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20,c21,c22
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
SVR,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
3,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
SVR,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
```

<p>You would get an output CSV file containing:</p>

<pre class="lang-none prettyprint-override"><code>c2,c3,c4,c6,c7,c11,c12,c13,c21
2,3,4,6,7,11,12,13,21
2,3,4,6,7,11,12,13,21
</code>```

Tested on Python 2.x. For Python 3.x, the files would need to be opened as:

```<code>with gzip.open('input.gz', 'rt', newline='') as f_gz, open('output.csv', 'w', newline='') as f_output:
</code>```

Body:
This can be done using Python's gzip library to read the .gz file, the csv library to parse the CSV file inside and the use of operator.itemgetter() to extract the required items from each row:

from operator import itemgetter
import csv
import gzip

with gzip.open('input.gz', 'rb') as f_gz, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_gz)
    csv_output = csv.writer(f_output)
    req_cols = itemgetter(1, 2, 3, 5, 6, 10, 11, 12, 20)
    csv_output.writerow(req_cols(next(csv_input)))

    for row in csv_input:
        if row[0] == 'SVR':
            csv_output.writerow(req_cols(row))

So if you had a CSV containing something like:

c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c14,c15,c16,c17,c18,c19,c20,c21,c22
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
SVR,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
3,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
SVR,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22

You would get an output CSV file containing:

c2,c3,c4,c6,c7,c11,c12,c13,c21
2,3,4,6,7,11,12,13,21
2,3,4,6,7,11,12,13,21

Tested on Python 2.x. For Python 3.x, the files would need to be opened as:

with gzip.open('input.gz', 'rt', newline='') as f_gz, open('output.csv', 'w', newline='') as f_output:


问:
Regex matching a word not followed by a string and allow multiple words (upto 5 words) in between
I'm trying to match a word ("Junior Consultant") not followed by a specific string "(m/f)" and allow multiple words (up to 5 words) in between.

Should match:

Junior Consultant in New York
Junior Consultant Banking
Junior Consultant w1 w2 w3 w4 w5
Junior Consultant w1 w2 w3 w4 w5 w6 (m/f)

Should NOT match:

Junior Consultant in New York (m/f)
Junior Consultant (m/f)
Junior Consultant w1 w2 w3 w4 w5 (m/f)

This is what I got so far:
Junior Consultant((?!\s\(m\/f\))(\s\w+)){0,5}

答:
Almost there, but you have to match all zero to five words before the "(m/f)" part. Try this:</p>

```<code>/Junior Consultant(?!(\s\w+){0,5}\s\(m\/f\))/
</code>```

Body:
Almost there, but you have to match all zero to five words before the "(m/f)" part. Try this:

/Junior Consultant(?!(\s\w+){0,5}\s\(m\/f\))/


问:
How to split an SQL Table into half and send the other half of the rows to new columns with SQL Query?
```<code>Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
</code>```

Output :

```<code>Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
</code>```

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

答:
First, this type of operation should be done at the application layer and not in the database.  That said, it can be an interesting exercise to see how to do this in the database.

I would use conditional aggregation or pivot.  Note that SQL tables are inherently unordered.  Your base table has no apparent ordering, so the values could come out in any order.

```<code>select max(case when seqnum % 2 = 0 then country end) as country_1,
       max(case when seqnum % 2 = 0 then percentage end) as percentage_1,
       max(case when seqnum % 2 = 1 then country end) as country_2,
       max(case when seqnum % 2 = 1 then percentage end) as percentage_2
from (select c.*,
             (row_number() over (order by (select null)) - 1) as seqnum
      from country c
     ) c
group by seqnum / 2;
</code>```

Body:
Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%

Output :

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

Body:
First, this type of operation should be done at the application layer and not in the database.  That said, it can be an interesting exercise to see how to do this in the database.

I would use conditional aggregation or pivot.  Note that SQL tables are inherently unordered.  Your base table has no apparent ordering, so the values could come out in any order.

select max(case when seqnum % 2 = 0 then country end) as country_1,
       max(case when seqnum % 2 = 0 then percentage end) as percentage_1,
       max(case when seqnum % 2 = 1 then country end) as country_2,
       max(case when seqnum % 2 = 1 then percentage end) as percentage_2
from (select c.*,
             (row_number() over (order by (select null)) - 1) as seqnum
      from country c
     ) c
group by seqnum / 2;


问:
`RLMArray` does not conform to protocol 'Encodable'
I want to Do:

Using JSONDecoder(), I convert json to Realm object.

And I save this object to Realm databases.

Problem:

RLMArray don't apply Codable protocol.

I could be conformed Decodable protocol, but Codable I couldn't.

Error Message:

Type 'Person' does not conform to protocol 'Encodable'

Code:

```<code>public class Hobby: Object, Codable {
    @objc dynamic var  title: String?
    @objc dynamic var  category: String?
}
public class Person: Object, Codable { // Error: Type 'Person' does not conform to protocol 'Encodable'
    @objc dynamic var  name: String?
    @objc dynamic var  hobbies: RLMArray<Hobby>?

    required convenience public init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        hobbies = try container.decode(RLMArray<Hobby>?.self, forKey: .hobbies)
    }
}
func sample() {
    let person = try? JSONDecoder().decode(Person.self, from: "{\"name\" : \"aaa\",\"hobbies\" : [{\"title\" : \"fishing\",\"category\" : \"outdoor\"},{\"title\" : \"reading\",\"type\" : \"indoor\"}]}".data(using: .utf8)!)
    print(person)
    let realm = try! Realm()
    try! realm.write {
        realm.add(person!)
    }
}
</code>```

Do you have some ideas?

Swift4
RealmSwift

答:
Codable is the exact same as Decodable + Encodable. If you want to conform to Codable you will need to implement the encoding functions, which for your Person object would be:

```<code>enum CodingKeys: String, CodingKey {
        case name
        case hobbies
// or: case hobbies = "customHobbiesKey" if you want to encode to a different key
}

func encode(to encoder: Encoder) throws {
    do {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(hobbies, forKey: .hobbies)
    } catch {
        print(error)
    }
}
</code>```

Add this to your Person class, and then implement the same thing for your Hobby class.

Because i'm not sure if you even want to encode: If all you need to do is create Realm-Objects from Json I would simply replace 'Codable' with the'Decodable'-Protocol.

EDIT: I noticed the issue is about the RLMArray. I'm not sure how codable works with RLMArray, but if it doesn't work you could try replacing the declaration with

let hobbies = List<Hobby>()

and then in init() replace the 'hobbies' line with:

```<code>let tempHobbyList: [Hobby] = try container.decode([Hobby].self, forKey: .hobbies)
self.hobbies.append(objectsIn: tempHobbyList)
</code>```

That's how I got my lists with realmObjects to work with codable

Body:
I want to Do:

Using JSONDecoder(), I convert json to Realm object.

And I save this object to Realm databases.

Problem:

RLMArray don't apply Codable protocol.

I could be conformed Decodable protocol, but Codable I couldn't.

Error Message:

Type 'Person' does not conform to protocol 'Encodable'

Code:

public class Hobby: Object, Codable {
    @objc dynamic var  title: String?
    @objc dynamic var  category: String?
}
public class Person: Object, Codable { // Error: Type 'Person' does not conform to protocol 'Encodable'
    @objc dynamic var  name: String?
    @objc dynamic var  hobbies: RLMArray<Hobby>?

    required convenience public init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        hobbies = try container.decode(RLMArray<Hobby>?.self, forKey: .hobbies)
    }
}
func sample() {
    let person = try? JSONDecoder().decode(Person.self, from: "{\"name\" : \"aaa\",\"hobbies\" : [{\"title\" : \"fishing\",\"category\" : \"outdoor\"},{\"title\" : \"reading\",\"type\" : \"indoor\"}]}".data(using: .utf8)!)
    print(person)
    let realm = try! Realm()
    try! realm.write {
        realm.add(person!)
    }
}

Do you have some ideas?

Swift4
RealmSwift

Body:
Codable is the exact same as Decodable + Encodable. If you want to conform to Codable you will need to implement the encoding functions, which for your Person object would be:

enum CodingKeys: String, CodingKey {
        case name
        case hobbies
// or: case hobbies = "customHobbiesKey" if you want to encode to a different key
}

func encode(to encoder: Encoder) throws {
    do {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(hobbies, forKey: .hobbies)
    } catch {
        print(error)
    }
}

Add this to your Person class, and then implement the same thing for your Hobby class.

Because i'm not sure if you even want to encode: If all you need to do is create Realm-Objects from Json I would simply replace 'Codable' with the'Decodable'-Protocol.

EDIT: I noticed the issue is about the RLMArray. I'm not sure how codable works with RLMArray, but if it doesn't work you could try replacing the declaration with

let hobbies = List<Hobby>()

and then in init() replace the 'hobbies' line with:

let tempHobbyList: [Hobby] = try container.decode([Hobby].self, forKey: .hobbies)
self.hobbies.append(objectsIn: tempHobbyList)

That's how I got my lists with realmObjects to work with codable


问:
How to check if entire html page is loaded based on  function by Web Driver C#?
I want to use Selenium WebDrier with C# to check content of page.

The problem is that my page is reloading partly, not entire page every time i do something. When I click, page is reloading and after that I want to click next step of my TC, so functions WaitForPageToLoad, waitForElementVisible is not working (don't know why) or something are not working. They Give me errors like "Unable to find element....". I don't want to use functions like Thread.sleep(1000000) I want to check if page is loaded and after that run my actions.

So I figured out that there is a .js function in my HTML that runs every time I commit something (I think so).

The script looks like that :

```<code>function(a) {
    if (a === !0 && !--e.readyWait || a !== !0 && !e.isReady) {
        if (!c.body)
            return setTimeout(e.ready, 1);
        e.isReady = !0;
        if (a !== !0 && --e.readyWait > 0)
            return;
        A.fireWith(c, [e]), e.fn.trigger && e(c).trigger("ready").off("ready")
    }
}

function onload(event) {
    onload()
}
</code>```

after that there is my  and  sections.

The question is: How to check if this function is running and when it ends to make my webDriver scripts run ??

答:
I did something like this :
Where InputArgs are [xpath_to_find, timeput]

private void waitForXpathToBeVisibleWithTimeout(String[] inputArgs)

```<code> for (int i = 0; i < Int32.Parse(inputArgs[1]); i++)
            {
                try
                {
                    element = driver.FindElement(By.XPath(inputArgs[0]));
                    break;
                }
                catch
                {
                    Thread.Sleep(1000);
                    continue;
                }
            }
            element = driver.FindElement(By.XPath(inputArgs[0]));

  }
</code>```

And it works nice !

Title: How to check if entire html page is loaded based on <html> function by Web Driver C#?

Body:
I want to use Selenium WebDrier with C# to check content of page.

The problem is that my page is reloading partly, not entire page every time i do something. When I click, page is reloading and after that I want to click next step of my TC, so functions WaitForPageToLoad, waitForElementVisible is not working (don't know why) or something are not working. They Give me errors like "Unable to find element....". I don't want to use functions like Thread.sleep(1000000) I want to check if page is loaded and after that run my actions.

So I figured out that there is a .js function in my HTML that runs every time I commit something (I think so).

The script looks like that :

function(a) {
    if (a === !0 && !--e.readyWait || a !== !0 && !e.isReady) {
        if (!c.body)
            return setTimeout(e.ready, 1);
        e.isReady = !0;
        if (a !== !0 && --e.readyWait > 0)
            return;
        A.fireWith(c, [e]), e.fn.trigger && e(c).trigger("ready").off("ready")
    }
}

function onload(event) {
    onload()
}

after that there is my  and  sections.

The question is: How to check if this function is running and when it ends to make my webDriver scripts run ??

Body:
I did something like this :
Where InputArgs are [xpath_to_find, timeput]

private void waitForXpathToBeVisibleWithTimeout(String[] inputArgs)

 for (int i = 0; i < Int32.Parse(inputArgs[1]); i++)
            {
                try
                {
                    element = driver.FindElement(By.XPath(inputArgs[0]));
                    break;
                }
                catch
                {
                    Thread.Sleep(1000);
                    continue;
                }
            }
            element = driver.FindElement(By.XPath(inputArgs[0]));

  }

And it works nice !


问:
How do I make a Firefox 57 addon that opens a link when left-clicked?
This may sound dumb, but I want to make a link open in a new tab whenever the icon in the toolbar is left-clicked. I've never made a Firefox addon before, and I'm pretty clueless on how you'd go about doing that.</p>

答:
You need browserAction in manifest.json, tabs.create and browserAction.onClicked.

Inside manifest.json:

```<code>"browser_action": {
  "browser_style": true,
  "default_icon": {
    "32": "icons/icon-32.png"
  }
}
</code>```

Inside background.js:

```<code>browser.browserAction.onClicked.addListener((tab) => {
    browser.tabs.create({url: "https://google.com"}); //
    // or
    browser.tabs.duplicate({tabId: tab.id}); // duplicate current tab, same as doing browser.tabs.create({url: tab.url}); but better (navigation history is kept)
});
</code>```

Don't forget to ask for the "tabs" or "activeTab" permission in manifest.json.

```<code>"permissions": ["tabs", "activeTab"]
</code>```

And don't forget to register background.js

```<code>"background": {
    "scripts": ["background.js"]
}
</code>```

Body:
You need browserAction in manifest.json, tabs.create and browserAction.onClicked.

Inside manifest.json:

"browser_action": {
  "browser_style": true,
  "default_icon": {
    "32": "icons/icon-32.png"
  }
}

Inside background.js:

browser.browserAction.onClicked.addListener((tab) => {
    browser.tabs.create({url: "https://google.com"}); //
    // or
    browser.tabs.duplicate({tabId: tab.id}); // duplicate current tab, same as doing browser.tabs.create({url: tab.url}); but better (navigation history is kept)
});

Don't forget to ask for the "tabs" or "activeTab" permission in manifest.json.

"permissions": ["tabs", "activeTab"]

And don't forget to register background.js

"background": {
    "scripts": ["background.js"]
}