问:
Apache camel - EIP design query
I have a  EIP design related query.I have a requirement to process csv file by chunks and call a Rest API.After completion of processing of whole file i need to call another Rest API telling processing is complete.I wanted the route to be transacted so i have queue in between in case of end system not available the retry will happen at broker level.

My flow is as below.
First flow:
csv File->Split by chunk of 100 records->Place message in queue

the second flow(Transacted route):
Picks message from queue ->call the rest API

the second flow is transacted.Since iam breaking the flow and it is asynchronous iam not sure how to call to the completion call.I do not have a persistent store to status of each chunk processing.

is there anyway i can achive it using JMS functionality or Camel?

答:
What you can use for your first flow is the Camel Splitter EIP:

http://camel.apache.org/splitter.html

And closely looking at the doc, you will find that there are three exchange properties available for each split exchange:

CamelSplitIndex: A split counter that increases for each Exchange being split. The counter starts from 0.

CamelSplitSize: The total number of Exchanges that was splitted. This header is not applied for stream based splitting. From Camel 2.9 onwards this header is also set in stream based splitting, but only on the completed Exchange.

CamelSplitComplete: Whether or not this Exchange is the last.

As they are exchange properties, you should put them to JMS headers before sending the messages to a queue. But then you should be able to make use of the information at the second flow, so you can know which is the last message.

Keep in mind, though, that it's all asynchronous so the CamelSplitComplete flag doesn't necessarily mean the last message at the second flow. You may create a stateful counter or utilise the Resequencer EIP http://camel.apache.org/resequencer.html to deal with the asynchronicity.

Title: Apache camel - EIP design query


来源: stackexchange

问:
Generating My Angular Project Release Notes with Standard Version
I created an Angular project using angular-cli and pushed it to GitHub. I then created a new branch and updated packages, installed standard-version and ran npm run release -- --first-release as instructed. I then pushed the whole into a new branch on GitHub, created a pull request, squashed and merged onto master, pulled back into local master, and ran standard-version again finally followed by git push --follow-tags origin master. Here's the state on GitHub:

All notes that I wrote in the pull request body are not visible in the changelog file, and they are obviously not in the chore(release) generated by standard-version. Why?

They are also not written within the Releases tabs at all, even though I can see the released tags there.

Should I have made the version 1.0.0 in packages.json before starting in order to adhere to semantic versioning?

What am I doing wrong?

答:
You're not doing anything wrong. chore doesn't show up in CHANGELOG.md (see: https://github.com/conventional-changelog/standard-version/issues/135)

To have release notes uploaded, you will to use something like https://github.com/conventional-changelog/conventional-github-releaser

It's up to you where to start. Generally, when labeled 0.x, the project is still unstable and will go through vast API changes. When the project becomes stable, bump the major to 1.x and adhere to semver.

ContentLicense: CC BY-SA 3.0


问:
Django - MySQL: 1045 Access Denied for 'user'@'localhost'
I have a Django app using a MySQL database. I created a database foo, then created a new user foo_user, granted all privileges on foo.* to foo_user, and flushed privileges.

I can log in from the command-line as foo_user and SHOW GRANTS; which gives me this:

```<code>+-----------------------------------------------------------+
| Grants for foo_user@localhost                             |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'foo_user'@'localhost'              |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'foo_user'@'localhost' |
+-----------------------------------------------------------+
</code>```

I can connect from Python using this snippet:

```<code>import MySQLdb

try:
    db = MySQLdb.connect('localhost', 'foo_user', 'verysecurepassword', 'foo')
    cursor = db.cursor()
    cursor.execute('SHOW GRANTS;')
    results = cursor.fetchall()

    for r in results:
        print(r)
except MySQLdb.Error as e:
    print(e)
</code>```

This prints the privileges for foo_user as one would expect.

settings.py

```<code>db_pass = ''
db_pass_file = os.path.join(os.path.expanduser('~'), 'db.passwd')
with open(db_pass_file, 'r') as dbpf:
    db_pass = dbpf.read()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foo',
        'USER': 'foo_user',
        'PASSWORD': db_pass,
        'HOST': 'localhost',
        'PORT': '3306',
    },
}
</code>```

However, when I try to makemigrations I get

```<code>django.db.utils.OperationalError: (1045, "Access denied for user 'foo_user'@'localhost' (using password: YES)")
</code>```

I've followed the advice of every SO answer I could find. I've dropped databases and users and then recreated them several times. I can't find anything obviously wrong with it and the error itself is not terribly helpful. My question is: how can I coerce more information out of either MySQL or Django so I can figure out what's going wrong?

ETA: python 3.5.2, Django 1.11.7, mysql Ver 14.14 Distrib 5.7.20, running on an EC2 instance

答:
The problem was an extra newline character at the end of the password being read from file.

The solution was to change

db_pass = dbpf.read()

to

db_pass = dbpf.read().rstrip()

Body:
I have a Django app using a MySQL database. I created a database foo, then created a new user foo_user, granted all privileges on foo.* to foo_user, and flushed privileges.

I can log in from the command-line as foo_user and SHOW GRANTS; which gives me this:

+-----------------------------------------------------------+
| Grants for foo_user@localhost                             |
+-----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'foo_user'@'localhost'              |
| GRANT ALL PRIVILEGES ON `foo`.* TO 'foo_user'@'localhost' |
+-----------------------------------------------------------+

I can connect from Python using this snippet:

import MySQLdb

try:
    db = MySQLdb.connect('localhost', 'foo_user', 'verysecurepassword', 'foo')
    cursor = db.cursor()
    cursor.execute('SHOW GRANTS;')
    results = cursor.fetchall()

    for r in results:
        print(r)
except MySQLdb.Error as e:
    print(e)

This prints the privileges for foo_user as one would expect.

settings.py

db_pass = ''
db_pass_file = os.path.join(os.path.expanduser('~'), 'db.passwd')
with open(db_pass_file, 'r') as dbpf:
    db_pass = dbpf.read()

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foo',
        'USER': 'foo_user',
        'PASSWORD': db_pass,
        'HOST': 'localhost',
        'PORT': '3306',
    },
}

However, when I try to makemigrations I get

django.db.utils.OperationalError: (1045, "Access denied for user 'foo_user'@'localhost' (using password: YES)")

I've followed the advice of every SO answer I could find. I've dropped databases and users and then recreated them several times. I can't find anything obviously wrong with it and the error itself is not terribly helpful. My question is: how can I coerce more information out of either MySQL or Django so I can figure out what's going wrong?

ETA: python 3.5.2, Django 1.11.7, mysql Ver 14.14 Distrib 5.7.20, running on an EC2 instance


问:
Java ASM java.lang.NoSuchMethodError
I am new to Java ASM. I am trying to instrument methods using Java agent and ASM. But, I am getting error like below:

```<code>Exception in thread "main" java.lang.NoSuchMethodError: java.io.FileOutputStream$1.<init>(Ljava/io/FileOutputStream;)V
    at java.io.FileOutputStream.close(FileOutputStream.java:354)
    at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:320)
    at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
    at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
    at WriteToFileExample.useFileWriter(WriteToFileExample.java:60)
    at WriteToFileExample.main(WriteToFileExample.java:30)
</code>```

I am using asm-6.0.

I tried to write simple test code and it works. But, for some of the methods in some classes, it does not work. I do not understand why! ClassVisitor is visiting the class and then for all the methods, it accepts MethodVisitor. If no such method is existing in a class how it accepts visitor and why it is throwing exception?

答: I have figured it out. FileOutputStream$1 is an inner class of FileOutputStram. Using java agent, I was not getting information about FileOutputStream rather I was getting information about FileOutputStream$1. But, when visiting method, it says no such method found named init, also for some other methods as there is no init method in FileOutputStream$1. Init method is in FileOutputStream. I changed java agent code to not to deal with the inner class but the actual FileOutputStream class and now it is fine.</p>

Title: Java ASM java.lang.NoSuchMethodError

Body:
I am new to Java ASM. I am trying to instrument methods using Java agent and ASM. But, I am getting error like below:

Exception in thread "main" java.lang.NoSuchMethodError: java.io.FileOutputStream$1.<init>(Ljava/io/FileOutputStream;)V
    at java.io.FileOutputStream.close(FileOutputStream.java:354)
    at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:320)
    at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
    at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
    at WriteToFileExample.useFileWriter(WriteToFileExample.java:60)
    at WriteToFileExample.main(WriteToFileExample.java:30)

I am using asm-6.0.

I tried to write simple test code and it works. But, for some of the methods in some classes, it does not work. I do not understand why! ClassVisitor is visiting the class and then for all the methods, it accepts MethodVisitor. If no such method is existing in a class how it accepts visitor and why it is throwing exception?


问:
Presenting a ViewController
Does presenting a ViewController cause the presented controller to run its viewDidLoad method?

If a view1 is loaded and another is presented. Then something triggers to present view1. Will it run through its viewDidLoad method?

IF not how should this be done? ViewDidAppear?

答:
Building on what Jesse relayed, the viewDidLoad is called when the view is loaded into memory (usually the first time the view controller is ever about to be presented since app launch - simplified, but this will suffice for now).

When you display other view controllers and then come back some how to this original "view1" view controller, unless there was a memory event that jettisoned it from memory, it will NOT call viewDidLoad again.

Instead, it will call the following, in order:

viewWillAppear:

viewDidAppear:

In viewWillAppear:, you have a place to do things "off screen" before your view controller is displayed.

In viewDidAppear:, you can do additional operations that are appropriate for when the view controller's view is already visible. For example, you want to run some little animation that the user will see once the view controller is fully visible.

In both of these methods, make sure you call super's implementation before you do anything. Also, to learn about this lifecycle, set a breakpoint or NSLog() statement in each of these methods (viewDidLoad, viewWillAppear, viewDidAppear) to see when they are called.

There's a concept piece in the Apple docs on View Controllers that is worth the 20 minute read - it'll clear up a lot of this key life cycle information about View Controllers, and these are central to iOS development. See the section "Understanding the View Management LifeCycle" at:

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/BasicViewControllers/BasicViewControllers.html%23//apple_ref/doc/uid/TP40007457-CH101-SW1

