问:
C# RestSharp POST Body using models
I'm just starting out with RestSharp using C#.

I encountered an error while doing the following scenario.

I have a class that I want to post to my WCF service via RestSharp. However, I found out that the date time property is causing the request fail to post.

This is the error message return from Rest Sharp.

The server encountered an error processing the request. See server logs for more details.

```<code>/*Model to POST to WCF*/
public class Ticket {
  public string Name {get;set;}
  public DateTime Time {get;set;}
}

/*WCF Api Endpoint*/
[OperationContract, WebInvoke(UriTemplate = "/placeTicket", Method
= "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
NewTicket MakeNewTicket(Ticket requestParams);

/*Rest Sharp Operation*/
Ticket model = new Ticket();
model.Name = "Danial";
model.Time = new DateTime();

var client = new RestClient(url);
var request = new RestRequest("/MakeNewTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(model);
</code>```

If i change the Time property to string, it works perfectly.

I've been stretching my head trying to solve this problem. Anyone able to guide me on this will be appreciated.

答:
I found a solution.
I need to serialize the model object sent to WCF service using microsoft date format handling. </p>

```<code>var client = new RestClient(url);
var request = new RestRequest("/placeTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
var requestModel = JsonConvert.SerializeObject(model, new
JsonSerializerSettings { DateFormatHandling =
DateFormatHandling.MicrosoftDateFormat } )
request.AddBody(model);
var responseData = client.Execute(request).Content;
</code>```

<p>I'm not sure why when passing pure model using the date format standard of  ISO 8601 not able to fire to my WCF service. However if I'm using Microsoft JSON date format setting. It works fine. </p>

Title: C# RestSharp POST Body using models

Body:
I'm just starting out with RestSharp using C#.

I encountered an error while doing the following scenario.

I have a class that I want to post to my WCF service via RestSharp. However, I found out that the date time property is causing the request fail to post.

This is the error message return from Rest Sharp.

The server encountered an error processing the request. See server logs for more details.

/*Model to POST to WCF*/
public class Ticket {
  public string Name {get;set;}
  public DateTime Time {get;set;}
}

/*WCF Api Endpoint*/
[OperationContract, WebInvoke(UriTemplate = "/placeTicket", Method
= "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat =
WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
NewTicket MakeNewTicket(Ticket requestParams);

/*Rest Sharp Operation*/
Ticket model = new Ticket();
model.Name = "Danial";
model.Time = new DateTime();

var client = new RestClient(url);
var request = new RestRequest("/MakeNewTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(model);

If i change the Time property to string, it works perfectly.

I've been stretching my head trying to solve this problem. Anyone able to guide me on this will be appreciated.

Body:
I found a solution.
I need to serialize the model object sent to WCF service using microsoft date format handling.

var client = new RestClient(url);
var request = new RestRequest("/placeTicket", Method.POST);
request.RequestFormat = DataFormat.Json;
var requestModel = JsonConvert.SerializeObject(model, new
JsonSerializerSettings { DateFormatHandling =
DateFormatHandling.MicrosoftDateFormat } )
request.AddBody(model);
var responseData = client.Execute(request).Content;

I'm not sure why when passing pure model using the date format standard of  ISO 8601 not able to fire to my WCF service. However if I'm using Microsoft JSON date format setting. It works fine.


来源: stackexchange

问:
Woocommerce orders not being received by PayPal, but email suggests otherwise
Having a nightmare with this and cannot find a solution anywhere - the only similar issues I find are the exact opposite problem!

Placing an order using PayPal (standard) at checkout puts the order 'On hold' in wp, but completes on the front end and the user even receives the PayPal receipt so are none the wiser. In the PayPal business account there is nothing.

Interestingly, PayPal express checkout works fine! So the account is definitely setup correctly. Something I have noticed is that the receipt from the express checkout transaction and from the standard have different Merchant names - the standard one (the one not working)has the name@emailaddress.com rather than the merchant name. This would suggest that this is the issue, but I've been into the business settings and checked this as well as the Woocommerce settings and everything is in order.

Any ideas? Thanks in advance!

答: I would recommend you just stick with Express Checkout.  It has many more features and options than PayPal Standard.  I would recommend the PayPal for WooCommerce, though, which is the one PayPal reps would recommend as well if you talk to them.</p>

ContentLicense: CC BY-SA 3.0


问:
What does "@Override" and "<? extends Page>" mean?
```<code>@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}
</code>```

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.

答:
And to the second question: a wildcard.

Both methods will return the same object (the Class instance representing HomePage), but they are declared in different ways, allowing the wild-carded version to be used by methods that don't care what kind of Page you have, as long as it's a subclass of Page.

ContentLicense: CC BY-SA 2.5

Body:
@Override
public Class< ? extends Page> getHomePage() {
            return HomePage.class;
}

public Class<HomePage> getHomePage(){
        return HomePage.class;
}

The first one has an annotation
    Override. What does that mean or
    what does it send to the framework.

Will both the methods return the same class. I mean what does this mean  ? extends Page. I mean the ? Mark.


问:
Finding max and count in one join
This problem might have an easy solution, but unfortunately, I can't figure it out.

I have two tables: Table A and Table B

```<code>Table A                         Table B
-------------------             ------------------------------
Id      NoOfItems               Id     itemNo         deliveredDate
X1          3                   X1       1              2017-07-01
                                X1       2              2017-07-02
                                X1       3              2017-07-03
</code>```

So what I need is to add the maximum deliveredDate of each Id to table A, but only if the number of delivered items in Table B equals NoOfItems in Table A.

So far I have written this query:

```<code>SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems= (select count(1) from B )
</code>```

)

答:
You almost had it:</p>

```<code>;with A as
(select 1 ID, 3 NoOfItems
union all select 2 ID, 2 NoOfItems
union all select 3 ID, 1 NoOfItems
)
, B as
(select 1 id, 1 itemno, '2017-07-01' deliveredDate
union all select 1, 2, '2017-07-02'
union all select 1, 3, '2017-07-03'
union all select 2, 1, '2017-08-02'
union all select 2, 2, '2017-08-03'
)
SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems = (select count(1) from B WHERE B.id = A.ID)
</code>```

Title: Finding max and count in one join

Body:
This problem might have an easy solution, but unfortunately, I can't figure it out.

I have two tables: Table A and Table B

Table A                         Table B
-------------------             ------------------------------
Id      NoOfItems               Id     itemNo         deliveredDate
X1          3                   X1       1              2017-07-01
                                X1       2              2017-07-02
                                X1       3              2017-07-03

So what I need is to add the maximum deliveredDate of each Id to table A, but only if the number of delivered items in Table B equals NoOfItems in Table A.

So far I have written this query:

SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems= (select count(1) from B )

)

Body:
You almost had it:

;with A as
(select 1 ID, 3 NoOfItems
union all select 2 ID, 2 NoOfItems
union all select 3 ID, 1 NoOfItems
)
, B as
(select 1 id, 1 itemno, '2017-07-01' deliveredDate
union all select 1, 2, '2017-07-02'
union all select 1, 3, '2017-07-03'
union all select 2, 1, '2017-08-02'
union all select 2, 2, '2017-08-03'
)
SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems = (select count(1) from B WHERE B.id = A.ID)


问:
Unable to publish Smart Tv app on Samsung Store
I am trying to publish 'Smart TV' app on 'Samsung Store (Saller Account)', but Its telling that we can not publish Smart Tv app, we can just publish 'Tizen TV' app.

I want to upload 'Smart tv' app. We are developing app in SDK link below.

'http://www.samsungdforum.com/Devtools/SdkDownload'.

Could anybody please help me to get rid this problem.

I am also attaching the message screen sort that Samsung Store (Saller account) showing.

答: Samsung now supporting only tizen sdk based development. </p>


问:
Sum in rows some other column rows values grouped by other column ID
Is it possible to do a query like this? I have the ID, some IN value, Out value and the last column TOTAL is the sum of the difference between IN and OUT. I just really need the complete sum.
The ID2 rows that are equals must be summed in the SUM column. There is no ID2 quantity fixed, some times it would be just one row to sum, other cases there will be more. I could also add a difference column, to just sum the value in that row for the same ID2.

My doubt here is, is it possible to sum in a row, the accumulated in some rows at other columns?

```<code>ID  ID2 IN  OUT TOTAL (IN-OUT)
1   2   200 150 blank-null-space-or whatever but a character
2   2   350 250 doesn't matter, also it can have the same SUM result as below
3   2   600 400 350 ( = 200 - 150 + 350 - 250 + 600 - 400)
4   3   100  80  20
</code>```

Or I have to do it at the client side in JavaScript? Which is better or you do suggest? Maybe it is easier in JavaScript but I wanted to do it all in one step to reduce the pool connections.

A simple verifiable example would be

```<code>CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "`EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);
</code>```

EDIT: Added an foreign ID column "EXT_ID" that have a condition show only one row and the one that has MAX value from the same "ID2".

Corrected SQL syntax.

答:
Edited

Yes, it is posible. You can use group by (if you only want the total)

```<code>CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL,
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);

