问:
Replace in ColdFusion spoiling SQL query
I've got the below MySQL query, it's causing an error, the error is below too.

```<code>    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city
</code>```

Error from database

```<code>SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city
</code>```

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?

答: The value stored in findWhere includes single-quotes at the beginning and end of the string.

Body:
I've got the below MySQL query, it's causing an error, the error is below too.

    SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
    FROM    sales s LEFT JOIN saleloc sl ON sl.saleId = s.id LEFT JOIN saledates sd ON sd.saleLoc = sl.id,
            auctioneers an,
            lookupcopy st,
            lookupcopy at
    #replace(findWhere,"''","'","all")# AND
    s.id = sd.saleId AND sl.saleId = s.id
    AND an.id = s.auctioneer
    AND st.id = s.saleType
    AND at.id = s.advertType
    GROUP BY id
    ORDER BY startDate, auctioneerName, city

Error from database

SELECT DISTINCT s.id as id, s.auctioneer as auctioneer, s.advertType as advertType, s.saleType as saleType, an.name as auctioneerName, st.entryCopy as saleTypeName, at.entryCopy as advertTypeName, s.heading AS heading, sl.city AS city, sd.id AS sdId, sd.startDate AS startDate
FROM sales s
LEFT JOIN saleloc sl ON sl.saleId = s.id
LEFT JOIN saledates sd ON sd.saleLoc = sl.id, auctioneers an, lookupcopy st, lookupcopy at
'WHERE s.advertType > 0
AND s.saleType > 0
AND sl.region = "2" '
AND s.id = sd.saleId
AND sl.saleId = s.id
AND an.id = s.auctioneer
AND st.id = s.saleType
AND at.id = s.advertType
GROUP BY id
ORDER BY startDate, auctioneerName, city

I didn't write this code and I'm not sure why the #Replace()# is being used, can anyone see how to fix the syntax error it's causing?


来源: stackexchange

问:
Haskell: use or uses in Getter
In Control.Lens we have Getter that can access the nested structure. Getter has use and uses, but it's not clear to me how they work. So it'd be great if someone can provide some simple examples that use or uses is utilised.

Why do I need to know it? because I'm reading some implementation in Haskell and  "uses" and "use" were used in them. In particualr it says:

```<code>inRange <- uses fsCurrentCoinRangeUpperBound (coinIndex <=)
</code>```

If the above code is just for comparing (<=) two values, then why do we need "uses" at all, there?

答:
As I tried to make clear in my answer to your other question over at Use cases of makePrisms with examples there is a lot of requisite knowledge required before you can understand this.

First up, you have to understand Lens quite well. Judging from your other question you're just beginning them. This is great! They're amazingly cool and it's excellent to tackle such things.

However, I'd give you a big amount of caution here, one of the dangers of Haskell is it's so powerful, and can be so expressive and terse, that it seems easy to try to skip stuff.

If you skipped understanding algebraic data types very well, for example, you can easily read code and think you have an understanding of it when you don't at all. This can then lead to compounded confusion, and you'll feel like you don't understand any of it, which actually might be true, but that feeling is not a good feeling to have when learning Haskell.

I don't want you to feel like that.

So I encourage you to learn Lens, but if you don't have the requisite knowledge for Lens, then I encourage you to go get that first. It's not too hard to understand this stuff to a degree, but the way Lens is written is not trivial or easy to approach for programmers who aren't quite familiar with at least simple types, parameterized types, Algebraic Data Types, Typeclasses, the Functor typeclass, and to really understand it, you need to understand several instances of Functor.

As well, if you're trying to understand use and uses, which only make sense when dealing with State values, then I'd suggest it's almost impossible to understand what's happening without knowing what State is, as well as what Lens does and is.

use and uses are for taking a lens and a state value and looking into the current state inside a State value. So, to a degree you really need to also understand what do syntax is doing, therefore the Monad typeclass to a degree, as well as how the State / MonadState work from that perspective.

If any of these preliminaries are skipped, you'll be confused.

I hope this helps! And I wish you well.

ContentLicense: CC BY-SA 3.0

Title: Haskell: use or uses in Getter

Body:
In Control.Lens we have Getter that can access the nested structure. Getter has use and uses, but it's not clear to me how they work. So it'd be great if someone can provide some simple examples that use or uses is utilised.

Why do I need to know it? because I'm reading some implementation in Haskell and  "uses" and "use" were used in them. In particualr it says:

inRange <- uses fsCurrentCoinRangeUpperBound (coinIndex <=)

If the above code is just for comparing (<=) two values, then why do we need "uses" at all, there?


问:
How would I replace a single character in a string?
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

```<code>import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)
</code>```

Help would be very much appreciated.

答:
```<code>re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm', Alpha)
</code>```

would just replace every character of the alphabet with nopqrstuvwxyzabcdefghijklm.

Take a look at str.translate.

Body:
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)

Help would be very much appreciated.

Body:
re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm', Alpha)

would just replace every character of the alphabet with nopqrstuvwxyzabcdefghijklm.

Take a look at str.translate.


问:
Put content in shaped divs
I'm trying to make divs that are shaped like slices of a circle, using this code (this is for the top section of the circle) in CSS:

```<code>width: 0;
height: 0;
border-left: 250px solid transparent;
border-right: 250px solid transparent;
border-top: 250px solid #FFA8A8;
border-bottom: 250px solid transparent;
position: fixed;
border-radius: 100%;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;
</code>```

and that makes the divs show up the way I want them to on the page, but when I try to put any text into them, it doesn't show up. I think I get why (because the actual height and width of the div are 0 and what shows up on the page is just the border), but how would I make divs that look the same but can contain text or images?

答:
instead border, use overflow to cut off round parts.

flex can also help with centering things

example:

body>div {
  width: 80vmin;
  height: 80vmin;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  counter-reset: divs;
}

div div {
  background: #FFA8A8;
  height: 40vmin;
  width: 40vmin;
  counter-increment: divs;
  display: flex;
}

div div:nth-child(odd) {
  background: gray;
  order: 1
}

div div:last-child {
  order: 2
}

div div:before {
  content: counter(divs);
  transform: rotate(45deg);
  margin: auto;
  font-size: 10vmin
}

html {
  min-height: 100%;
  display: flex;
}

