问:
C# saving and then retriving data via the clipboard
Okay,

So I have a program that automatically copies data to the clipboard and then into memory.  What I want to do is, to save the data that is on the clipboard prior to my program running and then to copyit back to the clipboard once I have finished what I need to do.

I can get the data fromt he clipboard as such:

```<code>IDataObject currentClipboard = Clipboard.GetDataObject();
</code>```

However, when I want to put the data back on to the clipboard, do I need to know what format that data is in to cast it?

Is there a way to do this?

Thanks.

答:
You cannot reliably restore the clipboard to its former state.  Period.  With simple formats, you may get away with it.  When you get into more complex formats, particularly OLE and private formats, it's much more complicated.  Read up on Delayed Rendering, and you'll realize the data isn't necessarily even ON THE CLIPBOARD YET.  So when you request the data, so you can store it away, you're going to cause lengthy delays. Consider 5000 cells from Excel, which can be rendered into about 24 different formats, most of which are using delayed rendering (meaning that they're not really on the clipboard until you request data in a particular format, and then Excel has to generate it on-demand).

And even if you could, every time you restore the data, you're going to generate a clipboard update event that is going to be sent to all registered clipboard viewers, which will react to your shennanegans.
In summary: Don't do it.

Body:
Okay,

So I have a program that automatically copies data to the clipboard and then into memory.  What I want to do is, to save the data that is on the clipboard prior to my program running and then to copyit back to the clipboard once I have finished what I need to do.

I can get the data fromt he clipboard as such:

IDataObject currentClipboard = Clipboard.GetDataObject();

However, when I want to put the data back on to the clipboard, do I need to know what format that data is in to cast it?

Is there a way to do this?

Thanks.


来源: stackexchange

问:
I am making a python tkinter calculator and can't get the value to change
I am making a calculator in python using Tkinter and I can't  get the button to change the text on the label. Thank you in advance.</p>

```<code>calc = Tk()
calc.title("Calculator")
calc.configure(bg='gray')

def nu1():
    numbers == '1'

numbers = '0'

screen = Label(calc, text=numbers)
screen.grid(row=0, column=0)

no1 = Button(calc, text='1', command=nu1)
no1.grid(row=0, column=2)
</code>```

答:
numbers == '1' tests if numbers equals the '1' string, and then it throws the result away. I suspect you meant to do

```<code>numbers = '1'
</code>```

but that still won't work. Firstly, that assignment creates a new numbers that's local to the nu1 function, it has nothing to do with your global numbers. Secondly, that's not how to change the text of a Label: you need to call its configure method, which can be shortened to config. Here's an example:

```<code>import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry('200x200')

def nu1():
    screen.config(text='1')

numbers = '0'

screen = tk.Label(calc, text=numbers)
screen.grid(row=0, column=0)

no1 = tk.Button(calc, text='1', command=nu1)
no1.grid(row=0, column=2)

calc.mainloop()
</code>```

That solves your immediate problem. However, you will find that this isn't adequate to build a calculator.

ContentLicense: CC BY-SA 3.0

Body:
I am making a calculator in python using Tkinter and I can't  get the button to change the text on the label. Thank you in advance.

calc = Tk()
calc.title("Calculator")
calc.configure(bg='gray')

def nu1():
    numbers == '1'

numbers = '0'

screen = Label(calc, text=numbers)
screen.grid(row=0, column=0)

no1 = Button(calc, text='1', command=nu1)
no1.grid(row=0, column=2)

Body:
numbers == '1' tests if numbers equals the '1' string, and then it throws the result away. I suspect you meant to do

numbers = '1'

but that still won't work. Firstly, that assignment creates a new numbers that's local to the nu1 function, it has nothing to do with your global numbers. Secondly, that's not how to change the text of a Label: you need to call its configure method, which can be shortened to config. Here's an example:

import tkinter as tk

calc = tk.Tk()
calc.title("Calculator")
calc.geometry('200x200')

def nu1():
    screen.config(text='1')

numbers = '0'

screen = tk.Label(calc, text=numbers)
screen.grid(row=0, column=0)

no1 = tk.Button(calc, text='1', command=nu1)
no1.grid(row=0, column=2)

calc.mainloop()

That solves your immediate problem. However, you will find that this isn't adequate to build a calculator.


问:
SQL Between AAA and ZZZ
I can't get codes that are between AAA and ZZZ, this is what I tried:

```<code>ALTER TABLE AIRPORT
ADD CONSTRAINT CORRECTCODE
CHECK (Code BETWEEN 'AAA' AND 'ZZZ' AND LENGTH(Code) = 3) ENABLE VALIDATE;
</code>```

It accepts the values I want, but it also accepts values that contain numbers like AB6. What am I doing wrong?

答:
You can use regexp_like. This checks if the 3 characters are upper-case.

```<code>CHECK(regexp_like(Code,'^[A-Z]{3}$'))
</code>```

If a mix of characters in upper and lower case should be supported, use a case-insensitive flag i as the third argument.

```<code>CHECK(regexp_like(Code,'^[A-Z]{3}$','i'))
</code>```

Title: SQL Between AAA and ZZZ

Body:
I can't get codes that are between AAA and ZZZ, this is what I tried:

ALTER TABLE AIRPORT
ADD CONSTRAINT CORRECTCODE
CHECK (Code BETWEEN 'AAA' AND 'ZZZ' AND LENGTH(Code) = 3) ENABLE VALIDATE;

It accepts the values I want, but it also accepts values that contain numbers like AB6. What am I doing wrong?

Body:
You can use regexp_like. This checks if the 3 characters are upper-case.

CHECK(regexp_like(Code,'^[A-Z]{3}$'))

If a mix of characters in upper and lower case should be supported, use a case-insensitive flag i as the third argument.

CHECK(regexp_like(Code,'^[A-Z]{3}$','i'))


问:
How to diff records within same file
I have following file format:

```<code>AAA-12345~TRAX~~AAAAAAAAAAAA111111ETC
AAA-12345~RCV~~BBBBBBBBBBBB222222ETC
BBB-78900~TRAX~~CCCCCCCCCCCC444444ETC
BBB-78900~RCV~~DDDDDDDDDDDD555555ETC
CCC-65432~TRAX~~HHHHHHHHHHHH888888ETC
</code>```

All lines are in pairs and each pair is identical up single ~.
Sometimes there are orphans like last record which has TRAX but no RCV.
Question is: using bash utilies like sed or awk or commands like grep or cut how do I find and display orphans only?

答:
Using awk:

```<code>awk -F~ '{a[$1]+=1} END{for(key in a) if(a[key]==1){print key}}'
</code>```

This is just loading the first field (split by tilde) as they key of an array and incrementing the value for that key each time it's found. Then when the file is finished, it iterates the array and prints out key's with just 1 for the value.

Title: How to diff records within same file

Body:
I have following file format:

AAA-12345~TRAX~~AAAAAAAAAAAA111111ETC
AAA-12345~RCV~~BBBBBBBBBBBB222222ETC
BBB-78900~TRAX~~CCCCCCCCCCCC444444ETC
BBB-78900~RCV~~DDDDDDDDDDDD555555ETC
CCC-65432~TRAX~~HHHHHHHHHHHH888888ETC

All lines are in pairs and each pair is identical up single ~.
Sometimes there are orphans like last record which has TRAX but no RCV.
Question is: using bash utilies like sed or awk or commands like grep or cut how do I find and display orphans only?

Body:
Using awk:

awk -F~ '{a[$1]+=1} END{for(key in a) if(a[key]==1){print key}}'

This is just loading the first field (split by tilde) as they key of an array and incrementing the value for that key each time it's found. Then when the file is finished, it iterates the array and prints out key's with just 1 for the value.


问:
node js console code is executed two times
I am executing following simple node js code

```<code>var http = require('http');

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type':'text/plain'});
    res.end('Hello Node JS');
    console.log('printing the message');
}).listen(8080);
</code>```

After executing the command node sample.js and

hitting the url on browser http://localhost:8080/

I am getting the console log statement twice on the command prompt as printing the message

Any Suggestions

EDIT:

Interestingly After checking on other browsers i.e. Firefox, IE no favicon.ico request is made on network tab and console message is printed only once.

As I understood, using express module is better option to handle requests in a typical web application

答:
check the Network area of your browser's developer console to find out what requests are being made.  I imagine you will see two:

GET /

GET /favicon.ico

your HTTP server is coded to respond to all requests by printing to console; so if you see two requests, you get two console messages.

Body:
I am executing following simple node js code

var http = require('http');

http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type':'text/plain'});
    res.end('Hello Node JS');
    console.log('printing the message');
}).listen(8080);

After executing the command node sample.js and

hitting the url on browser http://localhost:8080/

I am getting the console log statement twice on the command prompt as printing the message

Any Suggestions

EDIT:

Interestingly After checking on other browsers i.e. Firefox, IE no favicon.ico request is made on network tab and console message is printed only once.

As I understood, using express module is better option to handle requests in a typical web application