select "ID2", sum("IN" - "OUT")
  from "table1"
  group by "ID2";
</code>```

Old answer:

Yes, it is posible. You can use window functions

```<code>CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "IN" int DEFAULT NULL,
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "IN", "OUT") VALUES
(1, 2, 200, 150),
(2, 2, 350, 250),
(3, 2, 600, 400),
(4, 3, 100,  80);

select * , sum("IN" - "OUT") over (partition by "ID2" order by "ID")
  from "table1"
  order by "ID2", "ID";
</code>```

As you see in https://www.postgresql.org/docs/current/static/functions-window.html

A functional example: http://rextester.com/OVCTC74070

Body:
Is it possible to do a query like this? I have the ID, some IN value, Out value and the last column TOTAL is the sum of the difference between IN and OUT. I just really need the complete sum.
The ID2 rows that are equals must be summed in the SUM column. There is no ID2 quantity fixed, some times it would be just one row to sum, other cases there will be more. I could also add a difference column, to just sum the value in that row for the same ID2.

My doubt here is, is it possible to sum in a row, the accumulated in some rows at other columns?

ID  ID2 IN  OUT TOTAL (IN-OUT)
1   2   200 150 blank-null-space-or whatever but a character
2   2   350 250 doesn't matter, also it can have the same SUM result as below
3   2   600 400 350 ( = 200 - 150 + 350 - 250 + 600 - 400)
4   3   100  80  20

Or I have to do it at the client side in JavaScript? Which is better or you do suggest? Maybe it is easier in JavaScript but I wanted to do it all in one step to reduce the pool connections.

A simple verifiable example would be

CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "`EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);

EDIT: Added an foreign ID column "EXT_ID" that have a condition show only one row and the one that has MAX value from the same "ID2".

Corrected SQL syntax.

Body:
Edited

Yes, it is posible. You can use group by (if you only want the total)

CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "EXT_ID" int DEFAULT NULL,
  "IN" int DEFAULT NULL,
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "EXT_ID", "IN", "OUT") VALUES
(1, 2, 1, 200, 150),
(2, 2, 2, 350, 250),
(3, 2, 2, 600, 400),
(4, 3, 4, 100,  80),
(5, 3, 5, 130, 100),
(6, 4, 6, 100,  80),
(7, 4, 7, 120,  70),
(8, 4, 7, 150,  90);

select "ID2", sum("IN" - "OUT")
  from "table1"
  group by "ID2";

Old answer:

Yes, it is posible. You can use window functions

CREATE TABLE "table1" (
  "ID" int NOT NULL,
  "ID2" int DEFAULT NULL,
  "IN" int DEFAULT NULL,
  "OUT" int DEFAULT NULL
);

INSERT INTO "table1" ("ID", "ID2", "IN", "OUT") VALUES
(1, 2, 200, 150),
(2, 2, 350, 250),
(3, 2, 600, 400),
(4, 3, 100,  80);

select * , sum("IN" - "OUT") over (partition by "ID2" order by "ID")
  from "table1"
  order by "ID2", "ID";

As you see in https://www.postgresql.org/docs/current/static/functions-window.html

A functional example: http://rextester.com/OVCTC74070


问:
Rails 3: Social Stream Gem. Where is the code?
I've installed social_stream according to the README ( https://github.com/ging/social_stream ) and it works fine, however, I'd like to have the code in my app/ directory and the code isn't there.

The same question arises for Devise and other gems. When I install it, I'd like to have access to the controllers, models, views, etc but it seems nothing is in the app/.

What do I have to do in order to put the code there and being able to change it as I'd like? Or, access it in other folder.

Thank you

答:
With Bundler you can freeze all your gems in your directory. You can try that.

Having the file in your app directory is not really a good advice.


问:
When should we use redeploy button in Azure Resource groups
Azure resource groups give a redeploy button not sure how and when to use that. Would appreciate best practices.

答:
In general, when we facing difficulties troubleshooting, redeploying the deployment may help.

For example, when we can't connect to Azure VM or application access to windows-based Azure VM, we can try to redeploy it. When you redeploy a VM, it moves the VM to a new node within the Azure infrastructure and then powers it back on, retaining all your configuration options and associated resources.

More information about redeploy Azure VM, please refer to this link.

By default, when we select redeploy in Azure resource group deployments, Azure will use this template to deploy this resource.


问:
CakePHP 3 autocomplete AJAX responses
I have been trying to get cakephp to suggest input from data that is from my tables like autocomplete. I've done some reading about how some other people have done this but still can't figure it out. Currently it seems that every time my controller is waiting for an ajax request and it is always false. No errors come up from the console some i'm not sure what i'm doing wrong. I tried removing the if ($this->request->is('ajax')) statement but then I get a error about it cannot emit headers.
Here is my search function in InvoicesController which I have taken code from someone else example but failed to implement it.

```<code>     public function search()
{
    if ($this->request->is('ajax')) {
        $this->autoRender = false;
        pr('b');
        $name = $this->request->query['term'];
        $results = $this->Invoices->find('all', [
            'conditions' => [ 'OR' => [
                'id LIKE' => $id . '%',
            ]]
        ]);
        $resultsArr = [];
        foreach ($results as $result) {
             $resultsArr[] =['label' => $result['full_name'], 'value' => $result['id']];
        }
        echo json_encode($resultsArr);
    }
}
</code>```

And here is my search.ctp

```<code>    <?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']);?>
<script>
    jQuery('#id').autocomplete({
        source:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>',
        minLength: 1
    });
</script>
</code>```

This is my invoice table and the ids are what I want to be suggested from what users type in.

答:
I may not be seeing your exact problem but let me point out a few things I see that might help this issue.

Remove this line. It is not necessary

```<code>$this->autoRender = false;
</code>```

Instead you should be doing this at the end. See using the RequestHandler

```<code>$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', 'resultsArr');
</code>```

This will return the data without a root key

```<code> [
   {"label":"Label Value"},
   {"label":"Another Label Value"}
 ]
</code>```

Or you can do it like this

```<code>$this->set('_serialize', ['resultsArr']);
</code>```

This will return data like

```<code>{"resultArr":[
   {"label":"Label Value"},
   {"label":"Another Value"}
]}
</code>```

Replace your finder query with this.

```<code>$resultArr = $this->Invoices->find('all')
    ->where(['id LIKE' => $id . '%'])
    // If you want to remap your data use map
    // All queries are collections
    ->map(function ($invoice) {
        return ['label' => $invoice->full_name, 'id' => $invoice->id];
    });
</code>```

It seems to me you might want to review the new cakephp 3 orm. A lot of hard work went into writing these docs so that they could be easily read and relevant. I'm not one to push docs on people but it will save you hours of frustration.

Cakephp 3 ORM documentation

A few minor things I noticed that are also problems.

You never define $id.

You define $name but never use it.

pr is a debug statement and I am not sure why you have it.

Based on your comment, here is an update on ajax detection.

```<code>// By default the ajax detection is limited to the x-request-with header
// I didn't want to have to set that for every ajax request
// So I overrode that with the accepts header.
// Any request where Accept is application/json the system will assume it is an ajax request
$this->request->addDetector('ajax', function ($request) {
    $acceptHeaders = explode(',', $request->env('HTTP_ACCEPT'));

    return in_array('application/json', $acceptHeaders);
});
</code>```

Title: CakePHP 3 autocomplete AJAX responses

Body:
I have been trying to get cakephp to suggest input from data that is from my tables like autocomplete. I've done some reading about how some other people have done this but still can't figure it out. Currently it seems that every time my controller is waiting for an ajax request and it is always false. No errors come up from the console some i'm not sure what i'm doing wrong. I tried removing the if ($this->request->is('ajax')) statement but then I get a error about it cannot emit headers.
Here is my search function in InvoicesController which I have taken code from someone else example but failed to implement it.

     public function search()
{
    if ($this->request->is('ajax')) {
        $this->autoRender = false;
        pr('b');
        $name = $this->request->query['term'];
        $results = $this->Invoices->find('all', [
            'conditions' => [ 'OR' => [
                'id LIKE' => $id . '%',
            ]]
        ]);
        $resultsArr = [];
        foreach ($results as $result) {
             $resultsArr[] =['label' => $result['full_name'], 'value' => $result['id']];
        }
        echo json_encode($resultsArr);
    }
}