body {
  margin: auto;
  transform: rotate(-45deg)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

pen

Title: Put content in shaped divs

Body:
I'm trying to make divs that are shaped like slices of a circle, using this code (this is for the top section of the circle) in CSS:

width: 0;
height: 0;
border-left: 250px solid transparent;
border-right: 250px solid transparent;
border-top: 250px solid #FFA8A8;
border-bottom: 250px solid transparent;
position: fixed;
border-radius: 100%;
top: 50%;
left: 50%;
margin-top: -250px;
margin-left: -250px;

and that makes the divs show up the way I want them to on the page, but when I try to put any text into them, it doesn't show up. I think I get why (because the actual height and width of the div are 0 and what shows up on the page is just the border), but how would I make divs that look the same but can contain text or images?

Body:
instead border, use overflow to cut off round parts.

flex can also help with centering things

example:

body>div {
  width: 80vmin;
  height: 80vmin;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  counter-reset: divs;
}

div div {
  background: #FFA8A8;
  height: 40vmin;
  width: 40vmin;
  counter-increment: divs;
  display: flex;
}

div div:nth-child(odd) {
  background: gray;
  order: 1
}

div div:last-child {
  order: 2
}

div div:before {
  content: counter(divs);
  transform: rotate(45deg);
  margin: auto;
  font-size: 10vmin
}

html {
  min-height: 100%;
  display: flex;
}

body {
  margin: auto;
  transform: rotate(-45deg)
}

<div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

pen


问:
How can I structure python objects so they JSONify well?
I'm fairly new to python, coming from js.

I'm trying to communicate between client and server using json, and I'm having trouble understanding what the easily jsonifyable equivalent to an object attribute is in python (tornado).  Code below for Object creation taken from this SO answer (https://stackoverflow.com/a/2827726/4808079) throws some errors.

```<code>class MainHandler(tornado.web.RequestHandler):
    def post(self):
        #getting and parsing json works as expected
        args = json.loads(self.request.body.decode())

        #can't seem to figure out how to make this jsonify well
        out = []
        for num in range(0,5):
            addMe = type('', (), {})
            addMe.value = num
            addMe.square = num * num
            out.append(addMe)

        self.write(json.dumps(out))
</code>```

Console Error:

```<code>Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/tornado/web.py", line 1509, in _execute
    result = method(*self.path_args, **self.path_kwargs)
File "test_tornado.py", line 43, in post
    self.write(json.dumps(out))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <class '__main__.'> is not JSON serializable
</code>```

The equivalent of what I'm trying to above would be like so, in JavaScript:

```<code>var out = []
for(var num = 0; num < 5; num++) {
    var addMe = {};
    addMe.value = num;
    addMe.square = num*num;
    out.push(addMe);
}
return JSON.stringify(out);
</code>```

How am I supposed to structure an object in Python so that it JSONifies well?

答:
You can encode dicts out of the box:</p>

```<code>addMe = {
    'value': num,
    'square': num * num
}
</code>```

Body:
I'm fairly new to python, coming from js.

I'm trying to communicate between client and server using json, and I'm having trouble understanding what the easily jsonifyable equivalent to an object attribute is in python (tornado).  Code below for Object creation taken from this SO answer (https://stackoverflow.com/a/2827726/4808079) throws some errors.

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        #getting and parsing json works as expected
        args = json.loads(self.request.body.decode())

        #can't seem to figure out how to make this jsonify well
        out = []
        for num in range(0,5):
            addMe = type('', (), {})
            addMe.value = num
            addMe.square = num * num
            out.append(addMe)

        self.write(json.dumps(out))

Console Error:

Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/tornado/web.py", line 1509, in _execute
    result = method(*self.path_args, **self.path_kwargs)
File "test_tornado.py", line 43, in post
    self.write(json.dumps(out))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <class '__main__.'> is not JSON serializable

The equivalent of what I'm trying to above would be like so, in JavaScript:

var out = []
for(var num = 0; num < 5; num++) {
    var addMe = {};
    addMe.value = num;
    addMe.square = num*num;
    out.push(addMe);
}
return JSON.stringify(out);

How am I supposed to structure an object in Python so that it JSONifies well?

Body:
You can encode dicts out of the box:

addMe = {
    'value': num,
    'square': num * num
}


问:
Failed to get main window after 30 retries: kAXErrorServerNotFound
I have a suite of 26 tests. Sometimes some tests, any test, will fail with the following error:

```<code>Test Case ...
    t =     0.00s     Start Test at 2017-06-21 13:41:15.265
    t =     0.00s     Set Up
    t =     0.11s     Launch com.company.MyApp
    t =     4.06s         Wait for app to idle
    t =    10.27s             Unable to monitor animations
    t =    16.45s             Unable to monitor event loop
    t =    17.67s     Snapshot accessibility hierarchy for com.company.MyApp
    t =    23.84s         Assertion Failure: <unknown>:0: Failure getting snapshot Error Domain=XCTDaemonErrorDomain Code=12 "Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)" UserInfo={NSLocalizedDescription=Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)}
    t =    23.85s         Tear Down
</code>```

The tests do not show as failed in the report when using Xcode 8 but they do when using Xcode 9. With Xcode 9 the problem is similar but the logs different.

```<code>t =     0.00s Start Test at 2017-06-22 14:17:00.716
t =     0.08s Set Up
t =     0.18s Open com.company.MyApp
t =     0.26s     Launch com.company.MyApp
t =     3.39s         Wait for com.company.MyApp to idle
t =     9.58s             Unable to monitor animations
t =    15.76s             Unable to monitor event loop
t =    16.90s Snapshot accessibility hierarchy for app with pid 18003
t =    23.17s Tap "More" Button
t =    23.17s     Wait for com.company.MyApp to idle
t =    29.41s         Unable to monitor animations
t =    35.59s         Unable to monitor event loop
t =    35.61s     Find the "More" Button
t =    35.61s         Snapshot accessibility hierarchy for app with pid 18003
t =    41.92s         Wait for com.company.MyApp to idle
t =    48.16s             Unable to monitor animations
t =    54.34s             Unable to monitor event loop
t =    55.36s         Find the "More" Button (retry 1)
t =    55.37s             Snapshot accessibility hierarchy for app with pid 18003
t =    61.69s             Wait for com.company.MyApp to idle
t =    67.92s                 Unable to monitor animations
t =    74.10s                 Unable to monitor event loop
t =    75.12s         Find the "More" Button (retry 2)
t =    75.12s             Snapshot accessibility hierarchy for app with pid 18003
t =    81.44s             Wait for com.company.MyApp to idle
t =    87.66s                 Unable to monitor animations
t =    93.86s                 Unable to monitor event loop
t =    94.00s Assertion Failure: report.feature:11: Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)
t =    94.21s Find the Window
t =    94.21s     Snapshot accessibility hierarchy for app with pid 18003
t =   101.35s     Find the Window (retry 1)
t =   101.35s         Snapshot accessibility hierarchy for app with pid 18003
t =   108.53s     Find the Window (retry 2)
t =   108.53s         Snapshot accessibility hierarchy for app with pid 18003
t =   114.79s Assertion Failure: report.feature:10: Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)
t =   114.79s Tear Down
</code>```

The screenshots in the report show that the application is launched and seems idle.

Update

I reproduced the issue in a sample project that is a simple application with a tab bar view controller.

Update

There seem to be a known issue in the release notes of Xcode 9 Beta 6 regarding this

xcodebuild test can intermittently fail with ‘Domain=XCTestManagerErrorDomain Code=12
  “Failed to get main window after 30 retries”’. (29122169)

Workaround: Try the test again.

Let's just hope this get fixed before the final release of Xcode 9

答:
I have been struggling with this exact same issue on Xcode 8.3.2 — sad to hear that Xcode 9 beta hasn't fixed that yet :(

The only reliable fix so far has been resetting the iOS Simulator device(s). For instance:

osascript -e 'tell application "Simulator" to quit'
xcrun simctl erase all
```

<p>If you know your device ID, you can reset just that instead:</p>

<pre class="lang-bash prettyprint-override"><code>xcrun simctl erase DEVICE_ID
</code>```

(It goes without saying that you can wrap these commands in a simple shell script and run it from your Terminal when this issue pops up.)

Body:
I have a suite of 26 tests. Sometimes some tests, any test, will fail with the following error:

Test Case ...
    t =     0.00s     Start Test at 2017-06-21 13:41:15.265
    t =     0.00s     Set Up
    t =     0.11s     Launch com.company.MyApp
    t =     4.06s         Wait for app to idle
    t =    10.27s             Unable to monitor animations
    t =    16.45s             Unable to monitor event loop
    t =    17.67s     Snapshot accessibility hierarchy for com.company.MyApp
    t =    23.84s         Assertion Failure: <unknown>:0: Failure getting snapshot Error Domain=XCTDaemonErrorDomain Code=12 "Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)" UserInfo={NSLocalizedDescription=Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)}
    t =    23.85s         Tear Down

The tests do not show as failed in the report when using Xcode 8 but they do when using Xcode 9. With Xcode 9 the problem is similar but the logs different.

t =     0.00s Start Test at 2017-06-22 14:17:00.716
t =     0.08s Set Up
t =     0.18s Open com.company.MyApp
t =     0.26s     Launch com.company.MyApp
t =     3.39s         Wait for com.company.MyApp to idle
t =     9.58s             Unable to monitor animations
t =    15.76s             Unable to monitor event loop
t =    16.90s Snapshot accessibility hierarchy for app with pid 18003
t =    23.17s Tap "More" Button
t =    23.17s     Wait for com.company.MyApp to idle
t =    29.41s         Unable to monitor animations
t =    35.59s         Unable to monitor event loop
t =    35.61s     Find the "More" Button
t =    35.61s         Snapshot accessibility hierarchy for app with pid 18003
t =    41.92s         Wait for com.company.MyApp to idle
t =    48.16s             Unable to monitor animations
t =    54.34s             Unable to monitor event loop
t =    55.36s         Find the "More" Button (retry 1)
t =    55.37s             Snapshot accessibility hierarchy for app with pid 18003
t =    61.69s             Wait for com.company.MyApp to idle
t =    67.92s                 Unable to monitor animations
t =    74.10s                 Unable to monitor event loop
t =    75.12s         Find the "More" Button (retry 2)
t =    75.12s             Snapshot accessibility hierarchy for app with pid 18003
t =    81.44s             Wait for com.company.MyApp to idle
t =    87.66s                 Unable to monitor animations
t =    93.86s                 Unable to monitor event loop
t =    94.00s Assertion Failure: report.feature:11: Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)
t =    94.21s Find the Window
t =    94.21s     Snapshot accessibility hierarchy for app with pid 18003
t =   101.35s     Find the Window (retry 1)
t =   101.35s         Snapshot accessibility hierarchy for app with pid 18003
t =   108.53s     Find the Window (retry 2)
t =   108.53s         Snapshot accessibility hierarchy for app with pid 18003
t =   114.79s Assertion Failure: report.feature:10: Failed to get main window after 30 retries: kAXErrorServerNotFound (see <rdar://problem/15530121>)
t =   114.79s Tear Down

The screenshots in the report show that the application is launched and seems idle.

Update

I reproduced the issue in a sample project that is a simple application with a tab bar view controller.

Update

There seem to be a known issue in the release notes of Xcode 9 Beta 6 regarding this

xcodebuild test can intermittently fail with ‘Domain=XCTestManagerErrorDomain Code=12
  “Failed to get main window after 30 retries”’. (29122169)

Workaround: Try the test again.

Let's just hope this get fixed before the final release of Xcode 9

Body:
I have been struggling with this exact same issue on Xcode 8.3.2 — sad to hear that Xcode 9 beta hasn't fixed that yet :(

The only reliable fix so far has been resetting the iOS Simulator device(s). For instance:

osascript -e 'tell application "Simulator" to quit'
xcrun simctl erase all

If you know your device ID, you can reset just that instead:

xcrun simctl erase DEVICE_ID

(It goes without saying that you can wrap these commands in a simple shell script and run it from your Terminal when this issue pops up.)


问:
iOS AppDelegate crashes when adding didReceiveRemoteNotification
I have the following App delegate for an iOS app in Xcode 8.3:

```<code>@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  }
}
</code>```

When I start my app in either the simulator or on a device, it crashes with the following message:

```<code>2017-07-04 21:26:04.284336+0200 MyApp[352:25788] -[NSTaggedPointerString containsObject:]: unrecognized selector sent to instance 0xa00000070696f764
2017-07-04 21:26:04.284569+0200 MyApp[352:25788] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    [NSTaggedPointerString containsObject:]: unrecognized selector sent to  instance 0xa00000070696f764'
*** First throw call stack:
(0x188baefe0 0x187610538 0x188bb5ef4 0x188bb2f54 0x188aaed4c 0x18ef7d030 0x18ef630f4 0x18ef77d18 0x18ef60474 0x18a757884 0x18a7576f0 0x18a757aa0 0x188b5d42c 0x188b5cd9c 0x188b5a9a8 0x188a8ada4 0x18ed4a384 0x18ed45058 0x100106fc8 0x187a9959c)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

In the simulator, it's a slightly different error message:

```<code>2017-07-04 21:30:10.379 MyApp[55965:1127208] -[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60
2017-07-04 21:30:10.383 MyApp[55965:1127208] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60'
</code>```

Removing the application(:didReceiveRemoteNotification) method makes the crash disappear.

Does anyone have any clue what's going on?

答:
You likely have a third party framework that's causing the issue here. For one, you've posted Swift code, but are getting an Objective-C error message. It's likely that a library you're using is registering itself to handle notifications.

Second, the didReceiveRemoteNotification needs to always call it's completionHandler before exiting. So a blank function will cause issues.

You need to call completionHandler with a parameter of either .newData, .noData, or .failed depending on your results.

Body:
I have the following App delegate for an iOS app in Xcode 8.3:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  }
}

When I start my app in either the simulator or on a device, it crashes with the following message:

2017-07-04 21:26:04.284336+0200 MyApp[352:25788] -[NSTaggedPointerString containsObject:]: unrecognized selector sent to instance 0xa00000070696f764
2017-07-04 21:26:04.284569+0200 MyApp[352:25788] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-    [NSTaggedPointerString containsObject:]: unrecognized selector sent to  instance 0xa00000070696f764'
*** First throw call stack:
(0x188baefe0 0x187610538 0x188bb5ef4 0x188bb2f54 0x188aaed4c 0x18ef7d030 0x18ef630f4 0x18ef77d18 0x18ef60474 0x18a757884 0x18a7576f0 0x18a757aa0 0x188b5d42c 0x188b5cd9c 0x188b5a9a8 0x188a8ada4 0x18ed4a384 0x18ed45058 0x100106fc8 0x187a9959c)
libc++abi.dylib: terminating with uncaught exception of type NSException

In the simulator, it's a slightly different error message:

2017-07-04 21:30:10.379 MyApp[55965:1127208] -[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60
2017-07-04 21:30:10.383 MyApp[55965:1127208] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString containsObject:]: unrecognized selector sent to instance 0x608000028d60'

Removing the application(:didReceiveRemoteNotification) method makes the crash disappear.

Does anyone have any clue what's going on?


问:
Changed sort_index behaviour in pandas 0.20
The behaviour of sort_index seems to have changed. I want to sort by date for periods but it since I updated to 0.20 it is sorting by day of month. I've seen the list of changes but haven't managed to recover the same results. Any tips?

Thanks

Gist - Pandas 0.19.2

Gist - Pandas 0.20.2

答:
The comment from @Brad Solomon made me realize I could convert to the string format I wanted after sorting. Although the string sorting behaviour remains, I now obtain the same behaviour.

Instead of

```<code>colnames = ['Date', 'Client', 'Value', 'OtherValue']
df = pd.DataFrame(data={c:v for c,v in zip(colnames, [col1,col2,col3,col4])})
df2 = df.groupby(['Client',pd.to_datetime(df['Date']).dt.to_period('W-THU')]).sum().unstack(level=1).fillna(0)
new_cols = [i.start_time.strftime('%d/%m')+
            '-'+i.end_time.strftime('%d/%m')
           for i in df2.columns.levels[1]]
df2.columns.set_levels(new_cols,level=1,inplace=True)
df2.columns = df2.columns.swaplevel(0,1)
df2.sort_index(level=0, axis=1, inplace=True)
</code>```

writing

```<code>colnames = ['Date', 'Client', 'Value', 'OtherValue']
df = pd.DataFrame(data={c:v for c,v in zip(colnames, [col1,col2,col3,col4])})
df2 = df.groupby(['Client',pd.to_datetime(df['Date']).dt.to_period('W-THU')]).sum().unstack(level=1).fillna(0)
df2.columns = df2.columns.swaplevel(0,1)
df2.sort_index(level=0, axis=1, inplace=True)
new_cols = [i.start_time.strftime('%d/%m')+
            '-'+i.end_time.strftime('%d/%m')
           for i in df2.columns.levels[0]]
df2.columns.set_levels(new_cols,level=0,inplace=True)
</code>```

solves it.

Body:
The comment from @Brad Solomon made me realize I could convert to the string format I wanted after sorting. Although the string sorting behaviour remains, I now obtain the same behaviour.

Instead of

colnames = ['Date', 'Client', 'Value', 'OtherValue']
df = pd.DataFrame(data={c:v for c,v in zip(colnames, [col1,col2,col3,col4])})
df2 = df.groupby(['Client',pd.to_datetime(df['Date']).dt.to_period('W-THU')]).sum().unstack(level=1).fillna(0)
new_cols = [i.start_time.strftime('%d/%m')+
            '-'+i.end_time.strftime('%d/%m')
           for i in df2.columns.levels[1]]
df2.columns.set_levels(new_cols,level=1,inplace=True)
df2.columns = df2.columns.swaplevel(0,1)
df2.sort_index(level=0, axis=1, inplace=True)

writing

colnames = ['Date', 'Client', 'Value', 'OtherValue']
df = pd.DataFrame(data={c:v for c,v in zip(colnames, [col1,col2,col3,col4])})
df2 = df.groupby(['Client',pd.to_datetime(df['Date']).dt.to_period('W-THU')]).sum().unstack(level=1).fillna(0)
df2.columns = df2.columns.swaplevel(0,1)
df2.sort_index(level=0, axis=1, inplace=True)
new_cols = [i.start_time.strftime('%d/%m')+
            '-'+i.end_time.strftime('%d/%m')
           for i in df2.columns.levels[0]]
df2.columns.set_levels(new_cols,level=0,inplace=True)

solves it.


问:
Oauth 2.0 get access token without redirecting the user to different page
I wanted to implement a login flow where users can log on my website using

3rd party Oauth providers, OR

Email id and password.

For point 1, I get it that

Grant type would be "Authorization code".

My  website will redirect the user to 3rd party Oauth provider

I will get an authorization code and then access token using the code.

For point 2,

I will be hosting a Oauth server

I do not want to redirect user to a different page, so "authorization code", "client credentials" and "implicit" grant types isn't what I am looking for.

Which leaves me with "Resource owner password credentials".

If I use "Resource owner password credentials" I have to expose the client secret to the web application, which I heard is a bad idea.

My query:

What is the most appropriate way to get access token without redirecting the user to different page. Currently the authorization server is the server which is hosting the main application. I want this to validate a user using email and password which are stored on my website itself

If "Resource owner password credentials" is the way to go, what are the security implications of exposing the client secret.

I am new to Oauth so please correct me if I am wrong anywhere.

Note: My Client application is an Angular 2 app in browser.

Thanks.

答:
You can use a popup sign-in window to complete the sign in with the implicit flow.  This will load up the identity providers sign-in page (the /authorize endpoint), but will not do a full redirect in your browser. Then the identity provider can set the appropriate cookies and get you an access token. This is the canonical pattern for single-page apps (angular, react, etc.). Here's some reading that can give some color to the protocol (in the scope of Azure AD, but a lot of this transcends identity provider implementation details). </p>

<p>The resource owner password flow is generally not a good idea, but can be used in a few situations. Things like daemons apps or testing are good cases.  In general, it's very brittle and won't support things like MFA or dynamic consent situations. Moreover, it's intrinsically less secure that a tradtional implicit or auth code flow. Here's a great blog post about good cases to use it in the scope of Azure AD (enterprise account identity provider). </p>

Body:
You can use a popup sign-in window to complete the sign in with the implicit flow.  This will load up the identity providers sign-in page (the /authorize endpoint), but will not do a full redirect in your browser. Then the identity provider can set the appropriate cookies and get you an access token. This is the canonical pattern for single-page apps (angular, react, etc.). Here's some reading that can give some color to the protocol (in the scope of Azure AD, but a lot of this transcends identity provider implementation details).

The resource owner password flow is generally not a good idea, but can be used in a few situations. Things like daemons apps or testing are good cases.  In general, it's very brittle and won't support things like MFA or dynamic consent situations. Moreover, it's intrinsically less secure that a tradtional implicit or auth code flow. Here's a great blog post about good cases to use it in the scope of Azure AD (enterprise account identity provider).


问:
Vim: Maintain the history of a file after it has been changed and reloaded
If I'm editing a file in Vim, then some external program changes the file, Vim tells me:

```
W11: Warning: File "test.erl" has changed since editing started
See ":help W11" for more info.
[O]K, (L)oad File:
```

If I Load the file, though, all the undo history is lost.

Is there any way to avoid that?

答: Update: it appears that this is one of the new features in Vim 7.3: https://groups.google.com/group/vim_announce/browse_thread/thread/66c02efd1523554b</p>

ContentLicense: CC BY-SA 2.5

Body:
If I'm editing a file in Vim, then some external program changes the file, Vim tells me:

W11: Warning: File "test.erl" has changed since editing started
See ":help W11" for more info.
[O]K, (L)oad File:

If I Load the file, though, all the undo history is lost.

Is there any way to avoid that?


问:
"cannot declare abstract type variable because of virtual function" error despite the virtual function being defined/implemented
I'm writing code using inheritance, with a base class called BankAccount and a child class called MoneyMarket Account, and I'm receiving the following error for my code

```<code>hw7main.cpp: In function ‘int main()’:
hw7main.cpp:9: error: cannot declare variable ‘account1’ to be of abstract type ‘MoneyMarketAccount’
hw7.h:36: note:   because the following virtual functions are pure within ‘MoneyMarketAccount’:
hw7.h:41: note:     virtual bool MoneyMarketAccount::withdraw(double)
</code>```

Based on other the answers to similar questions, I tried to override the virtual function, withdraw, but I'm still getting the same error.

Here is my base class interface (file name: hw7base.h):

```<code>#ifndef HW7BASE_H
#define HW7BASE_H
#include <iostream>
#include <string>
using namespace std;

class BankAccount
{
    public:
    //constructors
    BankAccount();

    //member functions
    bool deposit(double money);
    virtual bool withdraw (double money)=0;

    //accessor functions
    void getName(BankAccount* account);
    void getBalance(BankAccount* account);

    //transfer function
    //virtual void transfer (BankAccount* deposit, BankAccount* withdrawal, double money);
    //private:
    string name;
    double balance;
};

#endif
</code>```

Here is my subclass interface (file name: hw7derived1.h):

```<code>#ifndef HW7DERIVED1_H
#define HW7DERIVED1_H
#include <iostream>
#include "hw7base.h"

using namespace std;

class MoneyMarketAccount: public BankAccount
{
    public:
        //constructor
        MoneyMarketAccount();
        //override function
        virtual bool withdraw(double money)=0;
        int number_of_withdrawals;

};

#endif
</code>```

And here is my subclass implementation (file name: hw7derived1.cpp):

```<code>#include "hw7derived1.h"
using namespace std;

//consturctor
MoneyMarketAccount::MoneyMarketAccount()
{
    number_of_withdrawals = 0;
}
bool MoneyMarketAccount::withdraw(double money)
{
    if (money<=0)
    {
        cout<<"Failed.\n";
        return false;
    }
    else
    {
        balance-=money;
            if(number_of_withdrawals>=2)
            {
                balance-=1.5;
                if (balance<0)
                {
                    balance=balance+1.5+money;
                    cout<<"Failed.\n";
                    return false;
                }
                else
                {
                    number_of_withdrawals++;
                    cout<<"Success.\n";
                    return true;
                }
            }
            else
            {
                if (balance<0)
                {
                    balance+=money;
                    cout<<"Failed.\n";
                    return false;
                }
                else
                {
                    number_of_withdrawals++;
                    cout<<"Success.\n";
                    return true;
                }
            }
    }
}
</code>```

Any help/insight is appreciated, thanks!

答:
This:

```<code>virtual bool withdraw(double money)=0;
</code>```

(In MoneyMarketAccount - the derived class) declares the function as pure (just as it was pure in the base class).
Even though you implement it (so it can be called - yes, pure virtual functions can have implementations and it does make sense sometimes), this still makes the MoneyMarketAccount abstract - and you cannot instantiate a abstract class.

You probably wanted to declare the function as

```<code>bool withdraw(double money) override;
</code>```

in MoneyMarketAccount. This will make the class concrete since there are no longer any pure (=0) functions and will also let the compiler help you in the future if the base class signature changes so you no longer override the pure virtual withdraw from it (the override bit - which makes the redundant virtual in the derived class extra redundant).

Body:
I'm writing code using inheritance, with a base class called BankAccount and a child class called MoneyMarket Account, and I'm receiving the following error for my code

hw7main.cpp: In function ‘int main()’:
hw7main.cpp:9: error: cannot declare variable ‘account1’ to be of abstract type ‘MoneyMarketAccount’
hw7.h:36: note:   because the following virtual functions are pure within ‘MoneyMarketAccount’:
hw7.h:41: note:     virtual bool MoneyMarketAccount::withdraw(double)

Based on other the answers to similar questions, I tried to override the virtual function, withdraw, but I'm still getting the same error.

Here is my base class interface (file name: hw7base.h):

#ifndef HW7BASE_H
#define HW7BASE_H
#include <iostream>
#include <string>
using namespace std;

class BankAccount
{
    public:
    //constructors
    BankAccount();

    //member functions
    bool deposit(double money);
    virtual bool withdraw (double money)=0;

    //accessor functions
    void getName(BankAccount* account);
    void getBalance(BankAccount* account);

    //transfer function
    //virtual void transfer (BankAccount* deposit, BankAccount* withdrawal, double money);
    //private:
    string name;
    double balance;
};

#endif

Here is my subclass interface (file name: hw7derived1.h):

#ifndef HW7DERIVED1_H
#define HW7DERIVED1_H
#include <iostream>
#include "hw7base.h"

using namespace std;

class MoneyMarketAccount: public BankAccount
{
    public:
        //constructor
        MoneyMarketAccount();
        //override function
        virtual bool withdraw(double money)=0;
        int number_of_withdrawals;

};

#endif

And here is my subclass implementation (file name: hw7derived1.cpp):

#include "hw7derived1.h"
using namespace std;

//consturctor
MoneyMarketAccount::MoneyMarketAccount()
{
    number_of_withdrawals = 0;
}
bool MoneyMarketAccount::withdraw(double money)
{
    if (money<=0)
    {
        cout<<"Failed.\n";
        return false;
    }
    else
    {
        balance-=money;
            if(number_of_withdrawals>=2)
            {
                balance-=1.5;
                if (balance<0)
                {
                    balance=balance+1.5+money;
                    cout<<"Failed.\n";
                    return false;
                }
                else
                {
                    number_of_withdrawals++;
                    cout<<"Success.\n";
                    return true;
                }
            }
            else
            {
                if (balance<0)
                {
                    balance+=money;
                    cout<<"Failed.\n";
                    return false;
                }
                else
                {
                    number_of_withdrawals++;
                    cout<<"Success.\n";
                    return true;
                }
            }
    }
}

Any help/insight is appreciated, thanks!

Body:
This:

virtual bool withdraw(double money)=0;

(In MoneyMarketAccount - the derived class) declares the function as pure (just as it was pure in the base class).
Even though you implement it (so it can be called - yes, pure virtual functions can have implementations and it does make sense sometimes), this still makes the MoneyMarketAccount abstract - and you cannot instantiate a abstract class.

You probably wanted to declare the function as

bool withdraw(double money) override;

in MoneyMarketAccount. This will make the class concrete since there are no longer any pure (=0) functions and will also let the compiler help you in the future if the base class signature changes so you no longer override the pure virtual withdraw from it (the override bit - which makes the redundant virtual in the derived class extra redundant).


问:
PHPExcel Writer Excel2007 error
I recently encountered this error in my report.

```<code>PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 3022731 bytes)
</code>```

I cant seem to resolved the problem, i already added:

```<code>set_time_limit(0);
ini_set('memory_limit', -1);
</code>```

in my script but it seems the issue is still persistent, by the way im using

```<code>PHPExcel ver 1.7.6
</code>```

My excel file output contains 55 headers and multiple worksheets (closely 45 - increasing) and each sheet contains about 150 to 500 records

I would like to seek for your help and advises to resolve my remedy T_T

Thanks!

答:
Maybe try using the https://github.com/PHPOffice/PhpSpreadsheet - it`s the rewritten version of PhpExcel. It works way better. I know, because I have used both.

If that does not help your problem you should use caching see: https://phpspreadsheet.readthedocs.io/en/develop/topics/memory_saving/

P.S. if you will be using sqlite3 caching make sure you have the proper extension php-sqlite3 installed, because it fails silently and does not cache if extension is not there.

Title: PHPExcel Writer Excel2007 error

Body:
I recently encountered this error in my report.

PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 3022731 bytes)

I cant seem to resolved the problem, i already added:

set_time_limit(0);
ini_set('memory_limit', -1);

in my script but it seems the issue is still persistent, by the way im using

PHPExcel ver 1.7.6

My excel file output contains 55 headers and multiple worksheets (closely 45 - increasing) and each sheet contains about 150 to 500 records

I would like to seek for your help and advises to resolve my remedy T_T

Thanks!


问:
How to pass the drodown selected value in thymeleaf to spring boot controller
Please help me with any working code.I am trying from since one week not getting the solution.</p>

答:
Java MVC frameworks encapsulate Servlet APIs and common functionality is provided to us using the framework's simpler APIs.

For a task as common as retrieving a parameter value from a request, Spring MVC and Boot use the @RequestParam annotation to retrieve the parameter value selected from a select with option tag.  So ak38's code would not need to use HttpServletRequest at all to get the parameter; instead, it would just annotate a paramter of the controller method the request calls:

HTML Form:

```<code><form role="form" id="sendAddress" th:action=@{/sendAddress} method="post">
    <select class="form-control" name="*nameOfCity*">
        <option value="">Select City</option>
        <option value="HYD">Hyderabad</option>
        <option value="MUM">Mumbai</option>
        <option value="DEL">Delhi</option>
    </select>
</form>
</code>```

Controller:

```<code>@RequestMapping(value={"/sendAddress"}, method = RequestMethod.POST)
public String messageCenterHome(**@RequestParam** String *nameOfCity*) {
    // value of nameOfCity is now value of "nameOfCity" paramter,
    // that is, the value of the option tag selected
    // return view
}
</code>```

Try it out, if you haven't already, as I've just seen this now and it's been a few months since the question was posted.

Body:
Java MVC frameworks encapsulate Servlet APIs and common functionality is provided to us using the framework's simpler APIs.

For a task as common as retrieving a parameter value from a request, Spring MVC and Boot use the @RequestParam annotation to retrieve the parameter value selected from a select with option tag.  So ak38's code would not need to use HttpServletRequest at all to get the parameter; instead, it would just annotate a paramter of the controller method the request calls:

HTML Form:

<form role="form" id="sendAddress" th:action=@{/sendAddress} method="post">
    <select class="form-control" name="*nameOfCity*">
        <option value="">Select City</option>
        <option value="HYD">Hyderabad</option>
        <option value="MUM">Mumbai</option>
        <option value="DEL">Delhi</option>
    </select>
</form>

Controller:

@RequestMapping(value={"/sendAddress"}, method = RequestMethod.POST)
public String messageCenterHome(**@RequestParam** String *nameOfCity*) {
    // value of nameOfCity is now value of "nameOfCity" paramter,
    // that is, the value of the option tag selected
    // return view
}

Try it out, if you haven't already, as I've just seen this now and it's been a few months since the question was posted.


问:
Converting HMAC Hash from C# to PHP
I've looked at numerous questions around this but can't see the mistake I'm making. I'm trying to generate a Shared Access Signature to access an Azure SB Queue.

My C# code is working correctly:

```<code>    var expiry = 1499177142;// GetExpiry();
    string stringToSign = HttpUtility.UrlEncode(resourceUri);// + "\n" + expiry;
    HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

    Console.WriteLine(Encoding.UTF8.GetBytes(stringToSign));

    var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    Console.WriteLine(signature);

    var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
    HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
    return sasToken;
// returns slXBw0u7Dt/YKS1Y+Wot02z730YXJ9NkS599JRzvDQI= for the signature element
</code>```

My PHP gives a very different result:

```<code>$stringToSign = rawurlencode($resourceURI);// . "%0A" . $expiry;

$sig = hash_hmac("sha256",utf8_encode($stringToSign),utf8_encode($key),false);
echo $sig."<br>";

$token = "SharedAccessSignature sr=".urlencode($resourceURI)
."&sig=".rawurlencode(base64_encode($sig))."&se=".$expiry."&skn=".$keyName;
return $token; //returns MGNlZWViYWRmMjE2NWJhZGRjNWNhNDZkYWRlOTQyMzc3ODBhMWM2ZjA1OTk4MjI0MGUzMzllZmY4ZTk2OGUxNA==
</code>```

I've tried encoding $stringToSign and $key and not in the hash, strtoupper and strtolower on the $stringToSign but can't get the result to be the same as C#

答:
This code should work in PHP and C#.

PHP:

```<code><?php

$resourceURI = "http://nifi-eventhub.servicebus.windows.net/hub1";
$keyName = "hub-user";
$key = "secret";
$expiry = '1499177142'; // timestamp

// The format for the string is <resourceURI> + \n + <expiry>
$stringToSign = strtolower(rawurlencode($resourceURI)) . "\n" . $expiry;

// Hash the URL encoded string using the shared access key
$sig = hash_hmac("sha256", utf8_encode($stringToSign), utf8_encode($key), false);

// Convert hexadecimal string to binary and then to base64
$sig = hex2bin($sig);
$sig = base64_encode($sig);

// 7kS3apSDpJFTYI1vxuo4t7syGG3FTBYI8foamMOtrEE=
echo $sig . "<br>\n";

// Generate authorization token
$token = "SharedAccessSignature sr=" . urlencode($resourceURI) . "&sig=" . rawurlencode($sig) . "&se=" . $expiry . "&skn=" . $keyName;
echo $token . "<br>\n";
</code>```

In C#

```<code>string expiry = "1499177142";
string resourceUri = "http://nifi-eventhub.servicebus.windows.net/hub1";
string keyName = "hub-user";
string secretkey = "secret";

string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretkey));
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));

var signature = Convert.ToBase64String(hashBytes);

// 7kS3apSDpJFTYI1vxuo4t7syGG3FTBYI8foamMOtrEE=
Console.WriteLine(signature);

var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

Console.WriteLine(sasToken);
</code>```

Title: Converting HMAC Hash from C# to PHP

Body:
I've looked at numerous questions around this but can't see the mistake I'm making. I'm trying to generate a Shared Access Signature to access an Azure SB Queue.

My C# code is working correctly:

    var expiry = 1499177142;// GetExpiry();
    string stringToSign = HttpUtility.UrlEncode(resourceUri);// + "\n" + expiry;
    HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

    Console.WriteLine(Encoding.UTF8.GetBytes(stringToSign));

    var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    Console.WriteLine(signature);

    var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
    HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
    return sasToken;
// returns slXBw0u7Dt/YKS1Y+Wot02z730YXJ9NkS599JRzvDQI= for the signature element

My PHP gives a very different result:

$stringToSign = rawurlencode($resourceURI);// . "%0A" . $expiry;

$sig = hash_hmac("sha256",utf8_encode($stringToSign),utf8_encode($key),false);
echo $sig."
";

$token = "SharedAccessSignature sr=".urlencode($resourceURI)
."&sig=".rawurlencode(base64_encode($sig))."&se=".$expiry."&skn=".$keyName;
return $token; //returns MGNlZWViYWRmMjE2NWJhZGRjNWNhNDZkYWRlOTQyMzc3ODBhMWM2ZjA1OTk4MjI0MGUzMzllZmY4ZTk2OGUxNA==

I've tried encoding $stringToSign and $key and not in the hash, strtoupper and strtolower on the $stringToSign but can't get the result to be the same as C#

Body:
This code should work in PHP and C#.

PHP:

<?php

$resourceURI = "http://nifi-eventhub.servicebus.windows.net/hub1";
$keyName = "hub-user";
$key = "secret";
$expiry = '1499177142'; // timestamp

// The format for the string is <resourceURI> + \n + <expiry>
$stringToSign = strtolower(rawurlencode($resourceURI)) . "\n" . $expiry;

// Hash the URL encoded string using the shared access key
$sig = hash_hmac("sha256", utf8_encode($stringToSign), utf8_encode($key), false);

// Convert hexadecimal string to binary and then to base64
$sig = hex2bin($sig);
$sig = base64_encode($sig);

// 7kS3apSDpJFTYI1vxuo4t7syGG3FTBYI8foamMOtrEE=
echo $sig . "<br>\n";

// Generate authorization token
$token = "SharedAccessSignature sr=" . urlencode($resourceURI) . "&sig=" . rawurlencode($sig) . "&se=" . $expiry . "&skn=" . $keyName;
echo $token . "<br>\n";

In C#

string expiry = "1499177142";
string resourceUri = "http://nifi-eventhub.servicebus.windows.net/hub1";
string keyName = "hub-user";
string secretkey = "secret";

string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;

HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretkey));
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));