问:
Error running Node.js' fs.rename() inside of a loop
I'm developing an application that has to organize some uploaded files, I'm separating them in folders with the ID of their request (I'm using express-request-id to get this ID).

The problem is that everytime I have more than a single file the "moving" process fails and I can't seem to fix it.

```<code>let request_folder = path.resolve(tmp_folder + "/" + req.id);

/* Checking if the folder exists */
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) { // it doesn't
        /* Trying to create it */
        fs.mkdir(request_folder, function(error) {
            if(error) {
                console.log("Error: Couldn't create the directory.");
                console.log(error);
            }
        });
    }
});

/* Moving uploaded files to their respective request folder */
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    fs.rename(file.path, new_file_path, function(error) {
        if(error) {
            console.log("Error: Couldn't move " + file.filename + ".");
            console.log(error);
        }
    });
});
</code>```

I'm one hundred percent sure both the folders and the files exist, but I when trying to move two files at once I get:

```<code>Error: Couldn't move Desert.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Desert.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f5725a73
\Desert.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Desert.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Desert.jpg' }
Error: Couldn't move Chrysanthemum.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Chrysanthemum.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f
5725a73\Chrysanthemum.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Chrysanthemum.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Chrysanthemum.jpg' }
</code>```

Does anyone know what am I doing wrong? Thanks!

答:
The fs operations you are using are async meaning they can happen in any order.

Your loop will ask node to create a folder and move the files basically at the same time. In other words, it will run a synchronous loop that will dispatch all fs actions concurrently. Meaning that you have no guarantees what will actually run first.

Try creating the folder before moving all the files:

```<code>fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) {
        return fs.mkdir(request_folder, function(error) {
            if(error) {
                return;
            }
            moveFiles();
        });
    }
    moveFiles();
});

function moveFiles() {
  req.files.forEach(function(file) {
    // ...
  });
}
</code>```

Using promises might make this a bit cleaner:

```<code>const access = util.promisify(fs.access);
const mkdir = util.promisify(fs.mkdir);
const rename = util.promisify(fs.rename);

access(request_folder, fs.constants.F_OK)
  .then(moveFiles, makeDirAndMoveFiles)
  .catch(console.error);

function moveFiles() {
  return Promise.all(
    req.files.map(file => {
      const new_file_path = path.resolve(request_folder + "/" + file.filename);
      return rename(file.path, new_file_path);
    })
  )
}

function makeDirAndMoveFiles() {
  return mkdir(request_folder).then(moveFiles);
}
</code>```

Body:
I'm developing an application that has to organize some uploaded files, I'm separating them in folders with the ID of their request (I'm using express-request-id to get this ID).

The problem is that everytime I have more than a single file the "moving" process fails and I can't seem to fix it.

let request_folder = path.resolve(tmp_folder + "/" + req.id);

/* Checking if the folder exists */
fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) { // it doesn't
        /* Trying to create it */
        fs.mkdir(request_folder, function(error) {
            if(error) {
                console.log("Error: Couldn't create the directory.");
                console.log(error);
            }
        });
    }
});

/* Moving uploaded files to their respective request folder */
req.files.forEach(function(file) {
    let new_file_path = path.resolve(request_folder + "/" + file.filename);
    fs.rename(file.path, new_file_path, function(error) {
        if(error) {
            console.log("Error: Couldn't move " + file.filename + ".");
            console.log(error);
        }
    });
});

I'm one hundred percent sure both the folders and the files exist, but I when trying to move two files at once I get:

Error: Couldn't move Desert.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Desert.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f5725a73
\Desert.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Desert.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Desert.jpg' }
Error: Couldn't move Chrysanthemum.jpg.
{ Error: ENOENT: no such file or directory, rename 'C:\Users\telmo.silva\csc-links\public\tmp\Chrysanthemum.jpg' -> 'C:\Users\telmo.silva\csc-links\public\tmp\d2abf375-d09f-440c-a5ba-adf4f
5725a73\Chrysanthemum.jpg'
  errno: -4058,
  code: 'ENOENT',
  syscall: 'rename',
  path: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\Chrysanthemum.jpg',
  dest: 'C:\\Users\\telmo.silva\\csc-links\\public\\tmp\\d2abf375-d09f-440c-a5ba-adf4f5725a73\\Chrysanthemum.jpg' }

Does anyone know what am I doing wrong? Thanks!

Body:
The fs operations you are using are async meaning they can happen in any order.

Your loop will ask node to create a folder and move the files basically at the same time. In other words, it will run a synchronous loop that will dispatch all fs actions concurrently. Meaning that you have no guarantees what will actually run first.

Try creating the folder before moving all the files:

fs.access(request_folder, fs.constants.F_OK, function(error) {
    if(error) {
        return fs.mkdir(request_folder, function(error) {
            if(error) {
                return;
            }
            moveFiles();
        });
    }
    moveFiles();
});

function moveFiles() {
  req.files.forEach(function(file) {
    // ...
  });
}

Using promises might make this a bit cleaner:

const access = util.promisify(fs.access);
const mkdir = util.promisify(fs.mkdir);
const rename = util.promisify(fs.rename);

access(request_folder, fs.constants.F_OK)
  .then(moveFiles, makeDirAndMoveFiles)
  .catch(console.error);

function moveFiles() {
  return Promise.all(
    req.files.map(file => {
      const new_file_path = path.resolve(request_folder + "/" + file.filename);
      return rename(file.path, new_file_path);
    })
  )
}

function makeDirAndMoveFiles() {
  return mkdir(request_folder).then(moveFiles);
}


问:
In which scenario do I use a particular STL container?
I've been reading up on STL containers in my book on C++, specifically the section on the STL and its containers. Now I do understand each and every one of them have their own specific properties, and I'm close to memorizing all of them... But what I do not yet grasp is in which scenario each of them is used.

What is the explanation? Example code is much prefered.

答:
Simple answer: use std::vector for everything unless you have a real reason to do otherwise.

When you find a case where you're thinking, "Gee, std::vector doesn't work well here because of X", go on the basis of X.

OwnerDisplayName: Daniel

LastEditorDisplayName: Daniel

OwnerDisplayName: David Thornley

ContentLicense: CC BY-SA 4.0


问:
Writing data from NSArray to Excel file?
I want to write all the values present in  an array to an excel sheet.Please suggest some way to do so.</p>

答:
You have a few options:

Do like @Jonah suggests (I voted for his answer because you had no details!)

Study the XML interchange format from MS Office XML Formats and use NSXML... objects and methods

Depends on what it is you are trying to accomplish

Frank

ContentLicense: CC BY-SA 2.5


问:
How to deregister / unregister Firebase user when registered using Phone Auth
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

```<code>[user deleteWithCompletion:^(NSError * _Nullable error) ..
</code>```

I get an error message saying the only recently authenticate users can be deleted.

```<code>"This operation is sensitive and requires recent authentication. Log in again before retrying this request."
</code>```

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

```<code>[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
</code>```

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

```<code>[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
</code>```

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?

答:
Please do not store credentials on the device. You are misreading the docs. It requires re-authentication for a reason. Storing a credential beats the point of that. You should simply reauthenticate the user to delete them. This is similar to asking an email/password user to provide their current password again before deleting their account, updating their password, updating email, updating shipping address, credit card info, etc.

Besides, even if you store these phone credentials:

they will expire in a few minutes as they are short lived.

they are only usable once so holding on to them is useless after sign-in.

Body:
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