And here is my search.ctp

    <?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']);?>

This is my invoice table and the ids are what I want to be suggested from what users type in.

Body:
I may not be seeing your exact problem but let me point out a few things I see that might help this issue.

Remove this line. It is not necessary

$this->autoRender = false;

Instead you should be doing this at the end. See using the RequestHandler

$this->set('resultsArr', $resultsArr);
// This line is what handles converting your array into json
// To get this to work you must load the request handler
$this->set('_serialize', 'resultsArr');

This will return the data without a root key

 [
   {"label":"Label Value"},
   {"label":"Another Label Value"}
 ]

Or you can do it like this

$this->set('_serialize', ['resultsArr']);

This will return data like

{"resultArr":[
   {"label":"Label Value"},
   {"label":"Another Value"}
]}

Replace your finder query with this.

$resultArr = $this->Invoices->find('all')
    ->where(['id LIKE' => $id . '%'])
    // If you want to remap your data use map
    // All queries are collections
    ->map(function ($invoice) {
        return ['label' => $invoice->full_name, 'id' => $invoice->id];
    });

It seems to me you might want to review the new cakephp 3 orm. A lot of hard work went into writing these docs so that they could be easily read and relevant. I'm not one to push docs on people but it will save you hours of frustration.

Cakephp 3 ORM documentation

A few minor things I noticed that are also problems.

You never define $id.

You define $name but never use it.

pr is a debug statement and I am not sure why you have it.

Based on your comment, here is an update on ajax detection.

// By default the ajax detection is limited to the x-request-with header
// I didn't want to have to set that for every ajax request
// So I overrode that with the accepts header.
// Any request where Accept is application/json the system will assume it is an ajax request
$this->request->addDetector('ajax', function ($request) {
    $acceptHeaders = explode(',', $request->env('HTTP_ACCEPT'));

    return in_array('application/json', $acceptHeaders);
});


问:
Opencv installed however python does not find the package
I have recently installed opencv on my raspberry pi 3 module B to do some vision processing and whilst I was developing this code for said processing I ran my code which is

```<code> import cv2
 import numpy as np
 vid = cv2.VideoCapture(0)
 vid.set(10,.05)

def onmouse(k,x,y,s,p):
   global hsv
   if k==1:   # left mouse, print pixel at x,y
      print hsv[y,x]

while(True):
cv2.namedWindow("hsv")
cv2.setMouseCallback("hsv",onmouse);
cv2.imshow('hsv',hsv)
ret, frame = vid.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_green = np.array([75,200,200])
upper_green = np.array([85,255,255])
mask = cv2.inRange(hsv, lower_green, upper_green)
res = cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow('orig',frame)
cv2.imshow('fff',res)

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

vid.release()
cv2.destroyAllWindows()
</code>```

after finishing this I ran my code to see if no errors occurred however I was presented by this

I was wondering if either I did something wrong with my code or I screwed up in installing opencv. Either way I would be grateful if anyone either had experiences with this same problem or someone has already resolved this issue.

FYI:
I got the instructions to install opencv from this site

As well as sorry for my messy code never really got the the hang of having everything neat as well as my potentially dumb question either way; Thank you for your attention

答: It appears the name of your script is cv2.py. So when you import cv2, it imports this script instead of the cv2 library. Use a different script name.

Body:
I have recently installed opencv on my raspberry pi 3 module B to do some vision processing and whilst I was developing this code for said processing I ran my code which is

 import cv2
 import numpy as np
 vid = cv2.VideoCapture(0)
 vid.set(10,.05)

def onmouse(k,x,y,s,p):
   global hsv
   if k==1:   # left mouse, print pixel at x,y
      print hsv[y,x]

while(True):
cv2.namedWindow("hsv")
cv2.setMouseCallback("hsv",onmouse);
cv2.imshow('hsv',hsv)
ret, frame = vid.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_green = np.array([75,200,200])
upper_green = np.array([85,255,255])
mask = cv2.inRange(hsv, lower_green, upper_green)
res = cv2.bitwise_and(frame,frame,mask=mask)
cv2.imshow('orig',frame)
cv2.imshow('fff',res)

if cv2.waitKey(1) & 0xFF == ord('q'):
    break

vid.release()
cv2.destroyAllWindows()

after finishing this I ran my code to see if no errors occurred however I was presented by this

I was wondering if either I did something wrong with my code or I screwed up in installing opencv. Either way I would be grateful if anyone either had experiences with this same problem or someone has already resolved this issue.

FYI:
I got the instructions to install opencv from this site

As well as sorry for my messy code never really got the the hang of having everything neat as well as my potentially dumb question either way; Thank you for your attention


问:
Express loading images relative to url
I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.

This code works fine.

```<code>app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
    res.render('some-file');
});
</code>```

Inside of some-file.ejs I have...

```<code><img src="assets/images/picture.jpg">
</code>```

But what doesnt work is when I have a second url pathway.

```<code>app.get("/overview/specific", function(req, res) {
    res.render('another-file');
});

<img src="assets/images/picture.jpg">
</code>```

In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?

Thanks in advance

答:
We serve favicons dynamically using an ExpressJS redirect, it works very well.

First, we retrieve the site object from memory with a quick lookup based on req.hostname, then send this response:

```<code>res.redirect(site.favicon);
</code>```

The favicon variable could be a static asset on our server, or an asset on another server too.  Our front-end code just calls /api/resources/favicon and it will receive the correct link in return.

Title: Express loading images relative to url

Body:
I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.

This code works fine.

app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
    res.render('some-file');
});

Inside of some-file.ejs I have...

But what doesnt work is when I have a second url pathway.

app.get("/overview/specific", function(req, res) {
    res.render('another-file');
});

In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?

Thanks in advance

Body:
We serve favicons dynamically using an ExpressJS redirect, it works very well.

First, we retrieve the site object from memory with a quick lookup based on req.hostname, then send this response:

res.redirect(site.favicon);

The favicon variable could be a static asset on our server, or an asset on another server too.  Our front-end code just calls /api/resources/favicon and it will receive the correct link in return.


问:
Go back to 2nd Previous Activity
The question might be dumb but I'll ask it, for example I have 3 Activities, Activity 1,2,3.

Activity 1, I click a button, goes to Activity 2
Activity 2, I click a button, goes to Activity 3.
Activity 3, I click the back button, I want it to go back to Activity 1. Any idea how to do it? Sorry Android Newbie. Thanks!

答:
Since Activity2 is pushed in the stack the back button of Activity3 will get you to Activity2. Hence the best you can do is not to push Activity2 in the stack.
In your manifest.xml, where you define your activity do the following:

```<code><activity android:name=".Activity2" android:noHistory="true" ... />
</code>```

developer.android.com says:

A value of "true" means that the activity will not leave a historical trace.
  It will not remain in the activity stack for the task,
  so the user will not be able to return to it.

For more details:
https://developer.android.com/guide/topics/manifest/activity-element.html

Hope this solves the issue :-) I know this question has been asked long time back, but it might help some...

Title: Go back to 2nd Previous Activity

Body:
Since Activity2 is pushed in the stack the back button of Activity3 will get you to Activity2. Hence the best you can do is not to push Activity2 in the stack.
In your manifest.xml, where you define your activity do the following:

<activity android:name=".Activity2" android:noHistory="true" ... />

developer.android.com says:

A value of "true" means that the activity will not leave a historical trace.
  It will not remain in the activity stack for the task,
  so the user will not be able to return to it.

For more details:
https://developer.android.com/guide/topics/manifest/activity-element.html

Hope this solves the issue :-) I know this question has been asked long time back, but it might help some...


问:
How to exchange data between classes?
I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.

So, let's assume we have 4 classes:

```<code>class Main_Window
{
    //...
    void load_data_menu_selected();
}

class Data
{
    //...
    double *data;
}

class Load_Data
{
    //...
    double *get_filename_and_load();
}

class Calculate
{
    //...
    int do_calculation()
}
</code>```

So, Main_Window is class for application's main window where it interacts with user input etc.

I want to do:

create an instance of class Data in the Main_Window

use Load_Data for loading data from file and store it in the Data

use Calculation class for doing something with read data in Data class

The question is: where I should create classes, to make Data class members available from other classes.  Should I use Inheritance?

答:
You need to know how to design in OO. Thinking in C is different from thinking in c++. You can that your classes have many methods. Well, that sound like a bad design.

I can recommend you to start with the SOLID principle.
Then start writing unit tests for your classes. TDD could help you improve your design even further.

Title: How to exchange data between classes?

Body:
I'm learning C++ and moving my project from C to C++. In the process, I stumbled on this problem: how to save/update variables that are in use in several classes? In C I used global variables, but it is not good for C++.