ContentLicense: CC BY-SA 2.5

Title: Presenting a ViewController


问:
Validate the user's input of only 0's and 1's
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

```<code>while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break
</code>```

答:
You're checking the length, but not validating the users input. eg,

s = '12345678' is a valid input into your code.

If you really want to validate, you could do something simple like

```<code>s1 = '11010101111'

if s1.count('1') + s1.count('0') == len(s1):
    print(int(s1,2))
</code>```

Body:
I have to convert an 8-bit binary number to a decimal number. I believe that I have the conversion correct along with validating if the user inputted an 8-bit binary number (no more, no less) but I am stuck on validating the user's input for only 0's and 1's.

Any help would be great. I feel like I am overthinking this but I tried everything.

Here is the code I have:

while True:
binary = input("Please enter a 8-bit binary number: ")
if len(binary) < 8 or len(binary) > 8:
    print("Must be an 8 bit binary!")

else:
    print(int(binary, 2))
    break

Body:
You're checking the length, but not validating the users input. eg,

s = '12345678' is a valid input into your code.

If you really want to validate, you could do something simple like

s1 = '11010101111'

if s1.count('1') + s1.count('0') == len(s1):
    print(int(s1,2))


问:
Unable to type more than 1 character with formgroup within a formarray in reactive form
I am thinking this could be a bug for Reactive Form. I would appreciate any help from more experienced Angular Experts.

Symptom: Unable to key in more than 1 character in input at given time.

Occurrence: When input is a FormGroup within a FormArray

Special Instructions : I have not Used FormBuilder

Code : Template(.html file)

```<code><form [formGroup]="profileSetup">
<div formArrayName="company">
          Company :
          <div *ngFor="let companyControl of profileSetup.get('company').value;let i=index;" [formGroupName]="i">
            <br>
            Company Name:<br>
            <input type="text" formControlName="company_name"><br>
            Company Address:<br>
            <input type="text" formControlName="company_address" ><br>
            Started On:<br>
            <input type="date" formControlName="started_on"><br>
            Ended On:<br>
            <input type="date" formControlName="ended_on"><br>
            Title(Worked As):<br>
            <input type="date" formControlName="title"><br>
        </div>
      </div>
      <input type="Submit" value="Submit">
    </form>
    <button value="Add Company" (click)="addCompany()"> Add Company</button><br>
</code>```

profile.component.ts

```<code>profileSetup:FormGroup
    ngOninit(){
      this.profileSetup=new FormGroup({
company:new FormArray([])
})
    }

addCompany(){
        const control=new FormGroup({
          company_name:new FormControl(''),
          company_address:new FormControl(''),
          started_on:new FormControl(''),
          ended_on:new FormControl(''),
          title:new FormControl('')
        });
        (<FormArray>this.profileSetup.get('company')).push(control);
        console.log(this.profileSetup.get('company').value);
      }
</code>```

答: In the ngFor, instead of .value it should be .controls</p>

Body:
I am thinking this could be a bug for Reactive Form. I would appreciate any help from more experienced Angular Experts.

Symptom: Unable to key in more than 1 character in input at given time.

Occurrence: When input is a FormGroup within a FormArray

Special Instructions : I have not Used FormBuilder

Code : Template(.html file)

<form [formGroup]="profileSetup">

          Company :

            Company Name:

            <input type="text" formControlName="company_name">

            Company Address:

            <input type="text" formControlName="company_address" >

            Started On:

            <input type="date" formControlName="started_on">

            Ended On:

            <input type="date" formControlName="ended_on">

            Title(Worked As):

            <input type="date" formControlName="title">

      <input type="Submit" value="Submit">
    </form>
    <button value="Add Company" (click)="addCompany()"> Add Company</button>

profile.component.ts

profileSetup:FormGroup
    ngOninit(){
      this.profileSetup=new FormGroup({
company:new FormArray([])
})
    }

addCompany(){
        const control=new FormGroup({
          company_name:new FormControl(''),
          company_address:new FormControl(''),
          started_on:new FormControl(''),
          ended_on:new FormControl(''),
          title:new FormControl('')
        });
        (<FormArray>this.profileSetup.get('company')).push(control);
        console.log(this.profileSetup.get('company').value);
      }


问:
Alpha Vantage API Excel
I’ve got an Alpha Vantage API key and am having issues with parsing the data. I’m unsure how to approach parsing the data as there are JSON and CSV options. The CSV seems to be a download, I’m not trying to manually download a new file every time I want to update the stock price.

This is how I used to get the prices of stocks in Excel:

I would always use CTRL-ALT-F9 to refresh everything.

Unfortunately, Yahoo has stopped this service so I have to fix it.

答:
You can use Alpha Vantage the same way. But it gives you more information for each call so you need to parse it.
To get the latest stock price for example, this works:</p>

```<code>=NUMBERVALUE(MID(WEBSERVICE("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=<key>&datatype=csv&symbol=MSFT&outputsize=compact"),49,6))
</code>```

Title: Alpha Vantage API Excel

Body:
You can use Alpha Vantage the same way. But it gives you more information for each call so you need to parse it.
To get the latest stock price for example, this works:

=NUMBERVALUE(MID(WEBSERVICE("https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&apikey=<key>&datatype=csv&symbol=MSFT&outputsize=compact"),49,6))


问:
how to initialize dynamic 3d Array help need java
hi how i dynamically initialize 3d array
i have 4 table but in each table no of rows are different and columns are 4
each table has different records .how to initialize in loop dynamically
lets suppose 1st table has 4 records
2nd table has 5 records
3rd table has 3 records
4th table has 7 records

e.g String data[][][]= new String[4][unknown][4];

答:
Arrays (even in Java) are statically allocated. The unknown size should be calculated to be the maximum value you require.

Essentially what you'll be creating is an array of arrays of strings.

```<code>String data[][][] = new String[4][7][4]
</code>```

If you want each row to be a different size, you'll be needing to create an array of LinkedLists or similar data structure.

```<code>LinkedList<String[]>[4] data = new LinkedList<String []>[4]();
</code>```

Hope that helps.

Body:
Arrays (even in Java) are statically allocated. The unknown size should be calculated to be the maximum value you require.

Essentially what you'll be creating is an array of arrays of strings.

String data[][][] = new String[4][7][4]

If you want each row to be a different size, you'll be needing to create an array of LinkedLists or similar data structure.

LinkedList<String[]>[4] data = new LinkedList<String []>[4]();

Hope that helps.


问:
Laravel 5.5 BadMethodCall
I've been working on my Laravel 5.5 app, and everything was going fine until I went to do a composer update and ran into this:

```<code>Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
  [BadMethodCallException]

Method get does not exist.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1
</code>```

I can't figure out where this is coming from, the debug message isn't clear to me.

EDIT: composer dump-autoload returns the same error

答:
This was a weird one-- I can only assume I'd accidentally accepted an IDE prompt to use a class / autocomplete, and so the web route file had

```<code>use Illuminate\Routing\Route;
</code>```

at the top. Thanks to @ankit patel for the hint about the routes-- I commented out all my routes and I could again use composer, but adding even a single get route to / would throw the error.

I removed the use statement and it again worked.

Title: Laravel 5.5 BadMethodCall

Body:
I've been working on my Laravel 5.5 app, and everything was going fine until I went to do a composer update and ran into this:

Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
  [BadMethodCallException]

Method get does not exist.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I can't figure out where this is coming from, the debug message isn't clear to me.

EDIT: composer dump-autoload returns the same error

Body:
This was a weird one-- I can only assume I'd accidentally accepted an IDE prompt to use a class / autocomplete, and so the web route file had

use Illuminate\Routing\Route;

at the top. Thanks to @ankit patel for the hint about the routes-- I commented out all my routes and I could again use composer, but adding even a single get route to / would throw the error.

I removed the use statement and it again worked.


问:
Javascript Round function
```<code>a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000
</code>```

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.

答:
If you're alright with using a library, lodash has a method for this, _.round(number, [precision=0]) - computes number rounded to precision.

console.log(_.round(31283700000, -6));
console.log(_.round(60204605, -4));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: Javascript Round function

Body:
a                formula       b
31,283,700,000   round(a,-6)   31,284,000,000
60,204,605       round(a,-4)   60,200,000

I have an excel formula to process the currency value,
but I have difficulties to achieve the same result by using javascript,
any ideas to solve this?

Thanks.

Body:
If you're alright with using a library, lodash has a method for this, _.round(number, [precision=0]) - computes number rounded to precision.

console.log(_.round(31283700000, -6));
console.log(_.round(60204605, -4));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
What is the best software to host a ruby on rails application on production?
Is webrick the only good option?
I know there is a way of using apache, but is it better than webrick?</p>

答:
Four Choices

There are really four choices, well, plus WEBrick, but that would be an unusual choice for a production server. Approximately in order of increasing complexity...

nginx + Mongrel

nginx + Passenger

Apache + Mongrel

Apache + Passenger

(There is Phusion Passenger Standalone, but that's really an nginx + passenger compiled together, so I'm not counting it, although it may be a good option for some people.)

A larger site may then add specialized layer 7 hardware (NetScaler, F5, ...) in front of the servers.


问:
implementing HTTP method PATCH in python using bottle framework and pymongo
I am trying to build a RESTful api using bottle.
I am currently having trouble implementing HTTP method PATCH, so I hope someone can help me out finding what I am doing wrong.
I am pretty new to python, bottle, and mongodb, so this is more of a learning process.

Here is how db is set up

```<code>dbname = "movies"
#plugin = MongoPlugin(uri, db, json_mongo=True)
connection = MongoClient(uri, 27017)
db = connection[dbname]
db[dbname].insert(movies)
</code>```

The data I put in the db

```<code>movies = [{'title' : 'Blade Runner', 'rel_date' : '25 June 1982', 'prod_company' : 'Warner Bros.'},
      {'title': 'Snatch', 'rel_date': '19 January 2001', 'prod_company': 'Columbia Pictures'},
      {'title': 'The Godfather', 'rel_date': '24 March 1972', 'prod_company': 'Paramount Pictures'},
      {"title": "Fight Club", "rel_date": "21 September 1999", "prod_company": "20th Century Fox" }]
</code>```

