问:
Python output dict to new json structure
I am new to Python and have run into a problem that I have not been able to solve despite a lot of searching and reading related posts.  Any help is much appreciated:
I have imported a json file into a dictionary that has this structure:

```<code>{
 "23991": {
 "5115": 10,
 "2611": 22
 },
 "43223": {
 "7252": 11,
 "4302": 2
 }
}
</code>```

I want to save it to a new json file with this structure:

```<code>[
 {
  "sni": {
   "code": "23991",
   "yrken": [
     {
       "code": "5115",
       "antal": 10
     },
     {
       "code": "2611",
       "antal": 22
     }
   ]
  }
},
{
  "sni": {
   "code": "43223",
   "yrken": [
     {
       "code": "7252",
       "antal": 11
     },
     {
       "code": "4302",
       "antal": 11
     }
   ]
  }
 }
]
</code>```

So far I have this code:

```<code>import os
import sys
import json

pathSNI2Yrke = "Smallsni2Yrke.json"
with open(pathSNI2Yrke) as data_file:
sni2Yrke = json.load(data_file)
#print(sni2Yrke)

for key in sni2Yrke:
    value = sni2Yrke[key]
    d = [{"sni":
          {"snicode": key,
           "yrken": [{ "yrkecode":list(value.keys()),
                      "antal": list(value.values())}]}}]
    j = json.dumps(d, indent=2)
    #f = open('sample.json', 'w')
    print ( j)
</code>```

Which gives me this result:

```<code>[
{
  "sni": {
   "snicode": "23991",
   "yrken": [
     {
      "yrkecode": [
        "5115",
        "2611"
       ],
      "antal": [
        10,
        22
       ]
     }
    ]
  }
 }
]
[
 {
  "sni": {
   "snicode": "43223",
   "yrken": [
     {
      "yrkecode": [
        "7252",
        "4302"
       ],
       "antal": [
         11,
         2
       ]
     }
    ]
   }
  }
]
</code>```