So, let's assume we have 4 classes:

class Main_Window
{
    //...
    void load_data_menu_selected();
}

class Data
{
    //...
    double *data;
}

class Load_Data
{
    //...
    double *get_filename_and_load();
}

class Calculate
{
    //...
    int do_calculation()
}

So, Main_Window is class for application's main window where it interacts with user input etc.

I want to do:

create an instance of class Data in the Main_Window

use Load_Data for loading data from file and store it in the Data

use Calculation class for doing something with read data in Data class

The question is: where I should create classes, to make Data class members available from other classes.  Should I use Inheritance?


问:
When should we use a parameter when to use variable in ARM templates
I am confused about where to use a variable and where to use a parameter in ARM templates. How do we make this call ?

The referenced script uses both. I am more curious of the justification of using variables.

Reference

Sample Service Fabric Azure Deploy Script

https://raw.githubusercontent.com/azure/azure-quickstart-templates/master/service-fabric-oms/azuredeploy.json

答:
In the Azure template json file:

parameters:Values that are provided when deployment is executed to customize resource deployment.

variables:Values that are used as JSON fragments in the template to simplify template language expressions.

More information please refer to this official document:Understand the structure and syntax of Azure Resource Manager templates.

I am more curious of the justification of using variables.

Based on my experience, if you only use the variable once, you don't need use variables. But if you want to use the variable multiple times, you had better use variables. Using variable can simplify your template to avoid duplication of content.

For example, if you don't use supportLogStorageAccountName more than once, you can just do:

```<code>"name": "[toLower(concat('sf', uniqueString(resourceGroup().id),'2'))]"
</code>```

However if you use provide variable supportLogStorageAccountName several\many times, you can use variable to avoid duplication.

Body:
In the Azure template json file:

parameters:Values that are provided when deployment is executed to customize resource deployment.

variables:Values that are used as JSON fragments in the template to simplify template language expressions.

More information please refer to this official document:Understand the structure and syntax of Azure Resource Manager templates.

I am more curious of the justification of using variables.

Based on my experience, if you only use the variable once, you don't need use variables. But if you want to use the variable multiple times, you had better use variables. Using variable can simplify your template to avoid duplication of content.

For example, if you don't use supportLogStorageAccountName more than once, you can just do:

"name": "[toLower(concat('sf', uniqueString(resourceGroup().id),'2'))]"

However if you use provide variable supportLogStorageAccountName several\many times, you can use variable to avoid duplication.

ContentLicense: CC BY-SA 4.0


问:
Javascript binding function to an object
```<code>const person = {
    name: "Mike",
    country: "New Zealand"
}

function personUpdate(name, country) {
    this.name = name
    this.country = country
}

personUpdate.bind(person)

personUpdate('Tony', 'Chile')
</code>```

Why doesn't this work? person still has original properties 'Mike' and 'New Zealand'. Why doesn't personUpdate.bind(person) I want to make it so that every call to personUpdate the this refers to the person object (and without using new).

答:
Calling .bind doesn't modify the function you pass in; it returns a new bound function.

So you want either:

```<code>var boundPersonUpdate = personUpdate.bind(person);
boundPersonUpdate(...); // call the bound version
</code>```

or:

```<code>personUpdate = personUpdate.bind(person); // overwrite the original function
</code>```

Body:
const person = {
    name: "Mike",
    country: "New Zealand"
}

function personUpdate(name, country) {
    this.name = name
    this.country = country
}

personUpdate.bind(person)

personUpdate('Tony', 'Chile')

Why doesn't this work? person still has original properties 'Mike' and 'New Zealand'. Why doesn't personUpdate.bind(person) I want to make it so that every call to personUpdate the this refers to the person object (and without using new).

Body:
Calling .bind doesn't modify the function you pass in; it returns a new bound function.

So you want either:

var boundPersonUpdate = personUpdate.bind(person);
boundPersonUpdate(...); // call the bound version

or:

personUpdate = personUpdate.bind(person); // overwrite the original function


问:
MapDB is thread-safe?
Is it true that the latest version of MapDB is thread-safe? I couldn't find anything concrete at Google and their website doesn't say anything about locking. </p>

答: You can see the code comments of the data structure you need, like  HTreeMap, or BtreeMap, they are both claimed as concurrent.</p>

Title: MapDB is thread-safe?


问:
How to use links in php mvc?
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

```<code>static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }
</code>```

My controller:

```<code>class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}
</code>```

Thx for any help, coz im rly confused.

答:
What framework are you using?
Based on what I see you are not using one, it's better and recommended to use a framework, especially if you are using MVC design</p>

Title: How to use links in php mvc?

Body:
First problem:

Main url: site-test

1. I clicked on the link tasks -> url: site-test/tasks

2. i click next link next page (Where "tasks" - contoller, "page" - action, "2" - action value) -> url: site-test/tasks/page/2

3. i pressed again tasks and url -> site-test/tasks/page/tasks instead site-test/tasks/ what i need.

tasks is located in template view.

Second problem:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

My route:

static function start()
    {
        $controller_name = 'add_task';
        $action_name = 'index';

        $routes = explode('/', $_SERVER['REQUEST_URI']);

        if ( !empty($routes[1]) )
        {
            $controller_name = $routes[1];
        }

        if ( !empty($routes[2]) )
        {
            $action_name = $routes[2];
        }

        $model_name = 'Model_'.$controller_name;
        $controller_name = 'Controller_'.$controller_name;
        $action_name = 'action_'.$action_name;

        $model_file = strtolower($model_name).'.php';
        $model_path = "application/models/".$model_file;
        if(file_exists($model_path))
        {
            include "application/models/".$model_file;
        }

        $controller_file = strtolower($controller_name).'.php';
        $controller_path = "application/controllers/".$controller_file;
        if(file_exists($controller_path))
        {
            include "application/controllers/".$controller_file;
        }

        $controller = new $controller_name;
        $action = $action_name;

        if(method_exists($controller, $action))
        {
            if ( !empty($routes[3]) )
            {
                $controller->$action($routes[3]);
            }
            else{
                $controller->$action();
            }
        }

    }

My controller:

class Controller_tasks extends Controller
{
    function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

    function action_index()
    {
        $data = $this->model->get_data_from_server();
        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }

    function action_page($page = 1)
    {
        var_dump($page);
        $data = $this->model->get_data_from_server($page);

        $this->view->generate('tasks_view.php', 'template_view.php', $data);
    }
}

Thx for any help, coz im rly confused.


问:
Can I retrieve current URI from Prism Xamarin Forms NavigationService?
I am creating iOS and Android apps using Xamarin.Forms. The app is used to complete a specific workflow. As the user completes entries on each page, I persist the entered data to local storage.

I want to also save a URI to restore the Prism navigation service to the current screen. Doing so will allow the user to resume the workflow where they left off even if the phone is reset, the app is closed by the OS, etc.

I haven't found a way to retrieve the current URI. Is this possible? I can create a dictionary to map screen keywords to URIs manually if necessary, but I'm hoping to avoid such a brittle solution. Thanks!

答:
There is currently no way to access the current Navigation Stack with Prism's Navigation Service. If this is something you need I would encourage you to open an issue on GitHub. </p>

<p>Note due to the way Navigation works with Xamarin Forms, you must navigate from a specific page. This requirement means that each ViewModel has to have its own instance of the Navigation Service in order to properly Navigate. </p>

Body:
There is currently no way to access the current Navigation Stack with Prism's Navigation Service. If this is something you need I would encourage you to open an issue on GitHub.

Note due to the way Navigation works with Xamarin Forms, you must navigate from a specific page. This requirement means that each ViewModel has to have its own instance of the Navigation Service in order to properly Navigate.


问:
How to clear pending VCS changes in TeamCity 7+?
We have a project configured in TeamCity 7.+ to watch a project in Subversion.  Each check-in will trigger a build.  However, in this case, we want to skip/clear the backlog.

To be very clear: I do not wish to "undo" these Subversion commits.  I want to keep the svn commits, but skip the TeamCity builds.

I tried disconnecting the Build Trigger (disable, then delete), but no luck.  The TeamCity queue remains.