var signature = Convert.ToBase64String(hashBytes);

// 7kS3apSDpJFTYI1vxuo4t7syGG3FTBYI8foamMOtrEE=
Console.WriteLine(signature);

var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

Console.WriteLine(sasToken);


问:
Converting all arrays in a PyTables/HDF5 file from float64 to float32
I have a PyTables file with a considerable amount of subdirectories. I have a way of iterating through all the array datatypes in the table. They are float64; I want to convert the file in place while converting all data points from float64 to float32.

According to this question, one way to overwrite arrays is to assign values. I have the following code snippet which tries to take this "count" value/array in the table, converts it to float32, and assigns it back to the table:

```<code>import h5py
import numpy as np

# filehead is a string for a file
with h5py.File(filehead, 'r+') as f:
    # Lots of stuff here ... e.g. `head` is a string

    print("/obsnorm/Standardizer/count {}".format(f[head+'/obsnorm/Standardizer/count']))
    print("count value: {}".format(f[head+'/obsnorm/Standardizer/count'].value))
    f[head+'/obsnorm/Standardizer/count'][...] = (f[head+'/obsnorm/Standardizer/count'].value).astype('float32')
    print("/obsnorm/Standardizer/count {}".format(f[head+'/obsnorm/Standardizer/count']))
    print("count value: {}".format(f[head+'/obsnorm/Standardizer/count'].value))
</code>```