[user deleteWithCompletion:^(NSError * _Nullable error) ..

I get an error message saying the only recently authenticate users can be deleted.

"This operation is sensitive and requires recent authentication. Log in again before retrying this request."

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?


问:
Does RxJava's Observable.subscriber()'s onNext callback have to use threadsafe objects?
This is what my code looks like:

```<code>ArrayList<T> result = new ArrayList<T>();
observable.subscribe(result::add, <something here>, <something here>);
</code>```

Is this not recommended? Should result be a thread-safe structure?

答: I have used it without problem with non thread safe objects and have had little to no issues. There are additional methods for RxJava's Observables i recommend looking into, when it comes to maintaining good concurrency practises.</p>

Body:
This is what my code looks like:

ArrayList<T> result = new ArrayList<T>();
observable.subscribe(result::add, <something here>, <something here>);

Is this not recommended? Should result be a thread-safe structure?


问:
Vertically align an input placeholder with CSS (or set line-height)
Is it possible to vertically align a placeholder independently of the parent input? There seems to be no way to have the placeholder in the code below appear in the vertical center of the input field. I've tried all css properties and workarounds I can think of or find online but the different font sizes on the input and the placeholder seem to make it impossible in webkit browsers at least.

Edit: Left is the issue, right is the desired look:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' placeholder='enter some text' /></code>```

答:
This feels like such a stupid "solution", but maybe you could substitute transform:scale(0.45) in place of the font-size: 9px;.  It seems to work just about anywhere font-size in ::-webkit-input-placeholder is supported.

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' placeholder='enter some text' /></code>```

Edit: Left Aligned

input {
  font-size: 22px;
  text-align: left;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
  transform-origin: 0% 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='text' placeholder='enter some text' /></code>```

Body:
Is it possible to vertically align a placeholder independently of the parent input? There seems to be no way to have the placeholder in the code below appear in the vertical center of the input field. I've tried all css properties and workarounds I can think of or find online but the different font sizes on the input and the placeholder seem to make it impossible in webkit browsers at least.

Edit: Left is the issue, right is the desired look:

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  font-size: 9px;
  text-transform: uppercase;
  color: #AAA;
}

<input type='text' placeholder='enter some text' />

Body:
This feels like such a stupid "solution", but maybe you could substitute transform:scale(0.45) in place of the font-size: 9px;.  It seems to work just about anywhere font-size in ::-webkit-input-placeholder is supported.

input {
  font-size: 22px;
  text-align: center;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
}

<input type='text' placeholder='enter some text' />

Edit: Left Aligned

input {
  font-size: 22px;
  text-align: left;
  font-weight: bold;
  line-height: 44px;
}

input::-webkit-input-placeholder {
  text-transform: uppercase;
  color: #AAA;
  transform: scale(0.45);
  transform-origin: 0% 50%;
}

<input type='text' placeholder='enter some text' />


问:
Unable to reference webservice (.asmx) in my ASP.NET Project
In my current project, I have a webservice file called MyServices.asmx. This webservice I want to reference in my Default.aspx.cs file.

My Code:

```<code>    MyServices newService = new MyServices();

    newService.addUser(txFirstName.Text, txLastName.Text, txtEmail.Text,
txtUserName.Text, txtPassword.Text, txtBalance.Text);
</code>```

But when I refer to that webservice (as shown below), I get error saying:
"The type or namespace name 'MyServices' could not be found (are you missing a using directive or an assembly reference?)"

What should I do to correct this error?

Current Solution of Adding Service Reference still gives me that error. Can you please suggest what could be wrong?

答:
You need to add a service reference to it.

In the project holding the Default.aspx.cs file, right click on "Service References" -> Add service reference.

You can then just click the "Discover" button to have the webservice listed.

Select it and click "OK".

Body:
In my current project, I have a webservice file called MyServices.asmx. This webservice I want to reference in my Default.aspx.cs file.

My Code:

    MyServices newService = new MyServices();

    newService.addUser(txFirstName.Text, txLastName.Text, txtEmail.Text,
txtUserName.Text, txtPassword.Text, txtBalance.Text);

But when I refer to that webservice (as shown below), I get error saying:
"The type or namespace name 'MyServices' could not be found (are you missing a using directive or an assembly reference?)"

What should I do to correct this error?

Current Solution of Adding Service Reference still gives me that error. Can you please suggest what could be wrong?


问:
Get final url after timed delay or redirect
I am trying to scrape a website, but when I open the webpage it has 5 seconds redirect delay, i.e. you have to wait for 5 sec and then the real page loads.
I have tried the following code .

```<code>from bs4 import BeautifulSoup
import time
import requests

r=requests.get("https://etherscan.io/address/0xc257274276a4e539741ca11b590b9447b26a8051",timeout=6)
time.sleep(5)
print(r.history)

data=r.text

soup=BeautifulSoup(data)

print(soup.prettify())
</code>```

But when I run the code I get the redirect page, not the final page. Thanks for help

答: If you really really are set on using something other than selenium or the API (which would make the most sense), you could take a look at this. It's a scraper meant to handle cloudflare sites, but it requires some other things (most notably Node.js) to run. While this is pretty neat, seems like a pain when there are easier solutions. </p>

Body:
I am trying to scrape a website, but when I open the webpage it has 5 seconds redirect delay, i.e. you have to wait for 5 sec and then the real page loads.
I have tried the following code .

from bs4 import BeautifulSoup
import time
import requests

r=requests.get("https://etherscan.io/address/0xc257274276a4e539741ca11b590b9447b26a8051",timeout=6)
time.sleep(5)
print(r.history)

data=r.text

soup=BeautifulSoup(data)

print(soup.prettify())

But when I run the code I get the redirect page, not the final page. Thanks for help


问:
FormRequest all() method causes Reflection exception in Laravel 5.5
Issue with laravel 5.5

If I use the all() method in formRequest class, It throws reflection exception

```<code>ReflectionException
Class App\Http\Requests\CashDepositRequest does not exist
</code>```

but when I remove the all() method, it works well.

This was not an issue in laravel 5.4

```<code><?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CashDepositRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'amount' => 'bail|required|numeric',
            'gateway' => 'bail|required|exists:gateways,id',
        ];
    }
    //This method causes reflection exception
    public function all()
    {
        $this->attributes = parent::all();
        $this->attributes['amount'] = $this->attributes['amount'];
        return $this->attributes;
    }
}
</code>```

Is there any other way to modify user input in the formRequest class in laravel 5.5?

答:
First of all all() is not property but class method.

Second thing is the signature of this method. Signature in parent class looks like this:

```<code>public function all($keys = null)
</code>```

so you should update it in child class to the same.

If you upgraded from previous releases in upgrade guide you can read:

If you are overriding the all method of the Illuminate\Http\Request class, you should update your method signature to reflect the new $keys argument:

and this is probably what causes the problem in your case.

Body:
Issue with laravel 5.5

If I use the all() method in formRequest class, It throws reflection exception

ReflectionException
Class App\Http\Requests\CashDepositRequest does not exist

but when I remove the all() method, it works well.

This was not an issue in laravel 5.4

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CashDepositRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }
    public function rules()
    {
        return [
            'amount' => 'bail|required|numeric',
            'gateway' => 'bail|required|exists:gateways,id',
        ];
    }
    //This method causes reflection exception
    public function all()
    {
        $this->attributes = parent::all();
        $this->attributes['amount'] = $this->attributes['amount'];
        return $this->attributes;
    }
}

Is there any other way to modify user input in the formRequest class in laravel 5.5?

Body:
First of all all() is not property but class method.

Second thing is the signature of this method. Signature in parent class looks like this:

public function all($keys = null)

so you should update it in child class to the same.

If you upgraded from previous releases in upgrade guide you can read:

If you are overriding the all method of the Illuminate\Http\Request class, you should update your method signature to reflect the new $keys argument:

and this is probably what causes the problem in your case.


问:
laravel cron job cannot save to DB
I have a problem in Laravel version 5.2 - cannot save data to DB.
I have created command send:birthday in Kernel:

```<code>use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Mtv::class,
        Commands\HappyBirthday::class,

    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {

        $schedule->command('sms:birthday')->cron('* * * * *');

    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}
</code>```

then class HappyBirthday.php jn Console/Commands

```<code><?php

namespace App\Console\Commands;
namespace App\Http\Controllers;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Auth;