And here is my method to handle PATCH

```<code>@app.route('/<name>', method='PATCH')
def update_movie(name):
    data = request.body.read_line()
    if not data:
        abort(404, 'No data received')
    entity = json.loads(data)
    db[dbname].update({'title' : name}, {'$set':entity}}) # edited
    return {'Message' : 'The movie was updated'}
</code>```

I use Postman to send requests. If i send PATCH request like this

```<code>http://localhost:8080/test
passing: {"rel_date": "new_date"}
</code>```

I get Error: 405 Method Not Allowed : the requested url caused an error.
Please help me figure out what I am doing wrong.
Thanks.

答:
Found the error. My rout was not set up properly, which caused a 405.
Also corrected some errors inside the function.</p>

```<code>@route('/movies/<name>', method='PATCH')
def update_movie(name):

    data = request.json
    if not data:
        abort(400, 'No data received')

    try:
        db[dbname].update_one({'title' : name}, {'$set': data})
    except Exception as e:
        print (e)

    return {'Message' : 'The movie was updated'}
</code>```

Body:
I am trying to build a RESTful api using bottle.
I am currently having trouble implementing HTTP method PATCH, so I hope someone can help me out finding what I am doing wrong.
I am pretty new to python, bottle, and mongodb, so this is more of a learning process.

Here is how db is set up

dbname = "movies"
#plugin = MongoPlugin(uri, db, json_mongo=True)
connection = MongoClient(uri, 27017)
db = connection[dbname]
db[dbname].insert(movies)

The data I put in the db

movies = [{'title' : 'Blade Runner', 'rel_date' : '25 June 1982', 'prod_company' : 'Warner Bros.'},
      {'title': 'Snatch', 'rel_date': '19 January 2001', 'prod_company': 'Columbia Pictures'},
      {'title': 'The Godfather', 'rel_date': '24 March 1972', 'prod_company': 'Paramount Pictures'},
      {"title": "Fight Club", "rel_date": "21 September 1999", "prod_company": "20th Century Fox" }]

And here is my method to handle PATCH

@app.route('/<name>', method='PATCH')
def update_movie(name):
    data = request.body.read_line()
    if not data:
        abort(404, 'No data received')
    entity = json.loads(data)
    db[dbname].update({'title' : name}, {'$set':entity}}) # edited
    return {'Message' : 'The movie was updated'}

I use Postman to send requests. If i send PATCH request like this

http://localhost:8080/test
passing: {"rel_date": "new_date"}

I get Error: 405 Method Not Allowed : the requested url caused an error.
Please help me figure out what I am doing wrong.
Thanks.

Body:
Found the error. My rout was not set up properly, which caused a 405.
Also corrected some errors inside the function.

@route('/movies/<name>', method='PATCH')
def update_movie(name):

    data = request.json
    if not data:
        abort(400, 'No data received')

    try:
        db[dbname].update_one({'title' : name}, {'$set': data})
    except Exception as e:
        print (e)

    return {'Message' : 'The movie was updated'}


问:
When one of the p tag is not empty, hide other p tag
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

```<code>if($('.discount).is(':not("empty)'))
</code>```

or

```<code>.discount.innerHTML.length != 0
</code>```

But all are not working. Can anyone give me some solution of it?

答:
Here you go with a solution https://jsfiddle.net/0fy0kpc0/1/