Unfortunately, the result of the printing is:

```<code>/obsnorm/Standardizer/count <HDF5 dataset "count": shape (), type "<f8">
count value: 512364.0
/obsnorm/Standardizer/count <HDF5 dataset "count": shape (), type "<f8">
count value: 512364.0
</code>```

In other words, before the assignment, the type of count is f8, or float64. After casting it, the type is still float64.

How do I modify this in-place so that the data is truly understood as float32?

答:
As suggested by hpaulj in the comments, I decided to simply recreate a duplicate HDF5 file except making the datasets of type f4 (same as float32) and I was able to achieve my coding goals.

The pseudocode is as follows:

```<code>import h5py
import numpy as np

# Open the original file jointly with new file, with `float32` at the end.
with h5py.File(oldfile, 'r') as f, h5py.File(newfile[:-3]+'_float32.h5', 'w') as newf:
    # `head` is some directory structure
    # Create groups to follow the same directory structure
    newf.create_group(head)

    # When it comes time to create a dataset, make the cast here.
    newdata = (f[head+'/name_here'].value).astype('float32')
    newf.create_dataset(head+'/name_here', data=newdata, dtype='f4')

    # Proceed for all other datasets.
</code>```

Body:
I have a PyTables file with a considerable amount of subdirectories. I have a way of iterating through all the array datatypes in the table. They are float64; I want to convert the file in place while converting all data points from float64 to float32.