As you see this isn't a correct json structure, and for the life of me I can't figure out how to get the structure right. The output goes all the way back to the root element so I get ...][... instead of ...},{.... between the "sni" blocks
If you have tips on how the code could be better or a better way of achieving the result please let me have them.

Body:
I am new to Python and have run into a problem that I have not been able to solve despite a lot of searching and reading related posts.  Any help is much appreciated:
I have imported a json file into a dictionary that has this structure:

{
 "23991": {
 "5115": 10,
 "2611": 22
 },
 "43223": {
 "7252": 11,
 "4302": 2
 }
}

I want to save it to a new json file with this structure:

[
 {
  "sni": {
   "code": "23991",
   "yrken": [
     {
       "code": "5115",
       "antal": 10
     },
     {
       "code": "2611",
       "antal": 22
     }
   ]
  }
},
{
  "sni": {
   "code": "43223",
   "yrken": [
     {
       "code": "7252",
       "antal": 11
     },
     {
       "code": "4302",
       "antal": 11
     }
   ]
  }
 }
]

So far I have this code:

import os
import sys
import json

pathSNI2Yrke = "Smallsni2Yrke.json"
with open(pathSNI2Yrke) as data_file:
sni2Yrke = json.load(data_file)
#print(sni2Yrke)

for key in sni2Yrke:
    value = sni2Yrke[key]
    d = [{"sni":
          {"snicode": key,
           "yrken": [{ "yrkecode":list(value.keys()),
                      "antal": list(value.values())}]}}]
    j = json.dumps(d, indent=2)
    #f = open('sample.json', 'w')
    print ( j)

Which gives me this result:

[
{
  "sni": {
   "snicode": "23991",
   "yrken": [
     {
      "yrkecode": [
        "5115",
        "2611"
       ],
      "antal": [
        10,
        22
       ]
     }
    ]
  }
 }
]
[
 {
  "sni": {
   "snicode": "43223",
   "yrken": [
     {
      "yrkecode": [
        "7252",
        "4302"
       ],
       "antal": [
         11,
         2
       ]
     }
    ]
   }
  }
]

As you see this isn't a correct json structure, and for the life of me I can't figure out how to get the structure right. The output goes all the way back to the root element so I get ...][... instead of ...},{.... between the "sni" blocks
If you have tips on how the code could be better or a better way of achieving the result please let me have them.

Body:
Using some nested comprehensions, you can do the following:

> d = {'43223': {'4302': 2, '7252': 11}, '23991': {'5115': 10, '2611': 22}}

> d2 = [
  {'sni':
    {'code': k1,
     'yrken': [{'code': k2, 'antal': v2} for k2, v2 in v1.items()]
    }
  }
  for k1, v1 in d.items()
]

> print json.dumps(d2, indent=1)
[
 {
  "sni": {
   "code": "43223",
   "yrken": [
    {
     "antal": 2,
     "code": "4302"
    },
    {
     "antal": 11,
     "code": "7252"
    }
   ]
  }
 },
 {
  "sni": {
   "code": "23991",
   "yrken": [
    {
     "antal": 10,
     "code": "5115"
    },
    {
     "antal": 22,
     "code": "2611"
    }
   ]
  }
 }
]


来源: stackexchange

问:
JMeter 400 Error File Upload
I'm trying to use JMeter to test a restful endpoint for uploading files, but I'm getting a 400 error. The one thing that jumps out at me is the boundary value; it's not the same I provided as the one shown in the request. I'm able to use the endpoint in the browser without issue, and I've replicated the headers revealed in the developer tools in FF.

Here is the relevant info from JMeter:

Result Tab:

Thread Name: Asdf - Load Test 1-1

Sample Start: 2017-06-05 08:47:46 EDT

Load time: 159

Connect Time: 28

Latency: 159

Size in bytes: 438

Sent bytes:821003

Headers size in bytes: 438

Body size in bytes: 0

Sample Count: 1

Error Count: 1

Data type ("text"|"bin"|""):

Response code: 400

Response message: Bad Request

Response headers:

HTTP/1.1 400 Bad Request

Date: Mon, 05 Jun 2017 12:47:46 GMT

Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

Strict-Transport-Security: max-age=31536000 ; includeSubDomains

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

Cache-Control: no-cache, must-revalidate

Content-Length: 0

Connection: close

HTTPSampleResult fields:

ContentType:

DataEncoding: null

Request Tab:

POST https://localhost/my/rest/endpoint

POST data:

--9amm365-gMmimP70lvs9jIvlIxOfkocUN

Content-Disposition: form-data; name="parseable"; filename="asdf.docx"

Content-Type: application/vnd.openxmlformats-

officedocument.wordprocessingml.document

Content-Transfer-Encoding: binary

--9amm365-gMmimP70lvs9jIvlIxOfkocUN--

[no cookies]

Request Headers:

Connection: keep-alive

Content-Type: multipart/form-data; boundary=--Uc_2uLvcVgc7SqvzIJxR3encUKw-
f7w9

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.5

Accept: application/json, text/plain, /

X-Request-OnBehalfOf: some-user-uuid

X-Requested-With: XMLHttpRequest

Content-Length: 820532

Host: localhost

User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

Response Data Tab is blank.

Server side implementation:

```<code>@POST
@Override
@EnhancedDetail
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("my/rest/endpoint")
public Response uploadProduct(@PathParam("id") final String id, MultiPart multipart) throws IOException {
    return processMultiFileUpload(id, multipart, MultiPartUploadType.DRAFT, false);
}
</code>```

答: I figured it out. I changed the Client Implementation on the HTTP Request to Java. Everything I've read said use HttpClient4, but I tried Java and it worked. </p>

ContentLicense: CC BY-SA 3.0

Title: JMeter 400 Error File Upload

Body:
I'm trying to use JMeter to test a restful endpoint for uploading files, but I'm getting a 400 error. The one thing that jumps out at me is the boundary value; it's not the same I provided as the one shown in the request. I'm able to use the endpoint in the browser without issue, and I've replicated the headers revealed in the developer tools in FF.

Here is the relevant info from JMeter:

Result Tab:

Thread Name: Asdf - Load Test 1-1

Sample Start: 2017-06-05 08:47:46 EDT

Load time: 159

Connect Time: 28

Latency: 159

Size in bytes: 438

Sent bytes:821003

Headers size in bytes: 438

Body size in bytes: 0

Sample Count: 1

Error Count: 1

Data type ("text"|"bin"|""):

Response code: 400

Response message: Bad Request

Response headers:

HTTP/1.1 400 Bad Request

Date: Mon, 05 Jun 2017 12:47:46 GMT

Server: Apache/2.4.25 (Win64) OpenSSL/1.0.2k

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Pragma: no-cache

Expires: 0

Strict-Transport-Security: max-age=31536000 ; includeSubDomains

X-XSS-Protection: 1; mode=block

X-Frame-Options: DENY

X-Content-Type-Options: nosniff

Cache-Control: no-cache, must-revalidate

Content-Length: 0

Connection: close

HTTPSampleResult fields:

ContentType:

DataEncoding: null

Request Tab:

POST https://localhost/my/rest/endpoint

POST data:

--9amm365-gMmimP70lvs9jIvlIxOfkocUN

Content-Disposition: form-data; name="parseable"; filename="asdf.docx"

Content-Type: application/vnd.openxmlformats-

officedocument.wordprocessingml.document

Content-Transfer-Encoding: binary

--9amm365-gMmimP70lvs9jIvlIxOfkocUN--

[no cookies]

Request Headers:

Connection: keep-alive

Content-Type: multipart/form-data; boundary=--Uc_2uLvcVgc7SqvzIJxR3encUKw-
f7w9

Accept-Encoding: gzip, deflate, br

Accept-Language: en-US,en;q=0.5

Accept: application/json, text/plain, /

X-Request-OnBehalfOf: some-user-uuid

X-Requested-With: XMLHttpRequest

Content-Length: 820532

Host: localhost

User-Agent: Apache-HttpClient/4.5.3 (Java/1.8.0_121)

Response Data Tab is blank.

Server side implementation:

@POST
@Override
@EnhancedDetail
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("my/rest/endpoint")
public Response uploadProduct(@PathParam("id") final String id, MultiPart multipart) throws IOException {
    return processMultiFileUpload(id, multipart, MultiPartUploadType.DRAFT, false);
}


问:
What is the Best way to handle a lot of data on a Recycleview
I need to load a long list of data (5000-1000) on a RecycleView, and each items of the RecycleView has many details, so 5 TextView, 1 ImageView and a ProgressBar. All the data are stored on the SQLite DB.
Is it better to load an ArrayList<Object> which contains all the data and them set it to the adapter or is it better to load the data on the adapter?
Please consider I have other thing to do on the adapter like retriving the images (with Glide).
Any suggestion or consideration would be helpful!

Thank you

答:
If you're using recycler view then I guess it's actually the best method (yet to me) for loading large lists...I think both method (store Arraylist and sent data to adapter) works in some cases, but recycler view destroys data that have been scrolled. But I think the best way and most efficient used by many developers is to set a limit to amount of data displayed on screen at once then use on scroll listener to load more, then recycler view does it jobs too!

Check it out here very perfect

Android Endless List


问:
How to hide mouse cursor with jquery
How to hide mouse cursor with jquery in entire webpage.
 I tried this

```<code>$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});
</code>```

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.

ContentLicense: CC BY-SA 2.5

Title: How to hide mouse cursor with jquery

Body:
How to hide mouse cursor with jquery in entire webpage.
 I tried this

$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.

Body: $('body').css('cursor', 'none');


问:
MVC5 - How do I define deserialization behavior for action parameter type?
```<code>    public class LogsController : Controller
    {
        public async Task<ActionResult> User(string id, int? page)
        {
            return await User(id, (Page)page);
        }

        private async Task<ActionResult> User(string id, Page page)
        {
            var data = await Repo.GetData(id, page, 10);
            var model = new UserLogs
            {
                User = id,
                Events = data,
                Pager = new PagerInput(page, 10, data.TotalCount)
            };

            return View("UserGrid", model);
        }
    }
</code>```

My Page class provides useful functionality such as making sure the page is never less than 1, ect. However, if my public action takes Page as a parameter, it is always null, no matter the value in the form or querystring, even though I have defined implicit casts to and from int.

Is there anyway I can tell the MVC how to deserialize a Page type? Such a providing some sort of method/ctor to convert from string?

I would like to define it on the actual Page type since I will be using it in multiple controllers/actions.

I would be nice to not need the double action definition.

答:
This custom model binder allows you to define deserialization behavior of any type by simply defining a constructor with a string parameter:

```<code>public class CustomModelBinder : DefaultModelBinder
{
    static Assembly _assembly = typeof(CustomModelBinder).Assembly;
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (_assembly.Equals(bindingContext.ModelType.Assembly))
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var ctor = bindingContext.ModelType.GetConstructor(new Type[] { typeof(string) });
            if (ctor != null && value != null)
                return ctor.Invoke(new object[] { value.AttemptedValue });
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}
</code>```

And register it...

```<code>protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}
</code>```

Body:
    public class LogsController : Controller
    {
        public async Task<ActionResult> User(string id, int? page)
        {
            return await User(id, (Page)page);
        }

        private async Task<ActionResult> User(string id, Page page)
        {
            var data = await Repo.GetData(id, page, 10);
            var model = new UserLogs
            {
                User = id,
                Events = data,
                Pager = new PagerInput(page, 10, data.TotalCount)
            };

            return View("UserGrid", model);
        }
    }

My Page class provides useful functionality such as making sure the page is never less than 1, ect. However, if my public action takes Page as a parameter, it is always null, no matter the value in the form or querystring, even though I have defined implicit casts to and from int.

Is there anyway I can tell the MVC how to deserialize a Page type? Such a providing some sort of method/ctor to convert from string?

I would like to define it on the actual Page type since I will be using it in multiple controllers/actions.

I would be nice to not need the double action definition.

Body:
This custom model binder allows you to define deserialization behavior of any type by simply defining a constructor with a string parameter:

public class CustomModelBinder : DefaultModelBinder
{
    static Assembly _assembly = typeof(CustomModelBinder).Assembly;
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (_assembly.Equals(bindingContext.ModelType.Assembly))
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var ctor = bindingContext.ModelType.GetConstructor(new Type[] { typeof(string) });
            if (ctor != null && value != null)
                return ctor.Invoke(new object[] { value.AttemptedValue });
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

And register it...

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.DefaultBinder = new CustomModelBinder();
}


问:
Is there anyway of implementing neural networks using swift for ios?
I have searched a lot and I have not yet been able to find anything that shows any implementation of neural networks using swift. I am planning to build an application using swift that involves the use of neural networks. So i'm wondering if I can get any help regarding this. If there is any documentation regarding neural networks in swift, I would be happy if anybody would provide some reference regarding it.</p>

答:
Bender lets you build and run neural nets on iOS. As it uses Metal under the hood, it runs fast and smooth. It also supports running TensorFlow models directly.

Disclaimer: I worked on this project.


问:
How do I map with rarely used state in clojure?
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

```<code>int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}
</code>```

However in Clojure the best I've come up with is:

```<code>(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))
</code>```

Which is pretty ugly considering that without the special case this would become:

```<code>(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)
</code>```

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

答:
As Alejandro said, an atom allows one to easily keep track of mutable state and use it where needed:

```<code>(def special-values-handled (atom 0))

(defn handle-case-1 [value]  ...)
(defn handle-case-2 [value]  ...)
...
(defn handle-special [value]
  (let [curr-cnt (swap! special-values-handled inc)]
    ...<use curr-cnt>... )
  ...)

(defn handle-cases [value]
  (cond
    (case-1? value)   (handle-case-1  value)
    (case-2? value)   (handle-case-2  value)
    ...
    (special? value)  (handle-special value)
    :else (throw (IllegalArgumentException. "msg"))))

...
(mapv handle-cases values)
</code>```

Never be afraid to use an atom when a piece of mutable state is the simplest way to solve a problem.

Another technique I sometimes use is to use a "context" map as the accumulator:

```<code>(defn handle-case-1 [ctx value] (update ctx :cum-result conj (f1 value)))
(defn handle-case-2 [ctx value] (update ctx :cum-result conj (f2 value)))
(defn handle-special [ctx value]
  (-> ctx
    (update :cum-result conj (f-special value))
    (update :cnt-special inc)))

(def values ...)
(def result-ctx
  (reduce
    (fn [ctx value]
      (cond
        (case-1? value) (handle-case-1 value)
        (case-2? value) (handle-case-2 value)
        (special? value) (handle-special value i)))
    {:cum-result  []
     :cnt-special 0}
    values))
</code>```

Body:
The situation is as follows: I'm transforming a sequence of values. The transformation of each value breaks down into a number of different cases. Most values are completely independent of each other. However there is one special case that requires me to keep track of how many special cases I've encountered so far. In imperative programming this is pretty straightforward:

int i = 0;
List<String> results = new ArrayList<>();
for (String value : values) {
  if (case1(value)) {
    results.add(handleCase1(value));
  } else if (case2(value)) {
  ...
  } else if (special(value)) {
    results.add(handleSpecial(value, i));
    i++;
  }
}

However in Clojure the best I've come up with is:

(first
 (reduce
  (fn [[results i] value]
      (cond
       (case-1? value) [(conj results (handle-case-1 value)) i]
       (case-2? value) ...
       (special? value) [(conj results (handle-special value i))
                         (inc i)]))
  [[] 0] values))

Which is pretty ugly considering that without the special case this would become:

(map #(cond
       (case-1? %) (handle-case-1 %)
       (case-2? %) ...)
      values)

The trouble is that I'm manually stitching a sequence together during the reduction. Also most cases don't even care about the index but must nonetheless pass it along for the next reduction step.

Is there a cleaner solution to this problem?

Body:
As Alejandro said, an atom allows one to easily keep track of mutable state and use it where needed:

(def special-values-handled (atom 0))

(defn handle-case-1 [value]  ...)
(defn handle-case-2 [value]  ...)
...
(defn handle-special [value]
  (let [curr-cnt (swap! special-values-handled inc)]
    ...<use curr-cnt>... )
  ...)

(defn handle-cases [value]
  (cond
    (case-1? value)   (handle-case-1  value)
    (case-2? value)   (handle-case-2  value)
    ...
    (special? value)  (handle-special value)
    :else (throw (IllegalArgumentException. "msg"))))

...
(mapv handle-cases values)

Never be afraid to use an atom when a piece of mutable state is the simplest way to solve a problem.

Another technique I sometimes use is to use a "context" map as the accumulator:

(defn handle-case-1 [ctx value] (update ctx :cum-result conj (f1 value)))
(defn handle-case-2 [ctx value] (update ctx :cum-result conj (f2 value)))
(defn handle-special [ctx value]
  (-> ctx
    (update :cum-result conj (f-special value))
    (update :cnt-special inc)))