How to do it?  My googling skills are failing me.  =(

答: According to this jetbrains support post, you can just detach the VCS Root and re-attach it.</p>


问:
Scale div to browser height vh troubles
I want the content inside of my div to scale with the browser vertically to prevent the need for scrolling The images will be different orientations so the width will be different. I know this can be achieved horizontally with width:100%; but max-height:100%; or height:auto; both still extend past the browser window for me and I'm not sure why.

EDIT: Had a lot of additional modal code in here, and simplified it down to the html/css and switched from simple width:100% height: 100% to vh and vw.

Fiddle :https://jsfiddle.net/duckyduck/6soe8zs0/

What's happening:

How I want it to look:

```<code><body>
<style>

.modal {
  display: block;
  position: fixed;
  z-index: 1;
  box-sizing:border-box;

  left: 0;
  top: 0;
height: 100%;
width:100%;

  overflow:auto;
  background-color:#D81E21;
}

.modal-content {
  position: relative;/*modal x button */
  width: auto;
  height: auto;
  background-color: #7E7DE1;
  max-height: 50vh;
  max-width:70vw;
  margin: auto;
  }

.mySlides{
    max-height:100%;
    max-width: 100%;
    height:auto;
    width:auto;
}

.roll-img {
display:flex;
flex-wrap:wrap;
}

.column {
flex:1;
}

.caption-container {
  text-align: center;
  background-color: black;
  padding: 2px 16px;
  color: white;
}

</style>

<div id="myModal" class="modal">

    <div class="modal-content">

        <div class="mySlides">
          <img src="images/5_2.jpg">
        </div>

        <div class="caption-container">
          <p id="caption"></p>
        </div>

      <div class="roll-img">
        <div class="column">
            <img class="demo cursor" src="images/5_2.jpg">
        </div>
      </div> <!--roll-img-->

  </div> <!--modal-content-->
</div> <!--myModal-->

</body>
</code>```

答:
Try using

min-height: 100vh;

vh refers to the viewport height.

Title: Scale div to browser height vh troubles


问:
Assignment in controller is not passing through to service
My assignment $scope.getForecastByLocationin the controller is not being passed through to the controller. Currently cityis specified to random city like "Berkeley", and this city is passed to the factory Data. But the idea is that when the user types a new city in the input, it takes the input and sends a new city parameter to the Data factory.

I've been doing console.logs and I can see that the button is working but calling Data.getApps($scope.inputcity); is not working and thus the city is always in "Berkeley".

Can anyone figure out why I can't send a new city to the Data factory? Thank you!

index.html

```<code> <input ng-model="city">
  </md-input-container>
  <md-button class="md-raised" ng-click="getForecastByLocation(city)">SUBMIT</md-button>
</code>```

controller.js

```<code>var app = angular.module('weatherApp.controllers', [])

    var city = 'Berkeley';

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function(city) {
                $scope.inputcity = city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else {
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }])//end of controller
</code>```

service.js

```<code>app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});
</code>```

EDIT:

I modified my controller code a bit from other people's suggestion and it currently looks like this. The factory is the same and I have deleted the parameter in the HTML.

```<code>app.controller('weatherCtrl', ['$scope','Data',

    function($scope, Data) {
$scope.city = 'Berkeley';

$scope.getForecastByLocation = function() {
                console.log($scope.city); //making sure I can read the input
                console.log('this is your input ' + $scope.city);
                Data.getApps($scope.city).then(function(data){
                console.log('this is your output ' + $scope.city); //should say "This is your output "tracy", but it still reads at "Berkeley"

                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
</code>```

答:
var app = angular.module('weatherApp.controllers', [])

    var city = 'Berkeley';

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function() {
                $scope.inputcity = $scope.city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else {
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }]);
    app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                promise = false; // reset the promise value.
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="weatherApp.controllers">
    <div ng-controller="weatherCtrl">
        <input ng-model="city">
        <md-button class="md-raised" ng-click="getForecastByLocation()">SUBMIT</md-button>
    </div>
</div></code>```

Body:
My assignment $scope.getForecastByLocationin the controller is not being passed through to the controller. Currently cityis specified to random city like "Berkeley", and this city is passed to the factory Data. But the idea is that when the user types a new city in the input, it takes the input and sends a new city parameter to the Data factory.

I've been doing console.logs and I can see that the button is working but calling Data.getApps($scope.inputcity); is not working and thus the city is always in "Berkeley".

Can anyone figure out why I can't send a new city to the Data factory? Thank you!

index.html

 <input ng-model="city">
  </md-input-container>
  <md-button class="md-raised" ng-click="getForecastByLocation(city)">SUBMIT</md-button>

controller.js

var app = angular.module('weatherApp.controllers', [])

    var city = 'Berkeley';

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function(city) {
                $scope.inputcity = city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else {
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }])//end of controller

service.js

app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});

EDIT:

I modified my controller code a bit from other people's suggestion and it currently looks like this. The factory is the same and I have deleted the parameter in the HTML.

app.controller('weatherCtrl', ['$scope','Data',

    function($scope, Data) {
$scope.city = 'Berkeley';

$scope.getForecastByLocation = function() {
                console.log($scope.city); //making sure I can read the input
                console.log('this is your input ' + $scope.city);
                Data.getApps($scope.city).then(function(data){
                console.log('this is your output ' + $scope.city); //should say "This is your output "tracy", but it still reads at "Berkeley"

                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }

Body:
var app = angular.module('weatherApp.controllers', [])

    var city = 'Berkeley';

    app.controller('weatherCtrl', ['$scope','Data',

        function($scope, Data) {
        $scope.getForecastByLocation = function() {
                $scope.inputcity = $scope.city;
                console.log($scope.inputcity);
                Data.getApps($scope.inputcity).then(function(data){
                    $scope.data = data;
                    $scope.name = data.name;
                    console.log($scope.data); //object shows "Berkeley"
                    console.log($scope.name);
                 });//initiate Data.getApps by passing in a new city
         }
        Data.getApps(city).then(function(data) {
          $scope.data = data;

          var vm = $scope;

          vm.description = data.weather[0].description;
          vm.speed = (2.237 * data.wind.speed).toFixed(1) + " mph";
          vm.name = data.name;
          vm.humidity = data.main.humidity + " %";
          vm.temp = data.main.temp;
          vm.fTemp = (vm.temp * (9 / 5) - 459.67).toFixed(1) + " °F";

        },function(res) {
            if(res.status === 500) {
                // server error, alert user somehow
            } else {
                // probably deal with these errors differently
            }
        }

        ); // end of function

    }]);
    app.factory('Data', function($http, $q) {

    var data = [],
       lastRequestFailed = true,
       promise;
   return {
      getApps: function(city) {
         if(!promise || lastRequestFailed) {
            // $http returns a promise, so we don't need to create one with $q

            promise = $http.get('http://api.openweathermap.org/data/2.5/weather?',{
              params: {
                q: city,
              }
            })
            .then(function(res) {
                lastRequestFailed = false;
                data = res.data;
                promise = false; // reset the promise value.
                return data;
            }, function(res) {
                return $q.reject(res);
            });
         }
         return promise;
      }
   }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="weatherApp.controllers">
    <div ng-controller="weatherCtrl">
        <input ng-model="city">
        <md-button class="md-raised" ng-click="getForecastByLocation()">SUBMIT</md-button>
    </div>
</div>


问:
rails 5.0.0 when installing "nio4r" : Failed to build gem native extension
Here is the logs: http://pastebin.com/CAgur9xd

```<code>Installing nio4r 1.2.1 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    C:/RailsInstaller/Ruby2.2.0/bin/ruby.exe -r ./siteconf20160720-8272-c88sgk.rb extconf.rb --with-cflags=-std=c99
checking for unistd.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/RailsInstaller/Ruby2.2.0/bin/$(RUBY_BASE_NAME)
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:587:in `try_cpp'
         from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:1060:in `block in have_header'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:911:in `block in checking_for'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:351:in `block (2 levels) in postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:321:in `open'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:351:in `block in postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:321:in `open'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:347:in `postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:910:in `checking_for'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:1059:in `have_header'
        from extconf.rb:3:in `<main>'

extconf failed, exit code 1
</code>```

when installing bundle it returns(starts at line 117 in the logs ):

```<code>Installing nio4r 1.2.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
</code>```

So the bundle can't be installed. It returns at the end :

```<code>An error occurred while installing nio4r (1.2.1), and Bundler cannot continue.
Make sure that `gem install nio4r -v '1.2.1'` succeeds before bundling.
</code>```

Note :I have tried the solutions in other questions, but it is still the same.
If it is possible to install "nio4r" manually please tell me how .

答:
Had this same issue on Ubuntu 16.04.
What I did to fix this :

Remove Gemfile.lock : sudo rm Gemfile.lock
Installed Ruby-Dev:

sudo apt-add-repository ppa:brightbox/ruby-ng
sudo apt-get update
sudo apt-get install  ruby2.4-dev

and the important step : REBOOT!

Body:
Here is the logs: http://pastebin.com/CAgur9xd