According to this question, one way to overwrite arrays is to assign values. I have the following code snippet which tries to take this "count" value/array in the table, converts it to float32, and assigns it back to the table:

import h5py
import numpy as np

# filehead is a string for a file
with h5py.File(filehead, 'r+') as f:
    # Lots of stuff here ... e.g. `head` is a string

    print("/obsnorm/Standardizer/count {}".format(f[head+'/obsnorm/Standardizer/count']))
    print("count value: {}".format(f[head+'/obsnorm/Standardizer/count'].value))
    f[head+'/obsnorm/Standardizer/count'][...] = (f[head+'/obsnorm/Standardizer/count'].value).astype('float32')
    print("/obsnorm/Standardizer/count {}".format(f[head+'/obsnorm/Standardizer/count']))
    print("count value: {}".format(f[head+'/obsnorm/Standardizer/count'].value))

Unfortunately, the result of the printing is:

/obsnorm/Standardizer/count <HDF5 dataset "count": shape (), type "<f8">
count value: 512364.0
/obsnorm/Standardizer/count <HDF5 dataset "count": shape (), type "<f8">
count value: 512364.0

In other words, before the assignment, the type of count is f8, or float64. After casting it, the type is still float64.

How do I modify this in-place so that the data is truly understood as float32?

Body:
As suggested by hpaulj in the comments, I decided to simply recreate a duplicate HDF5 file except making the datasets of type f4 (same as float32) and I was able to achieve my coding goals.

The pseudocode is as follows:

import h5py
import numpy as np

# Open the original file jointly with new file, with `float32` at the end.
with h5py.File(oldfile, 'r') as f, h5py.File(newfile[:-3]+'_float32.h5', 'w') as newf:
    # `head` is some directory structure
    # Create groups to follow the same directory structure
    newf.create_group(head)

    # When it comes time to create a dataset, make the cast here.
    newdata = (f[head+'/name_here'].value).astype('float32')
    newf.create_dataset(head+'/name_here', data=newdata, dtype='f4')

    # Proceed for all other datasets.


问:
Is there any way I can get a list of all possible responses from the google vision api?
I am using the google cloud vision api to analyze pictures. Is there a list of all the possible responses for the labelAnnotations method? </p>

答:
I think you're asking whether you can get a look at the list of possible labels/entities that the Cloud Vision API will detect. If that's the case, the short answer is no, not in any manageable way.

The more complicated answer is sort of, since most labels will have a property for the knowledge graph entry (e.g., {desc: 'dog', mid: '/m/0bt9lr'}). This means that you can look-up more information about the label/entity using the Knowledge Graph API.

While you can't "store a copy" of Google's Knowledge Graph as a list of choices in a drop-down on a page, you can use the API to do a look-up after the Vision API responds with an ID.


问:
Reduce the size of Flash memory embedded cpp
After a lot of research i could not find any solution to my question (if i did i woudln't be here ...)
I'm looking for solutions that permits me to reduce the flash memory used by my program.

I'm programming an embedded c++ programm and when i Flash my electronic card  in release mode everything is fine cause it doesn't overflow the space of the flash memory, but that is not the case when i do it in Debug mode... I want to know if it is possible to find functions (my goal is to do it without reducing the code) that could reduce Flash memory.I already thought about defragmentation but I don't find how to do it in embedded even though i don't even know if i can ...  I also tried the -Os cmd from gcc but without any big success

So I'm taking any advices or support and i'll be there at any question about my issue ;)

Thanks !

答:
Look at your map file.  Is there something there you don't
expect? Functions you aren't expecting (like floating point, or
exception handling, etc.) or something unreasonably large?

Turn on optimization except for the file you're interested in.

Make sure you've actually got optimizations turned on (look at the build log and ensure that you've got -Os being passed to each compile step)

Consider link time optimizations, but don't expect miracles

Welcome to embedded programming.  90% of the job is figuring out how to stuff the never ending requirements into the memory available.  Rinse and repeat.