(def values ...)
(def result-ctx
  (reduce
    (fn [ctx value]
      (cond
        (case-1? value) (handle-case-1 value)
        (case-2? value) (handle-case-2 value)
        (special? value) (handle-special value i)))
    {:cum-result  []
     :cnt-special 0}
    values))


问:
Android in-app-purchase validation on backend
I'm using validation of user's in app purchase with google API:
Purchases.products: get
https://developers.google.com/android-publisher/api-ref/purchases/products/get

In C# on the backend I create HttpWebRequest with this url:

```<code>var url = string.Format("https://www.googleapis.com/androidpublisher/v2/applications/{0}/purchases/products/{1}/tokens/{2}", packageName, androidProductId, token);
var request = HttpWebRequest.Create(url);
request.Method = "GET";
</code>```

The parameters packageName, productId and token, were set correctly.
After I send the request, google answers me with the next JSON object:

```<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}
</code>```

So, the problem is about authorization my backend server. How could this be fixed?

答: I use IAP for authorization on backend server. Please read this article(russian language).</p>

Body:
I'm using validation of user's in app purchase with google API:
Purchases.products: get
https://developers.google.com/android-publisher/api-ref/purchases/products/get

In C# on the backend I create HttpWebRequest with this url:

var url = string.Format("https://www.googleapis.com/androidpublisher/v2/applications/{0}/purchases/products/{1}/tokens/{2}", packageName, androidProductId, token);
var request = HttpWebRequest.Create(url);
request.Method = "GET";

The parameters packageName, productId and token, were set correctly.
After I send the request, google answers me with the next JSON object:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

So, the problem is about authorization my backend server. How could this be fixed?


问:
How to crop a Mat to ROI in Emgu (OpenCV for C#)
Some of the answers I found recommended using :

```<code>frame = ...
Rectangle ROI = ...
Mat crop = new Mat(frame, ROI)
</code>```

But this does not seem to wokr in Emgu 3.x

答:
I figured it out. To crop a Mat, you have to use an Image object as a buffer and use its .ROI property:</p>

```<code>Mat crop_color_frame(Mat input, Rectangle crop_region)
{
  /*
   * TODO(Ahmed): Figure out why I had to copy this into this class.
   * */
  Image<Bgr, Byte> buffer_im = input.ToImage<Bgr, Byte>();
  buffer_im.ROI = crop_region;

  Image<Bgr, Byte> cropped_im = buffer_im.Copy();

  return cropped_im.Mat;

}
</code>```

Body:
Some of the answers I found recommended using :

frame = ...
Rectangle ROI = ...
Mat crop = new Mat(frame, ROI)

But this does not seem to wokr in Emgu 3.x

Body:
I figured it out. To crop a Mat, you have to use an Image object as a buffer and use its .ROI property:

Mat crop_color_frame(Mat input, Rectangle crop_region)
{
  /*
   * TODO(Ahmed): Figure out why I had to copy this into this class.
   * */
  Image<Bgr, Byte> buffer_im = input.ToImage<Bgr, Byte>();
  buffer_im.ROI = crop_region;

  Image<Bgr, Byte> cropped_im = buffer_im.Copy();

  return cropped_im.Mat;

}


问:
A problem occurred somewhere in the SSL/TLS handshake
I've been having problems on my development server where cURL, while working perfectly with anything HTTP, does not function properly with anything HTTPS—even the exact same resource with different protocols (for testing I've been requesting google.com using both HTTP and HTTPS).

The cURL error returned is 35:

A problem occurred somewhere in the SSL/TLS handshake.

I have combed the web and SO for solutions, and all of them have been to either set CURLOPT_SSL_VERIFYPEER to false, which changes nothing, or to download the certificate file and set CURLOPT_CAINFO to its path, which also changes nothing.

When setting a certificate, I followed the instructions of this tutorial and this tutorial, trying to both download the certificate for the resource I'm requesting, and downloading a cert bundle.

I've also tried explicitly setting CURLOP_PORT to 443. For thoroughness of my question, other options I set are CURLOPT_VERBOSE=true, CURLOPT_RETURNTRANSFER=true, and CURLOPT_SSL_VERIFYHOST=2 (I've tried every combination of 1, and 2 with VERIFYPEER both true and false). I also have made sure in phpinfo() that I have OpenSSL and it is enabled.

I'm using a lot of old code that worked perfectly on my last production server, so this code has worked before. But that hosting was shared hosting and I don't know most of the configuration there.

答:
Find if your OS includes a directory of certificates.  If so then the required CA certs will often already be included.  On Ubuntu, for example, it's usually /etc/ssl/certs.  If this directory exists, set the CA path parameter:

```<code>curl_setopt($ch, CURLOPT_CAPATH, '/etc/ssl/certs');
</code>```

Alternatively you can reference a single CA certificate file.  Include a cacert.pem file in your project or install it on your server.  Download from a trusted source, e.g. cacert.org.  For a single file do not set the CAPATH and instead only set CAINFO:

```<code>curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cacert.pem');
</code>```

Turning off peer and host verification is a quick but insecure workaround to the real problem.  These features exist for good reason: so you can trust, via 3rd party, that the system you're connecting to is the one you expect.

```<code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Find if your OS includes a directory of certificates.  If so then the required CA certs will often already be included.  On Ubuntu, for example, it's usually /etc/ssl/certs.  If this directory exists, set the CA path parameter:

curl_setopt($ch, CURLOPT_CAPATH, '/etc/ssl/certs');

Alternatively you can reference a single CA certificate file.  Include a cacert.pem file in your project or install it on your server.  Download from a trusted source, e.g. cacert.org.  For a single file do not set the CAPATH and instead only set CAINFO:

curl_setopt($ch, CURLOPT_CAINFO, '/path/to/cacert.pem');

Turning off peer and host verification is a quick but insecure workaround to the real problem.  These features exist for good reason: so you can trust, via 3rd party, that the system you're connecting to is the one you expect.

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);


问:
What are some example javascript frameworks that people use?
I am really big fan of jQuery, but I don't see it as a framework for a site, more like a library.  I am looking for some sort of framework that will give me the tools to build really structured applications in javaScript.  I have found backbone.js, but find it somewhat confusing.  Is that a good one, and are there others similar to it?  an MVC pattern would be really cool, but I havent found anything.</p>

答: The Google Closure Library & Tools is pretty good, and is the framework they use to build Gmail, Google Maps, and so on.</p>


问:
How to improve/minimize varying response time of api
I created a rest api and I am not very happy with the performance of it. I spent some time to investigate and stumbled across a tool to easily track the performance of my api (www.apiscience.com).

They split the overall response time in 4 categories- connect, resolve, processing and transfer. The resolve part often takes about 150ms while the processing of the call itself only takes about 18ms which results in an average response time of 160ms (the call i tried here is really simple so the average would be higher normally).

My question is how can I improve/minimize the resolve time for my calls?

(side info: my servers are placed in Ireland and I chose Ireland as location for the tests too)

Thanks in advance!

Edit - What do they mean with Resolve Time?
(https://www.apiscience.com/blog/what-do-api-sciences-curl-based-timings-mean/)

API Science’s “Resolve Time” is the equivalent of Ken’s “DNS Lookup.”
  DNS stands for Domain Name System. A URL consists of text (and
  sometimes numbers); however, the communication addresses that compose
  the Internet are formulated as IP (Internet Protocol) addresses, for
  example, 208.80.152.2. Before a request can be routed between the
  requesting client and the server that will process the request, the IP
  address that the URL refers must be looked up. A request is sent to a
  DNS resolver by curl, and the resolver returns the correlated IP
  address. API Science’s “Resolve Time” is the time in milliseconds that
  it took this operation to complete.

答:
As the documentation mentions, the DNS resolution time is the amount of time an API consuming client waits before finding out where to route the actual calls to your API server - the mapping between your server's name and IP address.

Where you host your DNS can be completely independent from both where you host your API service, and where your domain name is registered, and there are multiple choices in the market for DNS hosting service. DNSPerf (of which I have no affiliation) does a comparison of services and is probably a good starting point for further research if you'd like to select a new DNS provider.


问:
background color not shown when there is image
I am trying to create a canvas where user can either add background image or background color and write a text over them. However i could not show background color when there is background image. I have created a fiddle of that to show an example. You can try add image and add color button in the fiddle.

http://jsbin.com/sukuvoqahi/edit?html,js,output

Here is my code

```<code>const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('image');
  canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
    canvasRef.renderAll();
  });
});

addBackgroundColor.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('color');
  canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
  })
});
</code>```

答:
Set backgroundImage property to null or 0 for the canvas (canvasRef), before setting the background color ...

const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
   e.preventDefault();
   console.log('image');
   canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
      canvasRef.renderAll();
   });
});

addBackgroundColor.addEventListener('click', (e) => {
   e.preventDefault();
   console.log('color');
   canvasRef.backgroundImage = null; //or set 0
   canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
      canvasRef.renderAll();
   })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas" width="350" height="350" style="border:1px solid #000000">
</canvas>
<button id="addImage">Add Image</button>
<button id="addBackgroundColor">Add Color</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script></code>```

Body:
I am trying to create a canvas where user can either add background image or background color and write a text over them. However i could not show background color when there is background image. I have created a fiddle of that to show an example. You can try add image and add color button in the fiddle.

http://jsbin.com/sukuvoqahi/edit?html,js,output

Here is my code

const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('image');
  canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
    canvasRef.renderAll();
  });
});

addBackgroundColor.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('color');
  canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
    canvasRef.renderAll();
  })
});