use App\Patients as PModel;
use App\Visit;
use App\Vizit;
use App\History;
use App\ViewHelper;
use App\Patients;
use DB;
use Mail;

       class HappyBirthday extends Command
        {
            /**
             * The name and signature of the console command.
             *
             * @var string
             */
            protected $signature = 'send:birthday';

            /**
             * The console command description.
             *
             * @var string
             */
            protected $description = 'Command description';

            /**
             * Create a new command instance.
             *
             * @return void
             */
            public function __construct()
            {
                parent::__construct();
            }

            /**
             * Execute the console command.
             *
             * @return mixed
             */

        public function handle()
        {

     $users=DB::select('SELECT * FROM patients where id=17');
     foreach( $users as $user ) {
        Mail::raw(' '.$user->id.' reached 18 ', function ($message) {
        $message->from('admin@site.com', 'admin@site.com');
        $message->to('memail@gmail.com')->subject('birthday');

        });
     }

  DB::table('users')->insert([
  ['status' => 'send']

  ]);

        }
</code>```

Almost everything works fine- mail sending every day to admin's email (every minute as example) but i cannot insert any row into users table. Any ideas? Thanks!

答:
Maybe you have other required fields in the table, not only the "status".
You can add all, and input into foreach for using variables:</p>

```<code>DB::table('users')->insert([
    'user_id' => $user->id,
    'status' => 'send'
]);
</code>```

Title: laravel cron job cannot save to DB

Body:
I have a problem in Laravel version 5.2 - cannot save data to DB.
I have created command send:birthday in Kernel:

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\Mtv::class,
        Commands\HappyBirthday::class,

    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {

        $schedule->command('sms:birthday')->cron('* * * * *');

    }

    /**
     * Register the Closure based commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        require base_path('routes/console.php');
    }
}

then class HappyBirthday.php jn Console/Commands

<?php

namespace App\Console\Commands;
namespace App\Http\Controllers;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Auth;

use App\Patients as PModel;
use App\Visit;
use App\Vizit;
use App\History;
use App\ViewHelper;
use App\Patients;
use DB;
use Mail;

       class HappyBirthday extends Command
        {
            /**
             * The name and signature of the console command.
             *
             * @var string
             */
            protected $signature = 'send:birthday';

            /**
             * The console command description.
             *
             * @var string
             */
            protected $description = 'Command description';

            /**
             * Create a new command instance.
             *
             * @return void
             */
            public function __construct()
            {
                parent::__construct();
            }

            /**
             * Execute the console command.
             *
             * @return mixed
             */

        public function handle()
        {

     $users=DB::select('SELECT * FROM patients where id=17');
     foreach( $users as $user ) {
        Mail::raw(' '.$user->id.' reached 18 ', function ($message) {
        $message->from('admin@site.com', 'admin@site.com');
        $message->to('memail@gmail.com')->subject('birthday');

        });
     }

  DB::table('users')->insert([
  ['status' => 'send']

  ]);

        }

Almost everything works fine- mail sending every day to admin's email (every minute as example) but i cannot insert any row into users table. Any ideas? Thanks!

Body:
Maybe you have other required fields in the table, not only the "status".
You can add all, and input into foreach for using variables:

DB::table('users')->insert([
    'user_id' => $user->id,
    'status' => 'send'
]);


问:
“2 duplicate symbols for architecture x86_64” in XCode 9
Recently I upgraded my components (Cordova, node.js, Ionic, etc.) on my Windows 10 computer and on my Mac in order to be (more or less) up-to-date.

Using Visual Studio 2015 on a different PC I am developing a hybrid mobile app, which can be built when it comes to Android.

However in regards to iOS when I start remotebuild --secure false on my Mac and try deploying the files from my Windows PC it finally fails with the following error to be seen in build.log on my Mac in detail as following:

duplicate symbol _OBJC_CLASS_$_CDVLogger in:
    /Users/Joey/Library/Developer/Xcode/DerivedData/MY-FAMOUS-APP-aeghcglepsoouoeuminlbzuvljeu/Build/Intermediates.noindex/MY-FAMOUS-APP.build/Debug-iphoneos/MY-FAMOUS-APP.build/Objects-normal/armv7/CDVLogger.o
    /Users/Joey/Library/Developer/Xcode/DerivedData/MY-FAMOUS-APP-aeghcglepsoouoeuminlbzuvljeu/Build/Products/Debug-iphoneos/libCordova.a(CDVLogger.o)
duplicate symbol _OBJC_METACLASS_$_CDVLogger in:
    /Users/Joey/Library/Developer/Xcode/DerivedData/MY-FAMOUS-APP-aeghcglepsoouoeuminlbzuvljeu/Build/Intermediates.noindex/MY-FAMOUS-APP.build/Debug-iphoneos/MY-FAMOUS-APP.build/Objects-normal/armv7/CDVLogger.o
    /Users/Joey/Library/Developer/Xcode/DerivedData/MY-FAMOUS-APP-aeghcglepsoouoeuminlbzuvljeu/Build/Products/Debug-iphoneos/libCordova.a(CDVLogger.o)
ld: 2 duplicate symbols for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I read a lot about possible solutions doing some crazy things in XCode, which are not targeting my problem: I write code only in Visual Studio using Angular.JS, Cordova and Ionic and want to enable an automatic setting in either of the files written in Visual Studio on my PC. Maybe a hook as described here would work, but I do not know what and how to write.

However if no solution for Visual Studio 2015 is possible, I would be happy to receive hints in what to change in XCode 9.

答:
According to http://cordova.apache.org/announcements/2017/09/08/ios-release.html :

Important! If you have included cordova-plugin-console in your project, you must remove it, otherwise your project will not build.

This caused my local build to fail. Not sure if this problem is yours aswell, but you can always try to remove it?

```<code>cordova plugin rm cordova-plugin-console
</code>```

And try to build again?

Body:
According to http://cordova.apache.org/announcements/2017/09/08/ios-release.html :

Important! If you have included cordova-plugin-console in your project, you must remove it, otherwise your project will not build.

This caused my local build to fail. Not sure if this problem is yours aswell, but you can always try to remove it?

cordova plugin rm cordova-plugin-console

And try to build again?


问:
Why does a HashMap sometimes print in natural order
I was going through the introduction of Hash Map in Java and I came across that Hash Maps are unordered and unsorted. So we should get the mappings in an arbitrary order of the keys when printing the using System.out.println(HM). For example, the following code

```<code>HashMap<Integer,String> HM = new HashMap<>();
HM.put(16,"hello16");
HM.put(6, "hello6");
HM.put(1, "hello1");
</code>```

prints {16=hello16, 1=hello1, 6=hello6} which is an apparently random order of keys. But when I replace the HM.put(16,"hello16"); with HM.put(15,"hello15");, it prints the mappings in the natural order of the keys, which is surprising and seems unlikely by chance:

```<code>{1=hello1, 6=hello6, 15=hello15}
</code>```

I asked a friend and he said that it's related to the initial capacity (=16) of the HashMap but he couldn't explain it clearly. Can anyone explain this difference in the output with this particular example.

答:
HashMap uses the keys' hashCode to throw the map entries in an indexed array of buckets. The retrieval order is more or less arbitrary. As Strings of the same length, only differing in last char, have in general a hash code equal to X + last char, there is an order in them.

An other Map implementing class TreeMap is a SortedMap, and keeps the entries in order of the keys.

A yet other Map implementation is the LinkedHashMap where the order is in order of putting the entries in the map.

Body:
I was going through the introduction of Hash Map in Java and I came across that Hash Maps are unordered and unsorted. So we should get the mappings in an arbitrary order of the keys when printing the using System.out.println(HM). For example, the following code

HashMap<Integer,String> HM = new HashMap<>();
HM.put(16,"hello16");
HM.put(6, "hello6");
HM.put(1, "hello1");

prints {16=hello16, 1=hello1, 6=hello6} which is an apparently random order of keys. But when I replace the HM.put(16,"hello16"); with HM.put(15,"hello15");, it prints the mappings in the natural order of the keys, which is surprising and seems unlikely by chance:

{1=hello1, 6=hello6, 15=hello15}

I asked a friend and he said that it's related to the initial capacity (=16) of the HashMap but he couldn't explain it clearly. Can anyone explain this difference in the output with this particular example.


问:
MooDialog.Request add Event
How can I add a close event to MooDialog.Request?

Update:
There is my code:

```<code>window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url,
      {view:'show'},
      {
        size:  {
          width: 460,
          height: 375,
          'zIndex':20
        }
      }
    );
    reqDialog.setRequestOptions({
        onClose: function(){
            alert('closed');
        }
    });
  });
});
</code>```

答:
It's pretty simple:

```<code>//Request => new MooDialog.Request(url[, RequestOptions, options]);
var reqD = new MooDialog.Request('URL',null,{
    onClose: function(){
        alert('closed');
    }
});
</code>```

doc

Edit your code need to be updated this way:

```<code>window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url, null, {
        class:'dialogClass',
        autoOpen: false,
        onClose: function(){
            alert('closed');
        }
    });

    reqDialog.open();

    /*
        if you want to add some custom requestOptions, you need to do i.e.:
        reqDialog.setRequestOptions({
           onRequest: function(){
              reqDialog.setContent('loading...');
           }
        }).open();
    */
});
</code>```

and you need some css to define the style of the dialog by dialogClass:

```<code>.dialogClass{
    width:460;
    height:375;
    z-index:20;
}
</code>```

Title: MooDialog.Request add Event

Body:
How can I add a close event to MooDialog.Request?

Update:
There is my code:

window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url,
      {view:'show'},
      {
        size:  {
          width: 460,
          height: 375,
          'zIndex':20
        }
      }
    );
    reqDialog.setRequestOptions({
        onClose: function(){
            alert('closed');
        }
    });
  });
});

Body:
It's pretty simple:

//Request => new MooDialog.Request(url[, RequestOptions, options]);
var reqD = new MooDialog.Request('URL',null,{
    onClose: function(){
        alert('closed');
    }
});

doc

Edit your code need to be updated this way:

window.addEvent('domready', function(){
  $('xyz').addEvent('click', function(e) {
    e.stop();
    var reqDialog = new MooDialog.Request(url, null, {
        class:'dialogClass',
        autoOpen: false,
        onClose: function(){
            alert('closed');
        }
    });

    reqDialog.open();

    /*
        if you want to add some custom requestOptions, you need to do i.e.:
        reqDialog.setRequestOptions({
           onRequest: function(){
              reqDialog.setContent('loading...');
           }
        }).open();
    */
});

and you need some css to define the style of the dialog by dialogClass:

.dialogClass{
    width:460;
    height:375;
    z-index:20;
}


问:
powershell equivalent of linux "mkdir -p"?
How can I get the powershell "mkdir" command to act exactly like Linux's mkdir -p command?

Under Linux, mkdir -p will create nested directories, but only if they don't exist already.  For example, suppose you have a directory /foo that you have write permissions for. mkdir -p /foo/bar/baz creates bar and baz within bar under existing /foo. You run the same command over again, you will not get an error, but nothing will be created.

答:
You can ignore errors in PowerShell with the -ErrorAction SilentlyContinue parameter (you can shorten this to -ea 0). The full PowerShell command is

```<code>New-Item /foo/bar/baz -ItemType Directory -ea 0
</code>```

You can shorten this to

```<code>md /foo/bar/baz -ea 0
</code>```

(You can also type mkdir instead of md if you prefer.)

Note that PowerShell will output the DirectoryInfo object it creates when using New-Item -ItemType Directory (or the md or mkdir aliases). If you don't want any output, you can pipe to Out-Null.

Body:
You can ignore errors in PowerShell with the -ErrorAction SilentlyContinue parameter (you can shorten this to -ea 0). The full PowerShell command is

New-Item /foo/bar/baz -ItemType Directory -ea 0

You can shorten this to

md /foo/bar/baz -ea 0

(You can also type mkdir instead of md if you prefer.)

Note that PowerShell will output the DirectoryInfo object it creates when using New-Item -ItemType Directory (or the md or mkdir aliases). If you don't want any output, you can pipe to Out-Null.


问:
How do Python implementations handle context swap during function calls?
I am trying to create a heavily modular and data-driven program in python, and I'd like to have calls between modules go through a central proxy singleton instead of every object holding references to objects they communicate with. The main reason for this is that I don't want objects to have any information of how other modules work in case they are switched around during runtime.

Currently, this proxy service is just a singleton that has a list of tuples with function names and a reference to the object that owns it. Any time a module comes across a command that isn't part of their own methods, the default behavior would be to send it up to this proxy service that would check is there is anyone online capable of executing it. If it finds someone, the proxy forwards the function call to the right object and then sends the return to the caller once it receives it.

The problem I have with this is that every time I need to do any inter-process communication, I am causing a context swap to an object that will end up bloating my callstack unnecessarily.

My question then is thus:

How are context changes such as this handled in python implementations? And what optimizations can I make to lower the impact
  of such context changes?

P.S.: The name proxy might be a bit misleading, but this is not a networked application. The whole thing is running in a single process in a single machine.

Edit: As asked here is a more concrete example.

```<code>class forwardToProxy:
       dict = {} #this dictionary would contain the names of commands such as "deleteName"
                 #and a first class function bound to the part of the program currently
                 #responsible for executing that command.

       def forward_command(command, arg):
           return dispatch[command](arg)
</code>```

This is one example of what I meant for a proxy object. The only thing this class does is forward commands to the parts of the program currently assigned to executing. My question pertains to the consequences of using this kind of structure.

Does every call a module makes to it create a new instance of this class in memory until it resolves?

If a command were to be forwarded to a module, that would in consequence forward another command, and would cause another module to forwards yet another command, how many instances of this object would be waiting in memory for the eventual return?

What exactly happens in memory every time we make an function call in different python implementations?(Please explain for both same-module and external-module calls)

What optimizations can be used to reduce the impact of such context changes(would @staticmethod help, for example)?

答:
Interesting topic. Frankly speaking Python is not expected to work fast, however, I observe more and more demand on that.

In short:

Function scope is a dict, and can't see much to optimize here.

A bit longer explanation:

I know that named tuple is used when space optimizations come to play. The reasoning is that with named tuple all keys are the same, and kept once. That way you can save some space in the proxy definition. However, if you call function, it creates a scope, which is dict. That is how Python works. How to optimize it? Well, you have to write that in C, to have full control over what, and when is allocated.

Body:
I am trying to create a heavily modular and data-driven program in python, and I'd like to have calls between modules go through a central proxy singleton instead of every object holding references to objects they communicate with. The main reason for this is that I don't want objects to have any information of how other modules work in case they are switched around during runtime.

Currently, this proxy service is just a singleton that has a list of tuples with function names and a reference to the object that owns it. Any time a module comes across a command that isn't part of their own methods, the default behavior would be to send it up to this proxy service that would check is there is anyone online capable of executing it. If it finds someone, the proxy forwards the function call to the right object and then sends the return to the caller once it receives it.

The problem I have with this is that every time I need to do any inter-process communication, I am causing a context swap to an object that will end up bloating my callstack unnecessarily.

My question then is thus:

How are context changes such as this handled in python implementations? And what optimizations can I make to lower the impact
  of such context changes?

P.S.: The name proxy might be a bit misleading, but this is not a networked application. The whole thing is running in a single process in a single machine.

Edit: As asked here is a more concrete example.

class forwardToProxy:
       dict = {} #this dictionary would contain the names of commands such as "deleteName"
                 #and a first class function bound to the part of the program currently
                 #responsible for executing that command.

       def forward_command(command, arg):
           return dispatch[command](arg)

This is one example of what I meant for a proxy object. The only thing this class does is forward commands to the parts of the program currently assigned to executing. My question pertains to the consequences of using this kind of structure.

Does every call a module makes to it create a new instance of this class in memory until it resolves?

If a command were to be forwarded to a module, that would in consequence forward another command, and would cause another module to forwards yet another command, how many instances of this object would be waiting in memory for the eventual return?

What exactly happens in memory every time we make an function call in different python implementations?(Please explain for both same-module and external-module calls)

What optimizations can be used to reduce the impact of such context changes(would @staticmethod help, for example)?


问:
WebSocket server health check with curl
I am trying to implement a healthcheck for WebSocket server with curl.

```<code>curl --include --no-buffer \
    --header "Connection: Upgrade" \
    --header "Upgrade: websocket" \
    --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
    --header "Sec-WebSocket-Version: 13" \
    http://localhost:3000