问:
Java: custom toString to fit any class
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

```<code>String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}
</code>```

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

答:
Yes, you're right that this can be achieved with reflection. It's already implemented in Apache Commons in ReflectionToStringBuilder

From documentation:

A typical invocation for this method would look like:

```<code>public String toString() {
   return ReflectionToStringBuilder.toString(this);
}
</code>```

But be aware of potential performance problems - reflection always introduces some overhead.

Title: Java: custom toString to fit any class

Body:
I want to create a toString() method that works for any class, printing all its attributes as if it worked like this:

String toString(){
    String s = "";
    for(Attribute att: this.Attributes){
        s += (att.name + ": " + att.toString() + "\n");
    }
    return s;
}

But this would work supposing all attributes have toString() method, so let's keep this supposition.

I guess this question includes concepts of reflection, and I don't know much about this concept nor how to apply this in Java.

Body:
Yes, you're right that this can be achieved with reflection. It's already implemented in Apache Commons in ReflectionToStringBuilder

From documentation:

A typical invocation for this method would look like:

public String toString() {
   return ReflectionToStringBuilder.toString(this);
}

But be aware of potential performance problems - reflection always introduces some overhead.


问:
Total sum of all inputs
I would like to have the total sum of all input of my array instantaneously in a div.
Here is my complete code:</p>

```<code><script type="text/javascript">
function calcul(i){
  var prix = Number(document.getElementById("Fr_Quantite_"+i).value);
  var quantite = Number(document.getElementById("Fr_Prix_"+i).value);
  var ttc = Number(prix * quantite);
  document.getElementById("Fr_Total_"+i).value = ttc;
}
</script>

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" id="TableauJaquery1" class="Tableau">
  <thead>
    <tr>
      <th align="center"><strong>Libellé</strong></th>
      <th width="80" align="center"><strong>Quantité</strong></th>
      <th width="100" align="center"><strong>Prix</strong></th>
      <th width="100" align="center"><strong>Total</strong></th>
    </tr>
  </thead>

  <tbody>
  <?php
  $Stat = $pdo->query("SELECT * FROM ".$TB_PRODUITS." WHERE ".$PAYS."='1' AND Activer = 1 AND Stock = '1' ORDER BY Marque ASC; ");
  $i = 0;
  while($data = $Stat->fetch(PDO::FETCH_ASSOC)){
  ?>
    <tr>
      <td align="left" valign="middle">
        <?php echo $data["Libelle"]." ".$data["Contenance"]; ?>
      </td>
      <td align="center" valign="middle">
        <input type="text" class="span2" id="Fr_Quantite_<?php echo $i;?>" style="width:100%; text-align:center; margin:0;" maxlength="2" value="0" onblur="calcul('<?php echo $i;?>')">
      </td>
      <td align="right" valign="middle">
       <input type="text" class="span2" id="Fr_Prix_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="<?php echo $data["Prix"]; ?>"  onblur="calcul('<?php echo $i;?>')">
      </td>
      <td align="right" valign="middle">
        <input type="text" class="span2" id="Fr_Total_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="0">
      </td>
    </tr>
  <?php
    $i++;
  }
  ?>
  </tbody>
</table>
</code>```

答:
A little hard to test with the PHP Code and such, but I would use oninput instead of onblur and use parseInt instead of Number. How does it work?

      Libellé
      Quantité
      Prix
      Total

    <?php
  $Stat = $pdo->query("SELECT * FROM ".$TB_PRODUITS." WHERE ".$PAYS."='1' AND Activer = 1 AND Stock = '1' ORDER BY Marque ASC; ");
  $i = 0;
  while($data = $Stat->fetch(PDO::FETCH_ASSOC)){
  ?>

        <?php echo $data["Libelle"]." ".$data["Contenance"]; ?>

        <input type="text" class="span2" id="Fr_Quantite_<?php echo $i;?>" style="width:100%; text-align:center; margin:0;" maxlength="2" value="0" oninput="calcul('<?php echo $i;?>')">

        <input type="text" class="span2" id="Fr_Prix_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="<?php echo $data[" Prix "]; ?>" oninput="calcul('<?php echo $i;?>')">

        <input type="text" class="span2 js-totals" id="Fr_Total_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="0">

    <?php
    $i++;
  }
  ?>

```

UPDATE: Added updateTotal function and js-total class to the total inputs for each row. You can update the total by running updateTotal(25). YOu can change 25 to what ever percent you want off the price.

This can set the "percent-off" from by selecting another element. If you want to do so, please ask another question and add a link here.

Title: Total sum of all inputs

Body:
I would like to have the total sum of all input of my array instantaneously in a div.
Here is my complete code:

      Libellé
      Quantité
      Prix
      Total

  <?php
  $Stat = $pdo->query("SELECT * FROM ".$TB_PRODUITS." WHERE ".$PAYS."='1' AND Activer = 1 AND Stock = '1' ORDER BY Marque ASC; ");
  $i = 0;
  while($data = $Stat->fetch(PDO::FETCH_ASSOC)){
  ?>

        <?php echo $data["Libelle"]." ".$data["Contenance"]; ?>

        <input type="text" class="span2" id="Fr_Quantite_<?php echo $i;?>" style="width:100%; text-align:center; margin:0;" maxlength="2" value="0" onblur="calcul('<?php echo $i;?>')">

       <input type="text" class="span2" id="Fr_Prix_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="<?php echo $data["Prix"]; ?>"  onblur="calcul('<?php echo $i;?>')">

        <input type="text" class="span2" id="Fr_Total_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="0">

  <?php
    $i++;
  }
  ?>

Body:
A little hard to test with the PHP Code and such, but I would use oninput instead of onblur and use parseInt instead of Number. How does it work?

<script type="text/javascript">
  function calcul(i) {
    var prix = parseInt(document.getElementById("Fr_Quantite_" + i).value);
    var quantite = parseInt(document.getElementById("Fr_Prix_" + i).value);
    var ttc = prix * quantite;
    document.getElementById("Fr_Total_" + i).value = ttc;

    updateTotal(25);
  }

  function updateTotal(sale) {
    var totals = document.getElementsByClassName("js-totals");
    var total = 0;

    for (var i=0; i < totals.length; i++) {
      total += totals[i].value;
    }
    total *= (100 - sale)/100;

    document.getElementById("TotalGlobal").innerHTML = total;
    document.getElementById("TotalGlobal25").innerHTML = total;
  }
</script>

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" id="TableauJaquery1" class="Tableau">
  <thead>
    <tr>
      <th align="center"><strong>Libellé</strong></th>
      <th width="80" align="center"><strong>Quantité</strong></th>
      <th width="100" align="center"><strong>Prix</strong></th>
      <th width="100" align="center"><strong>Total</strong></th>
    </tr>
  </thead>

  <tbody>
    <?php
  $Stat = $pdo->query("SELECT * FROM ".$TB_PRODUITS." WHERE ".$PAYS."='1' AND Activer = 1 AND Stock = '1' ORDER BY Marque ASC; ");
  $i = 0;
  while($data = $Stat->fetch(PDO::FETCH_ASSOC)){
  ?>
    <tr>
      <td align="left" valign="middle">
        <?php echo $data["Libelle"]." ".$data["Contenance"]; ?>
      </td>
      <td align="center" valign="middle">
        <input type="text" class="span2" id="Fr_Quantite_<?php echo $i;?>" style="width:100%; text-align:center; margin:0;" maxlength="2" value="0" oninput="calcul('<?php echo $i;?>')">
      </td>
      <td align="right" valign="middle">
        <input type="text" class="span2" id="Fr_Prix_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="<?php echo $data[" Prix "]; ?>" oninput="calcul('<?php echo $i;?>')">
      </td>
      <td align="right" valign="middle">
        <input type="text" class="span2 js-totals" id="Fr_Total_<?php echo $i;?>" style="width:100%; text-align:right; margin:0;" maxlength="2" readonly value="0">
      </td>
    </tr>
    <?php
    $i++;
  }
  ?>
  </tbody>
</table>

UPDATE: Added updateTotal function and js-total class to the total inputs for each row. You can update the total by running updateTotal(25). YOu can change 25 to what ever percent you want off the price.

This can set the "percent-off" from by selecting another element. If you want to do so, please ask another question and add a link here.


问:
Speed Control of MediaPlayer in Android
I am developing a player app and I am using MediaPlayer for that.

Now, I want to change the speed of the playing track.

I've seen so many apps with this functionality. How can I do this?

答:
Now you can use

mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(speed))

for API 23 and up!

Title: Speed Control of MediaPlayer in Android

ContentLicense: CC BY-SA 4.0


问:
SRP: Why use instance field values instead of parameters?
I've just read SRP, as easy as 123…, and all of it resonates with me except one paragraph, in a section named "Cohesion" (I've claimed before to "get" Cohesion, but this talk of parameters vs instance fields gives me pause...):

Take your class. Look at your methods.
  Do they have parameters or are they
  using instance fields? If they are
  using parameters, remove them. Make
  them instance fields. Do you end up
  with methods that only use one of the
  five instances? That most likely is a
  warning of the low cohesion that
  exists between that method and your
  class.

Is this removal of parameters merely a temporary exercise to reveal methods which are approaching static-ability (low cohesion), with the idea being that you return to the use of parameters when you're finished?

Or is the preference for instance fields over parameters an actual design technique to maintain high cohesion?

Have I somehow taken the quote out of context?

答:
CRUD is a real common approach to interface based programming.  Take two concrete classes that implement a CRUD interface:  Employee and Building.

Now imagine how your code will look being parameter based:

```<code>Employee employeeObj = new Employee();
Building buildingObj = new Building();

string firstName = "Bob";
employeeObj.Create(firstName);
</code>```

What about building?

```<code>BuildingTypes buildingType = BuildingTypes.One;
building.Create(buildingType);
</code>```

Woops...how are you supposed to implement CRUD interface with different parameters?  Create overloads?  More interfaces?  What about two params (firstname lastname)?

This will get so ugly so fast....because as soon as you use parameters with a CRUD interface you have more than one reason to change, which decreases the design's cohesion.

Let's try using our objects/instance based params...

```<code>Employee empObj = new Employee();
empObj.FirstName = "Bob";