Body:
Set backgroundImage property to null or 0 for the canvas (canvasRef), before setting the background color ...

const canvasRef = new fabric.Canvas('canvas');

const addImage = document.querySelector('#addImage');

const addBackgroundColor = document.querySelector('#addBackgroundColor');

addImage.addEventListener('click', (e) => {
   e.preventDefault();
   console.log('image');
   canvasRef.setBackgroundImage('https://www.cesarsway.com/sites/newcesarsway/files/styles/large_article_preview/public/Common-dog-behaviors-explained.jpg', () => {
      canvasRef.renderAll();
   });
});

addBackgroundColor.addEventListener('click', (e) => {
   e.preventDefault();
   console.log('color');
   canvasRef.backgroundImage = null; //or set 0
   canvasRef.setBackgroundColor('rgb(100,100,100)', () => {
      canvasRef.renderAll();
   })
});

<canvas id="canvas" width="350" height="350" style="border:1px solid #000000">
</canvas>
<button id="addImage">Add Image</button>
<button id="addBackgroundColor">Add Color</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>


问:
How to get closest n rows for specific row in table?
I have a table foo with its primary key id and some other columns.
My goal is to find for instance rows with id=3 and id=4 and rows with id=6 and id=7 for row with id=5 - in case I would like to find 2 closest previous and next rows.

In case there is only one or no such rows (e.g. for id=2 there is only previous row) I would like to get only possible ones.

The problem is there can be some rows missing.

Is there a common practice to make such queries?

答:
This is a possible solution by numbering all the records and fetching those where row number is 2 rows greater or lower than the selected ID.

```<code>create table foo(id int);
insert into foo values (1),(2),(4),(6),(7),(8),(11),(12);
</code>```

```<code>-- using ID = 6

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 6) - 2
and    rn <= (select rn from rnum where id = 6) + 2;
</code>```

```
id | rn
-: | -:
 2 |  2
 4 |  3
 6 |  4
 7 |  5
 8 |  6
```

```<code>-- using ID = 2

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 2) - 2
and    rn <= (select rn from rnum where id = 2) + 2;
</code>```

```
id | rn
-: | -:
 1 |  1
 2 |  2
 4 |  3
 6 |  4
```

dbfiddle here

Body:
This is a possible solution by numbering all the records and fetching those where row number is 2 rows greater or lower than the selected ID.

create table foo(id int);
insert into foo values (1),(2),(4),(6),(7),(8),(11),(12);

-- using ID = 6

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 6) - 2
and    rn <= (select rn from rnum where id = 6) + 2;

id | rn
-: | -:
 2 |  2
 4 |  3
 6 |  4
 7 |  5
 8 |  6

-- using ID = 2

with rnum as
(
    select id, row_number() over (order by id) rn
    from foo
)
select *
from   rnum
where  rn >= (select rn from rnum where id = 2) - 2
and    rn <= (select rn from rnum where id = 2) + 2;

id | rn
-: | -:
 1 |  1
 2 |  2
 4 |  3
 6 |  4

dbfiddle here


问:
Prolog - count occurrence of number
I want to write predicate which can count all encountered number:

```<code>count(1, [1,0,0,1,0], X).
X = 2.
</code>```

I tried to write it like:

```<code>count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.
</code>```

Why doesn't work it?

答:
You simply let the predicate fail at the unification Num = X. Basically, it's like you don't accept terms which are different from the only one you are counting.

I propose to you this simple solution which uses tail recursion and scans the list in linear time. Despite the length, it's very efficient and elegant, it exploits declarative programming techniques and the backtracking of the Prolog engine.

```<code>count(C, L, R) :-
    count(C, L, 0, R).

count(_, [], Acc, Acc).
count(C, [C|Xr], Acc, R) :-
    IncAcc is Acc + 1,
    count(C, Xr, IncAcc, R).
count(C, [X|Xr], Acc, R) :-
    dif(X, C),
    count(C, Xr, Acc, R).
</code>```

count/3 is the launcher predicate. It takes the term to count, the list and gives to you the result value.
The first count/4 is the basic case of the recursion.
The second count/4 is executed when the head of the list is unified with the term you are looking for.
The third count/4 is reached upon backtracking: If the term doesn’t match, the unification fails, you won't need to increment the accumulator.

Acc allows you to scan the entire list propagating the partial result of the recursive processing. At the end you simply have to return it.

Title: Prolog - count occurrence of number

Body:
I want to write predicate which can count all encountered number:

count(1, [1,0,0,1,0], X).
X = 2.

I tried to write it like:

count(_, [], 0).
count(Num, [H|T], X) :- count(Num, T, X1), Num = H, X is X1 + 1.

Why doesn't work it?

Body:
You simply let the predicate fail at the unification Num = X. Basically, it's like you don't accept terms which are different from the only one you are counting.

I propose to you this simple solution which uses tail recursion and scans the list in linear time. Despite the length, it's very efficient and elegant, it exploits declarative programming techniques and the backtracking of the Prolog engine.

count(C, L, R) :-
    count(C, L, 0, R).

count(_, [], Acc, Acc).
count(C, [C|Xr], Acc, R) :-
    IncAcc is Acc + 1,
    count(C, Xr, IncAcc, R).
count(C, [X|Xr], Acc, R) :-
    dif(X, C),
    count(C, Xr, Acc, R).

count/3 is the launcher predicate. It takes the term to count, the list and gives to you the result value.
The first count/4 is the basic case of the recursion.
The second count/4 is executed when the head of the list is unified with the term you are looking for.
The third count/4 is reached upon backtracking: If the term doesn’t match, the unification fails, you won't need to increment the accumulator.

Acc allows you to scan the entire list propagating the partial result of the recursive processing. At the end you simply have to return it.


问:
How to handle "don't allow" permission in iMessage extension?
I am developing one iMessage Extension in which I need to use photos from Photo Library, but here it generated one use case for which I am not getting any solution.

When OS ask for Photo permission access to user, then user set Don't allow, after that how to set permission on for iMessage Extension.

But I am not able to find settings menu for iMessage Extension app from which user set photo permission on.

NOTE: I am developing iMessage Extension without parent iOS App.

答:
You can enable this permission later from privacy setting. Please check below path to enable that permission

Settings -> Privacy -> Photos -> < Your app >


答:
I think this would fit your description.</p>

```<code>Select * from table where id between @n-2 and @n+2 and id <> @n
</code>```

Title: How to get closest n rows for specific row in table?

Body:
I have a table foo with its primary key id and some other columns.
My goal is to find for instance rows with id=3 and id=4 and rows with id=6 and id=7 for row with id=5 - in case I would like to find 2 closest previous and next rows.

In case there is only one or no such rows (e.g. for id=2 there is only previous row) I would like to get only possible ones.

The problem is there can be some rows missing.

Is there a common practice to make such queries?

Body:
I think this would fit your description.

Select * from table where id between @n-2 and @n+2 and id <> @n


答:
Enjoy:</p>

```<code>result = []

for code, dct in your_json.items():
    yrken = []
    for c, antal in dct.items():
        yrken.append({
            "code": c,
            "antal": antal
        })
    result.append({
        "sni": {
            "code": code,
            "yrken": yrken
        }
    })

print(result)
</code>```

Title: Python output dict to new json structure

Body:
I am new to Python and have run into a problem that I have not been able to solve despite a lot of searching and reading related posts.  Any help is much appreciated:
I have imported a json file into a dictionary that has this structure:

{
 "23991": {
 "5115": 10,
 "2611": 22
 },
 "43223": {
 "7252": 11,
 "4302": 2
 }
}

I want to save it to a new json file with this structure:

[
 {
  "sni": {
   "code": "23991",
   "yrken": [
     {
       "code": "5115",
       "antal": 10
     },
     {
       "code": "2611",
       "antal": 22
     }
   ]
  }
},
{
  "sni": {
   "code": "43223",
   "yrken": [
     {
       "code": "7252",
       "antal": 11
     },
     {
       "code": "4302",
       "antal": 11
     }
   ]
  }
 }
]

So far I have this code:

import os
import sys
import json

pathSNI2Yrke = "Smallsni2Yrke.json"
with open(pathSNI2Yrke) as data_file:
sni2Yrke = json.load(data_file)
#print(sni2Yrke)

for key in sni2Yrke:
    value = sni2Yrke[key]
    d = [{"sni":
          {"snicode": key,
           "yrken": [{ "yrkecode":list(value.keys()),
                      "antal": list(value.values())}]}}]
    j = json.dumps(d, indent=2)
    #f = open('sample.json', 'w')
    print ( j)

Which gives me this result:

[
{
  "sni": {
   "snicode": "23991",
   "yrken": [
     {
      "yrkecode": [
        "5115",
        "2611"
       ],
      "antal": [
        10,
        22
       ]
     }
    ]
  }
 }
]
[
 {
  "sni": {
   "snicode": "43223",
   "yrken": [
     {
      "yrkecode": [
        "7252",
        "4302"
       ],
       "antal": [
         11,
         2
       ]
     }
    ]
   }
  }
]