</code>```

I send an HTTP request to do the handcheck, and receive an HTTP 101 as expected :

```<code>HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: qGEgH3En71di5rrssAZTmtRTyFk=
</code>```

My issue is that after receiving that response, curl will just hang.

Is there any way to tell curl to exit after that successful handshake?

答:
You can use Connection: close instead of Connection: Upgrade in order to specify that the connection should be closed after the completion of the response :

curl --include --no-buffer \
    --header "Connection: close" \
    --header "Upgrade: websocket" \
    --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
    --header "Sec-WebSocket-Version: 13" \
    http://localhost:3000
```

Title: WebSocket server health check with curl

Body:
I am trying to implement a healthcheck for WebSocket server with curl.

curl --include --no-buffer \
    --header "Connection: Upgrade" \
    --header "Upgrade: websocket" \
    --header "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
    --header "Sec-WebSocket-Version: 13" \
    http://localhost:3000

I send an HTTP request to do the handcheck, and receive an HTTP 101 as expected :

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: qGEgH3En71di5rrssAZTmtRTyFk=

My issue is that after receiving that response, curl will just hang.

Is there any way to tell curl to exit after that successful handshake?


问:
Memory warning and crash when creating PDF
When genrating a large PDF, my app recives a memory a warning, then crashes during the generation process of the PDF.  The PDF is drawn into a web view, when the pages get above a certain amount (depending on device) I run out of memory

My research into this matter so far leads me to understand I need to:

change UIGraphicsBeginPDFContextToData to IGraphicsBeginPDFContextToFile

Create a reasonable path to a temporary file,

Give that to the function,

Give the file to the webview to load.

Delete the file when done.

Problem is, while I think I grasp it (just) in pricipal, I dont know how to go about acheiving this, or fully understand it so as to impliment it within my code.  Advice in this matter very much appricated

Im also open to any other ideas to stop the memory crash

```<code>@interface ICPDFPreviewController ()
@property (nonatomic, strong) Certificate *certificate;
@property (nonatomic, strong) NSData *pdfData;
@property (nonatomic) BOOL viewHasUnloaded;
- (void)generatePdf;
- (void)pdfDone:(NSData *)data;
- (NSData *)createPdfWithPages:(NSArray *)pages;
@end

@implementation ICPDFPreviewController
@synthesize certificate=_certificate;
@synthesize scrollView=_scrollView;
@synthesize webView=_webView;
@synthesize pdfData=_pdfData;
@synthesize viewHasUnloaded=_viewHasUnloaded;

- (void)generatePdf
 {
 NSMutableArray *pagesArray = [NSMutableArray array];

 if ([self.certificate.certificateType.title isEqualToString:@"Minor Works"]) {
[pagesArray addObject:[[ICPDFMinorWorksPage1 alloc] initWithCertificate:self.certificate]];
 [pagesArray addObject:[[ICPDFMinorWorksPage2 alloc] initWithCertificate:self.certificate]];

 } else if ([self.certificate.certificateType.title isEqualToString:@"EIC"]) {
[pagesArray addObject:[[ICPDFEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage4 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage5 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
ICPDFEICPageFinal *pageFinal = [[ICPDFEICPageFinal alloc]        initWithCertificate:self.certificate];
 pageFinal.pageNumber.text = [NSString stringWithFormat:@"%d", pagesArray.count+1];
[pagesArray addObject:pageFinal];

} else if ([self.certificate.certificateType.title isEqualToString:@"Domestic EIC"]) {
[pagesArray addObject:[[ICPDFDomesticEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage4 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFDomesticEICPageFinal alloc] initWithCertificate:self.certificate]];

} else if ([self.certificate.certificateType.title isEqualToString:@"EICR"]) {
[pagesArray addObject:[[ICPDFEICRPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPage2 alloc] initWithCertificate:self.certificate]];
[self addObservationsToPagesArray:pagesArray];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFEICRInspection alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPageFinal alloc] initWithCertificate:self.certificate]];
 }

// Set page count on all pages
int pageNumber = 0;
for (ICCertificateComponent *page in pagesArray) {
page.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageNumber];
page.pageCount.text = [NSString stringWithFormat:@"%d", pagesArray.count];
}

 NSData *pdfData = [self createPdfWithPages:pagesArray];
[self performSelectorOnMainThread:@selector(pdfDone:) withObject:pdfData waitUntilDone:YES];

 }

- (void)pdfDone:(NSData *)data
 {
 self.pdfData = data;
[self.webView loadData:self.pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8"      baseURL:nil];
 [ICUtils removeProgressView];
 }

 - (NSData *)createPdfWithPages:(NSArray *)pages
  {
 // Creates a mutable data object for updating with binary data, like a byte array
 NSMutableData *pdfData = [NSMutableData data];

 ICCertificateComponent *firstPage = [pages objectAtIndex:0];

UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

 for (int i = 0; i < pages.count; i++) {
 ICCertificateComponent *thisPage = [pages objectAtIndex:i];
 UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

 CGContextRef pdfContext = UIGraphicsGetCurrentContext();
 [thisPage.contentView.layer renderInContext:pdfContext];
 }

 UIGraphicsEndPDFContext();

 return pdfData;
}

- (void)addDistributionBoardsToPagesArray:(NSMutableArray *)pagesArray
{
int pageCount = pagesArray.count;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"       ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *boards = [self.certificate.distributionBoards      sortedArrayUsingDescriptors:sortDescriptors];
 for (DistributionBoard *thisBoard in boards) {
DebugLog(@"Creating a board page");
ICPDFDistributionBoard *boardPage = [[ICPDFDistributionBoard alloc]        initWithDistributionBoard:thisBoard];
boardPage.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
DebugLog(@"Page number is %d", pageCount);
[pagesArray addObject:boardPage];

NSSortDescriptor *circuitDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"     ascending:YES];
NSArray *circuitDescriptors = [[NSArray alloc] initWithObjects:circuitDescriptor, nil];
NSArray *circuits = [thisBoard.circuits sortedArrayUsingDescriptors:circuitDescriptors];

 //int circuitCount = circuits.count;
 ICPDFCircuitDetails *circuitDetails = boardPage.circuitDetails;

int circuitCount = 0;
for (Circuit *thisCircuit in circuits) {
circuitCount++;
if (circuitCount > 16) {
    // Add an extension page
    DebugLog(@"Adding an extension sheet");
    circuitCount = 1;
    ICPDFDistributionBoardExtension *boardExtension = [[ICPDFDistributionBoardExtension  alloc]   initWithDistributionBoard:thisBoard];
    [pagesArray addObject:boardExtension];
    boardExtension.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
    circuitDetails = boardExtension.circuitDetails;
   }
    NSString *key = [NSString stringWithFormat:@"circuitRow%d", circuitCount];
   ICCircuitRow *circuitRow = [circuitDetails valueForKey:key];
   [circuitRow populateFromCircuit:thisCircuit];
  }
 }
}
</code>```

debug console warnings are a load of these, then crash

```<code> 2013-02-08 10:38:35.475 iCertifi[5772:907] Received memory warning.
 2013-02-08 10:38:35.477 iCertifi[5772:907] <ICPDFPreviewController: 0x1eb28930>   didReceiveMemoryWarning
</code>```

答:
If nothing else works you could try my solution. It scrolls through the webView and adds one page at a time to the PDF. I couldn't solve this problem any other way.
The backside of this solution is that it uses a timer, and that you will see the scrolling in the app while the PDF is generated.

Here's the code:

```<code>...
    CGPoint savedContentOffset;
    CGRect savedFrame;
    NSMutableData * pdfData;
    int pdfOffset;
    NSTimer *timer;
...

- (void)preparePdf {
    CGFloat height = aWebView.scrollView.contentSize.height;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    int pageHeight = screenRect.size.height;

    savedContentOffset = aWebView.scrollView.contentOffset;
    savedFrame = aWebView.frame;
    pdfData=[NSMutableData data];

    aWebView.scrollView.contentOffset = CGPointZero;
    aWebView.frame = CGRectMake(aWebView.frame.origin.x,aWebView.frame.origin.y,aWebView.frame.size.width,pageHeight);

    UIGraphicsBeginPDFContextToData(pdfData, aWebView.frame, nil);

    NSLog(@"pageHeight = %d", pageHeight);
    pdfOffset = 0;

    timer = [NSTimer scheduledTimerWithTimeInterval: 0.4
                                             target: self
                                           selector: @selector(printPdfPage:)
                                           userInfo: nil
                                            repeats: YES];
}

- (void) printPdfPage: (NSTimer*) timer {
    CGFloat height = aWebView.scrollView.contentSize.height;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    int pageHeight = screenRect.size.height;

    NSLog(@"pdfOffset = %d", pdfOffset);
    UIGraphicsBeginPDFPage();
    [aWebView drawViewHierarchyInRect:CGRectMake(0, 0, screenRect.size.width, pageHeight) afterScreenUpdates:YES];

    pdfOffset += pageHeight;
    aWebView.scrollView.contentOffset = CGPointMake(0, pdfOffset);

    if (pdfOffset > height) {
        [timer invalidate];
        NSLog(@"pdf data size: %ld", pdfData.length);
        [self emailPdf: pdfData];
    }
}

- (void) emailPdf: (NSMutableData*) pdfData {

    // finally end the PDF context.
    UIGraphicsEndPDFContext();

    aWebView.scrollView.contentOffset = savedContentOffset;
    aWebView.frame = savedFrame;

    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    mailer.mailComposeDelegate = self;
    [mailer setSubject:[@"iPad Screenshot " stringByAppendingString:[self getDate]]];
    [mailer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[[self getDate] stringByAppendingPathExtension:@"pdf"]];
    NSString *emailBody = @"";
    [mailer setMessageBody:emailBody isHTML:NO];
    [self presentViewController:mailer animated:YES completion:nil];

    if ([SVProgressHUD isVisible]) {
        [SVProgressHUD showSuccessWithStatus:@"Screenshot prepared."];
    }
    pdfData = nil;
    timer = nil;
}
</code>```