Installing nio4r 1.2.1 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    C:/RailsInstaller/Ruby2.2.0/bin/ruby.exe -r ./siteconf20160720-8272-c88sgk.rb extconf.rb --with-cflags=-std=c99
checking for unistd.h... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/RailsInstaller/Ruby2.2.0/bin/$(RUBY_BASE_NAME)
C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:587:in `try_cpp'
         from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:1060:in `block in have_header'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:911:in `block in checking_for'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:351:in `block (2 levels) in postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:321:in `open'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:351:in `block in postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:321:in `open'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:347:in `postpone'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:910:in `checking_for'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/mkmf.rb:1059:in `have_header'
        from extconf.rb:3:in `'

extconf failed, exit code 1

when installing bundle it returns(starts at line 117 in the logs ):

Installing nio4r 1.2.1 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

So the bundle can't be installed. It returns at the end :

An error occurred while installing nio4r (1.2.1), and Bundler cannot continue.
Make sure that `gem install nio4r -v '1.2.1'` succeeds before bundling.

Note :I have tried the solutions in other questions, but it is still the same.
If it is possible to install "nio4r" manually please tell me how .


问:
<audio> tag for mp3 doesn't really work on Chrome
First of all here is the website I'm currently coding :

http://www.clairereviens.com/

On each button, there is one  tag for one mp3 sample. All the mp3 are playing perfectly with Safari, but with Chrome only a few buttons are working.

I tested with type audio/mp3 and audio/mpeg, but it doesn't change.
Thanks guys

答:
I had the same problem with Google Chrome. It's more of like a version problem of chrome. To fix that re-encode the MP3 files to a lower bitrate using Audacity or other Media Converters.

For more info: https://stackoverflow.com/a/32719143/8009667


问:
Adding custom parameters to devise registration - unpermitted parameters
I've been trying to customize the devise register method to register with more parameters and also update more(no luck so far), but I always get Unpermitted parameters: error. I tried using this Adding extra registration fields with Devise and https://github.com/plataformatec/devise#strong-parameters, but I cant get over that.

I've also thought about creating a new table to hold a foreign key the user id and put in there stuff like user_id, display_name, profile_picture, but I would have the same problem when trying to submit everything from the same page(mess with the devise controller).

Do you have any suggestions on how I can solve this? What else do I have to post?

routes.rb

```<code>devise_for :users, controllers: { registrations: 'users/registrations' }
</code>```

users/regC

```<code>def create
    build_resource(registration_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        respond_with resource, :location => after_sign_up_path_for(resource)
      end
    else
      clean_up_passwords
      respond_with resource
    end
  end

private
  def registration_paramss
    params.require(:user).permit(:email, :display_name, :terms_of_services, :profile, :password, :password_confirmation)
  end
</code>```

答:
For Devise 4.2.0 you can whitelist additional parameters for your users table by adding those values to keys. By default devise gives you the comment to go off of now. Below I added :avatar

```<code>  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute, :avatar])
  end
</code>```

Body:
I've been trying to customize the devise register method to register with more parameters and also update more(no luck so far), but I always get Unpermitted parameters: error. I tried using this Adding extra registration fields with Devise and https://github.com/plataformatec/devise#strong-parameters, but I cant get over that.

I've also thought about creating a new table to hold a foreign key the user id and put in there stuff like user_id, display_name, profile_picture, but I would have the same problem when trying to submit everything from the same page(mess with the devise controller).

Do you have any suggestions on how I can solve this? What else do I have to post?

routes.rb

devise_for :users, controllers: { registrations: 'users/registrations' }

users/regC

def create
    build_resource(registration_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        respond_with resource, :location => after_sign_up_path_for(resource)
      end
    else
      clean_up_passwords
      respond_with resource
    end
  end

private
  def registration_paramss
    params.require(:user).permit(:email, :display_name, :terms_of_services, :profile, :password, :password_confirmation)
  end

Body:
For Devise 4.2.0 you can whitelist additional parameters for your users table by adding those values to keys. By default devise gives you the comment to go off of now. Below I added :avatar

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:attribute, :avatar])
  end


答:
I believe your controller is trying to assign $scope.inputcity to the value of var city = 'Berkeley instead of assigning it to the value of the function argument city. It is best practice to avoid using the same name for a variable accessible from the function's scope and the function's argument.

Instead of passing city as an argument for ng-click="getForecastByLocation(city)", why not just access $scope.city directly in your controller?

Your function could look like this:

```<code>$scope.getForecastByLocation = function() {
            console.log($scope.city);
            Data.getApps($scope.city).then(function(data){
                $scope.data = data;
                $scope.name = data.name;
                console.log($scope.data); //object shows "Berkeley"
                console.log($scope.name);
             });
     }
</code>```

Title: Assignment in controller is not passing through to service

Body:
I believe your controller is trying to assign $scope.inputcity to the value of var city = 'Berkeley instead of assigning it to the value of the function argument city. It is best practice to avoid using the same name for a variable accessible from the function's scope and the function's argument.

Instead of passing city as an argument for ng-click="getForecastByLocation(city)", why not just access $scope.city directly in your controller?

Your function could look like this:

$scope.getForecastByLocation = function() {
            console.log($scope.city);
            Data.getApps($scope.city).then(function(data){
                $scope.data = data;
                $scope.name = data.name;
                console.log($scope.data); //object shows "Berkeley"
                console.log($scope.name);
             });
     }


问:
Flying Saucer does not render well the page (and outputs CSS)!
I searched and searched and looked at the code from Flying Saucer demos and browser. I cannot understand why this does not work.

It should display the report.html demo. This is what it displays: http://i55.tinypic.com/288v807.png

I am using Flying Saucer inside an applet.
My configuration file is exactly the same as the demo browser and it's loaded correctly.

```<code>// this variable contains the xml
contentFileString = "..";

ScalableXHTMLPanel view = new ScalableXHTMLPanel();
view.setCenteredPagedView(true);
view.setBackground(Color.WHITE);

int text_width = 200;
view.setPreferredSize(new Dimension(text_width, text_width));
Document document = XMLResource.load(new StringReader(contentFileString)).getDocument();
view.setDocument(document);

// .. render the frame
FSScrollPane scroll = new FSScrollPane(view);

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
frame.pack();
frame.setSize(700, 600);
frame.setVisible(true);
</code>```

You could say its from loading FS from the document. I already tried loading it from an URI and it gives me the same output. It's driving me insane. Has anybody had this issue?

答:
Listen to me carefully: DO NOT use the core-renderer-minimal.jar

This was one of the most stupid errors. Just that, use the core-renderer.jar and you're good to go.

Body:
I searched and searched and looked at the code from Flying Saucer demos and browser. I cannot understand why this does not work.

It should display the report.html demo. This is what it displays: http://i55.tinypic.com/288v807.png

I am using Flying Saucer inside an applet.
My configuration file is exactly the same as the demo browser and it's loaded correctly.

// this variable contains the xml
contentFileString = "..";

ScalableXHTMLPanel view = new ScalableXHTMLPanel();
view.setCenteredPagedView(true);
view.setBackground(Color.WHITE);

int text_width = 200;
view.setPreferredSize(new Dimension(text_width, text_width));
Document document = XMLResource.load(new StringReader(contentFileString)).getDocument();
view.setDocument(document);

// .. render the frame
FSScrollPane scroll = new FSScrollPane(view);

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scroll, BorderLayout.CENTER);
frame.pack();
frame.setSize(700, 600);
frame.setVisible(true);

You could say its from loading FS from the document. I already tried loading it from an URI and it gives me the same output. It's driving me insane. Has anybody had this issue?


问:
How to filter queryset with exclude and ForeignKey
I have two models

```<code>class Entry(models.Model):
    properties = here

class ReadedEntries(models.Model):
    entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