As you see this isn't a correct json structure, and for the life of me I can't figure out how to get the structure right. The output goes all the way back to the root element so I get ...][... instead of ...},{.... between the "sni" blocks
If you have tips on how the code could be better or a better way of achieving the result please let me have them.

Body:
Enjoy:

result = []

for code, dct in your_json.items():
    yrken = []
    for c, antal in dct.items():
        yrken.append({
            "code": c,
            "antal": antal
        })
    result.append({
        "sni": {
            "code": code,
            "yrken": yrken
        }
    })

print(result)


问:
Set the value of a global variable in a function
I'm currently working on an SAP Fiori app that consumes an OData service.

I created a method in my controller fonct that calculates a variable coming from my OData.

I want to capture this value and put it in a global variable every time the view is refreshed.

I created a global variable like this:

```<code>var boo1;
return Controller.extend("com.controller.Detail", {...});
</code>```

and I passed boo1 as a parameter in my method fonct inside my onInit method but it is undefined.

Here's a snippet of my controller's code:

```<code>sap.ui.define([
    "com/util/Controller"
], function(Controller) {
    "use strict";

    var boo1;
    return Controller.extend("com.controller.Detail", {
        onInit: function() {
            this.fonct(boo1);
            alert(boo1);
        },

        fonct: function(ovar) {
            var that = this;
            var oModel = that.getView().getModel();
            oModel.read("/alertSet", {
                success: function(data) {
                    var a = JSON.stringify(data);
                    var b = a.slice(332,-4);
                    ovar = b;
                }
            });
        }

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

答:
Please, avoid defining global variables (such as before sap.ui.define) especially if you are working on apps that are going to be placed into the Fiori Launchpad. This approach is considered harmful. This is also repeated in the documentation:

In control and class modules, you should not use global variables at all.(src)

We're using "use strict" purposely to disallow such practices.

Also, defining properties or adding models on sap.ui.getCore() is an anti-pattern for Fiori apps. Not only does this lead to the same flaws as defining global variables but models set on the core are not propagated to the views by default because components are meant to be used modularly. Therefore, defining such data to the corresponding component instead of the core is the way to go for Fiori apps.

==> FLP Best Practices

I created a global variable

```<code>var boo1;
return Controller.extend("com.controller.Detail", {...});
</code>```

What you created though was not a global variable since boo1 was declared inside an anonymous function. Instead, boo1 was stored in a closure which allowed the prototype methods (onInit and fonc) to maintain the lexical environment within which boo1 was made accessible not only by the methods but also by other instances of com.controller.Detail. In terms of Java, we can say that boo1 is a private static variable. But it's not a global variable.

That being said..

I passed boo1 as a parameter in my method fonct inside my onInit method but it is undefined

The closure makes passing boo1 as an argument unnecessary (unless you want a hard copy of boo1 to maintain multiple states of it). The method fonct can access boo1 directly, even in the anonymous callbacks defined in fonct.

Now, you may be asking why boo1 was undefined. There are two reasons:

boo1 was undefined before calling fonct. If boo1 were an object instead of undefined, then ovar would have been a reference to the boo1 object and the change to any ovar property would have took place in the boo1 object. But undefined is not an object. So ovar doesn't know what boo1 is at all. Note: The evaluation strategy of JS is "Call by object-sharing".

alert(boo1) gets fired right after calling fonct. Unless oModel works synchronously (which I strongly recommend not to do so), the browser doesn't wait for the success callback to get fired in order to invoke alert(boo1) later. The alert is fired immediately, and then the success callback where boo1 should be manipulated.

Removing ovar and using boo1 instead updates boo1 properly in the success callback.

```<code>fonct: function(/*no ovar*/) {
    //...
    oModel.read("/alertSet", {
        success: function(data) {
            //...
            boo1 = /*new value*/;
            alert(boo1);
        }.bind(this)
    });
}
</code>```

Body:
I'm currently working on an SAP Fiori app that consumes an OData service.

I created a method in my controller fonct that calculates a variable coming from my OData.

I want to capture this value and put it in a global variable every time the view is refreshed.

I created a global variable like this:

var boo1;
return Controller.extend("com.controller.Detail", {...});

and I passed boo1 as a parameter in my method fonct inside my onInit method but it is undefined.

Here's a snippet of my controller's code:

sap.ui.define([
    "com/util/Controller"
], function(Controller) {
    "use strict";

    var boo1;
    return Controller.extend("com.controller.Detail", {
        onInit: function() {
            this.fonct(boo1);
            alert(boo1);
        },

        fonct: function(ovar) {
            var that = this;
            var oModel = that.getView().getModel();
            oModel.read("/alertSet", {
                success: function(data) {
                    var a = JSON.stringify(data);
                    var b = a.slice(332,-4);
                    ovar = b;
                }
            });
        }

    });
});

Body:
Please, avoid defining global variables (such as before sap.ui.define) especially if you are working on apps that are going to be placed into the Fiori Launchpad. This approach is considered harmful. This is also repeated in the documentation:

In control and class modules, you should not use global variables at all.(src)

We're using "use strict" purposely to disallow such practices.

Also, defining properties or adding models on sap.ui.getCore() is an anti-pattern for Fiori apps. Not only does this lead to the same flaws as defining global variables but models set on the core are not propagated to the views by default because components are meant to be used modularly. Therefore, defining such data to the corresponding component instead of the core is the way to go for Fiori apps.

==> FLP Best Practices

I created a global variable

var boo1;
return Controller.extend("com.controller.Detail", {...});

What you created though was not a global variable since boo1 was declared inside an anonymous function. Instead, boo1 was stored in a closure which allowed the prototype methods (onInit and fonc) to maintain the lexical environment within which boo1 was made accessible not only by the methods but also by other instances of com.controller.Detail. In terms of Java, we can say that boo1 is a private static variable. But it's not a global variable.

That being said..

I passed boo1 as a parameter in my method fonct inside my onInit method but it is undefined

The closure makes passing boo1 as an argument unnecessary (unless you want a hard copy of boo1 to maintain multiple states of it). The method fonct can access boo1 directly, even in the anonymous callbacks defined in fonct.

Now, you may be asking why boo1 was undefined. There are two reasons:

boo1 was undefined before calling fonct. If boo1 were an object instead of undefined, then ovar would have been a reference to the boo1 object and the change to any ovar property would have took place in the boo1 object. But undefined is not an object. So ovar doesn't know what boo1 is at all. Note: The evaluation strategy of JS is "Call by object-sharing".

alert(boo1) gets fired right after calling fonct. Unless oModel works synchronously (which I strongly recommend not to do so), the browser doesn't wait for the success callback to get fired in order to invoke alert(boo1) later. The alert is fired immediately, and then the success callback where boo1 should be manipulated.

Removing ovar and using boo1 instead updates boo1 properly in the success callback.

fonct: function(/*no ovar*/) {
    //...
    oModel.read("/alertSet", {
        success: function(data) {
            //...
            boo1 = /*new value*/;
            alert(boo1);
        }.bind(this)
    });
}


问:
Xampp localhost not working
I am running laravel on xampp and I have problem with accessing pages,
http://localhost/laravel/public/ I get a login page which is good
however when I go for example http://localhost/laravel/public/smokeyard

I get 404 error with The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

Route:

```<code>Route::get('smokeyard', 'GuzzleController@smokeyard');
</code>```

Controller:

```<code>function smokeyard(){
    return view('smokeyard');
}
</code>```

All my views are located in resources folder.

答:
if you want to access laravel project without running artisan serve, you need to change few settings,

copy the .htaccess file from the public folder and paste it in the root folder of your application

rename the server.php in the root directory to index.php

now go to localhost/your_project_name/smokeyard for the url you want to check

hope this helps

Title: Xampp localhost not working

Body:
I am running laravel on xampp and I have problem with accessing pages,
http://localhost/laravel/public/ I get a login page which is good
however when I go for example http://localhost/laravel/public/smokeyard

I get 404 error with The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

Route:

Route::get('smokeyard', 'GuzzleController@smokeyard');

Controller:

function smokeyard(){
    return view('smokeyard');
}

All my views are located in resources folder.


问:
Validating string date without using java.util.Date class in Java
This question was ask me in one of interview "How can we validate (Valid or invalid) string date in java without using java.util.date class.Dateformat could be in any form i.e. dd-MM-yyyy,yyyy-dd-MM and so on.".Please help if anyone have idea.TIA

答:
The simplest solution would be to parse java.util.Date to java.time.LocalDate then you have a standard yyyy-mm-dd. this should be easy to validate. Can you identify the source of your date object? If you can obtain a calendar object fro you source or from the date object then this method I wrote should help with the parsing.</p>

```<code>/**
 *  Utility method that parses java.util.Date to java 8's java.time.LocalDat
 * <p>
 * TODO finish method design
 *
 * @param calendarObj
 * @return
 */
public static LocalDate parseCalendarToLocalDate(Calendar calendarObj) {

    int month = calendarObj.get(Calendar.MONTH);
    int year = calendarObj.get(Calendar.YEAR);
    int day = calendarObj.get(Calendar.DAY_OF_MONTH);

    LocalDate localDateObj =  LocalDate.of(year,(month+1),day);
    return localDateObj;
}
</code>```

Body:
The simplest solution would be to parse java.util.Date to java.time.LocalDate then you have a standard yyyy-mm-dd. this should be easy to validate. Can you identify the source of your date object? If you can obtain a calendar object fro you source or from the date object then this method I wrote should help with the parsing.

/**
 *  Utility method that parses java.util.Date to java 8's java.time.LocalDat
 * <p>
 * TODO finish method design
 *
 * @param calendarObj
 * @return
 */
public static LocalDate parseCalendarToLocalDate(Calendar calendarObj) {

    int month = calendarObj.get(Calendar.MONTH);
    int year = calendarObj.get(Calendar.YEAR);
    int day = calendarObj.get(Calendar.DAY_OF_MONTH);

    LocalDate localDateObj =  LocalDate.of(year,(month+1),day);
    return localDateObj;
}


问:
Powershell, How to match files names with partial names stored in text file
Sorry for the dump question as I am a beginner in PowerShell. We have a lot of coming files into a directory, and they are always increasing and decreasing in that directory because it is moved to another directory after we are done from using them.

We have a priority file list in a txt file which has only partial name of the file name.

For example, for the file name:

2017-06-5---666-12-05-01.txt

In the priority list, I have the partial name as ---666---.

How can I check if the files in the folder are already in the priority list by using Powershell?

I wrote the below script since I need only the files which are older than a given time. But it is not working.

```<code>Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -contains "*$PriorityList*"} |
ForEach-Object { $counterP++}
</code>```

答:
First of all, the file name in your example doesn't match the partial name. So let's assume that pattern is "666". If you have several patterns, you can join them in one filter:

```<code>$PriorityList = "---666---","---555---"
$PriorityFilter = $PriorityList -join '|'
</code>```

Then use this filter to check Name property:

```<code>Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -match $PriorityFilter |
ForEach-Object { $counterP++}
</code>```

The -contains operator works with a collection as left operand and do not accept wildcards for matching.

Body:
Sorry for the dump question as I am a beginner in PowerShell. We have a lot of coming files into a directory, and they are always increasing and decreasing in that directory because it is moved to another directory after we are done from using them.

We have a priority file list in a txt file which has only partial name of the file name.

For example, for the file name:

2017-06-5---666-12-05-01.txt

In the priority list, I have the partial name as ---666---.

How can I check if the files in the folder are already in the priority list by using Powershell?

I wrote the below script since I need only the files which are older than a given time. But it is not working.

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -contains "*$PriorityList*"} |
ForEach-Object { $counterP++}

Body:
First of all, the file name in your example doesn't match the partial name. So let's assume that pattern is "666". If you have several patterns, you can join them in one filter:

$PriorityList = "---666---","---555---"
$PriorityFilter = $PriorityList -join '|'

Then use this filter to check Name property:

Get-ChildItem -path $Struct.Path  -filter $Struct.filter |
Where-Object {$_.CreationTime -lt $time} |
Where-Object {$_.Name -match $PriorityFilter |
ForEach-Object { $counterP++}

The -contains operator works with a collection as left operand and do not accept wildcards for matching.


问:
What measurement do you use in your development process to determine *Doneness* of your software?
I just finished listening to a very eye-opening podcast on Hanselminutes about the definition of "Done". So my question to everyone is "When do you consider a piece of software to be "Done"? Is it when it's fully unit tested? Is it when it's completely documented? What measurement do you use in your development process to determine Doneness of your software?

答:
When the software can be used to satisfy the requirements that define the system.

But I've always thought, "software is never done, it just reaches an acceptable level of incompleteness."

OwnerDisplayName: Micah


问:
jsonp and POST action
I know from reading on here that it is not possible to do a cross domain POST action using jsonp and javascript.
But I have to write back data to a web service that's on a different domain using javascript - how do others do it? Just hack it and use a GET action?</p>

答: I've ended up just using a GET method and sending my details back. Not the way REST is supposed to be used but on investigation this is what a number of other web sites seem to do.</p>

Title: jsonp and POST action


问:
JavaScript runtime error: Unable to add dynamic content
I'm making a javascript metro app and have some code like this:

```<code>    <script>
       document.writeln(foo());//this line is trouble
    </script>