empObj.Create();

Building buildingObj = new Building();
buildingObj.BuildingType = BuildingTypes.One;

buildingObj.Create();
</code>```

With simple CRUD and no params one can even sprinkle in polymorphism:

```<code>someObj.Create();
</code>```

This also leads to encapsulated composition, decoupling, SRP, etc...

Body:
CRUD is a real common approach to interface based programming.  Take two concrete classes that implement a CRUD interface:  Employee and Building.

Now imagine how your code will look being parameter based:

Employee employeeObj = new Employee();
Building buildingObj = new Building();

string firstName = "Bob";
employeeObj.Create(firstName);

What about building?

BuildingTypes buildingType = BuildingTypes.One;
building.Create(buildingType);

Woops...how are you supposed to implement CRUD interface with different parameters?  Create overloads?  More interfaces?  What about two params (firstname lastname)?

This will get so ugly so fast....because as soon as you use parameters with a CRUD interface you have more than one reason to change, which decreases the design's cohesion.

Let's try using our objects/instance based params...

Employee empObj = new Employee();
empObj.FirstName = "Bob";

empObj.Create();

Building buildingObj = new Building();
buildingObj.BuildingType = BuildingTypes.One;

buildingObj.Create();

With simple CRUD and no params one can even sprinkle in polymorphism:

someObj.Create();

This also leads to encapsulated composition, decoupling, SRP, etc...


问:
Python CashFlow Calculator
I am trying to formulate an equation that can calculate the outstanding_balance in one go using python. It is quite simple using the iterative process. For example:

```<code>for month in range(1, self.amortMonths + 1):

        # Calculate intial and future interest payments

        interest = self.originalPrin * self.rate / 12

        # Calculate intial and future principal payments

        principal_pmt = self.pmt - interest

        # Outstanding balance is reduced by the principal_pmt

        self.originalPrin = self.originalPrin - principal_pmt
</code>```

So self.amortMonths is basically the monthly duration at which the loan must be payed off and along with self.rate, they will determine the self.pmt variable which is the monthly amount the borrower has to pay inorder to reduce the self.oringalPrin value to 0 by the end of self.amortMonths.

Example:

Lets say I have a loan of $1000 (OutstandingPrin) with an interest rate of 10% then my interest payment for the first month is 1000 * 10% = $100. In order to find the self.pmt amount I used a numpy.pmt function which takes the outstandingPrin, rate, amortMonths as parameters to generate a monthly payment value that will reduce the OutstandingPrin to 0 by the end of the amortMonths. Lets say that self.pmt = $120 then the principal_pmt = 120 - 100 = $20. So the outstandingPrin for the next month is 1000-20=$980. Then this just becomes an iterative process.

So I actually need some help to determine an equation that can do this in one go without the need for an iterative process. Apparently, I need to use linear algebra but I don't come from a math background so I was wondering if anyone has any ideas?

EDIT:

So something like this:

Balance_i = Balance_i-1 - (pmt - Balance_i-1 * Rate).

答:
Below creates a Python implementation of this Excel example with the following values set:

```<code>import pandas as pd
import numpy as np

prin = 200000 # principal/beginning loan balance
rate = 0.0675 # annual rate; monthly will be 6.75%/12
n = 30 # years; total periods will be 360 w/ monthly pmts
</code>```

Next, you can use NumPy's Financial functions to find the interest and principal per period.  Note that these don't depend on your running loan balance.  The nice thing is that the results below are arrays (payment schedules):

```<code>months = np.arange(1, n * 12 + 1) # months 1 thru 360
principal = np.ppmt(rate / 12, months, n * 12, prin)
interest = np.ipmt(rate / 12, months, n * 12, prin)
</code>```

Computing the outstanding balance as of a certain time uses:

Which we can define below.  Careful with signs when you implement.

```<code>def balance(pv, r, n, p):
    dfac = (1 + r / 12) ** n
    return pv * dfac - p * (dfac - 1) / (r / 12)
</code>```

Also, compute a "constant" PMT value.  This is the interest plus principal and is constant throughout all periods.  It's a scalar value, rather than array.

```<code>pmt = np.pmt(rate / 12, n * 12, prin)
</code>```

Finally, put the above together in table form:

```<code>table = pd.DataFrame({'Beg Balance' : balance(prin, rate, months - 1, -pmt),
                      'Principal' : principal,
                      'Interest' : interest,
                      'End Balance' : balance(prin, rate, months, -pmt)},
                     index=months)

# Check that the loan amortizes down to 0
assert np.allclose(table['End Balance'].tail(1), 0)

print(table.round(2))
     Beg Balance  End Balance  Interest  Principal
1      200000.00    199827.80  -1125.00    -172.20
2      199827.80    199654.64  -1124.03    -173.16
3      199654.64    199480.50  -1123.06    -174.14
4      199480.50    199305.38  -1122.08    -175.12
5      199305.38    199129.28  -1121.09    -176.10
..           ...          ...       ...        ...
356      6377.95      5116.63    -35.88   -1261.32
357      5116.63      3848.22    -28.78   -1268.42
358      3848.22      2572.67    -21.65   -1275.55
359      2572.67      1289.94    -14.47   -1282.72
360      1289.94        -0.00     -7.26   -1289.94
</code>```

Title: Python CashFlow Calculator

Body:
I am trying to formulate an equation that can calculate the outstanding_balance in one go using python. It is quite simple using the iterative process. For example:

for month in range(1, self.amortMonths + 1):

        # Calculate intial and future interest payments

        interest = self.originalPrin * self.rate / 12

        # Calculate intial and future principal payments

        principal_pmt = self.pmt - interest

        # Outstanding balance is reduced by the principal_pmt

        self.originalPrin = self.originalPrin - principal_pmt

So self.amortMonths is basically the monthly duration at which the loan must be payed off and along with self.rate, they will determine the self.pmt variable which is the monthly amount the borrower has to pay inorder to reduce the self.oringalPrin value to 0 by the end of self.amortMonths.

Example:

Lets say I have a loan of $1000 (OutstandingPrin) with an interest rate of 10% then my interest payment for the first month is 1000 * 10% = $100. In order to find the self.pmt amount I used a numpy.pmt function which takes the outstandingPrin, rate, amortMonths as parameters to generate a monthly payment value that will reduce the OutstandingPrin to 0 by the end of the amortMonths. Lets say that self.pmt = $120 then the principal_pmt = 120 - 100 = $20. So the outstandingPrin for the next month is 1000-20=$980. Then this just becomes an iterative process.

So I actually need some help to determine an equation that can do this in one go without the need for an iterative process. Apparently, I need to use linear algebra but I don't come from a math background so I was wondering if anyone has any ideas?

EDIT:

So something like this:

Balance_i = Balance_i-1 - (pmt - Balance_i-1 * Rate).

Body:
Below creates a Python implementation of this Excel example with the following values set:

import pandas as pd
import numpy as np

prin = 200000 # principal/beginning loan balance
rate = 0.0675 # annual rate; monthly will be 6.75%/12
n = 30 # years; total periods will be 360 w/ monthly pmts

Next, you can use NumPy's Financial functions to find the interest and principal per period.  Note that these don't depend on your running loan balance.  The nice thing is that the results below are arrays (payment schedules):

months = np.arange(1, n * 12 + 1) # months 1 thru 360
principal = np.ppmt(rate / 12, months, n * 12, prin)
interest = np.ipmt(rate / 12, months, n * 12, prin)

Computing the outstanding balance as of a certain time uses:

Which we can define below.  Careful with signs when you implement.

def balance(pv, r, n, p):
    dfac = (1 + r / 12) ** n
    return pv * dfac - p * (dfac - 1) / (r / 12)

Also, compute a "constant" PMT value.  This is the interest plus principal and is constant throughout all periods.  It's a scalar value, rather than array.

pmt = np.pmt(rate / 12, n * 12, prin)

Finally, put the above together in table form:

table = pd.DataFrame({'Beg Balance' : balance(prin, rate, months - 1, -pmt),
                      'Principal' : principal,
                      'Interest' : interest,
                      'End Balance' : balance(prin, rate, months, -pmt)},
                     index=months)

# Check that the loan amortizes down to 0
assert np.allclose(table['End Balance'].tail(1), 0)

print(table.round(2))
     Beg Balance  End Balance  Interest  Principal
1      200000.00    199827.80  -1125.00    -172.20
2      199827.80    199654.64  -1124.03    -173.16
3      199654.64    199480.50  -1123.06    -174.14
4      199480.50    199305.38  -1122.08    -175.12
5      199305.38    199129.28  -1121.09    -176.10
..           ...          ...       ...        ...
356      6377.95      5116.63    -35.88   -1261.32
357      5116.63      3848.22    -28.78   -1268.42
358      3848.22      2572.67    -21.65   -1275.55
359      2572.67      1289.94    -14.47   -1282.72
360      1289.94        -0.00     -7.26   -1289.94


问:
How to install Scikit-Learn for Julia (Jupyter notebook)
So I currently have Scikit-Learn installed via anaconda for Python. However I wish to use Scikit-Learn in Julia on a Jupyter notebook, (see the link I am using) http://scikitlearnjl.readthedocs.io/en/latest/quickstart/.

I have ran:

```<code>Pkg.add("ScikitLearn")
Pkg.update()
</code>```

which both ran perfectly and installed/updated. However when I run the next line of code (as the tutorial states):

```<code>using ScikitLearn
@sk_import linear_model: LogisticRegression
</code>```

I get the error message:

```<code>INFO: Precompiling module ScikitLearn.
WARNING: Module Compat with uuid 32171850160196 is missing from the
cache.
This may mean module Compat does not support precompilation but is
imported by a module that does.
ERROR: LoadError: Declaring __precompile__(false) is not allowed in
files that are being precompiled.
in require(::Symbol) at ./loading.jl:385
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in macro expansion; at ./none:2 [inlined]
in anonymous at ./<missing>:?
in eval(::Module, ::Any) at ./boot.jl:234
in eval(::Module, ::Any) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in process_options(::Base.JLOptions) at ./client.jl:242
in _start() at ./client.jl:321
in _start() at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
while loading
/Users/lawrence/.julia/v0.5/ScikitLearnBase/src/ScikitLearnBase.jl, in
expression starting on line 5
ERROR: LoadError: LoadError: Failed to precompile ScikitLearnBase to
/Users/lawrence/.julia/lib/v0.5/ScikitLearnBase.ji.
in compilecache(::String) at ./loading.jl:593
in require(::Symbol) at ./loading.jl:393
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in macro expansion; at ./none:2 [inlined]
in anonymous at ./<missing>:?
in eval(::Module, ::Any) at ./boot.jl:234
in eval(::Module, ::Any) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in process_options(::Base.JLOptions) at ./client.jl:242
in _start() at ./client.jl:321
in _start() at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
while loading /Users/lawrence/.julia/v0.5/ScikitLearn/src/Skcore.jl, in
expression starting on line 7
while loading
/Users/lawrence/.julia/v0.5/ScikitLearn/src/ScikitLearn.jl, in
expression starting on line 12
Failed to precompile ScikitLearn to
/Users/lawrence/.julia/lib/v0.5/ScikitLearn.ji.