Body:
When genrating a large PDF, my app recives a memory a warning, then crashes during the generation process of the PDF.  The PDF is drawn into a web view, when the pages get above a certain amount (depending on device) I run out of memory

My research into this matter so far leads me to understand I need to:

change UIGraphicsBeginPDFContextToData to IGraphicsBeginPDFContextToFile

Create a reasonable path to a temporary file,

Give that to the function,

Give the file to the webview to load.

Delete the file when done.

Problem is, while I think I grasp it (just) in pricipal, I dont know how to go about acheiving this, or fully understand it so as to impliment it within my code.  Advice in this matter very much appricated

Im also open to any other ideas to stop the memory crash

@interface ICPDFPreviewController ()
@property (nonatomic, strong) Certificate *certificate;
@property (nonatomic, strong) NSData *pdfData;
@property (nonatomic) BOOL viewHasUnloaded;
- (void)generatePdf;
- (void)pdfDone:(NSData *)data;
- (NSData *)createPdfWithPages:(NSArray *)pages;
@end

@implementation ICPDFPreviewController
@synthesize certificate=_certificate;
@synthesize scrollView=_scrollView;
@synthesize webView=_webView;
@synthesize pdfData=_pdfData;
@synthesize viewHasUnloaded=_viewHasUnloaded;

- (void)generatePdf
 {
 NSMutableArray *pagesArray = [NSMutableArray array];

 if ([self.certificate.certificateType.title isEqualToString:@"Minor Works"]) {
[pagesArray addObject:[[ICPDFMinorWorksPage1 alloc] initWithCertificate:self.certificate]];
 [pagesArray addObject:[[ICPDFMinorWorksPage2 alloc] initWithCertificate:self.certificate]];

 } else if ([self.certificate.certificateType.title isEqualToString:@"EIC"]) {
[pagesArray addObject:[[ICPDFEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage4 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICPage5 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
ICPDFEICPageFinal *pageFinal = [[ICPDFEICPageFinal alloc]        initWithCertificate:self.certificate];
 pageFinal.pageNumber.text = [NSString stringWithFormat:@"%d", pagesArray.count+1];
[pagesArray addObject:pageFinal];

} else if ([self.certificate.certificateType.title isEqualToString:@"Domestic EIC"]) {
[pagesArray addObject:[[ICPDFDomesticEICPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFDomesticEICPage4 alloc] initWithCertificate:self.certificate]];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFDomesticEICPageFinal alloc] initWithCertificate:self.certificate]];

} else if ([self.certificate.certificateType.title isEqualToString:@"EICR"]) {
[pagesArray addObject:[[ICPDFEICRPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPage2 alloc] initWithCertificate:self.certificate]];
[self addObservationsToPagesArray:pagesArray];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFEICRInspection alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPageFinal alloc] initWithCertificate:self.certificate]];
 }

// Set page count on all pages
int pageNumber = 0;
for (ICCertificateComponent *page in pagesArray) {
page.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageNumber];
page.pageCount.text = [NSString stringWithFormat:@"%d", pagesArray.count];
}

 NSData *pdfData = [self createPdfWithPages:pagesArray];
[self performSelectorOnMainThread:@selector(pdfDone:) withObject:pdfData waitUntilDone:YES];

 }

- (void)pdfDone:(NSData *)data
 {
 self.pdfData = data;
[self.webView loadData:self.pdfData MIMEType:@"application/pdf" textEncodingName:@"utf-8"      baseURL:nil];
 [ICUtils removeProgressView];
 }

 - (NSData *)createPdfWithPages:(NSArray *)pages
  {
 // Creates a mutable data object for updating with binary data, like a byte array
 NSMutableData *pdfData = [NSMutableData data];

 ICCertificateComponent *firstPage = [pages objectAtIndex:0];

UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

 for (int i = 0; i < pages.count; i++) {
 ICCertificateComponent *thisPage = [pages objectAtIndex:i];
 UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

 CGContextRef pdfContext = UIGraphicsGetCurrentContext();
 [thisPage.contentView.layer renderInContext:pdfContext];
 }

 UIGraphicsEndPDFContext();

 return pdfData;
}

- (void)addDistributionBoardsToPagesArray:(NSMutableArray *)pagesArray
{
int pageCount = pagesArray.count;
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"       ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
NSArray *boards = [self.certificate.distributionBoards      sortedArrayUsingDescriptors:sortDescriptors];
 for (DistributionBoard *thisBoard in boards) {
DebugLog(@"Creating a board page");
ICPDFDistributionBoard *boardPage = [[ICPDFDistributionBoard alloc]        initWithDistributionBoard:thisBoard];
boardPage.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
DebugLog(@"Page number is %d", pageCount);
[pagesArray addObject:boardPage];

NSSortDescriptor *circuitDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdAt"     ascending:YES];
NSArray *circuitDescriptors = [[NSArray alloc] initWithObjects:circuitDescriptor, nil];
NSArray *circuits = [thisBoard.circuits sortedArrayUsingDescriptors:circuitDescriptors];

 //int circuitCount = circuits.count;
 ICPDFCircuitDetails *circuitDetails = boardPage.circuitDetails;

int circuitCount = 0;
for (Circuit *thisCircuit in circuits) {
circuitCount++;
if (circuitCount > 16) {
    // Add an extension page
    DebugLog(@"Adding an extension sheet");
    circuitCount = 1;
    ICPDFDistributionBoardExtension *boardExtension = [[ICPDFDistributionBoardExtension  alloc]   initWithDistributionBoard:thisBoard];
    [pagesArray addObject:boardExtension];
    boardExtension.pageNumber.text = [NSString stringWithFormat:@"%d", ++pageCount];
    circuitDetails = boardExtension.circuitDetails;
   }
    NSString *key = [NSString stringWithFormat:@"circuitRow%d", circuitCount];
   ICCircuitRow *circuitRow = [circuitDetails valueForKey:key];
   [circuitRow populateFromCircuit:thisCircuit];
  }
 }
}

debug console warnings are a load of these, then crash

 2013-02-08 10:38:35.475 iCertifi[5772:907] Received memory warning.
 2013-02-08 10:38:35.477 iCertifi[5772:907] <ICPDFPreviewController: 0x1eb28930>   didReceiveMemoryWarning

Body:
If nothing else works you could try my solution. It scrolls through the webView and adds one page at a time to the PDF. I couldn't solve this problem any other way.
The backside of this solution is that it uses a timer, and that you will see the scrolling in the app while the PDF is generated.

Here's the code:

...
    CGPoint savedContentOffset;
    CGRect savedFrame;
    NSMutableData * pdfData;
    int pdfOffset;
    NSTimer *timer;
...

- (void)preparePdf {
    CGFloat height = aWebView.scrollView.contentSize.height;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    int pageHeight = screenRect.size.height;

    savedContentOffset = aWebView.scrollView.contentOffset;
    savedFrame = aWebView.frame;
    pdfData=[NSMutableData data];

    aWebView.scrollView.contentOffset = CGPointZero;
    aWebView.frame = CGRectMake(aWebView.frame.origin.x,aWebView.frame.origin.y,aWebView.frame.size.width,pageHeight);

    UIGraphicsBeginPDFContextToData(pdfData, aWebView.frame, nil);

    NSLog(@"pageHeight = %d", pageHeight);
    pdfOffset = 0;

    timer = [NSTimer scheduledTimerWithTimeInterval: 0.4
                                             target: self
                                           selector: @selector(printPdfPage:)
                                           userInfo: nil
                                            repeats: YES];
}

- (void) printPdfPage: (NSTimer*) timer {
    CGFloat height = aWebView.scrollView.contentSize.height;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    int pageHeight = screenRect.size.height;

    NSLog(@"pdfOffset = %d", pdfOffset);
    UIGraphicsBeginPDFPage();
    [aWebView drawViewHierarchyInRect:CGRectMake(0, 0, screenRect.size.width, pageHeight) afterScreenUpdates:YES];

    pdfOffset += pageHeight;
    aWebView.scrollView.contentOffset = CGPointMake(0, pdfOffset);

    if (pdfOffset > height) {
        [timer invalidate];
        NSLog(@"pdf data size: %ld", pdfData.length);
        [self emailPdf: pdfData];
    }
}

- (void) emailPdf: (NSMutableData*) pdfData {

    // finally end the PDF context.
    UIGraphicsEndPDFContext();

    aWebView.scrollView.contentOffset = savedContentOffset;
    aWebView.frame = savedFrame;

    MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
    mailer.mailComposeDelegate = self;
    [mailer setSubject:[@"iPad Screenshot " stringByAppendingString:[self getDate]]];
    [mailer addAttachmentData:pdfData mimeType:@"application/pdf" fileName:[[self getDate] stringByAppendingPathExtension:@"pdf"]];
    NSString *emailBody = @"";
    [mailer setMessageBody:emailBody isHTML:NO];
    [self presentViewController:mailer animated:YES completion:nil];

    if ([SVProgressHUD isVisible]) {
        [SVProgressHUD showSuccessWithStatus:@"Screenshot prepared."];
    }
    pdfData = nil;
    timer = nil;
}


问:
how to make a dictionary using two lists
so I have this code and I am trying to create a lastnames to firstnames dictionary. I have created two lists out of my original dictionary which is:

```<code>person_to_friends = {
    'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
    'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
    'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
    'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
    'Alex Dunphy': ['Luke Dunphy'],
    'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
    'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
    'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
    'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
    'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
    'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}

family_dictionary = []
friends_dictionary = []
last_names = []
for person in person_to_friends:
    family_dictionary.append(person)
    for name in person_to_friends[person]:
        friends_dictionary.append(name)
</code>```

The above code gives me two lists, and I'm trying to use these to create a lastnames_to_firstnames dictionary where the keys are the lastnames of the people and the values should be all the names of the people with this lastname. I'm not sure how to proceed from here.

答: If your strings are formatted <FirstName> <LastName> or <FirstName> <Middle> <LastName> and are only separated by spaces, you should check out the split function.

Body:
so I have this code and I am trying to create a lastnames to firstnames dictionary. I have created two lists out of my original dictionary which is:

person_to_friends = {
    'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', 'Manny Delgado'],
    'Claire Dunphy': ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy'],
    'Manny Delgado': ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],
    'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', 'Luke Dunphy'],
    'Alex Dunphy': ['Luke Dunphy'],
    'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],
    'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],
    'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],
    'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],
    'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'],
    'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']
}

family_dictionary = []
friends_dictionary = []
last_names = []
for person in person_to_friends:
    family_dictionary.append(person)
    for name in person_to_friends[person]:
        friends_dictionary.append(name)

The above code gives me two lists, and I'm trying to use these to create a lastnames_to_firstnames dictionary where the keys are the lastnames of the people and the values should be all the names of the people with this lastname. I'm not sure how to proceed from here.


答:
You don't need to create two separate lists to solve your problem. You can do this working with the original. Here's what you'd need to do, in this order:

Extract all names from your dictionary

Remove duplicates

Iterate over each name, split into first and last names, and populate a dictionary

```<code>from itertools import chain

n = {}
for v in set(chain.from_iterable([k ] + v for k, v in person_to_friends.items())):
     f, l = v.rsplit(None, 1)
     n.setdefault(l, []).append(f)
</code>```

```<code>print(n)

{
    "Delgado": [
        "Manny"
    ],
    "D-Cat": [
        "Chairman",
        "Gilbert"
    ],
    "Dunphy": [
        "Claire",
        "Alex",
        "Haley Gwendolyn",
        "Phil",
        "Luke"
    ],
    "D-Money": [
        "Dylan"
    ],
    "Tucker": [
        "Cameron"
    ],
    "Pritchett": [
        "Gloria",
        "Mitchell",
        "Jay"
    ]
}
</code>```

Here, person_to_friends is your input. You can also use collections.defaultdict object instead of a dict with setdefault. I use itertools.chain to flatten your dictionary. Makes the rest of the process simpler.

As mentioned, this is how you'd use a defaultdict to your advantage.

```<code>from collections import defaultdict

n = defaultdict(list)
for v in set(chain.from_iterable([k ] + v for k, v in person_to_friends.items())):
     f, l = v.rsplit(None, 1)
     n[l].append(f)
</code>```

This happens to be slightly more efficient than dict + setdefault.

Title: how to make a dictionary using two lists

Body:
You don't need to create two separate lists to solve your problem. You can do this working with the original. Here's what you'd need to do, in this order:

Extract all names from your dictionary

Remove duplicates

Iterate over each name, split into first and last names, and populate a dictionary

from itertools import chain

n = {}
for v in set(chain.from_iterable([k ] + v for k, v in person_to_friends.items())):
     f, l = v.rsplit(None, 1)
     n.setdefault(l, []).append(f)

print(n)

{
    "Delgado": [
        "Manny"
    ],
    "D-Cat": [
        "Chairman",
        "Gilbert"
    ],
    "Dunphy": [
        "Claire",
        "Alex",
        "Haley Gwendolyn",
        "Phil",
        "Luke"
    ],
    "D-Money": [
        "Dylan"
    ],
    "Tucker": [
        "Cameron"
    ],
    "Pritchett": [
        "Gloria",
        "Mitchell",
        "Jay"
    ]
}

Here, person_to_friends is your input. You can also use collections.defaultdict object instead of a dict with setdefault. I use itertools.chain to flatten your dictionary. Makes the rest of the process simpler.

As mentioned, this is how you'd use a defaultdict to your advantage.

from collections import defaultdict

n = defaultdict(list)
for v in set(chain.from_iterable([k ] + v for k, v in person_to_friends.items())):
     f, l = v.rsplit(None, 1)
     n[l].append(f)

This happens to be slightly more efficient than dict + setdefault.


问:
how to modify struct fields in golang
I have example play.golang.org/p/Y1KX-t5Sj9 where I define method Modify() on struct User

```<code>type User struct {
  Name string
  Age int
}
func (u *User) Modify() {
  *u = User{Name: "Paul"}
}
</code>```

in the main() I am defining struct literal &User{Name: "Leto", Age: 11} then call u.Modify(). That results in printing 'Paul 0' I like that struct field Name is changed , but what is the correct way to keep Age field ?

答:
Just modify the field you want to change:

```<code>func (u *User) Modify() {
  u.Name = "Paul"
}
</code>```

This is covered well in the Go tour which you should definitely read through, it doesn't take long.

Title: how to modify struct fields in golang

Body:
I have example play.golang.org/p/Y1KX-t5Sj9 where I define method Modify() on struct User

type User struct {
  Name string
  Age int
}
func (u *User) Modify() {
  *u = User{Name: "Paul"}
}

in the main() I am defining struct literal &User{Name: "Leto", Age: 11} then call u.Modify(). That results in printing 'Paul 0' I like that struct field Name is changed , but what is the correct way to keep Age field ?

Body:
Just modify the field you want to change:

func (u *User) Modify() {
  u.Name = "Paul"
}

This is covered well in the Go tour which you should definitely read through, it doesn't take long.


问:
Delete Tortoise SVN Commits
I messed up with some commits in my project and I'd like to totally remove the commits I made, and not having any trace anymore (no revert).

Because I deleted some folders in my arborescence then restored them, but I lost all the logs that were on these subfolders and I totally need to know the modifications that have been made on these subfolders.

From the main folder, all the logs are visible, but not anymore in the subfolders

Does someone has an idea how to do it ???

答:
You cannot remove revisions, but I think what you could to in your case is the following: Use the repository browser and go to the revision where you still had your folders, copy the required folders to some "temp" folder in the root of your repository. Switch back to the "HEAD" of the repository and move the copied folders back into your project folder.

This way you will be able to see the entire history, just make sure that you uncheck the "Stop on copy/rename" checkbox in the log window.

Title: Delete Tortoise SVN Commits


问:
SQL Between AAA and ZZZ
I can't get codes that are between AAA and ZZZ, this is what I tried:

```<code>ALTER TABLE AIRPORT
ADD CONSTRAINT CORRECTCODE
CHECK (Code BETWEEN 'AAA' AND 'ZZZ' AND LENGTH(Code) = 3) ENABLE VALIDATE;
</code>```

It accepts the values I want, but it also accepts values that contain numbers like AB6. What am I doing wrong?

答:
It sounds like you're just looking for any three letter, upper-case code. If that's true, the easiest way to do so would be with regex, like;</p>

```<code>CHECK (REGEXP_LIKE (Code, '[A-Z]{3}'))
</code>```

Title: SQL Between AAA and ZZZ

Body:
I can't get codes that are between AAA and ZZZ, this is what I tried:

ALTER TABLE AIRPORT
ADD CONSTRAINT CORRECTCODE
CHECK (Code BETWEEN 'AAA' AND 'ZZZ' AND LENGTH(Code) = 3) ENABLE VALIDATE;

It accepts the values I want, but it also accepts values that contain numbers like AB6. What am I doing wrong?

Body:
It sounds like you're just looking for any three letter, upper-case code. If that's true, the easiest way to do so would be with regex, like;

CHECK (REGEXP_LIKE (Code, '[A-Z]{3}'))


问:
vba cycle through labels to change caption?
I have a list of lables like lblData1, lblData2, etc.
I would like to change their caption with a cycle like:

```<code>For i = 1 To 10
    lblData & i.Caption = "Something"
Next
</code>```

But logically is not working..how can i achieve this?

答:
Nevermind, I found out I can do:</p>

```<code>For i = 1 To X
    Controls("lblData " & i).Caption =  "Something"
Next
</code>```

Body:
I have a list of lables like lblData1, lblData2, etc.
I would like to change their caption with a cycle like:

For i = 1 To 10
    lblData & i.Caption = "Something"
Next

But logically is not working..how can i achieve this?

Body:
Nevermind, I found out I can do:

For i = 1 To X
    Controls("lblData " & i).Caption =  "Something"
Next


答:
The hashCode of an Integer is the value itself.   Your HashMap has 16 buckets, which means that the bucket that a value is assigned to is key % 16, which is a number from 0 to 15.

If your keys are in the range 0 to 15, then the bucket number is the key.  Things only get messy when you use keys > 15 or < 0.

When you print a HashMap, the entries appear in bucket order.  That is, a key in bucket 0 gets printed first, if there is one; then a key in bucket 1 and so on.  In the case of your HashMap where all the keys are between 0 and 15, this is exactly the same as key order.

Title: Why does a HashMap sometimes print in natural order


问:
source R file from private gitlab with basic auth
I would like to source an .R file from a private gitlab serveur. I need to use the basic authentication with user/password

I tried this kind of instruction without succes

```<code>httr::GET("http://vpsxxxx.ovh.net/root/project/raw/9f8a404b5b33c216d366d80b7d48e34577598069/R/script.R",
authenticate("user", "password",type="basic"))
</code>```

any idea?

Regards

edit : I found this way... but I need to download all the project...

```<code>bundle <- tempfile()
git2r::clone("http://vpsxxx.ovh.net/root/projet.git",
             bundle, credentials=git2r::cred_user_pass("user", "password"))
source(file.path(bundle,"R","script.R"))
</code>```

答:
you can use gitlab API to get a file from a repository. gitlabr can help you do that. Current version 0.9 is compatible with apiV3 and V4.

This should work (it work on my end on a private gitlab with apiv3)

library(gitlabr)
my_gitlab <- gl_connection("https://private-gitlab.com",
                       login = "username",
                       password = "password",
                       api_version = "v4") # by default. put v3 here if needed