</code>```

and when I tried to run, it gave me a rather long error:

Unhandled exception at line 20, column 9 in ms-appx://a375ffac-3b69-475a-bd53-ee3c1ccf4c4e/default.html

0x800c001c - JavaScript runtime error: Unable to add dynamic content.
  A script attempted to inject dynamic content, or elements previously
  modified dynamically, that might be unsafe. For example, using the
  innerHTML property to add script or malformed HTML will generate this
  exception. Use the toStaticHTML method to filter dynamic content, or
  explicitly create elements and attributes with a method such as
  createElement.  For more information, see
  http://go.microsoft.com/fwlink/?LinkID=247104.

How can I get around this?

答:
Windows 8 store apps have a restriction on placing dynamic content inside innerHTML attribute. To fix this you need to include winstore-jscompat.js file from following location in your page as first reference. Please see this link to know more about winstore-jscompat.

This file is not required on Windows 10.

Body:
I'm making a javascript metro app and have some code like this:

and when I tried to run, it gave me a rather long error:

Unhandled exception at line 20, column 9 in ms-appx://a375ffac-3b69-475a-bd53-ee3c1ccf4c4e/default.html

0x800c001c - JavaScript runtime error: Unable to add dynamic content.
  A script attempted to inject dynamic content, or elements previously
  modified dynamically, that might be unsafe. For example, using the
  innerHTML property to add script or malformed HTML will generate this
  exception. Use the toStaticHTML method to filter dynamic content, or
  explicitly create elements and attributes with a method such as
  createElement.  For more information, see
  http://go.microsoft.com/fwlink/?LinkID=247104.

How can I get around this?


问:
Why do razor pages return a Task<IActionResult> rather than an IActionResult?
Razor Pages are introduced in Asp.Net Core 2.0 as way to create page centric web applications and in many ways are easier to write than the typical controller, view, model approach.  I've been studying the documentation at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ and one of the things I find curious is that the action methods in the code-behind file utilize the async await pattern and therefore return a Task<IActionResult> rather than returning IActionResult the way a standard Asp.Net Core action method does. I find it odd because this approach is more complex than the approach used by a standard Asp.Net Core action method and that seems to run contrary to the design simplicity of Razor Pages.

Modified example from that source:

```<code>  public class ContactModel : PageModel {

    public async Task<IActionResult> OnPostAsync() {
        //Other code omitted

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

For comparision, in a regular Asp.Net Core Controller this same code would look like:

```<code> public class Contact: Controller {

    [HttpPost]
    public IActionResult OnPost() {
        //Other code omitted

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

Why does the Razor Pages action method use the async await pattern returning a Task<IActionResult> rather than using the simpler approach that the regular Asp.Net core action methods uses by simply returning a IActionResult?  Why was such a design choice made?

答:
I believe the example you reference is asynchronous but that is not stopping you from creating an action that is synchronous by just using the same signature as in your 2nd code block (not sure about the HttpPostAttribute though as it looks like its naming convention).

```<code>public IActionResult OnPost() {  /* code here */ }
</code>```

Body:
Razor Pages are introduced in Asp.Net Core 2.0 as way to create page centric web applications and in many ways are easier to write than the typical controller, view, model approach.  I've been studying the documentation at https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ and one of the things I find curious is that the action methods in the code-behind file utilize the async await pattern and therefore return a Task<IActionResult> rather than returning IActionResult the way a standard Asp.Net Core action method does. I find it odd because this approach is more complex than the approach used by a standard Asp.Net Core action method and that seems to run contrary to the design simplicity of Razor Pages.

Modified example from that source:

  public class ContactModel : PageModel {

    public async Task<IActionResult> OnPostAsync() {
        //Other code omitted

        return Page();
    }
  }

For comparision, in a regular Asp.Net Core Controller this same code would look like:

 public class Contact: Controller {

    [HttpPost]
    public IActionResult OnPost() {
        //Other code omitted

        return View();
    }
 }

Why does the Razor Pages action method use the async await pattern returning a Task<IActionResult> rather than using the simpler approach that the regular Asp.Net core action methods uses by simply returning a IActionResult?  Why was such a design choice made?

Body:
I believe the example you reference is asynchronous but that is not stopping you from creating an action that is synchronous by just using the same signature as in your 2nd code block (not sure about the HttpPostAttribute though as it looks like its naming convention).

public IActionResult OnPost() {  /* code here */ }


问:
Twilio incoming call not working in android voice sdk
i have used android voice sdk
github link

if i click call button i am getting congratulatory message and not showing any notification like incoming call. Please help i am doing this from long time.

in twilio site it is showing correct but not getting incoming calls.

答:
Twilio developer evangelist here.

The basics of the Quickstart application get you to the point that you make an outgoing call and the example TwiML Application returns a congratulations voice message, as you've discovered.

You now have to build on top of this in order to place calls to other clients.

First you need to update the server application so that you pass an identity to it rather than using the default.

Then you need to add a UI within your own application that can give you a choice of clients to dial. I don't know what your app does, so you need to figure how you want to display this to users yourself. You could just give them a free text field to type the name of another client into or list all active users.

You'll then need to pass the client name you want to call into the parameters when you create the call.

You will also need to update the server route to receive those parameters and place the call to the other client.

To cover all of this, I recommend following the full quickstart tutorial for Twilio Programmable Voice on Android.


问:
Resolving macro variable inside PROC SQL
I have a macro variable I need to use within PROC SQL. The way it resolves appears to have perfect syntax, but I am getting a syntax error and I'm not sure why;

```<code>%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = %bquote('&test')
;QUIT;
</code>```

The error I get throws a red line under the resolved text, 'mytext', and says

ERROR 22-322: Syntax error, expecting one of the following: a name, a
  quoted string, a numeric constant, a datetime constant,
                a missing value, (, *, +, -, ALL, ANY, BTRIM, CALCULATED, CASE, INPUT, PUT, SELECT, SOME, SUBSTRING, TRANSLATE,
                USER.

I don't feel like this error applies here. If I hard code in 'mytext' it works fine. Am I missing something right under my nose? Can anyone lend me a hand?

Thanks!!!

答:
The BQUOTE function tries to resolve the value immediately at execution time.  Try removing it and using double quotes instead:</p>

```<code>%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = "&test"
;QUIT;
</code>```

Body:
I have a macro variable I need to use within PROC SQL. The way it resolves appears to have perfect syntax, but I am getting a syntax error and I'm not sure why;

%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = %bquote('&test')
;QUIT;

The error I get throws a red line under the resolved text, 'mytext', and says

ERROR 22-322: Syntax error, expecting one of the following: a name, a
  quoted string, a numeric constant, a datetime constant,
                a missing value, (, *, +, -, ALL, ANY, BTRIM, CALCULATED, CASE, INPUT, PUT, SELECT, SOME, SUBSTRING, TRANSLATE,
                USER.

I don't feel like this error applies here. If I hard code in 'mytext' it works fine. Am I missing something right under my nose? Can anyone lend me a hand?

Thanks!!!

Body:
The BQUOTE function tries to resolve the value immediately at execution time.  Try removing it and using double quotes instead:

%let test = mytext;
PROC SQL;
CREATE TABLE myTalbe&test AS
SELECT DISTINCT
    a.column
FROM
    tablename a
WHERE
    a.column = "&test"
;QUIT;


问:
Updating SQL database table using WPF datagrid
I'm new to WPF and I'm trying to have a datagrid automatically update a table in a local SQL database when a user edits it.

I feel like I'm close as I've gotten the insert to work, but I can't figure out the update(or the delete, but I haven't looked into that much yet).

I'm using a table adapter for the grid which calls a stored procedure for the update command. My problem is that when I call the update command for it in the CurrentCellChanged event, it is not passing in the ID parameter for the stored procedure, so the update fails.

Here is the relevant code behind for the WPF xaml.vb page:

```<code>Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("AARP_Conn").ToString)
' construct the dataset
Dim dataset As New AARPDataSet
' use a table adapter to populate the Customers table
Dim adapter As New AARPDataSetTableAdapters.tblRiskTiersTableAdapter

Private Sub _grdRiskTiers_CurrentCellChanged(sender As Object, e As EventArgs) Handles _grdRiskTiers.CurrentCellChanged
    'this line gets error: upRiskTier expects parameter @ID, which was not supplied.
    adapter.Update(dataset.tblRiskTiers)
End Sub

Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

        adapter.Fill(dataset.tblRiskTiers)

        ' use the dataset  as the DataContext for this Window
        Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub
</code>```

Here is the datagrid markup:

```<code><DataGrid x:Name="_grdRiskTiers" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="45,20,0,0" VerticalAlignment="Top" Height="199" Width="192" Grid.ColumnSpan="2">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding ID}" ></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding LowTierCreditScore}" Header="Low Tier Credit Score"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>
</code>```

And here is the stored procedure for updating:

```<code>CREATE PROCEDURE [dbo].[upRiskTier]
    @ID as int,
    @NewLowTierCreditScore as int