</code>```

How can I get the no readed entries from a user?

I try:

```<code>not_looked_videos = Entry.objects.exclude(ReadedEntries.objects.filter(user=request.user))
</code>```

but I get:

```<code>ValueError: need more than 0 values to unpack
</code>```

答:
Try to use isnull to get all enries with empty ReadedEtries set:

```<code>Entry.objects.filter(readedentries__isnull=True)
</code>```

Or to exclude only readed entries for current:
user

```<code>Entry.objects.exclude(readedentries__user=request.user))
</code>```

Body:
I have two models

class Entry(models.Model):
    properties = here

class ReadedEntries(models.Model):
    entry = models.ForeignKey(Entry, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

How can I get the no readed entries from a user?

I try:

not_looked_videos = Entry.objects.exclude(ReadedEntries.objects.filter(user=request.user))

but I get:

ValueError: need more than 0 values to unpack

Body:
Try to use isnull to get all enries with empty ReadedEtries set:

Entry.objects.filter(readedentries__isnull=True)

Or to exclude only readed entries for current:
user

Entry.objects.exclude(readedentries__user=request.user))


问:
Why is my PHP not autostarting with NginX on Windows 10?
I'm running a new install of Windows 10. I need to create a local testing environment for PHP. I've set up and run NginX/PHP servers on Ubuntu Linux before, but never on Windows. I've installed the NginX and PHP binaries for Windows.

After I've booted up and logged in, if I cd to C:\nginx and run nginx.exe, the Nginx server starts up and runs fine, and I get the "Welcome to NginX" screen at http://127.0.0.1.

Then, if I cd to C:\nginx\php and run php-cgi.exe -b 127.0.0.1:9000 -c c:/nginx/php/php.ini, the PHP server runs, and I can access http://127.0.0.1/php.info and get the output of php_info();. So it seems everything is installed okay.

My goal now, is to to have the PHP server autostart when I boot the machine. I downloaded the Non-Sucking Service Manager, and opened a command prompt in Administraror mode, and ran nssm edit nginx. I filled out the screens as follows:

Then I did the same for PHP:

However, while NginX seems to be starting at boot, PHP does not. After a boot, without manually starting anything at the command line, I get the NginX welcome screen. However, if I try to view the PHP info page, I get the following message:

Unable to connect

Firefox can’t establish a connection to the server at 127.0.0.1.

How do I get PHP to autostart on boot?

This is my nginx.conf file:

```<code>worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include             mime.types;
    default_type        text/html;
    sendfile            on;
    keepalive_timeout   65;

    server {

        #Uncomment and edit the line below if you want to use a custom domainname
        #server_name    your.domain.com;

        listen          80;
        root            c:/nginx/html;

    location ~ .php$ {
        root html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME c:/nginx/html/$fastcgi_script_name;
        include fastcgi_params;
    }
    }
}
</code>```

答:
Your nginx.conf seems OK.

... However, while NginX seems to be starting at boot ...

I wouldn't trust NGINX welcome page, it most likely comes from cache. I also don't trust a service status Running unless there are nginx processes started by nssm.

In my tests both nginx and php services were not started properly.

I needed to set AppNoConsole=1 for both services to make them work.

According to the author(s) this is a known issue with Windows 10 Creators Update.

2017-04-26: Users of Windows 10 Creators Update should use prelease
  build 2.2.4-101 to avoid an issue with services failing to start. If
  for some reason you cannot use that build you can also set
  AppNoConsole=1 in the registry, noting that applications which expect
  a console window may behave unexpectedly.

You can change this setting via NSSM Service Editor GUI > Process > Console window. Just clear the checkbox and click Edit service. It's done.

The same operation can be done with commands too.

net stop php
net stop nginx

nssm set php AppNoConsole 1
nssm set nginx AppNoConsole 1

net start nginx
net start php
```

Body:
I'm running a new install of Windows 10. I need to create a local testing environment for PHP. I've set up and run NginX/PHP servers on Ubuntu Linux before, but never on Windows. I've installed the NginX and PHP binaries for Windows.

After I've booted up and logged in, if I cd to C:\nginx and run nginx.exe, the Nginx server starts up and runs fine, and I get the "Welcome to NginX" screen at http://127.0.0.1.

Then, if I cd to C:\nginx\php and run php-cgi.exe -b 127.0.0.1:9000 -c c:/nginx/php/php.ini, the PHP server runs, and I can access http://127.0.0.1/php.info and get the output of php_info();. So it seems everything is installed okay.

My goal now, is to to have the PHP server autostart when I boot the machine. I downloaded the Non-Sucking Service Manager, and opened a command prompt in Administraror mode, and ran nssm edit nginx. I filled out the screens as follows:

Then I did the same for PHP:

However, while NginX seems to be starting at boot, PHP does not. After a boot, without manually starting anything at the command line, I get the NginX welcome screen. However, if I try to view the PHP info page, I get the following message:

Unable to connect

Firefox can’t establish a connection to the server at 127.0.0.1.

How do I get PHP to autostart on boot?

This is my nginx.conf file:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include             mime.types;
    default_type        text/html;
    sendfile            on;
    keepalive_timeout   65;

    server {

        #Uncomment and edit the line below if you want to use a custom domainname
        #server_name    your.domain.com;

        listen          80;
        root            c:/nginx/html;

    location ~ .php$ {
        root html;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME c:/nginx/html/$fastcgi_script_name;
        include fastcgi_params;
    }
    }
}


问:
How to use a Proxy Server with Alamofire 4 and Swift 3
I'm trying to use my Proxy for an API request that needs a specified IP.
To debug my issue, I'm requesting the IP from a webservice.

This is my current code:

```<code>import UIKit
import Alamofire

class ViewController: UIViewController {

    var requestManager = Alamofire.SessionManager.default

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        var proxyConfiguration = [NSObject: AnyObject]()
        proxyConfiguration[kCFNetworkProxiesHTTPProxy] = "http://xxx@eu-west-static-01.quotaguard.com" as AnyObject?
        proxyConfiguration[kCFNetworkProxiesHTTPPort] = "9293" as AnyObject?
        proxyConfiguration[kCFNetworkProxiesHTTPEnable] = 1 as AnyObject?

        let cfg = Alamofire.SessionManager.default.session.configuration
        cfg.connectionProxyDictionary = proxyConfiguration

        let ip = URL(string: "https://api.ipify.org?format=json")

        requestManager = Alamofire.SessionManager(configuration: cfg)
        requestManager.request(ip!).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")
            }
        }
    }
}
</code>```

The problem: the responded IP is the same with or without the proxyConfiguration.

PS: physical device used.

答:
Based off Manishg's answer I use the following to avoid warnings

```<code>let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders

var proxyConfiguration = [String: AnyObject]()
proxyConfiguration.updateValue(1 as AnyObject, forKey: "HTTPEnable")
proxyConfiguration.updateValue("eu-west-static-01.quotaguard.com" as AnyObject, forKey: "HTTPProxy")
proxyConfiguration.updateValue(9293 as AnyObject, forKey: "HTTPPort")
proxyConfiguration.updateValue(1 as AnyObject, forKey: "HTTPSEnable")
proxyConfiguration.updateValue("eu-west-static-01.quotaguard.com" as AnyObject, forKey: "HTTPSProxy")
proxyConfiguration.updateValue(9293 as AnyObject, forKey: "HTTPSPort")
configuration.connectionProxyDictionary = proxyConfiguration

sharedManager = Alamofire.SessionManager(configuration: configuration)
</code>```

The https constants have been deprecated and could be removed at anytime. By using the string values, the code might break but it won't crash

Body:
I'm trying to use my Proxy for an API request that needs a specified IP.
To debug my issue, I'm requesting the IP from a webservice.

This is my current code:

import UIKit
import Alamofire

class ViewController: UIViewController {

    var requestManager = Alamofire.SessionManager.default

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        var proxyConfiguration = [NSObject: AnyObject]()
        proxyConfiguration[kCFNetworkProxiesHTTPProxy] = "http://xxx@eu-west-static-01.quotaguard.com" as AnyObject?
        proxyConfiguration[kCFNetworkProxiesHTTPPort] = "9293" as AnyObject?
        proxyConfiguration[kCFNetworkProxiesHTTPEnable] = 1 as AnyObject?

        let cfg = Alamofire.SessionManager.default.session.configuration
        cfg.connectionProxyDictionary = proxyConfiguration

        let ip = URL(string: "https://api.ipify.org?format=json")

        requestManager = Alamofire.SessionManager(configuration: cfg)
        requestManager.request(ip!).response { response in
            print("Request: \(response.request)")
            print("Response: \(response.response)")
            print("Error: \(response.error)")

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")
            }
        }
    }
}

The problem: the responded IP is the same with or without the proxyConfiguration.

PS: physical device used.

Body:
Based off Manishg's answer I use the following to avoid warnings

let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders

var proxyConfiguration = [String: AnyObject]()
proxyConfiguration.updateValue(1 as AnyObject, forKey: "HTTPEnable")
proxyConfiguration.updateValue("eu-west-static-01.quotaguard.com" as AnyObject, forKey: "HTTPProxy")
proxyConfiguration.updateValue(9293 as AnyObject, forKey: "HTTPPort")
proxyConfiguration.updateValue(1 as AnyObject, forKey: "HTTPSEnable")
proxyConfiguration.updateValue("eu-west-static-01.quotaguard.com" as AnyObject, forKey: "HTTPSProxy")
proxyConfiguration.updateValue(9293 as AnyObject, forKey: "HTTPSPort")
configuration.connectionProxyDictionary = proxyConfiguration

sharedManager = Alamofire.SessionManager(configuration: configuration)