my_file <- my_gitlab(gl_get_file, project = "project_name", file_path = "path/to/file")
```

<p>This will get you a character version of your file. You can also get back a raw version to deal with it in another way.</p>

```raw <- gl_get_file(project = "project_name",
                   file_path = "file/to/path",
                   gitlab_con = my_gitlab,
                   to_char = F)
temp_file <- tempfile()
writeBin(raw, temp_file)
```

<p>You can now source the code</p>

```source(temp_file)
```

It is one solution among others. I did not manage to source the file without using the API.

Know that :
* You can use an Access Token instead of username and password
* You can use the gitlabr several ways. It is documented in the vignette. I used 2 differents ways here.
* Version 1.0 will not be compatible with v3 api. But I think you use v4.

Feel free to get back to me so that I update this post if need a clearer answer.

Body:
I would like to source an .R file from a private gitlab serveur. I need to use the basic authentication with user/password

I tried this kind of instruction without succes

httr::GET("http://vpsxxxx.ovh.net/root/project/raw/9f8a404b5b33c216d366d80b7d48e34577598069/R/script.R",
authenticate("user", "password",type="basic"))

any idea?

Regards

edit : I found this way... but I need to download all the project...

bundle <- tempfile()
git2r::clone("http://vpsxxx.ovh.net/root/projet.git",
             bundle, credentials=git2r::cred_user_pass("user", "password"))
source(file.path(bundle,"R","script.R"))

Body:
you can use gitlab API to get a file from a repository. gitlabr can help you do that. Current version 0.9 is compatible with apiV3 and V4.

This should work (it work on my end on a private gitlab with apiv3)

library(gitlabr)
my_gitlab <- gl_connection("https://private-gitlab.com",
                       login = "username",
                       password = "password",
                       api_version = "v4") # by default. put v3 here if needed
my_file <- my_gitlab(gl_get_file, project = "project_name", file_path = "path/to/file")

This will get you a character version of your file. You can also get back a raw version to deal with it in another way.

raw <- gl_get_file(project = "project_name",
                   file_path = "file/to/path",
                   gitlab_con = my_gitlab,
                   to_char = F)
temp_file <- tempfile()
writeBin(raw, temp_file)

You can now source the code

source(temp_file)

It is one solution among others. I did not manage to source the file without using the API.

Know that :
* You can use an Access Token instead of username and password
* You can use the gitlabr several ways. It is documented in the vignette. I used 2 differents ways here.
* Version 1.0 will not be compatible with v3 api. But I think you use v4.

Feel free to get back to me so that I update this post if need a clearer answer.


问:
Microservice shared database
I know that this question has been discussed a lot already, but I would like to describe my situation.

As far as I know, there are techniques and best practices to solve the shared database in microservices architectures (event sourcing, CQRS...) but all of that seems to complex for my case, let me explain.

I built a rest API using nodejs. This API allow you to fetch, using a GET request, the data stored in a mysql database.
Now I need to import a lot of data in the same database (creating every time a new table). The first solution could be to add a new endpoint (POST request) to the existing microservice  to create the new table and add the new data.

But I was thinking about to create a different nodejs microservice (import service) because the import feature could be very CPU time consuming and nodejs is single thread;  I don’t want that a user has to wait to fetch the data because another one is importing the new one.

The problem whit that solution is that I have to share the same database between the 2 microservices. Using the typical approaches (event sourcing, CQRS) could be the best solution but it complexs too much the architecture ( for this project I don't need to address the data consistency problem).

There are others 2 solution that I can use:

create a common Lib to access the DB and use the lib in the microservices

The “import microservice” instead of access to the database directly, can use the API rest of the other service to post the new data as soon as they are ready to be imported.

What is the best solution? Do you know other possible ways to address this problem?

Thank you very much

答:
In the microservices world, services should be divided according to the bussiness domain that each service represents and not by specific technical functionality as you are proposing. This is an architectural design that I don't recommend bypassing just to workaround some specific technical funtionality.

The approach to solve your problem is not by splitting the microservice into two services that are in the same business domain.

Your problem is a performance issue. Performance issues are generally solved by scaling. It is totally normal to replicate your serivices by deploying multiple containers. Docker gives you this option by default where when deploying a service, you can specify the number of replicas to deploy.

Title: Microservice shared database


问:
Get title from newly opened page puppeteer
I am trying to get the a new tab and scrape the title of that page with puppeteer.

This is what I have

```<code>// use puppeteer
const puppeteer = require('puppeteer');

//set wait length in ms: 1000ms = 1sec
const short_wait_ms = 1000

async function run() {
    const browser = await puppeteer.launch({
        headless: false, timeout: 0});
    const page = await browser.newPage();

        await page.goto('https://biologyforfun.wordpress.com/2017/04/03/interpreting-random-effects-in-linear-mixed-effect-models/');

    // second page DOM elements
    const CLICKHERE_SELECTOR = '#post-2068 > div > div.entry-content > p:nth-child(2) > a:nth-child(1)';

    // main page
    await page.waitFor(short_wait_ms);
    await page.click(CLICKHERE_SELECTOR);

    // new tab opens - move to new tab
    let pages = await browser.pages();

    //go to the newly opened page

    //console.log title -- Generalized Linear Mixed Models in Ecology and in R

}

run();
</code>```

I can't figure out how to use browser.page() to start working on the new page.

答:
You shouldn't need to move to the new tab.

To get the title of any page you can use:

```<code>const pageTitle = await page.title();
</code>```

Also after you click something and you're waiting for the new page to load you should wait for the load event or the network to be Idle:

```<code>// Wait for redirection
await page.waitForNavigation({waitUntil: 'networkidle', networkIdleTimeout: 1000});
</code>```

Check the docs: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions

Body:
I am trying to get the a new tab and scrape the title of that page with puppeteer.

This is what I have

// use puppeteer
const puppeteer = require('puppeteer');

//set wait length in ms: 1000ms = 1sec
const short_wait_ms = 1000

async function run() {
    const browser = await puppeteer.launch({
        headless: false, timeout: 0});
    const page = await browser.newPage();

        await page.goto('https://biologyforfun.wordpress.com/2017/04/03/interpreting-random-effects-in-linear-mixed-effect-models/');

    // second page DOM elements
    const CLICKHERE_SELECTOR = '#post-2068 > div > div.entry-content > p:nth-child(2) > a:nth-child(1)';

    // main page
    await page.waitFor(short_wait_ms);
    await page.click(CLICKHERE_SELECTOR);

    // new tab opens - move to new tab
    let pages = await browser.pages();

    //go to the newly opened page

    //console.log title -- Generalized Linear Mixed Models in Ecology and in R

}

run();

I can't figure out how to use browser.page() to start working on the new page.

Body:
You shouldn't need to move to the new tab.

To get the title of any page you can use:

const pageTitle = await page.title();

Also after you click something and you're waiting for the new page to load you should wait for the load event or the network to be Idle:

// Wait for redirection
await page.waitForNavigation({waitUntil: 'networkidle', networkIdleTimeout: 1000});

Check the docs: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagewaitfornavigationoptions


问:
NetValidatePasswordPolicy issue on XP
My project has a requirement that it needs to check the password complexity before create the new account.

```<code>My code looks like:

NET_API_STATUS status;
NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG inputArg = {0};
NET_VALIDATE_OUTPUT_ARG* pOutputArg = NULL;

inputArg.ClearPassword = NewPass;
inputArg.PasswordMatch = TRUE;

status = NetValidatePasswordPolicy(DC, NULL, NetValidatePasswordChange,
            &inputArg, (void**)&pOutputArg);
printf("status: %d, validationStatus: %d\n", status, pOutputArg->ValidationStatus);

NetValidatePasswordPolicyFree((void**)&pOutputArg);
</code>```

I am working on windows XP.When I try to run, it prompt waring saying:

The procedure entry point NetValidPasswordPolicyFree could not be located in the dynamic link library NETAPI32.dll

From the MSDN it said the API is only valid in 2003 server and 2008 server.
    Does it mean it can not work on XP?
    Or can i find any other APIs to do the same thing as NetValidPasswordPolicy?

I googled a lot for this issue and found someone had asked similar question but it went unanswered :(. So, here I am trying my luck.

Even I tried to analyze 'NETAPI32.dll' in Reflector.exe, but while opening the .dll file it error out: Object reference not set to an instance of an object.

I am stuck badly and could not able to find any way. Any help will be appreciated :)

答:
Issue has been solved :).

NetValidPasswordPolicy API from 'NETAPI32.dll' has requirements that it is not 'client' supported. Because of this requirement I am getting the warning: Entry point not found.
I tried my project on Windows 2003 server and it worked.

And my second question about 'Reflector.exe' is also invalid because 'NETAPI32.dll' is not .Net dll so Reflector wont recognize it.

Title: NetValidatePasswordPolicy issue on XP

Body:
My project has a requirement that it needs to check the password complexity before create the new account.

My code looks like:

NET_API_STATUS status;
NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG inputArg = {0};
NET_VALIDATE_OUTPUT_ARG* pOutputArg = NULL;

inputArg.ClearPassword = NewPass;
inputArg.PasswordMatch = TRUE;

status = NetValidatePasswordPolicy(DC, NULL, NetValidatePasswordChange,
            &inputArg, (void**)&pOutputArg);
printf("status: %d, validationStatus: %d\n", status, pOutputArg->ValidationStatus);

NetValidatePasswordPolicyFree((void**)&pOutputArg);

I am working on windows XP.When I try to run, it prompt waring saying:

The procedure entry point NetValidPasswordPolicyFree could not be located in the dynamic link library NETAPI32.dll

From the MSDN it said the API is only valid in 2003 server and 2008 server.
    Does it mean it can not work on XP?
    Or can i find any other APIs to do the same thing as NetValidPasswordPolicy?

I googled a lot for this issue and found someone had asked similar question but it went unanswered :(. So, here I am trying my luck.

Even I tried to analyze 'NETAPI32.dll' in Reflector.exe, but while opening the .dll file it error out: Object reference not set to an instance of an object.

I am stuck badly and could not able to find any way. Any help will be appreciated :)