AS
IF EXISTS(SELECT * FROM tblRiskTiers WHERE LowTierCreditScore = @NewLowTierCreditScore) BEGIN
    DELETE FROM tblRiskTiers WHERE ID = @ID
END ELSE BEGIN
    UPDATE tblRiskTiers SET LowTierCreditScore = @NewLowTierCreditScore
    WHERE ID = @ID
END
</code>```

How can I get the update command to pass in the ID to the stored procedure?

UPDATE: The following updated code resolved my issue

```<code>Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

adapter.Fill(dataset.tblRiskTiers)

Dim command = New SqlCommand("[dbo].[upRiskTier]")
command.CommandType = System.Data.CommandType.StoredProcedure
command.Connection = oConn
command.Parameters.Add("@ID", System.Data.SqlDbType.Int, 5, "ID")
command.Parameters.Add("@NewLowTierCreditScore", System.Data.SqlDbType.Int, 5, "LowTierCreditScore")
adapter.Adapter.UpdateCommand = command
' use the Customer table as the DataContext for this Window
Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub
</code>```

答:
This error 'this line gets error: upRiskTier expects parameter @ID, which was not supplied.' mean  - your adapter doesn't configured properly.. There aren't relations between column and parameters in your adapter.UpdateCommand...

In next example show how to set relations between columns in DataTable and command parameters. Check your code where you configure SqlDataAdapter.

```<code>   // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;
</code>```

In your case - your command should be

```<code>command = new SqlCommand("[dbo].[upRiskTier]");
command.CommandType = CommandType.StoredProcedure;
</code>```

More detailed you can see in article on MSDN

Body:
I'm new to WPF and I'm trying to have a datagrid automatically update a table in a local SQL database when a user edits it.

I feel like I'm close as I've gotten the insert to work, but I can't figure out the update(or the delete, but I haven't looked into that much yet).

I'm using a table adapter for the grid which calls a stored procedure for the update command. My problem is that when I call the update command for it in the CurrentCellChanged event, it is not passing in the ID parameter for the stored procedure, so the update fails.

Here is the relevant code behind for the WPF xaml.vb page:

Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("AARP_Conn").ToString)
' construct the dataset
Dim dataset As New AARPDataSet
' use a table adapter to populate the Customers table
Dim adapter As New AARPDataSetTableAdapters.tblRiskTiersTableAdapter

Private Sub _grdRiskTiers_CurrentCellChanged(sender As Object, e As EventArgs) Handles _grdRiskTiers.CurrentCellChanged
    'this line gets error: upRiskTier expects parameter @ID, which was not supplied.
    adapter.Update(dataset.tblRiskTiers)
End Sub

Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

        adapter.Fill(dataset.tblRiskTiers)

        ' use the dataset  as the DataContext for this Window
        Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub

Here is the datagrid markup:

<DataGrid x:Name="_grdRiskTiers" AutoGenerateColumns="False" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="45,20,0,0" VerticalAlignment="Top" Height="199" Width="192" Grid.ColumnSpan="2">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding ID}" ></DataGridTextColumn>
                <DataGridTextColumn Binding="{Binding LowTierCreditScore}" Header="Low Tier Credit Score"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

And here is the stored procedure for updating:

CREATE PROCEDURE [dbo].[upRiskTier]
    @ID as int,
    @NewLowTierCreditScore as int
AS
IF EXISTS(SELECT * FROM tblRiskTiers WHERE LowTierCreditScore = @NewLowTierCreditScore) BEGIN
    DELETE FROM tblRiskTiers WHERE ID = @ID
END ELSE BEGIN
    UPDATE tblRiskTiers SET LowTierCreditScore = @NewLowTierCreditScore
    WHERE ID = @ID
END

How can I get the update command to pass in the ID to the stored procedure?

UPDATE: The following updated code resolved my issue

Private Sub RiskTiersForm_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

adapter.Fill(dataset.tblRiskTiers)

Dim command = New SqlCommand("[dbo].[upRiskTier]")
command.CommandType = System.Data.CommandType.StoredProcedure
command.Connection = oConn
command.Parameters.Add("@ID", System.Data.SqlDbType.Int, 5, "ID")
command.Parameters.Add("@NewLowTierCreditScore", System.Data.SqlDbType.Int, 5, "LowTierCreditScore")
adapter.Adapter.UpdateCommand = command
' use the Customer table as the DataContext for this Window
Me.DataContext = dataset.tblRiskTiers.DefaultView

End Sub

Body:
This error 'this line gets error: upRiskTier expects parameter @ID, which was not supplied.' mean  - your adapter doesn't configured properly.. There aren't relations between column and parameters in your adapter.UpdateCommand...

In next example show how to set relations between columns in DataTable and command parameters. Check your code where you configure SqlDataAdapter.

   // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;

In your case - your command should be

command = new SqlCommand("[dbo].[upRiskTier]");
command.CommandType = CommandType.StoredProcedure;

More detailed you can see in article on MSDN


问:
How to change a listbox unselected item colour from code behind
I have to create listBox via code behind. After that I have to change the colour that the selected item has when the listbox is not selected.
I have found that solution but am not able to render it via code behind.

Thank you

答:
Very easy if it's ok for you overriding the windows colour on the listbox

```<code>listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = Brushes.Blue;
</code>```

I picked your rgb colour so to be precise it's:

```<code>listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = new SolidColorBrush(Color.FromArgb(255, (byte)51, (byte)153, (byte)255));
</code>```

Body:
Very easy if it's ok for you overriding the windows colour on the listbox

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = Brushes.Blue;

I picked your rgb colour so to be precise it's:

listBox1.Resources[SystemColors.InactiveSelectionHighlightBrushKey] = new SolidColorBrush(Color.FromArgb(255, (byte)51, (byte)153, (byte)255));


问:
Problem in c# windows service using linq
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

```<code>protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }
</code>```

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

```<code>if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
</code>```

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.

答:
Ok thanks to Murph's advice I have found my solution, here it is if anyone wants a reference,

In my service i have

```<code>private ReversalSender _revSender;
    private Thread _revSenderThread;

    public EftcObReversalService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _revSender = new ReversalSender();
        _revSenderThread = new Thread(new ThreadStart(_revSender.Run));
        _revSenderThread.Start();

        var timer = new System.Timers.Timer(5000);
        timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
        timer.Start();
    }

    void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        _revSender.Signal();
    }

    protected override void OnStop()
    {
        _revSender.Stop();
        _revSenderThread.Join(60000);
    }