$(function(){
  if($('.discount').html().length){
   console.log("yeah!")
   $('.information p:nth-child(2)').hide();
   $('.information p:nth-child(3)').hide();
   $('.information p:nth-child(4)').hide();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div></code>```

Mistake was in .discount.innerHTML.length != 0 line in jsfiddle

Here you go with one more solution https://jsfiddle.net/0fy0kpc0/2/

$(function(){
  if (!$('.discount').is(':empty')){
    console.log("yeah!")
    $('.information p:nth-child(2)').hide();
    $('.information p:nth-child(3)').hide();
    $('.information p:nth-child(4)').hide();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div></code>```

Hope this will help you.

ContentLicense: CC BY-SA 4.0

Body:
I am having the structure like this JSFiddle.

What I want to do is that: When the class ("discount") is not empty, the other 3 p tags will be hidden. When the class ("discount") is empty, the other 3 p tags will be shown.

I have been trying

if($('.discount).is(':not("empty)'))

or

.discount.innerHTML.length != 0

But all are not working. Can anyone give me some solution of it?

Body:
Here you go with a solution https://jsfiddle.net/0fy0kpc0/1/

$(function(){
  if($('.discount').html().length){
   console.log("yeah!")
   $('.information p:nth-child(2)').hide();
   $('.information p:nth-child(3)').hide();
   $('.information p:nth-child(4)').hide();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

Mistake was in .discount.innerHTML.length != 0 line in jsfiddle

Here you go with one more solution https://jsfiddle.net/0fy0kpc0/2/

$(function(){
  if (!$('.discount').is(':empty')){
    console.log("yeah!")
    $('.information p:nth-child(2)').hide();
    $('.information p:nth-child(3)').hide();
    $('.information p:nth-child(4)').hide();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="information">
  <p class="s">
    <em class="discount">DISCOUNT PROMOTION</em>
  </p>
  <p class="s">
    Title
  </p>
  <p class="s">
    Name
  </p>
  <p class="s">
    Detail
  </p>

</div>

Hope this will help you.


问:
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
I have this class in php:

```<code>class DBManager
{
    private $db;
    private $queryResult;

    public static function getInsetance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new DBManager();
        }
        return $inst;
    }

    private function __construct()
    {
        $this->db = mysqli_connect('localhost', 'root', '', 'mydb');
        if (mysqli_connect_errno()) {
            echo 'DB CONNECTION ERROR';
            die;
        } else {
            mysqli_query($this->db, 'SET NAMES UTF8');

        }
    }

    public function _destruct()
    {
        mysqli_close($this->db);
    }

    /**
     * @param $query
     * @return bool|mysqli_result
     */
    public function runQuery($query)
    {
        return $this->queryResult = mysqli_query($this->db, $query);
    }

    /**
     * @return mysql_result
     */
    public function getLastQueryResult()
    {
        return $this->queryResult;
    }
}
</code>```

And in another file, I want to do some different query. I want to get the last id of INSERT query in this code:

```<code>session_start();
require 'DBManager.php';

$db = DBManager::getInsetance();

    $query = "INSERT INTO `test`(`creator`, `name`) VALUES
             ('$creatorid','$name')";

    $result = $db->runQuery($query);
</code>```

答:
I found:

In  DBManager class i must do this changs:

```<code>   public function runQuery($query)
    {
        $this->queryResult = mysqli_query($this->db, $query);
        $last_id = mysqli_insert_id($this->db);
        if($last_id !== 0){
            return   $last_id;
        }

        return $this->queryResult;

    }
</code>```

and i will get $result in server file.

Body:
How i can get the last id of INSERT query when i'm using an external php file for doing all type of querys?
I have this class in php:

class DBManager
{
    private $db;
    private $queryResult;

    public static function getInsetance()
    {
        static $inst = null;
        if ($inst === null) {
            $inst = new DBManager();
        }
        return $inst;
    }

    private function __construct()
    {
        $this->db = mysqli_connect('localhost', 'root', '', 'mydb');
        if (mysqli_connect_errno()) {
            echo 'DB CONNECTION ERROR';
            die;
        } else {
            mysqli_query($this->db, 'SET NAMES UTF8');

        }
    }

    public function _destruct()
    {
        mysqli_close($this->db);
    }

    /**
     * @param $query
     * @return bool|mysqli_result
     */
    public function runQuery($query)
    {
        return $this->queryResult = mysqli_query($this->db, $query);
    }

    /**
     * @return mysql_result
     */
    public function getLastQueryResult()
    {
        return $this->queryResult;
    }
}

And in another file, I want to do some different query. I want to get the last id of INSERT query in this code:

session_start();
require 'DBManager.php';

$db = DBManager::getInsetance();

    $query = "INSERT INTO `test`(`creator`, `name`) VALUES
             ('$creatorid','$name')";

    $result = $db->runQuery($query);

Body:
I found:

In  DBManager class i must do this changs:

   public function runQuery($query)
    {
        $this->queryResult = mysqli_query($this->db, $query);
        $last_id = mysqli_insert_id($this->db);
        if($last_id !== 0){
            return   $last_id;
        }

        return $this->queryResult;

    }

and i will get $result in server file.


问:
subset and change multiple columns with different "functions"
How is it possible to change multiple columns on subset by some conditions in a pandas dataframe?

For example given the input data:

```<code>import pandas as pd
dat = pd.DataFrame({"y": ("441912", "abc", "121", "4455")})
dat['leny'] = dat['y'].str.len()
dat['yfoo'] = None

dat

        y leny yfoo
1: 441912    6   NA
2:    abc    3   NA
3:    121    3   NA
4:   4455    4   NA
</code>```

Then subset the rows for which y starts with 44 and has a length of 4 or 5, then for those rows strip the 44 from the beginning in y, substract 2 from leny and set yfoo to False, resulting to the following output:

```<code>        y leny  yfoo
1: 441912    6    NA
2:    abc    3    NA
3:    121    3    NA
4:     55    2 FALSE
</code>```

My attempt at doing this:

```<code># pandas struggle follows
dat[dat.leny.isin((4, 5)) & dat.y.str.match('^44', na=False)]
</code>```

What do I do next?

答:
Using a comprehension to gather data.</p>

```<code>y = dat.y.values.tolist()

dat2 = np.array([
    [x[2:], len(x) - 2, False, i]
    for i, x in enumerate(y)
    if x.startswith('44') and (len(x) // 2 == 2)
], object)

dat.iloc[dat2[:, -1].astype(int), :] = dat2[:, :-1]

dat

        y  leny   yfoo
0  441912     6   None
1     abc     3   None
2     121     3   None
3      55     2  False
</code>```

Body:
How is it possible to change multiple columns on subset by some conditions in a pandas dataframe?

For example given the input data:

import pandas as pd
dat = pd.DataFrame({"y": ("441912", "abc", "121", "4455")})
dat['leny'] = dat['y'].str.len()
dat['yfoo'] = None

dat

        y leny yfoo
1: 441912    6   NA
2:    abc    3   NA
3:    121    3   NA
4:   4455    4   NA

Then subset the rows for which y starts with 44 and has a length of 4 or 5, then for those rows strip the 44 from the beginning in y, substract 2 from leny and set yfoo to False, resulting to the following output:

        y leny  yfoo
1: 441912    6    NA
2:    abc    3    NA
3:    121    3    NA
4:     55    2 FALSE

My attempt at doing this:

# pandas struggle follows
dat[dat.leny.isin((4, 5)) & dat.y.str.match('^44', na=False)]

What do I do next?

Body:
Using a comprehension to gather data.

y = dat.y.values.tolist()

dat2 = np.array([
    [x[2:], len(x) - 2, False, i]
    for i, x in enumerate(y)
    if x.startswith('44') and (len(x) // 2 == 2)
], object)

dat.iloc[dat2[:, -1].astype(int), :] = dat2[:, :-1]

dat

        y  leny   yfoo
0  441912     6   None
1     abc     3   None
2     121     3   None
3      55     2  False


问:
Euclidean distance matrix performance between two shapes
The problem I am having is that I have to calculate a Euclidean distance matrix between shapes that can range from 20,000 up to 60,000 points, which produces 10-20GB amounts of data. I have to run each of these calculates thousands of times so 20GB x 7,000 (each calculation is a different point cloud). The shapes can be either 2D or 3D.

EDITED (Updated questions)

Is there a more efficient way to calculate the forward and backward distances without using two separate nested loops?

I know I could save the data matrix and calculate the minimum
distances in each direction, but then there is a huge memory issue
with large point clouds.

Is there a way to speed up this calculation and/or clean up the code to trim off time?

The irony is that I only need the matrix to calculate a very simple metric, but it requires the entire matrix to find that metric (Average Hausdorff distance).

Data example where each column represents a dimension of the shape and each row is a point in the shape:

```<code>first_configuration <- matrix(1:6,2,3)
second_configuration <- matrix(6:11,2,3)
colnames(first_configuration) <- c("x","y","z")
colnames(second_configuration) <- c("x","y","z")
</code>```

This code calculates a Euclidean distance between between coordinates:

```<code>m <- nrow(first_configuration)
n <- nrow(second_configuration)

D <- sqrt(pmax(matrix(rep(apply(first_configuration * first_configuration, 1, sum), n), m, n, byrow = F) + matrix(rep(apply(second_configuration * second_configuration, 1, sum), m), m, n, byrow = T) - 2 * first_configuration %*% t(second_configuration), 0))
D
</code>```

Output:

```<code>     [,1]      [,2]
[1,] 8.660254 10.392305
[2,] 6.928203  8.660254
</code>```

EDIT: included hausdorff average code

```<code>d1 <- mean(apply(D, 1, min))
d2 <- mean(apply(D, 2, min))
average_hausdorff <- mean(d1, d2)
</code>```

EDIT (Rcpp solution):
Here is my attempt to implement it in Rcpp so the matrix is never saved to memory. Working now but very slow.

```<code>sourceCpp(code=
#include <Rcpp.h>
#include <limits>
using namespace Rcpp;

// [[Rcpp::export]]
double edist_rcpp(NumericVector x, NumericVector y){
    double d = sqrt( sum( pow(x - y, 2) ) );
    return d;
}

// [[Rcpp::export]]
double avg_hausdorff_rcpp(NumericMatrix x, NumericMatrix y){
    int nrowx = x.nrow();
    int nrowy = y.nrow();
    double new_low_x = std::numeric_limits<int>::max();
    double new_low_y = std::numeric_limits<int>::max();

    double mean_forward = 0;
    double mean_backward = 0;
    double mean_hd;
    double td;

    //forward
    for(int i = 0; i < nrowx; i++) {
        for(int j = 0; j < nrowy; j++) {
            NumericVector v1 = x.row(i);
            NumericVector v2 = y.row(j);
            td = edist_rcpp(v1, v2);
            if(td < new_low_x) {
                new_low_x = td;
            }
        }
        mean_forward = mean_forward + new_low_x;
        new_low_x = std::numeric_limits<int>::max();
    }

    //backward
    for(int i = 0; i < nrowy; i++) {
        for(int j = 0; j < nrowx; j++) {
            NumericVector v1 = y.row(i);
            NumericVector v2 = x.row(j);
            td = edist_rcpp(v1, v2);
            if(td < new_low_y) {
                new_low_y = td;
            }
        }
        mean_backward = mean_backward + new_low_y;
        new_low_y = std::numeric_limits<int>::max();
    }

    //hausdorff mean
    mean_hd = (mean_forward / nrowx + mean_backward / nrowy) / 2;

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

EDIT (RcppParallel solution):
Definitely faster than the serial Rcpp solution and most certainly the R solution. If anyone has tips on how to improve my RcppParallel code to trim off some extra time it would be much appreciated!

```<code>sourceCpp(code=
#include <Rcpp.h>
#include <RcppParallel.h>
#include <limits>

// [[Rcpp::depends(RcppParallel)]]
struct minimum_euclidean_distances : public RcppParallel::Worker {
    //Input
    const RcppParallel::RMatrix<double> a;
    const RcppParallel::RMatrix<double> b;

    //Output
    RcppParallel::RVector<double> medm;

    minimum_euclidean_distances(const Rcpp::NumericMatrix a, const Rcpp::NumericMatrix b, Rcpp::NumericVector medm) : a(a), b(b), medm(medm) {}

    void operator() (std::size_t begin, std::size_t end) {
        for(std::size_t i = begin; i < end; i++) {
            double new_low = std::numeric_limits<double>::max();
            for(std::size_t j = 0; j < b.nrow(); j++) {
                double dsum = 0;
                for(std::size_t z = 0; z < b.ncol(); z++) {
                    dsum = dsum + pow(a(i,z) - b(j,z), 2);
                }
                dsum = pow(dsum, 0.5);
                if(dsum < new_low) {
                    new_low = dsum;
                }
            }
            medm[i] = new_low;
        }
    }
};

// [[Rcpp::export]]
double mean_directional_hausdorff_rcpp(Rcpp::NumericMatrix a, Rcpp::NumericMatrix b){
    Rcpp::NumericVector medm(a.nrow());
    minimum_euclidean_distances minimum_euclidean_distances(a, b, medm);
    RcppParallel::parallelFor(0, a.nrow(), minimum_euclidean_distances);
    double results = Rcpp::sum(medm);
    results = results / a.nrow();
    return results;
}

// [[Rcpp::export]]
double max_directional_hausdorff_rcpp(Rcpp::NumericMatrix a, Rcpp::NumericMatrix b){
    Rcpp::NumericVector medm(a.nrow());
    minimum_euclidean_distances minimum_euclidean_distances(a, b, medm);
    RcppParallel::parallelFor(0, a.nrow(), minimum_euclidean_distances);
    double results = Rcpp::max(medm);
    return results;
}
)
</code>```

Benchmarks using large point clouds of sizes 37,775 and 36,659:

```<code>//Rcpp serial solution
system.time(avg_hausdorff_rcpp(ll,rr))
   user  system elapsed
409.143   0.000 409.105

//RcppParallel solution
system.time(mean(mean_directional_hausdorff_rcpp(ll,rr), mean_directional_hausdorff_rcpp(rr,ll)))
   user  system elapsed
260.712   0.000  33.265
</code>```

答:
I try to use JuliaCall to do the calculation for the average Hausdorff distance.
JuliaCall embeds Julia in R.

I only try a serial solution in JuliaCall. It seems to be faster than the RcppParallel and the Rcpp serial solution in the question, but I don't have the benchmark data. Since ability for parallel computation is built in Julia. A parallel computation version in Julia should be written without much difficulty. I will update my answer after finding that out.

Below is the julia file I wrote:

```<code># Calculate the min distance from the k-th point in as to the points in bs
function min_dist(k, as, bs)
    n = size(bs, 1)
    p = size(bs, 2)
    dist = Inf
    for i in 1:n
        r = 0.0
        for j in 1:p
            r += (as[k, j] - bs[i, j]) ^ 2
            ## if r is already greater than the upper bound,
            ## then there is no need to continue doing the calculation
            if r > dist
                continue
            end
        end
        if r < dist
            dist = r
        end
    end
    sqrt(dist)
end

function avg_min_dist_from(as, bs)
    distsum = 0.0
    n1 = size(as, 1)
    for k in 1:n1
        distsum += min_dist_from(k, as, bs)
    end
    distsum / n1
end

function hausdorff_avg_dist(as, bs)
    (avg_min_dist_from(as, bs) + avg_min_dist_from(bs, as)) / 2
end
</code>```

And this is the R code to use the julia function:

```<code>first_configuration <- matrix(1:6,2,3)
second_configuration <- matrix(6:11,2,3)
colnames(first_configuration) <- c("x","y","z")
colnames(second_configuration) <- c("x","y","z")

m <- nrow(first_configuration)
n <- nrow(second_configuration)

D <- sqrt(matrix(rep(apply(first_configuration * first_configuration, 1, sum), n), m, n, byrow = F) + matrix(rep(apply(second_configuration * second_configuration, 1, sum), m), m, n, byrow = T) - 2 * first_configuration %*% t(second_configuration))
D

d1 <- mean(apply(D, 1, min))
d2 <- mean(apply(D, 2, min))
average_hausdorff <- mean(d1, d2)

library(JuliaCall)
## the first time of julia_setup could be quite time consuming
julia_setup()
## source the julia file which has our hausdorff_avg_dist function
julia_source("hausdorff.jl")

## check if the julia function is correct with the example
average_hausdorff_julia <- julia_call("hausdauff_avg_dist",
                                      first_configuration,
                                      second_configuration)
## generate some large random point clouds
n1 <- 37775
n2 <- 36659
as <- matrix(rnorm(n1 * 3), n1, 3)
bs <- matrix(rnorm(n2 * 3), n2, 3)

system.time(julia_call("hausdauff_avg_dist", as, bs))
</code>```

The time on my laptop was less than 20 seconds, note this is performance of the serial version of JuliaCall! I used the same data to test RCpp serial solution in the question, which took more than 10 minutes to run. I don't have RCpp parallel on my laptop now so I can't try that. And as I said, Julia has built-in ability to do parallel computation.

Body:
The problem I am having is that I have to calculate a Euclidean distance matrix between shapes that can range from 20,000 up to 60,000 points, which produces 10-20GB amounts of data. I have to run each of these calculates thousands of times so 20GB x 7,000 (each calculation is a different point cloud). The shapes can be either 2D or 3D.

EDITED (Updated questions)

Is there a more efficient way to calculate the forward and backward distances without using two separate nested loops?

I know I could save the data matrix and calculate the minimum
distances in each direction, but then there is a huge memory issue
with large point clouds.

Is there a way to speed up this calculation and/or clean up the code to trim off time?

The irony is that I only need the matrix to calculate a very simple metric, but it requires the entire matrix to find that metric (Average Hausdorff distance).

Data example where each column represents a dimension of the shape and each row is a point in the shape:

first_configuration <- matrix(1:6,2,3)
second_configuration <- matrix(6:11,2,3)
colnames(first_configuration) <- c("x","y","z")
colnames(second_configuration) <- c("x","y","z")

This code calculates a Euclidean distance between between coordinates:

m <- nrow(first_configuration)
n <- nrow(second_configuration)

D <- sqrt(pmax(matrix(rep(apply(first_configuration * first_configuration, 1, sum), n), m, n, byrow = F) + matrix(rep(apply(second_configuration * second_configuration, 1, sum), m), m, n, byrow = T) - 2 * first_configuration %*% t(second_configuration), 0))
D

Output:

     [,1]      [,2]
[1,] 8.660254 10.392305
[2,] 6.928203  8.660254

EDIT: included hausdorff average code

d1 <- mean(apply(D, 1, min))
d2 <- mean(apply(D, 2, min))
average_hausdorff <- mean(d1, d2)

EDIT (Rcpp solution):
Here is my attempt to implement it in Rcpp so the matrix is never saved to memory. Working now but very slow.

sourceCpp(code=
#include <Rcpp.h>
#include <limits>
using namespace Rcpp;

// [[Rcpp::export]]
double edist_rcpp(NumericVector x, NumericVector y){
    double d = sqrt( sum( pow(x - y, 2) ) );
    return d;
}

// [[Rcpp::export]]
double avg_hausdorff_rcpp(NumericMatrix x, NumericMatrix y){
    int nrowx = x.nrow();
    int nrowy = y.nrow();
    double new_low_x = std::numeric_limits<int>::max();
    double new_low_y = std::numeric_limits<int>::max();

    double mean_forward = 0;
    double mean_backward = 0;
    double mean_hd;
    double td;

    //forward
    for(int i = 0; i < nrowx; i++) {
        for(int j = 0; j < nrowy; j++) {
            NumericVector v1 = x.row(i);
            NumericVector v2 = y.row(j);
            td = edist_rcpp(v1, v2);
            if(td < new_low_x) {
                new_low_x = td;
            }
        }
        mean_forward = mean_forward + new_low_x;
        new_low_x = std::numeric_limits<int>::max();
    }

    //backward
    for(int i = 0; i < nrowy; i++) {
        for(int j = 0; j < nrowx; j++) {
            NumericVector v1 = y.row(i);
            NumericVector v2 = x.row(j);
            td = edist_rcpp(v1, v2);
            if(td < new_low_y) {
                new_low_y = td;
            }
        }
        mean_backward = mean_backward + new_low_y;
        new_low_y = std::numeric_limits<int>::max();
    }

    //hausdorff mean
    mean_hd = (mean_forward / nrowx + mean_backward / nrowy) / 2;

    return mean_hd;
}
)

EDIT (RcppParallel solution):
Definitely faster than the serial Rcpp solution and most certainly the R solution. If anyone has tips on how to improve my RcppParallel code to trim off some extra time it would be much appreciated!

sourceCpp(code=
#include <Rcpp.h>
#include <RcppParallel.h>
#include <limits>

// [[Rcpp::depends(RcppParallel)]]
struct minimum_euclidean_distances : public RcppParallel::Worker {
    //Input
    const RcppParallel::RMatrix<double> a;
    const RcppParallel::RMatrix<double> b;

    //Output
    RcppParallel::RVector<double> medm;

    minimum_euclidean_distances(const Rcpp::NumericMatrix a, const Rcpp::NumericMatrix b, Rcpp::NumericVector medm) : a(a), b(b), medm(medm) {}

    void operator() (std::size_t begin, std::size_t end) {
        for(std::size_t i = begin; i < end; i++) {
            double new_low = std::numeric_limits<double>::max();
            for(std::size_t j = 0; j < b.nrow(); j++) {
                double dsum = 0;
                for(std::size_t z = 0; z < b.ncol(); z++) {
                    dsum = dsum + pow(a(i,z) - b(j,z), 2);
                }
                dsum = pow(dsum, 0.5);
                if(dsum < new_low) {
                    new_low = dsum;
                }
            }
            medm[i] = new_low;
        }
    }
};

// [[Rcpp::export]]
double mean_directional_hausdorff_rcpp(Rcpp::NumericMatrix a, Rcpp::NumericMatrix b){
    Rcpp::NumericVector medm(a.nrow());
    minimum_euclidean_distances minimum_euclidean_distances(a, b, medm);
    RcppParallel::parallelFor(0, a.nrow(), minimum_euclidean_distances);
    double results = Rcpp::sum(medm);
    results = results / a.nrow();
    return results;
}

// [[Rcpp::export]]
double max_directional_hausdorff_rcpp(Rcpp::NumericMatrix a, Rcpp::NumericMatrix b){
    Rcpp::NumericVector medm(a.nrow());
    minimum_euclidean_distances minimum_euclidean_distances(a, b, medm);
    RcppParallel::parallelFor(0, a.nrow(), minimum_euclidean_distances);
    double results = Rcpp::max(medm);
    return results;
}
)

Benchmarks using large point clouds of sizes 37,775 and 36,659:

//Rcpp serial solution
system.time(avg_hausdorff_rcpp(ll,rr))
   user  system elapsed
409.143   0.000 409.105

//RcppParallel solution
system.time(mean(mean_directional_hausdorff_rcpp(ll,rr), mean_directional_hausdorff_rcpp(rr,ll)))
   user  system elapsed
260.712   0.000  33.265

Body:
I try to use JuliaCall to do the calculation for the average Hausdorff distance.
JuliaCall embeds Julia in R.

I only try a serial solution in JuliaCall. It seems to be faster than the RcppParallel and the Rcpp serial solution in the question, but I don't have the benchmark data. Since ability for parallel computation is built in Julia. A parallel computation version in Julia should be written without much difficulty. I will update my answer after finding that out.

Below is the julia file I wrote:

# Calculate the min distance from the k-th point in as to the points in bs
function min_dist(k, as, bs)
    n = size(bs, 1)
    p = size(bs, 2)
    dist = Inf
    for i in 1:n
        r = 0.0
        for j in 1:p
            r += (as[k, j] - bs[i, j]) ^ 2
            ## if r is already greater than the upper bound,
            ## then there is no need to continue doing the calculation
            if r > dist
                continue
            end
        end
        if r < dist
            dist = r
        end
    end
    sqrt(dist)
end

function avg_min_dist_from(as, bs)
    distsum = 0.0
    n1 = size(as, 1)
    for k in 1:n1
        distsum += min_dist_from(k, as, bs)
    end
    distsum / n1
end

function hausdorff_avg_dist(as, bs)
    (avg_min_dist_from(as, bs) + avg_min_dist_from(bs, as)) / 2
end

And this is the R code to use the julia function:

first_configuration <- matrix(1:6,2,3)
second_configuration <- matrix(6:11,2,3)
colnames(first_configuration) <- c("x","y","z")
colnames(second_configuration) <- c("x","y","z")

m <- nrow(first_configuration)
n <- nrow(second_configuration)

D <- sqrt(matrix(rep(apply(first_configuration * first_configuration, 1, sum), n), m, n, byrow = F) + matrix(rep(apply(second_configuration * second_configuration, 1, sum), m), m, n, byrow = T) - 2 * first_configuration %*% t(second_configuration))
D

d1 <- mean(apply(D, 1, min))
d2 <- mean(apply(D, 2, min))
average_hausdorff <- mean(d1, d2)

library(JuliaCall)
## the first time of julia_setup could be quite time consuming
julia_setup()
## source the julia file which has our hausdorff_avg_dist function
julia_source("hausdorff.jl")

## check if the julia function is correct with the example
average_hausdorff_julia <- julia_call("hausdauff_avg_dist",
                                      first_configuration,
                                      second_configuration)
## generate some large random point clouds
n1 <- 37775
n2 <- 36659
as <- matrix(rnorm(n1 * 3), n1, 3)
bs <- matrix(rnorm(n2 * 3), n2, 3)

system.time(julia_call("hausdauff_avg_dist", as, bs))

The time on my laptop was less than 20 seconds, note this is performance of the serial version of JuliaCall! I used the same data to test RCpp serial solution in the question, which took more than 10 minutes to run. I don't have RCpp parallel on my laptop now so I can't try that. And as I said, Julia has built-in ability to do parallel computation.


问:
Non-dependent name lookup and lambda
I have the following code:

```<code>template <class T>
class Outer
{
public:
    Outer();

    template <class U>
    void templateFunc()
    {
    }

private:
    class Inner
    {
    public:
        Inner(Outer& outer)
        {
            outer.templateFunc<int>();
            Outer* outer_ptr = &outer;
            [outer_ptr]()
            {
                outer_ptr->templateFunc<int>();
            }();
        }
    };

    Inner m_inner;
};

template <class T>
Outer<T>::Outer()
    : m_inner(*this)
{
}

int main()
{
    Outer<double> outer;
}
</code>```

As you can see, there is a template class that contains a nested class, which in constructor calls some template method of its enclosing class. AFAIK, even though enclosing class is a template class - for the nested class it is a non-dependent name, so calling its template method without template should not be a problem. The problem happens when I define a lambda inside nested class' constructor, capture pointer to outer class, and try to call the same template method - g++7.2 gives the following compilation error:

```<code>prog.cc: In lambda function:

prog.cc:22:41: error: expected primary-expression before 'int'
                outer_ptr->templateFunc<int>();
                                        ^~~
prog.cc:22:41: error: expected ';' before 'int'
</code>```

However, g++-5.4 and g++-6.3 compile this code just fine. So it seems that g++-7.2 treats the outer_ptr's type inside the lambda as a dependent name - and I cannot understand why.  Can someone explain this to me?

答:
Yes, this is a gcc regression. Filed as 82980.

Here's a reduced example:

```<code>template <class T>
struct Outer
{
    template <class U>
    void f();

    void bar(Outer outer) {
        [outer](){ outer.f<int>(); };
    }
};

int main() { }
</code>```

outer.f is member access for the current instantiation, so that expression shouldn't count as type dependent, so you shouldn't need to provide the template keyword.

Title: Non-dependent name lookup and lambda

Body:
I have the following code:

template <class T>
class Outer
{
public:
    Outer();

    template <class U>
    void templateFunc()
    {
    }

private:
    class Inner
    {
    public:
        Inner(Outer& outer)
        {
            outer.templateFunc<int>();
            Outer* outer_ptr = &outer;
            [outer_ptr]()
            {
                outer_ptr->templateFunc<int>();
            }();
        }
    };

    Inner m_inner;
};

template <class T>
Outer<T>::Outer()
    : m_inner(*this)
{
}

int main()
{
    Outer<double> outer;
}

As you can see, there is a template class that contains a nested class, which in constructor calls some template method of its enclosing class. AFAIK, even though enclosing class is a template class - for the nested class it is a non-dependent name, so calling its template method without template should not be a problem. The problem happens when I define a lambda inside nested class' constructor, capture pointer to outer class, and try to call the same template method - g++7.2 gives the following compilation error:

prog.cc: In lambda function:

prog.cc:22:41: error: expected primary-expression before 'int'
                outer_ptr->templateFunc<int>();
                                        ^~~
prog.cc:22:41: error: expected ';' before 'int'

However, g++-5.4 and g++-6.3 compile this code just fine. So it seems that g++-7.2 treats the outer_ptr's type inside the lambda as a dependent name - and I cannot understand why.  Can someone explain this to me?

Body:
Yes, this is a gcc regression. Filed as 82980.

Here's a reduced example:

template <class T>
struct Outer
{
    template <class U>
    void f();

    void bar(Outer outer) {
        [outer](){ outer.f<int>(); };
    }
};

int main() { }

outer.f is member access for the current instantiation, so that expression shouldn't count as type dependent, so you shouldn't need to provide the template keyword.


问:
Swift 4 ,CoreData: error: Failed to load model named textTabelView
When I using Swift4 in Xcode 9 gives me

2017-11-13 10:17:15.807151+0800 textTabelView[1146:53409] [discovery]
  errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
  2017-11-13 10:17:16.369075+0800 textTabelView[1146:52958] [error] error:  Failed
  to load model named textTabelView CoreData: error:  Failed to load model named textTabelView

My Codes:

```<code>@IBAction func savaArea(_ sender: UIBarButtonItem) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    area = AreaMO(context: appDelegate.persistentContainer.viewContext)
    area.area = areaText.text
    area.province = provinceText.text
    area.part = partText.text
    area.isVisited = visitedLabel.text
    if let imageData = UIImageJPEGRepresentation(coverImageView.image!, 0.8){
        area.image = NSData(data: imageData) as Data
    }
    print("saving...")
    appDelegate.saveContext()

    performSegue(withIdentifier: "unwindToArea", sender: self)

}
</code>```

The AppDelegat.swift about CoreData:

```<code>// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "textTabelView")

    ...
}
</code>```

i'm sure I did import the CoreData correctly.

The project can build normally, but when I touch the button (which @IBaction is), the warning was printed in the console and the app crashed

How can I fixed it?

答:
This is the same error you would get if the name of your NSPersistentContainer parameter did not match the name of your xcdatamodeld file. Possible solutions:

Double check that the the data model is named "textTabelView.xcdatamodeld",

delete the old xcdatamodeld file and create a new one if the name is corrupted with some invisible characters, or

clean build the app folder (⌥⇧⌘K) (ie option+shift+apple+K).

Good luck!

Body:
When I using Swift4 in Xcode 9 gives me

2017-11-13 10:17:15.807151+0800 textTabelView[1146:53409] [discovery]
  errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}
  2017-11-13 10:17:16.369075+0800 textTabelView[1146:52958] [error] error:  Failed
  to load model named textTabelView CoreData: error:  Failed to load model named textTabelView

My Codes:

@IBAction func savaArea(_ sender: UIBarButtonItem) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    area = AreaMO(context: appDelegate.persistentContainer.viewContext)
    area.area = areaText.text
    area.province = provinceText.text
    area.part = partText.text
    area.isVisited = visitedLabel.text
    if let imageData = UIImageJPEGRepresentation(coverImageView.image!, 0.8){
        area.image = NSData(data: imageData) as Data
    }
    print("saving...")
    appDelegate.saveContext()

    performSegue(withIdentifier: "unwindToArea", sender: self)

}

The AppDelegat.swift about CoreData:

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "textTabelView")

    ...
}

i'm sure I did import the CoreData correctly.

The project can build normally, but when I touch the button (which @IBaction is), the warning was printed in the console and the app crashed

How can I fixed it?


问:
C# - Split Fully Uppercase String Into Separate Words (No Spaces)
Im currently working on a project where I will need to separate individual words from a string. The catch is that all the words in the string are capitalized and have no spaces. The following is an example of the kind of input the program is receiving:

"COMPUTERFIVECODECOLOR"

This should be split into the following result:

"COMPUTER"
"FIVE"
"CODE"
"COLOR"

So far, I have been using the following method to split my strings (and it has worked for all scenarios except this edge case):

```<code>private static List<string> NormalizeSections(List<string> wordList)
        {
            var modifiedList = new List<string>();
            foreach (var word in wordList)
            {
                int index = wordList.IndexOf(word);
                var split = Regex.Split(word, @"(\p{Lu}\p{Ll}+)").ToList();
                split.RemoveAll(i => i == "");

                modifiedList.AddRange(split);
            }
            return modifiedList;
        }
</code>```

If anyone has any ideas on how to handle this, I would be more than happy to hear them. Also, please let me know if I can provide additional information.

答:
I am making some assumptions on how you want to search for matching words. Firstly, at a given character index, preference will be given to the longest matching word in the dictionary.
Secondly, if at a given character index no word is found, we move on to the next character and search again.

The implementation below uses a Trie to index the dictionary of all valid words. Rather than looping through each word in the dictionary, we then progress through each character in the input string, looking for the longest word.

I lifted the implementation of the Trie in C# from this very handy SO answer: https://stackoverflow.com/a/6073004

Edit: fixed a bug in the Trie when adding a word which is a substring of existing word, such as Emergency then Emerge.

The code is available on DotNetFiddle.

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

public class Program
{
    public static void Main()
    {

        var words = new[] { "COMPUTE", "FIVE", "CODE", "COLOR", "PUT", "EMERGENCY", "MERGE", "EMERGE" };

        var trie = new Trie(words);

        var input = "COMPUTEEMERGEFIVECODECOLOR";

        for (var charIndex = 0; charIndex < input.Length; charIndex++)
        {
            var longestWord = FindLongestWord(trie.Root, input, charIndex);

            if (longestWord == null)
            {
                Console.WriteLine("No word found at char index {0}", charIndex);
            }
            else
            {
                Console.WriteLine("Found {0} at char index {1}", longestWord, charIndex);

                charIndex += longestWord.Length - 1;
            }
        }

    }

    static private string FindLongestWord(Trie.Node node, string input, int charIndex)
    {
        var character = char.ToUpper(input[charIndex]);

        string longestWord = null;

        foreach (var edge in node.Edges)
        {
            if (edge.Key.ToChar() == character)
            {
                var foundWord = edge.Value.Word;

                if (!edge.Value.IsTerminal)
                {
                    var longerWord = FindLongestWord(edge.Value, input, charIndex + 1);

                    if (longerWord != null) foundWord = longerWord;
                }

                if (foundWord != null && (longestWord == null || edge.Value.Word.Length > longestWord.Length))
                {
                    longestWord = foundWord;
                }
            }
        }

        return longestWord;
    }
}

//Trie taken from: https://stackoverflow.com/a/6073004
public struct Letter
{
    public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static implicit operator Letter(char c)
    {
        return new Letter() { Index = Chars.IndexOf(c) };
    }
    public int Index;
    public char ToChar()
    {
        return Chars[Index];
    }
    public override string ToString()
    {
        return Chars[Index].ToString();
    }
}

public class Trie
{
    public class Node
    {
        public string Word;
        public bool IsTerminal { get { return Edges.Count == 0 && Word != null; } }
        public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
    }

    public Node Root = new Node();

    public Trie(string[] words)
    {
        for (int w = 0; w < words.Length; w++)
        {
            var word = words[w];
            var node = Root;
            for (int len = 1; len <= word.Length; len++)
            {
                var letter = word[len - 1];
                Node next;
                if (!node.Edges.TryGetValue(letter, out next))
                {
                    next = new Node();

                    node.Edges.Add(letter, next);
                }

                if (len == word.Length)
                {
                    next.Word = word;
                }

                node = next;
            }
        }
    }

}
</code>```

Output is:

```<code>Found COMPUTE at char index 0
Found EMERGE at char index 7
Found FIVE at char index 13
Found CODE at char index 17
Found COLOR at char index 21
</code>```

Body:
Im currently working on a project where I will need to separate individual words from a string. The catch is that all the words in the string are capitalized and have no spaces. The following is an example of the kind of input the program is receiving:

"COMPUTERFIVECODECOLOR"

This should be split into the following result:

"COMPUTER"
"FIVE"
"CODE"
"COLOR"

So far, I have been using the following method to split my strings (and it has worked for all scenarios except this edge case):

private static List<string> NormalizeSections(List<string> wordList)
        {
            var modifiedList = new List<string>();
            foreach (var word in wordList)
            {
                int index = wordList.IndexOf(word);
                var split = Regex.Split(word, @"(\p{Lu}\p{Ll}+)").ToList();
                split.RemoveAll(i => i == "");

                modifiedList.AddRange(split);
            }
            return modifiedList;
        }

If anyone has any ideas on how to handle this, I would be more than happy to hear them. Also, please let me know if I can provide additional information.

Body:
I am making some assumptions on how you want to search for matching words. Firstly, at a given character index, preference will be given to the longest matching word in the dictionary.
Secondly, if at a given character index no word is found, we move on to the next character and search again.

The implementation below uses a Trie to index the dictionary of all valid words. Rather than looping through each word in the dictionary, we then progress through each character in the input string, looking for the longest word.

I lifted the implementation of the Trie in C# from this very handy SO answer: https://stackoverflow.com/a/6073004

Edit: fixed a bug in the Trie when adding a word which is a substring of existing word, such as Emergency then Emerge.

The code is available on DotNetFiddle.

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {

        var words = new[] { "COMPUTE", "FIVE", "CODE", "COLOR", "PUT", "EMERGENCY", "MERGE", "EMERGE" };

        var trie = new Trie(words);

        var input = "COMPUTEEMERGEFIVECODECOLOR";

        for (var charIndex = 0; charIndex < input.Length; charIndex++)
        {
            var longestWord = FindLongestWord(trie.Root, input, charIndex);

            if (longestWord == null)
            {
                Console.WriteLine("No word found at char index {0}", charIndex);
            }
            else
            {
                Console.WriteLine("Found {0} at char index {1}", longestWord, charIndex);

                charIndex += longestWord.Length - 1;
            }
        }

    }

    static private string FindLongestWord(Trie.Node node, string input, int charIndex)
    {
        var character = char.ToUpper(input[charIndex]);

        string longestWord = null;

        foreach (var edge in node.Edges)
        {
            if (edge.Key.ToChar() == character)
            {
                var foundWord = edge.Value.Word;

                if (!edge.Value.IsTerminal)
                {
                    var longerWord = FindLongestWord(edge.Value, input, charIndex + 1);

                    if (longerWord != null) foundWord = longerWord;
                }

                if (foundWord != null && (longestWord == null || edge.Value.Word.Length > longestWord.Length))
                {
                    longestWord = foundWord;
                }
            }
        }

        return longestWord;
    }
}

//Trie taken from: https://stackoverflow.com/a/6073004
public struct Letter
{
    public const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static implicit operator Letter(char c)
    {
        return new Letter() { Index = Chars.IndexOf(c) };
    }
    public int Index;
    public char ToChar()
    {
        return Chars[Index];
    }
    public override string ToString()
    {
        return Chars[Index].ToString();
    }
}

public class Trie
{
    public class Node
    {
        public string Word;
        public bool IsTerminal { get { return Edges.Count == 0 && Word != null; } }
        public Dictionary<Letter, Node> Edges = new Dictionary<Letter, Node>();
    }

    public Node Root = new Node();

    public Trie(string[] words)
    {
        for (int w = 0; w < words.Length; w++)
        {
            var word = words[w];
            var node = Root;
            for (int len = 1; len <= word.Length; len++)
            {
                var letter = word[len - 1];
                Node next;
                if (!node.Edges.TryGetValue(letter, out next))
                {
                    next = new Node();

                    node.Edges.Add(letter, next);
                }

                if (len == word.Length)
                {
                    next.Word = word;
                }

                node = next;
            }
        }
    }

}

Output is:

Found COMPUTE at char index 0
Found EMERGE at char index 7
Found FIVE at char index 13
Found CODE at char index 17
Found COLOR at char index 21


问:
Python requests POST image file to rails paperclip, Rails: params ParseError
I am downloading an image with Google Drive API and uploading the file to my Rails API with Paperclip.

I've downloaded the Google Drive image as BytesIO() and used Pillow to save/convert the bytes into an image named tmp.png. I am now using requests to POST my file to Rails:

```<code># I have a io.BytesIO() instance fh, with the image byte data.

fh.seek(0)
img = Image.open(fh)
img.save('tmp.png')
response = requests.post(LOCALHOST_MEDIA_ENDPOINT,
                         data={
                             "media": {
                                 "attachment": open('tmp.png', 'rb')
                                 # I've also tried just using img
                             }
                         },
                         headers={
                             'content-type': 'application/json'
                         })
</code>```

The media/paperclip controller works; it's been tested with form submit on a Node application with a file dropzone. However, when I make this request, my localhost log spits out:

```<code>Started POST "/media" for 172.18.0.1 at 2017-11-14 02:16:35 +0000
web_1  | Error occurred while parsing request parameters.
web_1  | Contents:
web_1  |
web_1  | media=attachment
web_1  |
web_1  | ActionDispatch::Http::Parameters::ParseError (822: unexpected token at 'media=attachment'):
web_1  |
web_1  | actionpack (5.1.2) lib/action_dispatch/http/parameters.rb:113:in `rescue in parse_formatted_parameters'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/parameters.rb:107:in `parse_formatted_parameters'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/request.rb:358:in `block in POST'
web_1  | rack (2.0.3) lib/rack/request.rb:57:in `fetch'
web_1  | rack (2.0.3) lib/rack/request.rb:57:in `fetch_header'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/request.rb:357:in `POST'
web_1  | actionpack (5.1.2) lib/action_controller/metal/params_wrapper.rb:286:in `_wrapper_enabled?'
web_1  | actionpack (5.1.2) lib/action_controller/metal/params_wrapper.rb:235:in `process_action'
web_1  | activerecord (5.1.2) lib/active_record/railties/controller_runtime.rb:22:in `process_action'
web_1  | actionpack (5.1.2) lib/abstract_controller/base.rb:124:in `process'
web_1  | actionpack (5.1.2) lib/action_controller/metal.rb:189:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_controller/metal.rb:253:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:31:in `serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:46:in `block in serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `each'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:832:in `call'
web_1  | omniauth (1.6.1) lib/omniauth/strategy.rb:189:in `call!'
web_1  | omniauth (1.6.1) lib/omniauth/strategy.rb:167:in `call'
web_1  | omniauth (1.6.1) lib/omniauth/builder.rb:63:in `call'
web_1  | rack (2.0.3) lib/rack/session/abstract/id.rb:232:in `context'
web_1  | rack (2.0.3) lib/rack/session/abstract/id.rb:226:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/cookies.rb:613:in `call'
web_1  | olive_branch (1.2.3) lib/olive_branch/middleware.rb:14:in `call'
web_1  | warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
web_1  | warden (1.2.7) lib/warden/manager.rb:35:in `catch'
web_1  | warden (1.2.7) lib/warden/manager.rb:35:in `call'
web_1  | rack (2.0.3) lib/rack/etag.rb:25:in `call'
web_1  | rack (2.0.3) lib/rack/conditional_get.rb:38:in `call'
web_1  | rack (2.0.3) lib/rack/head.rb:12:in `call'
web_1  | activerecord (5.1.2) lib/active_record/migration.rb:556:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:26:in `block in call'
web_1  | activesupport (5.1.2) lib/active_support/callbacks.rb:97:in `run_callbacks'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:24:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:59:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:36:in `call_app'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:24:in `block in call'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `block in tagged'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:26:in `tagged'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `tagged'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:24:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/request_id.rb:25:in `call'
web_1  | rack (2.0.3) lib/rack/runtime.rb:22:in `call'
web_1  | activesupport (5.1.2) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/static.rb:125:in `call'
web_1  | rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
web_1  | rack-cors (1.0.1) lib/rack/cors.rb:93:in `call'
web_1  | railties (5.1.2) lib/rails/engine.rb:522:in `call'
web_1  | puma (3.9.1) lib/puma/configuration.rb:224:in `call'
web_1  | puma (3.9.1) lib/puma/server.rb:602:in `handle_request'
web_1  | puma (3.9.1) lib/puma/server.rb:435:in `process_client'
web_1  | puma (3.9.1) lib/puma/server.rb:299:in `block in run'
web_1  | puma (3.9.1) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
</code>```

My controller:

```<code>def create
  @medium = Medium.new(medium_params)

  if @medium.save
    render json: @medium.to_json(
             :only => [:id, :title, :caption],
             :methods => [
               :attachment_url,
               :medium_attachment_url,
               :thumb_attachment_url
             ]
           ), status: :created, location: @medium
  else
    render json: @medium.errors, status: :unprocessable_entity
  end
end
...
def medium_params
  params.require(:medium).permit(
     # other irrelevant string/int permitted params
    :attachment
  )
end
</code>```

I'm thinking that maybe the image is somehow encoded differently in this request than how a form submits the data. But I am unfortunately very stuck.

答:
Create a multipart/form-data request instead of application/json.

Or if you want to use base64 encoded file content, you'll have to do some additional work of decoding and assigning image to papercip (Use paperclip for saving base64 images obtained from an api)

Body:
I am downloading an image with Google Drive API and uploading the file to my Rails API with Paperclip.

I've downloaded the Google Drive image as BytesIO() and used Pillow to save/convert the bytes into an image named tmp.png. I am now using requests to POST my file to Rails:

# I have a io.BytesIO() instance fh, with the image byte data.

fh.seek(0)
img = Image.open(fh)
img.save('tmp.png')
response = requests.post(LOCALHOST_MEDIA_ENDPOINT,
                         data={
                             "media": {
                                 "attachment": open('tmp.png', 'rb')
                                 # I've also tried just using img
                             }
                         },
                         headers={
                             'content-type': 'application/json'
                         })

The media/paperclip controller works; it's been tested with form submit on a Node application with a file dropzone. However, when I make this request, my localhost log spits out:

Started POST "/media" for 172.18.0.1 at 2017-11-14 02:16:35 +0000
web_1  | Error occurred while parsing request parameters.
web_1  | Contents:
web_1  |
web_1  | media=attachment
web_1  |
web_1  | ActionDispatch::Http::Parameters::ParseError (822: unexpected token at 'media=attachment'):
web_1  |
web_1  | actionpack (5.1.2) lib/action_dispatch/http/parameters.rb:113:in `rescue in parse_formatted_parameters'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/parameters.rb:107:in `parse_formatted_parameters'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/request.rb:358:in `block in POST'
web_1  | rack (2.0.3) lib/rack/request.rb:57:in `fetch'
web_1  | rack (2.0.3) lib/rack/request.rb:57:in `fetch_header'
web_1  | actionpack (5.1.2) lib/action_dispatch/http/request.rb:357:in `POST'
web_1  | actionpack (5.1.2) lib/action_controller/metal/params_wrapper.rb:286:in `_wrapper_enabled?'
web_1  | actionpack (5.1.2) lib/action_controller/metal/params_wrapper.rb:235:in `process_action'
web_1  | activerecord (5.1.2) lib/active_record/railties/controller_runtime.rb:22:in `process_action'
web_1  | actionpack (5.1.2) lib/abstract_controller/base.rb:124:in `process'
web_1  | actionpack (5.1.2) lib/action_controller/metal.rb:189:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_controller/metal.rb:253:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:31:in `serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:46:in `block in serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `each'
web_1  | actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `serve'
web_1  | actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:832:in `call'
web_1  | omniauth (1.6.1) lib/omniauth/strategy.rb:189:in `call!'
web_1  | omniauth (1.6.1) lib/omniauth/strategy.rb:167:in `call'
web_1  | omniauth (1.6.1) lib/omniauth/builder.rb:63:in `call'
web_1  | rack (2.0.3) lib/rack/session/abstract/id.rb:232:in `context'
web_1  | rack (2.0.3) lib/rack/session/abstract/id.rb:226:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/cookies.rb:613:in `call'
web_1  | olive_branch (1.2.3) lib/olive_branch/middleware.rb:14:in `call'
web_1  | warden (1.2.7) lib/warden/manager.rb:36:in `block in call'
web_1  | warden (1.2.7) lib/warden/manager.rb:35:in `catch'
web_1  | warden (1.2.7) lib/warden/manager.rb:35:in `call'
web_1  | rack (2.0.3) lib/rack/etag.rb:25:in `call'
web_1  | rack (2.0.3) lib/rack/conditional_get.rb:38:in `call'
web_1  | rack (2.0.3) lib/rack/head.rb:12:in `call'
web_1  | activerecord (5.1.2) lib/active_record/migration.rb:556:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:26:in `block in call'
web_1  | activesupport (5.1.2) lib/active_support/callbacks.rb:97:in `run_callbacks'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:24:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:59:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:36:in `call_app'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:24:in `block in call'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `block in tagged'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:26:in `tagged'
web_1  | activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `tagged'
web_1  | railties (5.1.2) lib/rails/rack/logger.rb:24:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/request_id.rb:25:in `call'
web_1  | rack (2.0.3) lib/rack/runtime.rb:22:in `call'
web_1  | activesupport (5.1.2) lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
web_1  | actionpack (5.1.2) lib/action_dispatch/middleware/static.rb:125:in `call'
web_1  | rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
web_1  | rack-cors (1.0.1) lib/rack/cors.rb:93:in `call'
web_1  | railties (5.1.2) lib/rails/engine.rb:522:in `call'
web_1  | puma (3.9.1) lib/puma/configuration.rb:224:in `call'
web_1  | puma (3.9.1) lib/puma/server.rb:602:in `handle_request'
web_1  | puma (3.9.1) lib/puma/server.rb:435:in `process_client'
web_1  | puma (3.9.1) lib/puma/server.rb:299:in `block in run'
web_1  | puma (3.9.1) lib/puma/thread_pool.rb:120:in `block in spawn_thread'

My controller:

def create
  @medium = Medium.new(medium_params)

  if @medium.save
    render json: @medium.to_json(
             :only => [:id, :title, :caption],
             :methods => [
               :attachment_url,
               :medium_attachment_url,
               :thumb_attachment_url
             ]
           ), status: :created, location: @medium
  else
    render json: @medium.errors, status: :unprocessable_entity
  end
end
...
def medium_params
  params.require(:medium).permit(
     # other irrelevant string/int permitted params
    :attachment
  )
end

I'm thinking that maybe the image is somehow encoded differently in this request than how a form submits the data. But I am unfortunately very stuck.


问:
How to fit log(a-x) type functions with scipy. curve_fit?
I am trying to fit a function which looks like log(y)=a*log(b-x)+c, where a, b and c are the parameters that need to be fitted. The relevant bit of code is

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def logfunc(T, a, b, c):
    v=(a*np.log(b-T))+c
    return v

popt, pcov=curve_fit(logfunc, T, np.log(Energy), check_finite=False, bounds=([0.1, 1.8, 0.1], [1.0, 2.6, 1.0]))

plt.plot(T, logfunc(T, *popt))
plt.show
</code>```

Where T and Energy is some data that was generated (I use it to plot other things so the data should be fine). T is between 0.3 and 3.2. I am pretty sure that the problem is the fact that there is a point where b=T because I keep getting the error ValueError: Residuals are not finite in the initial point. but I am not sure how to solve this.

答:
You may find the lmfit package (http://lmfit.github.io/lmfit-py/) useful for this sort of problem.  This provides a higher-level approach to curve fitting problems and a better abstraction of Parameters and Models than scipy.optimize package or curve_fit() function.

For the problem here, two important features of lmfit are

the ability to set bounds on variables.  curve_fit() can do this as well, but only by working with ordered lists of min/max bounds.  With lmfit, the bounds belong to Parameter objects.

having a way to explicitly set a policy for handling NaN values, which could definitely cause problems for your fit.

With lmfit, your script would be written approximately as

```<code>import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

def logfunc(T, a, b, c):
    return (a*np.log(b-T))+c

log_model = Model(logfunc, nan_policy='raise')  # raise error on NaNs
params = log_model.make_params(a=0.5, b=2.0, c=0.5) # initial values
params['b'].min = 1.8  # set min/max values
params['b'].max = 2.6
params['c'].min = 0.1  # and so forth

result = log_model.fit(np.log(Energy), params, T=T)

print(result.fit_report())

plt.plot(T, Energy, 'bo', label='data')
plt.plot(T, np.exp(result.best_fit), 'r--', label='fit')
plt.legend()
plt.xlabel('T')
plt.ylabel('Energy')
plt.gca().set_yscale('log', basey=10)
plt.show()
</code>```

This is slightly more verbose than your starting script because it gives a labeled plot and because using Parameter objects instead of scalars gives more flexibility and clarity.

For your fit, you might consider setting the nan_policy to 'omit', which will omit NaNs as they occur -- never a great idea, but sometimes helpful to get you started on finding where log(b-T) is valid.  You could also alter your model function to do something like

```<code>def logfunc(T, a, b, c):
    arg = b - T
    arg[np.where(arg < 1.e-16)] = 1.e-16
    return a*np.log(arg) + c
</code>```

To explicitly prevent one obvious cause of NaNs.

Body:
I am trying to fit a function which looks like log(y)=a*log(b-x)+c, where a, b and c are the parameters that need to be fitted. The relevant bit of code is

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def logfunc(T, a, b, c):
    v=(a*np.log(b-T))+c
    return v

popt, pcov=curve_fit(logfunc, T, np.log(Energy), check_finite=False, bounds=([0.1, 1.8, 0.1], [1.0, 2.6, 1.0]))

plt.plot(T, logfunc(T, *popt))
plt.show

Where T and Energy is some data that was generated (I use it to plot other things so the data should be fine). T is between 0.3 and 3.2. I am pretty sure that the problem is the fact that there is a point where b=T because I keep getting the error ValueError: Residuals are not finite in the initial point. but I am not sure how to solve this.

Body:
You may find the lmfit package (http://lmfit.github.io/lmfit-py/) useful for this sort of problem.  This provides a higher-level approach to curve fitting problems and a better abstraction of Parameters and Models than scipy.optimize package or curve_fit() function.

For the problem here, two important features of lmfit are

the ability to set bounds on variables.  curve_fit() can do this as well, but only by working with ordered lists of min/max bounds.  With lmfit, the bounds belong to Parameter objects.

having a way to explicitly set a policy for handling NaN values, which could definitely cause problems for your fit.

With lmfit, your script would be written approximately as

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

def logfunc(T, a, b, c):
    return (a*np.log(b-T))+c

log_model = Model(logfunc, nan_policy='raise')  # raise error on NaNs
params = log_model.make_params(a=0.5, b=2.0, c=0.5) # initial values
params['b'].min = 1.8  # set min/max values
params['b'].max = 2.6
params['c'].min = 0.1  # and so forth

result = log_model.fit(np.log(Energy), params, T=T)

print(result.fit_report())

plt.plot(T, Energy, 'bo', label='data')
plt.plot(T, np.exp(result.best_fit), 'r--', label='fit')
plt.legend()
plt.xlabel('T')
plt.ylabel('Energy')
plt.gca().set_yscale('log', basey=10)
plt.show()

This is slightly more verbose than your starting script because it gives a labeled plot and because using Parameter objects instead of scalars gives more flexibility and clarity.

For your fit, you might consider setting the nan_policy to 'omit', which will omit NaNs as they occur -- never a great idea, but sometimes helpful to get you started on finding where log(b-T) is valid.  You could also alter your model function to do something like

def logfunc(T, a, b, c):
    arg = b - T
    arg[np.where(arg < 1.e-16)] = 1.e-16
    return a*np.log(arg) + c

To explicitly prevent one obvious cause of NaNs.


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
if a,b,c are really booleans:

```<code>li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
name = li[a*4 + b*2 + c]
</code>```

if they are not booleans:

```<code>li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
a,b,c = map(bool,(a,b,c))
name = li[a*4 + b*2 + c]
</code>```

idea from Clint Miller

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
if a,b,c are really booleans:

li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
name = li[a*4 + b*2 + c]

if they are not booleans:

li = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
a,b,c = map(bool,(a,b,c))
name = li[a*4 + b*2 + c]

idea from Clint Miller