The https constants have been deprecated and could be removed at anytime. By using the string values, the code might break but it won't crash


问:
How to get an HTML file using Python?
I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: http://www.infolanka.com/miyuru_gee/art/art.html.

How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page?

答:
And respect robots.txt and throttle your requests :)

(Apparently urllib2 does already according to this helpful SO post).

Title: How to get an HTML file using Python?


问:
Express loading images relative to url
I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.

This code works fine.

```<code>app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
    res.render('some-file');
});
</code>```

Inside of some-file.ejs I have...

```<code><img src="assets/images/picture.jpg">
</code>```

But what doesnt work is when I have a second url pathway.

```<code>app.get("/overview/specific", function(req, res) {
    res.render('another-file');
});

<img src="assets/images/picture.jpg">
</code>```

In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?

Thanks in advance

答:
Try to use /assets/images/picture.jpg.

Add / before the path. Then it will take /app/public/ as a root and be sure that the image will be at :

/app/public/assets/images/picture.jpg

Now wherever you want picture.jpg just pass this absolute path.

Title: Express loading images relative to url

Body:
I'm building a fairly basic webpage using express. However, I'm having some trouble with my image pathways.

This code works fine.

app.use(express.static(path.join(__dirname, "/app/public/")));
app.get("/overview", function(req, res) {
    res.render('some-file');
});

Inside of some-file.ejs I have...

But what doesnt work is when I have a second url pathway.

app.get("/overview/specific", function(req, res) {
    res.render('another-file');
});

In this example I'm trying to load the exact same image (in my case its a banner thats reused on every single page). This gives me an error that the image is not found. What I've noticed from the console errors is that the image is being loaded from localhost:3000/overview/assets/images/picture.jpg
I don't understand why express is trying to load the image from whatever the first pathway is (overview in this case). Overview shouldnt be in the pathway!
Can anyone help me out debugging this issue?

Thanks in advance


问:
Receiving an error when nodes make contact
I am currently making a game in which you are a space ship in the middle and there are enemy ships moving towards you and you have to shoot at them to win.

While I was testing the game I saw that I received an error when (it appears to be) two or more enemy ships hit the player ship at the same time. I am not certain if this is what's causing the error but it looks like it when I test it.

I made the game so that whenever enemy players touch the player, the game ends and a function is called to change the game scene. This is where the error is called, whenever the scene is about to change.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

here is the code for the didBegin(contact: SKPhysicsContact)

```<code>func didBegin(_ contact: SKPhysicsContact) {

    var BodyOne = SKPhysicsBody()
    var BodyTwo = SKPhysicsBody()

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
        BodyOne = contact.bodyA
        BodyTwo = contact.bodyB
                }
    else{
        BodyOne = contact.bodyB
        BodyTwo = contact.bodyA
    }

    //SHIPS TOUCH EACH OTHER CHECK
    if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.LeftV{

        GameOver1()

       BodyTwo.node?.removeFromParent()
       BodyOne.node?.removeFromParent()

    }

    if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.RightV{

        GameOver1()
        BodyOne.node?.removeFromParent()
        BodyTwo.node?.removeFromParent()

        //more code is under here

    }
</code>```

And here is the code of the game changing scene. (which works when 1 enemy touches the player but doesn't seem to when 2 or more makes contact with the player)

```<code>func GameOver1(){

    ButtonAudioPlayer.stop()
    removeAllChildren()
    removeAllActions()
    let scene = GameOver(size: self.size)
    let sKView = self.view! as SKView       // <----- error shows here
    sKView.ignoresSiblingOrder = true
    scene.scaleMode = .aspectFill
    sKView.presentScene(scene)

}
</code>```

Can someone please help me resolve this issue.

答:
Your view object is nil, which is peculiar if you are defining GameOver1 inside of the active scene. Move your GameOver1 function to your main scene, and that should fix the issue.

Or, you could make a global variable and assign it to the initial SKView object inside of your GameViewController. This is not a best practice but it will work.

```<code>var gView = SKView()

class GameViewController: UIViewController {
  // Stuff..

  if let view = self.view as! SKView? {
      gView = view
</code>```

Also, you have other potential crash issues in this code.

As KOD said in comments multiple contacts can happen in 1 frame.. but you are killing the node (and thus pb) which means the scheduled .didBegin is going to find nil or some other error and crash.

A better way to do this is to flag the node for removal AFTER the physics step--once contacts are safely handled.

Set their mask to some high-number instead of removing it:

```<code>var nodesToKill = SKNode()

override func didBeginContact(/*prams*/) {
  // Stuff...

  BodyB.node!.categoryBitMask = 35 // Or some other number so as
                                   // to not trigger another contact.
  BodyB.node!.moveToParent(nodesToKill) //moves the node off the scene entirely
}

override func didSimulatePhysics(/*prams*/) {

  nodesToKill.removeAllChildren() // or do nodesToKill = SKNode() and let ARC take care of it for you
}
</code>```

Also, you probably want to all of the node removal stuff BEFORE calling GameOver, as that can cause issues as well with trying to do stuff with nodes that no longer exist.

A somewhat contrived way around this (if the above didn't work) is something like this:

```<code>var flag_shouldGameOver = false

override func didFinishUpdate() {
  if flag_shouldGameOver == true {
     flag_shouldGameOver = false
     GameOver1()
  }
}
</code>```

Body:
I am currently making a game in which you are a space ship in the middle and there are enemy ships moving towards you and you have to shoot at them to win.

While I was testing the game I saw that I received an error when (it appears to be) two or more enemy ships hit the player ship at the same time. I am not certain if this is what's causing the error but it looks like it when I test it.

I made the game so that whenever enemy players touch the player, the game ends and a function is called to change the game scene. This is where the error is called, whenever the scene is about to change.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

here is the code for the didBegin(contact: SKPhysicsContact)

func didBegin(_ contact: SKPhysicsContact) {

    var BodyOne = SKPhysicsBody()
    var BodyTwo = SKPhysicsBody()

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask{
        BodyOne = contact.bodyA
        BodyTwo = contact.bodyB
                }
    else{
        BodyOne = contact.bodyB
        BodyTwo = contact.bodyA
    }

    //SHIPS TOUCH EACH OTHER CHECK
    if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.LeftV{

        GameOver1()

       BodyTwo.node?.removeFromParent()
       BodyOne.node?.removeFromParent()

    }

    if BodyOne.categoryBitMask == NumberingPhysics.SpaceShip && BodyTwo.categoryBitMask == NumberingPhysics.RightV{

        GameOver1()
        BodyOne.node?.removeFromParent()
        BodyTwo.node?.removeFromParent()

        //more code is under here

    }

And here is the code of the game changing scene. (which works when 1 enemy touches the player but doesn't seem to when 2 or more makes contact with the player)

func GameOver1(){

    ButtonAudioPlayer.stop()
    removeAllChildren()
    removeAllActions()
    let scene = GameOver(size: self.size)
    let sKView = self.view! as SKView       // <----- error shows here
    sKView.ignoresSiblingOrder = true
    scene.scaleMode = .aspectFill
    sKView.presentScene(scene)

}

Can someone please help me resolve this issue.

Body:
Your view object is nil, which is peculiar if you are defining GameOver1 inside of the active scene. Move your GameOver1 function to your main scene, and that should fix the issue.

Or, you could make a global variable and assign it to the initial SKView object inside of your GameViewController. This is not a best practice but it will work.

var gView = SKView()

class GameViewController: UIViewController {
  // Stuff..

  if let view = self.view as! SKView? {
      gView = view

Also, you have other potential crash issues in this code.

As KOD said in comments multiple contacts can happen in 1 frame.. but you are killing the node (and thus pb) which means the scheduled .didBegin is going to find nil or some other error and crash.

A better way to do this is to flag the node for removal AFTER the physics step--once contacts are safely handled.

Set their mask to some high-number instead of removing it:

var nodesToKill = SKNode()

override func didBeginContact(/*prams*/) {
  // Stuff...

  BodyB.node!.categoryBitMask = 35 // Or some other number so as
                                   // to not trigger another contact.
  BodyB.node!.moveToParent(nodesToKill) //moves the node off the scene entirely
}

override func didSimulatePhysics(/*prams*/) {

  nodesToKill.removeAllChildren() // or do nodesToKill = SKNode() and let ARC take care of it for you
}

Also, you probably want to all of the node removal stuff BEFORE calling GameOver, as that can cause issues as well with trying to do stuff with nodes that no longer exist.

A somewhat contrived way around this (if the above didn't work) is something like this:

var flag_shouldGameOver = false

override func didFinishUpdate() {
  if flag_shouldGameOver == true {
     flag_shouldGameOver = false
     GameOver1()
  }
}