</code>```

Now to make sure that we have no concurrency issues accesing the DB the ReversalSender has a ManualResetEvent

```<code>public class ReversalSender
{
    private bool _running = true;
    private ManualResetEvent _reset = new ManualResetEvent(false);

    public void Run()
    {
        while (_running)
        {
            _reset.WaitOne();
            //We now need to grab all the waiting reversals
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);
            if (reversals.Any())
            {
                foreach (var rev in reversals)
                {
                    if (_running)
                        SendReversal(rev);
                }
            }
            db.SubmitChanges();
        }
    }

    private void SendReversal(FiReversal rev)
    {
       .....
    }

    public void Signal()
    {
        _reset.Set();
    }

    public void Stop()
    {
        _running = false;
    }
}
</code>```

Body:
I am having a bit of a problem in a windows service I have developed, I seem to be having a DB conflict using linq, I think i understand why the problem is happening but would like to get some advice in resolving it.

I have a database with a table that holds messages that need to be sent every at certain intervals from the service here is my code snippet.

protected override void OnStart(string[] args)
    {
        timer = new Timer(10000);
        timer.Elapsed += new ElapsedEventHandler(TimeElapsed);
        timer.Interval = 10000;
        timer.Start();
        EventLogger.LogEvent("Timer started succesfuly", EventLogEntryType.Information);

    }

    protected override void OnStop()
    {
        if (timer != null)
            timer.Stop();
        EventLogger.LogEvent("Timer stopped.", EventLogEntryType.Information);
    }

    private void TimeElapsed(object source, ElapsedEventArgs e)
    {
        try
        {
            EventLogger.LogEvent("Checking for reversals", EventLogEntryType.Information);
            //We now need to check for reversals that are waiting to be sent
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);

            if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }
        }
        catch (Exception ex)
        {
            EventLogger.LogEvent(ex.Message + "\n" + ex.StackTrace, EventLogEntryType.Error);
        }
    }

The error I get now is

Row not found or changed.
   at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
   at System.Data.Linq.DataContext.SubmitChanges()
   at EftcObReversalService.EftcObReversalService.TimeElapsed(Object source, ElapsedEventArgs e)

From what I can see is this is caused from the following code,

if (reversals.Any())
            {
                EventLogger.LogEvent(reversals.Count() + " reversals found and being processed.", EventLogEntryType.Information);
                //Mark the reversal
                foreach (var rev in reversals)
                {
                    MarkReversal(rev);
                }
                db.SubmitChanges();

                //We now need to send the reversal
                foreach (var rev in reversals)
                {
                    SendReversal(rev);
                }
                db.SubmitChanges();
                EventLogger.LogEvent("Finished processing reversal queue", EventLogEntryType.Information);
            }

What happens here is, I read in from the table what is marked with a "WAITING_TO_SEND", once I have that I decide to mark the entries with a "PENDING" status. I do this as i do not want the entries to be read in again when the timer swings through and this thread has not completed yet.

Once I have marked all the entires I then handle each one in the SendReversal method, where I also mark the status as "COMPLETED" when it was completed OK or change the status back to "WAITING_TO_SEND".

I think this error is being cause from the 2 db.SubmitChanges, as the entry has changes and been written by the first submit and is different from the second submit?

If anyone has any thoughts or solutions please let me know.

Body:
Ok thanks to Murph's advice I have found my solution, here it is if anyone wants a reference,

In my service i have

private ReversalSender _revSender;
    private Thread _revSenderThread;

    public EftcObReversalService()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        _revSender = new ReversalSender();
        _revSenderThread = new Thread(new ThreadStart(_revSender.Run));
        _revSenderThread.Start();

        var timer = new System.Timers.Timer(5000);
        timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
        timer.Start();
    }

    void TimerElapsed(object sender, ElapsedEventArgs e)
    {
        _revSender.Signal();
    }

    protected override void OnStop()
    {
        _revSender.Stop();
        _revSenderThread.Join(60000);
    }

Now to make sure that we have no concurrency issues accesing the DB the ReversalSender has a ManualResetEvent

public class ReversalSender
{
    private bool _running = true;
    private ManualResetEvent _reset = new ManualResetEvent(false);

    public void Run()
    {
        while (_running)
        {
            _reset.WaitOne();
            //We now need to grab all the waiting reversals
            ReversalsDataContext db = new ReversalsDataContext();
            var reversals = db.FiReversals.Where(r => r.Status == Reversal.ReversalStatus.WAITING_TO_SEND);
            if (reversals.Any())
            {
                foreach (var rev in reversals)
                {
                    if (_running)
                        SendReversal(rev);
                }
            }
            db.SubmitChanges();
        }
    }

    private void SendReversal(FiReversal rev)
    {
       .....
    }

    public void Signal()
    {
        _reset.Set();
    }

    public void Stop()
    {
        _running = false;
    }
}


答:
I would try the following:

```<code>SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
</code>```

followed by

```<code>SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2
</code>```

You may be able to combine the above into the following:

```<code>SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
UNION
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2
</code>```

Body:
I have a table foo with its primary key id and some other columns.
My goal is to find for instance rows with id=3 and id=4 and rows with id=6 and id=7 for row with id=5 - in case I would like to find 2 closest previous and next rows.

In case there is only one or no such rows (e.g. for id=2 there is only previous row) I would like to get only possible ones.

The problem is there can be some rows missing.

Is there a common practice to make such queries?

Body:
I would try the following:

SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2

followed by

SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2

You may be able to combine the above into the following:

SELECT * FROM table WHERE id > ? ORDER BY id ASC LIMIT 2
UNION
SELECT * FROM table WHERE id <= ? ORDER BY id DESC LIMIT 2


问:
Handle Security exceptions in Spring Boot Resource Server
How can I get my custom ResponseEntityExceptionHandler or OAuth2ExceptionRenderer to handle Exceptions raised by Spring security on a pure resource server?

We implemented a

```<code>@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
</code>```

so whenever there is an error on the resource server we want it to answer with

```<code>{
  "message": "...",
  "type": "...",
  "status": 400
}
</code>```

The resource server uses the application.properties setting:

```<code>security.oauth2.resource.userInfoUri: http://localhost:9999/auth/user
</code>```

to authenticate and authorize a request against our auth server.

However any spring security error will always bypass our exception handler at

```<code>    @ExceptionHandler(InvalidTokenException.class)
    public ResponseEntity<Map<String, Object>> handleInvalidTokenException(InvalidTokenException e) {
        return createErrorResponseAndLog(e, 401);
    }
</code>```

and produce either

```<code>{
  "timestamp": "2016-12-14T10:40:34.122Z",
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied",
  "path": "/api/templates/585004226f793042a094d3a9/schema"
}
</code>```

or

```<code>{
  "error": "invalid_token",
  "error_description": "5d7e4ab5-4a88-4571-b4a4-042bce0a076b"
}
</code>```

So how do I configure the security exception handling for a resource server? All I ever find are examples on how to customize the Auth Server by implementing a custom OAuth2ExceptionRenderer. But I can't find where to wire this to the resource server's security chain.

Our only configuration/setup is this:

```<code>@SpringBootApplication
@Configuration
@ComponentScan(basePackages = {"our.packages"})
@EnableAutoConfiguration
@EnableResourceServer
</code>```

答:
In case if you're using @EnableResourceServer, you may also find convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in your @Configuration class. By doing this, you may simply register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

```<code>@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}
</code>```

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.

Body:
How can I get my custom ResponseEntityExceptionHandler or OAuth2ExceptionRenderer to handle Exceptions raised by Spring security on a pure resource server?

We implemented a

@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

so whenever there is an error on the resource server we want it to answer with

{
  "message": "...",
  "type": "...",
  "status": 400
}

The resource server uses the application.properties setting:

security.oauth2.resource.userInfoUri: http://localhost:9999/auth/user

to authenticate and authorize a request against our auth server.

However any spring security error will always bypass our exception handler at

    @ExceptionHandler(InvalidTokenException.class)
    public ResponseEntity<Map<String, Object>> handleInvalidTokenException(InvalidTokenException e) {
        return createErrorResponseAndLog(e, 401);
    }

and produce either

{
  "timestamp": "2016-12-14T10:40:34.122Z",
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied",
  "path": "/api/templates/585004226f793042a094d3a9/schema"
}

or

{
  "error": "invalid_token",
  "error_description": "5d7e4ab5-4a88-4571-b4a4-042bce0a076b"
}

So how do I configure the security exception handling for a resource server? All I ever find are examples on how to customize the Auth Server by implementing a custom OAuth2ExceptionRenderer. But I can't find where to wire this to the resource server's security chain.

Our only configuration/setup is this:

@SpringBootApplication
@Configuration
@ComponentScan(basePackages = {"our.packages"})
@EnableAutoConfiguration
@EnableResourceServer

Body:
In case if you're using @EnableResourceServer, you may also find convenient to extend ResourceServerConfigurerAdapter instead of WebSecurityConfigurerAdapter in your @Configuration class. By doing this, you may simply register a custom AuthenticationEntryPoint by overriding configure(ResourceServerSecurityConfigurer resources) and using resources.authenticationEntryPoint(customAuthEntryPoint()) inside the method.

Something like this:

@Configuration
@EnableResourceServer
public class CommonSecurityConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthEntryPoint());
    }

    @Bean
    public AuthenticationEntryPoint customAuthEntryPoint(){
        return new AuthFailureHandler();
    }
}

There's also a nice OAuth2AuthenticationEntryPoint that can be extended (since it's not final) and partially re-used while implementing a custom AuthenticationEntryPoint. In particular, it adds "WWW-Authenticate" headers with error-related details.