in compilecache(::String) at ./loading.jl:593
in require(::Symbol) at ./loading.jl:422
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
</code>```

If anyone knows what I need to do to get the functions to work on Julia please do let me know. I really appreciate any help that anyone can give!
Thank-you for your time.

答: So I found the code in the link worked after a restarting my laptop. After a restart when I ran the code Julia uninstalled numpy and then reinstalled numpy together with SciKit (despite saying it had already installed SciKit). There must of been some problem that numpy was causing with installation.</p>

Body:
So I currently have Scikit-Learn installed via anaconda for Python. However I wish to use Scikit-Learn in Julia on a Jupyter notebook, (see the link I am using) http://scikitlearnjl.readthedocs.io/en/latest/quickstart/.

I have ran:

Pkg.add("ScikitLearn")
Pkg.update()

which both ran perfectly and installed/updated. However when I run the next line of code (as the tutorial states):

using ScikitLearn
@sk_import linear_model: LogisticRegression

I get the error message:

INFO: Precompiling module ScikitLearn.
WARNING: Module Compat with uuid 32171850160196 is missing from the
cache.
This may mean module Compat does not support precompilation but is
imported by a module that does.
ERROR: LoadError: Declaring __precompile__(false) is not allowed in
files that are being precompiled.
in require(::Symbol) at ./loading.jl:385
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in macro expansion; at ./none:2 [inlined]
in anonymous at ./<missing>:?
in eval(::Module, ::Any) at ./boot.jl:234
in eval(::Module, ::Any) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in process_options(::Base.JLOptions) at ./client.jl:242
in _start() at ./client.jl:321
in _start() at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
while loading
/Users/lawrence/.julia/v0.5/ScikitLearnBase/src/ScikitLearnBase.jl, in
expression starting on line 5
ERROR: LoadError: LoadError: Failed to precompile ScikitLearnBase to
/Users/lawrence/.julia/lib/v0.5/ScikitLearnBase.ji.
in compilecache(::String) at ./loading.jl:593
in require(::Symbol) at ./loading.jl:393
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in include_from_node1(::String) at ./loading.jl:488
in include_from_node1(::String) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in macro expansion; at ./none:2 [inlined]
in anonymous at ./<missing>:?
in eval(::Module, ::Any) at ./boot.jl:234
in eval(::Module, ::Any) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
in process_options(::Base.JLOptions) at ./client.jl:242
in _start() at ./client.jl:321
in _start() at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?
while loading /Users/lawrence/.julia/v0.5/ScikitLearn/src/Skcore.jl, in
expression starting on line 7
while loading
/Users/lawrence/.julia/v0.5/ScikitLearn/src/ScikitLearn.jl, in
expression starting on line 12
Failed to precompile ScikitLearn to
/Users/lawrence/.julia/lib/v0.5/ScikitLearn.ji.

in compilecache(::String) at ./loading.jl:593
in require(::Symbol) at ./loading.jl:422
in require(::Symbol) at /Applications/Julia-
0.5.app/Contents/Resources/julia/lib/julia/sys.dylib:?

If anyone knows what I need to do to get the functions to work on Julia please do let me know. I really appreciate any help that anyone can give!
Thank-you for your time.


问:
javascript - check a radiobutton from a radiobutton group by it's value from code
i'm working on a project, and i need to check a radiobutton from a radiobutton group by it's value.

i have this radiobutton group.

```<code><label class="radio-inline">
    <input type="radio" name="slect" id="optradio"  value="oriente" checked>=Orienté
</label>
<label class="radio-inline">
    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté
</label>
</code>```

in my code i have a variable, i manage to affect it to  one of two values

```<code>var x="Nonoriente"       or     var x="oriente"
</code>```

My goal is to automatiquly check the équivalent value of x in the radiobuttons when an event is triggered.

答:
First of all, fix the elephant in the room: you cannot have duplicate IDs in your markup. It is not some arbitrary rule that we made up, but browser behaviour when handling duplicated ID is undefined. No project will ever require you to have duplicate IDs—that just means bad design.

If you want to select by value, the only way is to select all the radio buttons on the page that matches this selector: input[type="radio"][value="Nonoriente"]. Then you iterate through this node collection and set their checked property to true.

p/s: This approach is inefficient, but considering that you have mentioned restraints in your project, it might be the only viable solution.

var btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  var radioInputs = document.querySelectorAll('input[type="radio"][value="Nonoriente"]');

  for (i = 0; i < radioInputs.length; ++i) {
    radioInputs[i].checked = true;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="radio-inline">
    <input type="radio" name="slect" id="optradio"  value="oriente" checked>Orienté
</label>
<label class="radio-inline">
    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté
</label>

<button type="button" id="btn">Click to check nonoriente</button></code>```

Body:
i'm working on a project, and i need to check a radiobutton from a radiobutton group by it's value.

i have this radiobutton group.

    <input type="radio" name="slect" id="optradio"  value="oriente" checked>=Orienté

    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté

in my code i have a variable, i manage to affect it to  one of two values

var x="Nonoriente"       or     var x="oriente"

My goal is to automatiquly check the équivalent value of x in the radiobuttons when an event is triggered.

Body:
First of all, fix the elephant in the room: you cannot have duplicate IDs in your markup. It is not some arbitrary rule that we made up, but browser behaviour when handling duplicated ID is undefined. No project will ever require you to have duplicate IDs—that just means bad design.

If you want to select by value, the only way is to select all the radio buttons on the page that matches this selector: input[type="radio"][value="Nonoriente"]. Then you iterate through this node collection and set their checked property to true.

p/s: This approach is inefficient, but considering that you have mentioned restraints in your project, it might be the only viable solution.

var btn = document.getElementById('btn');

btn.addEventListener('click', function() {
  var radioInputs = document.querySelectorAll('input[type="radio"][value="Nonoriente"]');

  for (i = 0; i < radioInputs.length; ++i) {
    radioInputs[i].checked = true;
  }
});

<label class="radio-inline">
    <input type="radio" name="slect" id="optradio"  value="oriente" checked>Orienté
</label>
<label class="radio-inline">
    <input type="radio" name="slect" id="optradio" value="Nonoriente">Non orienté
</label>

<button type="button" id="btn">Click to check nonoriente</button>


问:
Connect to Azure App Service from Azure VM
I am planning on using an outsourcing team for data processing and want to avoid them downloading or storing client data on their local machines. To facilitate this, I want to create an Azure VM in which they can do all their work (msoft office, etc.) and access an ASP MVC app hosted as an app service in Azure. The MVC app is integrated with the corporate AD and for the outsourcing logins I want to see if the request is coming from my VM or the internet (the latter gets denied). So far I have:

Created a ASP MVC5 app and an Azure VM

Connected the two via VPN (point to site)

When I attempt to go to the public URL for the website on the VM, I get the "this page can't be displayed" thing, which leads me to believe I'm on the right track (now I have to update the hostfile of the machine to the private IP of the mvc app service app?). How do I do the following:

Connect to the app service via web browser (this needs to be over the vnet so that I can pick and choose in the app code who can login outside the network)

Get the network ip of the app service so I can update the VM hostfile

Am I on the right track here? Thanks in advance!

答:
Your understanding of Azure App service is not accurate. Azure App service cannot be accessed via a private IP. They already sit inside a private vnet. They can be only accessed via public hostname with a common DNS name (azurewebsites.net)

Your scenario requires the Azure Web app and the VM to reside in the same VNET, which is not possible. There is another offering called ILB ASE, which allows you to do this. But it's a more elaborate setup. See this for more information: Using ILB with AN ASE

In your scenario you can restrict access to the web app via IP Restrictions module.  See this article: IP & Domain Restrictions in Azure App Service

I understand this not the solution u wanted. What you want can be achieved via ILB ASE, but that is an expensive and elaborate set-up.

HTH


问:
Object_detection implementation details
I would like to understand how the recently-published object_detection models are prepared for use in Tensorflow with the long-term goal to modify one of the meta-architectures.

Is there a write-up on how the meta-architectures (such as Faster R-CNN or SSD) are implemented, or is reading the code the only way to find out? In particular, I understand how these meta-architectures are defined in general (as it is described in corresponding papers), but I do not understand how they are implemented in Tensorflow.

Even a very high-level overview, describing how the flow works in this context (or with an unrelated model) would be very useful. (I am aware of the short object_detection docs and the detection architecture guide, but that's not it.)

What is particularly overwhelming when looking at these object_detection models, say, from a Keras background, is that the models are defined using relatively-large proto and config files with scant comments, while involving non-standard layers. Furthermore, the procedure to obtain, e.g., the frozen_inference_graph.pb file used in training from the proto and config files is not obvious at all.

Any sources of information or hints are much appreciated.

答:
I went through the code base last week for both the Faster R-CNN and SSD pipeline. I would highly recommend you go through the code base. The functions/methods are very well documented and if you know the specifics from the corresponding papers, it can be easily understood. For understanding how information from the config files affect the model, I recommend going through the various builders (within the builders folder). If you are using an SSD model for training, check the corresponding function in model_builder.py. This is where all information from config is used to construct the instances of the various classes. model_builder.py is invoked by the train() function inside trainer.py

So to answer you in short, as someone who was in your shoes a week back the best approach I recommend is for you to go through the code :).

Title: Object_detection implementation details