问:
swift Xcode reading application settings
I am new to swift/ios programming.  I created a small app with settings but I can't seem to read value.

```<code>        UserDefaults.standard.register(defaults: [String : Any]())

    let settings = UserDefaults.standard;

    let k = Bundle.main.infoDictionary!;

    let b = settings.dictionaryRepresentation()

  let val3 = Bundle.main.object(forInfoDictionaryKey: "digit_preference")

    let value2 = settings.string(forKey: "digit_preference")
</code>```

I can't find my settings "digit_preference" in Bundle.main.InfoDictionary or UserDefaults.standard.dictionaryRepresentation()

I can view my application settings properly in my phone. (Digits set to 2)

答:
You need to cast the file data to a dictionary at first since the root structure is a Dictionary. This of course, if the file you're showing us is actually a .plist file; the following is how to access a .plist file, but the first step is also common for almost every other file type in your app bundle. What differs (say from .txt, .json, etc) is the second step depending on what you want to do..

Like so:

```<code>guard let idForResource = Bundle.main.path(forResource: "pListFilename", ofType: ".plist"),
       let dict = NSDictionary(contentsOfFile: idForResource) as? [String: Any] else {
      return }
</code>```

Then you access the variable through dict like you would from any other dictionary.

Body:
I am new to swift/ios programming.  I created a small app with settings but I can't seem to read value.

        UserDefaults.standard.register(defaults: [String : Any]())

    let settings = UserDefaults.standard;

    let k = Bundle.main.infoDictionary!;

    let b = settings.dictionaryRepresentation()

  let val3 = Bundle.main.object(forInfoDictionaryKey: "digit_preference")

    let value2 = settings.string(forKey: "digit_preference")

I can't find my settings "digit_preference" in Bundle.main.InfoDictionary or UserDefaults.standard.dictionaryRepresentation()

I can view my application settings properly in my phone. (Digits set to 2)

Body:
You need to cast the file data to a dictionary at first since the root structure is a Dictionary. This of course, if the file you're showing us is actually a .plist file; the following is how to access a .plist file, but the first step is also common for almost every other file type in your app bundle. What differs (say from .txt, .json, etc) is the second step depending on what you want to do..

Like so:

guard let idForResource = Bundle.main.path(forResource: "pListFilename", ofType: ".plist"),
       let dict = NSDictionary(contentsOfFile: idForResource) as? [String: Any] else {
      return }

Then you access the variable through dict like you would from any other dictionary.


来源: stackexchange

问:
How do I make it so that when I click on a button in Html How do I make it so the web page redirects itself to the place its supposed to go

 <!DOCTYPE html>

    <title>______</title>
    <button class="btn about">About</button>
    <button class="btn socialmedia">Social Media</button></button>
    <button class="btn profile">Profile</button>
    <button class="btn contact">Contact</button>
    <button class="btn homepage">Homepage</button>```

I want it to be that when they click on contact it brings them to a page that I make that has all the contact info on it.  Please explain in the simplist way possible.

答:
If you dont like wrapping it  tag, Ex:

```<code><a href="http://www.example.com"><button class="btn about">About</button></a>
</code>```

You can use JS or JQuery

1. Inline JS

```<code><button class="btn about" onclick="window.location='http://www.example.com';">About</button>
</code>```

2. JS Function

```<code><script>
    function visitPage(){
        window.location='http://www.example.com';
    }
</script>

<button class="btn about" onclick="visitPage();">About</button>
</code>```

3. JQuery

```<code><button id="about">About</button>

$('#about').click(function() {
  window.location='http://www.example.com';
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
 <!DOCTYPE html>

    <title>______</title>
    <button class="btn about">About</button>
    <button class="btn socialmedia">Social Media</button></button>
    <button class="btn profile">Profile</button>
    <button class="btn contact">Contact</button>
    <button class="btn homepage">Homepage</button>

I want it to be that when they click on contact it brings them to a page that I make that has all the contact info on it.  Please explain in the simplist way possible.

Body:
If you dont like wrapping it <a> tag, Ex:

<a href="http://www.example.com"><button class="btn about">About</button></a>

You can use JS or JQuery

1. Inline JS

<button class="btn about" onclick="window.location='http://www.example.com';">About</button>

2. JS Function

<script>
    function visitPage(){
        window.location='http://www.example.com';
    }
</script>

<button class="btn about" onclick="visitPage();">About</button>

3. JQuery

<button id="about">About</button>

$('#about').click(function() {
  window.location='http://www.example.com';
});


问:
IBM DB2 unable to access database from PHP after reboot
System: Windows 8

I have been working on a project for school using IBM DB2 Express-C, Xampp, and PHP to access the database.

Everything has been working perfectly. Then one day I rebooted my computer.

IBM Database Manager returned the following error at startup:

SQL5005C The operation failed because the database manager failed to access either the database manager configuration file or the database configuration file.

I have tried running db2stop and db2start.

I am still able to access my database via the db2 command line terminal as if nothing is wrong.

However, when I try to access my database from PHP I now get the following error from my PHP file:

58031
[IBM][CLI Driver] SQL1031N The database directory cannot be found on the indicated file system. SQLSTATE=58031 SQLCODE=-1031

答:
The possible reason is that you lost the database files on your hard disk.

Use command to check.

```<code>db2diag -g db=database name > log.txt
</code>```

open log.txt,you will see the message like below. In this case, I lost some db2 config files.

Create missing folder and copy the db2
config files from the backup

Using backup file to restore database.

Body:
The possible reason is that you lost the database files on your hard disk.

Use command to check.

db2diag -g db=database name > log.txt

open log.txt,you will see the message like below. In this case, I lost some db2 config files.

Create missing folder and copy the db2
config files from the backup

Using backup file to restore database.


问:
Match a string which is few lines above another line where the first string was matched
So, I have this text file which is huge. I need to look for a string and when I match it, I need to go a few lines back(above the current line) and search for another string and extract some information from that line that contains the second string. How can I do this in Python using regex match?
I am trying to do something like this.

```<code>substr1 = re.compile("ACT",re.IGNORECASE)
substr2 = re.compile(vector,re.IGNORECASE)

try:
    with open (filepath, 'rt') as in_file:
        for linenum, line in enumerate(in_file):
            if substr2.search(line) != None:
                print(linenum,line)

                    # Code to trace back a few lines to look for substr1

                break
except FileNotFoundError:                   # If the file not found,
    print("pattern not found.")                # print an error message.
</code>```

It is kind of like I want to read it backward when I match the first string and look for the first occurrence of the second string. The number of lines varies and I cannot thus use the dequeue option I think. I am totally new to Python.
Any help is appreciated, thank you!
Am adding an example log file that I am reading.

```<code>X 123
X 1234
X 12345
Vector1
----
-----
-----
X 1231
X 12344
X 123456
vector a
vector b
vector c
vector d
-------
-------
Vector
----
-----
-----
X 1233
X 12345
X 123451
Vector2
</code>```

String 1 : Vector
String 2 : X

Output should be X 123456

答:
You do not need to backtrack. Instead, just search forward in a smarter manner. If you search for substr1 first, the only issue that could happen is that more occurrences of substr1 will be found before you find substr2. The way to handle that is to keep updating match of substr1 as you go.

From your description, it does not appear that you need regex at all. Instead, you appear to be looking for simple string containment tests.

```<code>substr1 = 'X'
substr2 = 'Vector'

with open (filepath, 'rt') as in_file:
    matched = None
    for linenum, line in enumerate(in_file, start=1):
        if substr1 in line:
            matched = line
        elif matched and line == substr2:
            # Process the second string
            print(matched)
            break
</code>```

If you have whitespace at the end of your lines, as you do in the sample you give, you may want to use line.startswith(substr2) instead of line == substr2.

Minor fixes:

start=1 will make your line numbers start with 1, which is probably what you want.

If you want to compare against None, the proper way is is not None instead of !=. Additionally, regex.search returns a match object. It will always be truthy if a match occurs. The idiomatic way to check it is without even is not None.

Body:
So, I have this text file which is huge. I need to look for a string and when I match it, I need to go a few lines back(above the current line) and search for another string and extract some information from that line that contains the second string. How can I do this in Python using regex match?
I am trying to do something like this.

substr1 = re.compile("ACT",re.IGNORECASE)
substr2 = re.compile(vector,re.IGNORECASE)

try:
    with open (filepath, 'rt') as in_file:
        for linenum, line in enumerate(in_file):
            if substr2.search(line) != None:
                print(linenum,line)

                    # Code to trace back a few lines to look for substr1

                break
except FileNotFoundError:                   # If the file not found,
    print("pattern not found.")                # print an error message.

It is kind of like I want to read it backward when I match the first string and look for the first occurrence of the second string. The number of lines varies and I cannot thus use the dequeue option I think. I am totally new to Python.
Any help is appreciated, thank you!
Am adding an example log file that I am reading.

X 123
X 1234
X 12345
Vector1
----
-----
-----
X 1231
X 12344
X 123456
vector a
vector b
vector c
vector d
-------
-------
Vector
----
-----
-----
X 1233
X 12345
X 123451
Vector2

String 1 : Vector
String 2 : X

Output should be X 123456

Body:
You do not need to backtrack. Instead, just search forward in a smarter manner. If you search for substr1 first, the only issue that could happen is that more occurrences of substr1 will be found before you find substr2. The way to handle that is to keep updating match of substr1 as you go.

From your description, it does not appear that you need regex at all. Instead, you appear to be looking for simple string containment tests.

substr1 = 'X'
substr2 = 'Vector'

with open (filepath, 'rt') as in_file:
    matched = None
    for linenum, line in enumerate(in_file, start=1):
        if substr1 in line:
            matched = line
        elif matched and line == substr2:
            # Process the second string
            print(matched)
            break

If you have whitespace at the end of your lines, as you do in the sample you give, you may want to use line.startswith(substr2) instead of line == substr2.

Minor fixes:

start=1 will make your line numbers start with 1, which is probably what you want.

If you want to compare against None, the proper way is is not None instead of !=. Additionally, regex.search returns a match object. It will always be truthy if a match occurs. The idiomatic way to check it is without even is not None.


问:
c# A better way to Copy/Merge multiple arrays into one array
Would anyone be able to advise if there's a better way to copy multiple arrays into a single array? The resulting array must have the elements in the same order such as arrayOne values first then arraySecond values next etc.

Following is a mockup of what I'm currently executing which working as expected. Looking for a smarter way of doing this.

```<code>// Initialise the first array.
string[] arrayOne = new string[5];
arrayOne[0] = "arrayOneValue[0]";
arrayOne[1] = "arrayOneValue[1]";
arrayOne[2] = "arrayOneValue[2]";
arrayOne[3] = "arrayOneValue[3]";
arrayOne[4] = "arrayOneValue[4]";

// Initialise the second array.
string[] arrayTwo = new string[6];
arrayTwo[0] = "arrayTwoValue[0]";
arrayTwo[1] = "arrayTwoValue[1]";
arrayTwo[2] = "arrayTwoValue[2]";
arrayTwo[3] = "arrayTwoValue[3]";
arrayTwo[4] = "arrayTwoValue[4]";
arrayTwo[5] = "arrayTwoValue[5]";

// Initialise the third array.
string[] arrayThree = new string[3];
arrayThree[0] = "arrayThreeValue[0]";
arrayThree[1] = "arrayThreeValue[1]";
arrayThree[2] = "arrayThreeValue[2]";

// string[] arrayN = new string[n]
//.
//.
//.

// Initialise the target array.
string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length];
// ArrayN - string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length + arrayN.Length];

// Copy/merge the three arrays into the target array.
Array.Copy(arrayOne, 0, finalArray, 0, arrayOne.Length);
Array.Copy(arrayTwo, 0, finalArray, arrayOne.Length, arrayTwo.Length);
Array.Copy(arrayThree, 0, finalArray, (arrayOne.Length + arrayTwo.Length), arrayThree.Length);
//.
//.
//.
//.
// ArrayN - Array.Copy(arrayN, 0, finalArray, (arrayOne.Length + arrayTwo.Length + arrayN), arrayN.Length) ?;
</code>```

As you can see for arrayN the code can get longer. I have a maximum of 5 arrays I'm trying to copy into one array, therefore, it's manageable. I'm using this technique as part of a WebAPI where a collection of oracle parameter objects are consolidated based on business rules to be passed to several Oracle stored procedures. Any advise here is appreciated. Thanks in advance.
Result

```<code>Console output
/*--- Destination array -
arrayOneValue[0]
arrayOneValue[1]
arrayOneValue[2]
arrayOneValue[3]
arrayOneValue[4]
arrayTwoValue[0]
arrayTwoValue[1]
arrayTwoValue[2]
arrayTwoValue[3]
arrayTwoValue[4]
arrayTwoValue[5]
arrayThreeValue[0]
arrayThreeValue[1]
arrayThreeValue[2]*/
</code>```

答:
You can put your input arrays in a collection and iterate over them. I only mention this because this may be more efficient than using LINQ. It depends on the data you're dealing with, but probably not enough to make a difference.

In the code below, on my machine, LINQ takes 9000-13000 ticks (one tick = 100 ns) while calling Array.Copy is ~500 ticks.

public static void Benchmark1()
{
    var arr1 = Enumerable.Range(1,10000).ToArray();
    var arr2 = Enumerable.Range(10001,20000).ToArray();
    var arr3 = Enumerable.Range(20001,30000).ToArray();
    var arr4 = Enumerable.Range(30001,40000).ToArray();

    var sw = Stopwatch.StartNew();
    var result = arr1.Concat(arr2).Concat(arr3).Concat(arr4).ToArray();
    sw.Stop();
    Console.WriteLine($"Elpased ticks: {sw.ElapsedTicks}");
}

public static void Benchmark2()
{
    var arr1 = Enumerable.Range(1,10000).ToArray();
    var arr2 = Enumerable.Range(10001,20000).ToArray();
    var arr3 = Enumerable.Range(20001,30000).ToArray();
    var arr4 = Enumerable.Range(30001,40000).ToArray();

    var arrays = new List<int[]>() {arr1, arr2, arr3, arr4};

    var sw = Stopwatch.StartNew();

    int finalLen = 0;
    foreach (var arr in arrays)
    {
        finalLen += arr.Length;
    }

    var result = new int[finalLen];
    int currentPosition = 0;

    foreach (var arr in arrays)
    {
        Array.Copy(arr, 0, result, currentPosition, arr.Length);
        currentPosition += arr.Length;
    }

    sw.Stop();
    Console.WriteLine($"Elpased ticks: {sw.ElapsedTicks}");
}
```

Body:
Would anyone be able to advise if there's a better way to copy multiple arrays into a single array? The resulting array must have the elements in the same order such as arrayOne values first then arraySecond values next etc.

Following is a mockup of what I'm currently executing which working as expected. Looking for a smarter way of doing this.

// Initialise the first array.
string[] arrayOne = new string[5];
arrayOne[0] = "arrayOneValue[0]";
arrayOne[1] = "arrayOneValue[1]";
arrayOne[2] = "arrayOneValue[2]";
arrayOne[3] = "arrayOneValue[3]";
arrayOne[4] = "arrayOneValue[4]";

// Initialise the second array.
string[] arrayTwo = new string[6];
arrayTwo[0] = "arrayTwoValue[0]";
arrayTwo[1] = "arrayTwoValue[1]";
arrayTwo[2] = "arrayTwoValue[2]";
arrayTwo[3] = "arrayTwoValue[3]";
arrayTwo[4] = "arrayTwoValue[4]";
arrayTwo[5] = "arrayTwoValue[5]";

// Initialise the third array.
string[] arrayThree = new string[3];
arrayThree[0] = "arrayThreeValue[0]";
arrayThree[1] = "arrayThreeValue[1]";
arrayThree[2] = "arrayThreeValue[2]";

// string[] arrayN = new string[n]
//.
//.
//.

// Initialise the target array.
string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length];
// ArrayN - string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length + arrayN.Length];

// Copy/merge the three arrays into the target array.
Array.Copy(arrayOne, 0, finalArray, 0, arrayOne.Length);
Array.Copy(arrayTwo, 0, finalArray, arrayOne.Length, arrayTwo.Length);
Array.Copy(arrayThree, 0, finalArray, (arrayOne.Length + arrayTwo.Length), arrayThree.Length);
//.
//.
//.
//.
// ArrayN - Array.Copy(arrayN, 0, finalArray, (arrayOne.Length + arrayTwo.Length + arrayN), arrayN.Length) ?;

As you can see for arrayN the code can get longer. I have a maximum of 5 arrays I'm trying to copy into one array, therefore, it's manageable. I'm using this technique as part of a WebAPI where a collection of oracle parameter objects are consolidated based on business rules to be passed to several Oracle stored procedures. Any advise here is appreciated. Thanks in advance.
Result

Console output
/*--- Destination array -
arrayOneValue[0]
arrayOneValue[1]
arrayOneValue[2]
arrayOneValue[3]
arrayOneValue[4]
arrayTwoValue[0]
arrayTwoValue[1]
arrayTwoValue[2]
arrayTwoValue[3]
arrayTwoValue[4]
arrayTwoValue[5]
arrayThreeValue[0]
arrayThreeValue[1]
arrayThreeValue[2]*/


问:
Form without CSRF token: what are the risks
What exactly are the risks I'm exposing myself to if I don't use csrf tokens in my forms? I'm not looking for simple labels or names of the risks, because these can be confusing. I need to understand what exactly an attacker can do and only under what circumstances they can do this, in plain English.</p>

答:
A CSRF vulnerability is one which allows a malicious user (or website) to make an unsuspecting user perform an action on your site which they didn't want to happen.

Some real world examples would be things like if you allowed a user to delete an account over GET instead of POST, someone could post the following comment on your site (assuming the site has some way to post comments or other input, etc.)

I thought I'd make a comment on your site. Check out this cool image!

And now any time a logged in user loads that page, their account would be deleted. If it was done over POST instead of GET, someone could craft a form and trick users into submitting it and the same result would happen. Whereas if you used a CSRF token, this wouldn't be possible.

Another example would be that an external site could craft a form which POSTs to your site, and perform an undesirable action. So let's say your site has a shopping cart which doesn't use CSRF tokens. A malicious site could create a form with a button that says "Click here to register", but actually orders 1000 of something from your site. If a logged in user from your site visits this malicious site and clicks the button, they'll get a nice surprise in the mail.

Obviously there are other cases, these are just a few examples. A Google search should show up plenty of articles and tutorials, many of which will probably have some other examples. The Wikipedia page also has some examples which you might find interesting.

The main idea of the examples is that someone can trick your site into performing an action as if it came from a user, when really the user wasn't aware it was happening or didn't want it to happen. If you have any sort of action on your site which is destructive (i.e. can delete things from a user account, logout a user, etc.) or critical (i.e. deals with money) you should probably use CSRF tokens. If your site is just a photo album for friends, etc. then you probably don't need to bother with CSRF tokens (although it's always good to practice for when you do build a site that needs them).

Unless you add a token to ensure that a request came from a form your site presented to the user intentionally, you don't really have a way of knowing if the user intended to perform the action.

So you always want to use a unique token on every form you generate that POSTs and validate any requests that are POSTed to your site have a valid token for the current user. Also make sure to expire the tokens after some amount of time so that they don't last forever.

ContentLicense: CC BY-SA 2.5

Body:
A CSRF vulnerability is one which allows a malicious user (or website) to make an unsuspecting user perform an action on your site which they didn't want to happen.

Some real world examples would be things like if you allowed a user to delete an account over GET instead of POST, someone could post the following comment on your site (assuming the site has some way to post comments or other input, etc.)

I thought I'd make a comment on your site. Check out this cool image!

  <img src='http://example.com/delete_my_account.php" />

And now any time a logged in user loads that page, their account would be deleted. If it was done over POST instead of GET, someone could craft a form and trick users into submitting it and the same result would happen. Whereas if you used a CSRF token, this wouldn't be possible.

Another example would be that an external site could craft a form which POSTs to your site, and perform an undesirable action. So let's say your site has a shopping cart which doesn't use CSRF tokens. A malicious site could create a form with a button that says "Click here to register", but actually orders 1000 of something from your site. If a logged in user from your site visits this malicious site and clicks the button, they'll get a nice surprise in the mail.

Obviously there are other cases, these are just a few examples. A Google search should show up plenty of articles and tutorials, many of which will probably have some other examples. The Wikipedia page also has some examples which you might find interesting.

The main idea of the examples is that someone can trick your site into performing an action as if it came from a user, when really the user wasn't aware it was happening or didn't want it to happen. If you have any sort of action on your site which is destructive (i.e. can delete things from a user account, logout a user, etc.) or critical (i.e. deals with money) you should probably use CSRF tokens. If your site is just a photo album for friends, etc. then you probably don't need to bother with CSRF tokens (although it's always good to practice for when you do build a site that needs them).

Unless you add a token to ensure that a request came from a form your site presented to the user intentionally, you don't really have a way of knowing if the user intended to perform the action.

So you always want to use a unique token on every form you generate that POSTs and validate any requests that are POSTed to your site have a valid token for the current user. Also make sure to expire the tokens after some amount of time so that they don't last forever.


问:
Spring Integration + Spring Boot Actuator Endpoints not showing up
I have been trying to learn more about Spring Boot and I would like to add the Actuator endpoints to my test Spring integration/Spring Boot project.  However, it is a plain, CLI Spring integration project--there are no current REST or web services.  I'd ideally like to add the ability to view the endpoints with a browser while the jar is running from the command line.

I have been looking through the tutorials and I'm not finding a lot on adding it to a regular project, rather than a web project.

I've added the dependencies (spring-boot-actuator), and can see the endpoints from the jconsole, but I never see a connection to a port on my system (using netstat) and never can navigate there.

Is there a tutorial or something that can show me how to have REST endpoints with a CLI project?

Thank you

newbo

答:
According to Spring Docs, in order to show the endpoint user need to have ACTUATOR role.If you need to access without having the role you need to add the following value to application.properties:

```<code>management.security.enabled=false
</code>```

Body:
According to Spring Docs, in order to show the endpoint user need to have ACTUATOR role.If you need to access without having the role you need to add the following value to application.properties:

management.security.enabled=false


问:
JPA @Id @GeneratedValue annotations vs DB primary key?
I have an app accessing an existing MySQL DB utilizing JDBC and am converting to JPA.  My DB is already setup with primary keys which are auto generated.  Do I need to annotate my entity classes w/ @Id, @GeneratedValue... when this is already defined in the DB?  Will the annotations override / conflict with the DB primary key / indexes already defined?</p>

答:
It not going to conflict with the DB primary key and the JPA annotations.Since primary key is already indexed, it's not a problem at all.

You should add annotations in entity classes.It is not going to conflict with already defined DB.If you deploy the system in new DB environment then annotations must be needed.


问:
Parse Error on Nodejs POST request
I am looking to send a request to a server running on localhost and process its' response and reply back to the user. </p>

```<code>        var post_data = qs.stringify({
            'parameter':'some value'
        });

        var post_options = {
            uri: 'http://localhost:9000',

            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(post_data)
            }
        };

        var post_req = request(post_options,function(error,response,body){
            response.setEncoding('utf-8');
            if(response.statusCode==200)
            {
                console.log(body);
                var resp_data = JSON.parse(body);
                var result = validate(resp_data,expected_output);
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{"Content-Type":"application/json"});
                res.write(JSON.stringify(result));
                res.end();
            }
        });
        post_req.write(post_data);
        post_req.end();
</code>```

<p>However, the 'body' parameter in the call back function of 'post_req' is undefined even though server running on localhost:9000 returns a response. On checking the 'error' parameter, it shows 'Error: Parse Error'. Help me out. </p>

答:
I have found the fix!

It was my back end python server running at http://localhost:9000 that has been sending out junky responses.

Solution for fixing my python server found at Python's BaseHTTPServer returns junky responses

Title: Parse Error on Nodejs POST request

Body:
I am looking to send a request to a server running on localhost and process its' response and reply back to the user.

        var post_data = qs.stringify({
            'parameter':'some value'
        });

        var post_options = {
            uri: 'http://localhost:9000',

            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(post_data)
            }
        };

        var post_req = request(post_options,function(error,response,body){
            response.setEncoding('utf-8');
            if(response.statusCode==200)
            {
                console.log(body);
                var resp_data = JSON.parse(body);
                var result = validate(resp_data,expected_output);
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{"Content-Type":"application/json"});
                res.write(JSON.stringify(result));
                res.end();
            }
        });
        post_req.write(post_data);
        post_req.end();

However, the 'body' parameter in the call back function of 'post_req' is undefined even though server running on localhost:9000 returns a response. On checking the 'error' parameter, it shows 'Error: Parse Error'. Help me out.


问:
How to use custom control in Fiori launchpad of Cloud Foundry
As I deploy Monitor app as a SAPUI5 app in Fiori launchpad in Cloud Foundry, I encountered an error:

404 Not Found:
  https://sapui5.hana.ondemand.com/resources/sap/ui/iot/controls/IoTChart.js

My Configuration in FLP:

/xs-app.json:

```<code>{
  "source": "^/resources/sap/ui/iot/(.*)$",
  "destination": "IOTAS_CONTROLS",
  "target": "/sap/ui/iot/$1"
}
</code>```

/mtad.yaml

```<code>modules:
    requires:
      - name: IOTAS_CONTROLS
        group: destinations
        properties:
        forwardAuthToken: true
        strictSSL: false
        name: IOTAS_CONTROLS
        url: ~{url}
resources:
  - name: IOTAS_CONTROLS
    properties:
    url: https://sapuiiot-sb.cfapps.sap.hana.ondemand.com
</code>```

/Main.view.xml

```<code>     <mvc:View
            controllerName="monitor.controller.Main"
            xmlns:iot="sap.ui.iot.controls"
            xmlns:iotele="sap.ui.iot.elements"
          xmlns:action="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
            displayBlock="false">
            <iot:IoTChart noOfHours="1" headerTitle="Temperature & Gas Volume" subheaderTitle="Unit: Degree & M3"/>
</code>```

I have tried to read "https://xxx-flp-sandbox.cfapps.sap.hana.ondemand.com/resources/sap/ui/iot/controls/IoTChart.js" in Controller.js, it is redirected to "https://sapuiiot-sb.cfapps.sap.hana.ondemand.com/sap/ui/iot/controls/IoTChart.js" successfully, which proved the route in xs-app.json worked.

So my question is, it seems if sap.ui.iot.controls is required in XML View, it will always called with domain: https://sapui5.hana.ondemand.com without pass route in xs-app.js.

This project is run successfully in webIDE, because in neo-app.json, it defined a route, which redirect all /resource/, request is always in webIDE host, but in cloud foundry, it is in sapui5.hana.ondemand host

Any Suggestion?

Tried:

```<code>jQuery.sap.registerResourcePath("iotChart", "../../../../resources/sap/ui/iot/library")
jQuery.sap.require("iotChart")

//Still load host sapui5.hana.ondemand.com
var core=sap.ui.getCore();
core.loadLibrary("sap.ui.iot.controls");
</code>```

答:
Solved by add one line in Component.js:

```<code>init : function() {
    jQuery.sap.registerModulePath("sap.ui.iot", "../../../../resources/sap/ui/iot");
}
</code>```

Besides, "sap.ui.iot" still cannot declared at rootView.view.xml, because by that time, path is not registered. But new sap.ui.controls.IoTChart() can be used in controller

Body:
As I deploy Monitor app as a SAPUI5 app in Fiori launchpad in Cloud Foundry, I encountered an error:

404 Not Found:
  https://sapui5.hana.ondemand.com/resources/sap/ui/iot/controls/IoTChart.js

My Configuration in FLP:

/xs-app.json:

{
  "source": "^/resources/sap/ui/iot/(.*)$",
  "destination": "IOTAS_CONTROLS",
  "target": "/sap/ui/iot/$1"
}

/mtad.yaml

modules:
    requires:
      - name: IOTAS_CONTROLS
        group: destinations
        properties:
        forwardAuthToken: true
        strictSSL: false
        name: IOTAS_CONTROLS
        url: ~{url}
resources:
  - name: IOTAS_CONTROLS
    properties:
    url: https://sapuiiot-sb.cfapps.sap.hana.ondemand.com

/Main.view.xml

     <mvc:View
            controllerName="monitor.controller.Main"
            xmlns:iot="sap.ui.iot.controls"
            xmlns:iotele="sap.ui.iot.elements"
          xmlns:action="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
            displayBlock="false">
            <iot:IoTChart noOfHours="1" headerTitle="Temperature & Gas Volume" subheaderTitle="Unit: Degree & M3"/>

I have tried to read "https://xxx-flp-sandbox.cfapps.sap.hana.ondemand.com/resources/sap/ui/iot/controls/IoTChart.js" in Controller.js, it is redirected to "https://sapuiiot-sb.cfapps.sap.hana.ondemand.com/sap/ui/iot/controls/IoTChart.js" successfully, which proved the route in xs-app.json worked.

So my question is, it seems if sap.ui.iot.controls is required in XML View, it will always called with domain: https://sapui5.hana.ondemand.com without pass route in xs-app.js.

This project is run successfully in webIDE, because in neo-app.json, it defined a route, which redirect all /resource/, request is always in webIDE host, but in cloud foundry, it is in sapui5.hana.ondemand host

Any Suggestion?

Tried:

jQuery.sap.registerResourcePath("iotChart", "../../../../resources/sap/ui/iot/library")
jQuery.sap.require("iotChart")

//Still load host sapui5.hana.ondemand.com
var core=sap.ui.getCore();
core.loadLibrary("sap.ui.iot.controls");

Body:
Solved by add one line in Component.js:

init : function() {
    jQuery.sap.registerModulePath("sap.ui.iot", "../../../../resources/sap/ui/iot");
}

Besides, "sap.ui.iot" still cannot declared at rootView.view.xml, because by that time, path is not registered. But new sap.ui.controls.IoTChart() can be used in controller


问:
How to extend a php class with more classes
I was wondering if it was a way to get what you would see as

```<code>class main_class extends main_class {...}
</code>```

But php was not happy. :(

So then I though to myself lets ask stackoverflow, I'm sure someone will know a solution.
Never the less several hours of debugging I self-solved my problem, with only a little code.

The problem was the fact of class some_class won't let you override an existing class so what I needed to do was use __get and __call and add another 2 lines into my __construct function.

So here is my solved-code:

```<code>class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
</code>```

Then simply run this to extend my main_class without overriding the original functions, so it has me run my new functions but if I need to I can get the original functions:

```<code>$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;
</code>```

Now lets load our class and run a function from our mod:

```<code>$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via My main_class but this is a mod that extended main_class without renaming it.");
</code>```

Okay well my mod was not for sending emails but instead redirects sub-domains to there aliased pathname, but you understand the concept shown here.

Edit: After I solved the issue I saw a comment saying a possible duplicate exists so I check it out and find out someone else has an extremely similar solution, but please don't mark it as a duplicate as he was asking about adding to a class that was already constructed, I want to override functions while constructing. My solution takes in an array of constructed classes and "merges" them into my main_class, This method does reserve the original functions but I can also call the original functions using another function to by-pass the __call function.

Thanks to anyone who posted answers.

答:
In C# you would do this by defining a partial class. It's basically like writing more of the same class in a different file. I'm not sure if PHP supports this, but this article may help?

http://www.toosweettobesour.com/2008/05/01/partial-classes-in-php/

Body:
I was wondering if it was a way to get what you would see as

class main_class extends main_class {...}

But php was not happy. :(

So then I though to myself lets ask stackoverflow, I'm sure someone will know a solution.
Never the less several hours of debugging I self-solved my problem, with only a little code.

The problem was the fact of class some_class won't let you override an existing class so what I needed to do was use __get and __call and add another 2 lines into my __construct function.

So here is my solved-code:

class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}

Then simply run this to extend my main_class without overriding the original functions, so it has me run my new functions but if I need to I can get the original functions:

$MODS_ENABLED=array();
class mod_mail {...}
$MODS_ENABLED[]=new mod_mail;

Now lets load our class and run a function from our mod:

$obj = new main_class(...);
$obj -> mail("root@localhost", "me@me.me", "Testing a mod.", "This email was sent via My main_class but this is a mod that extended main_class without renaming it.");

Okay well my mod was not for sending emails but instead redirects sub-domains to there aliased pathname, but you understand the concept shown here.

Edit: After I solved the issue I saw a comment saying a possible duplicate exists so I check it out and find out someone else has an extremely similar solution, but please don't mark it as a duplicate as he was asking about adding to a class that was already constructed, I want to override functions while constructing. My solution takes in an array of constructed classes and "merges" them into my main_class, This method does reserve the original functions but I can also call the original functions using another function to by-pass the __call function.

Thanks to anyone who posted answers.


问:
using <![CDATA in xml response
I have looked for an answer to this question but I have been unable to find an answer that works for my application.

I need to give a response from a sql query in xml format but the response is a url so i will need to use cdata. Here is my code.

```<code>if ($_POST['action']=="getSermon")
{
    //echo"You got it";
    $SQL = "SELECT * FROM sermons";

    $allsermon = mysql_query($SQL);
    $sermonrow = mysql_fetch_assoc($allsermon);

    header('Content-type: text/xml; charset=utf-8');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    echo $xml;
    echo "<SERMON_INFO>";
    do {
        echo "<SERMON>";
        echo "<ID>" . $sermonrow['id'] . "</ID>";
        echo "<NAME>" . $sermonrow['Name'] . "</NAME>";
        echo "<URL>".<![CDATA[$sermonrow['url']]>."</NAME>";
        //echo "<URL>". $sermonrow['url'] . "</URL>";
        echo "</SERMON>";
        mysql_free_result($result);
    } while ($sermonrow = mysql_fetch_assoc($allsermon));
    mysql_free_result($allsermon);
    echo "</SERMON_INFO>";
    mysql_close($db);

}
</code>```

when i do this i get an error 500 and the page will not load.

答:
The correct syntax is

```<code>echo "<URL><![CDATA[".$sermonrow['url']."]]></URL>";
</code>```

But I'd rather you use an XML library like  DOMDocument or SimpleXML to build your document, more complex, but you'll be less prone to simple errors like mixing up a closing tag name (see </NAME>).

ContentLicense: CC BY-SA 4.0

Title: using <![CDATA in xml response

Body:
I have looked for an answer to this question but I have been unable to find an answer that works for my application.

I need to give a response from a sql query in xml format but the response is a url so i will need to use cdata. Here is my code.

if ($_POST['action']=="getSermon")
{
    //echo"You got it";
    $SQL = "SELECT * FROM sermons";

    $allsermon = mysql_query($SQL);
    $sermonrow = mysql_fetch_assoc($allsermon);

    header('Content-type: text/xml; charset=utf-8');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    echo $xml;
    echo "<SERMON_INFO>";
    do {
        echo "<SERMON>";
        echo "<ID>" . $sermonrow['id'] . "</ID>";
        echo "<NAME>" . $sermonrow['Name'] . "</NAME>";
        echo "<URL>".<![CDATA[$sermonrow['url']]>."</NAME>";
        //echo "<URL>". $sermonrow['url'] . "</URL>";
        echo "</SERMON>";
        mysql_free_result($result);
    } while ($sermonrow = mysql_fetch_assoc($allsermon));
    mysql_free_result($allsermon);
    echo "</SERMON_INFO>";
    mysql_close($db);

}

when i do this i get an error 500 and the page will not load.

Body:
The correct syntax is

echo "<URL><![CDATA[".$sermonrow['url']."]]></URL>";

But I'd rather you use an XML library like  DOMDocument or SimpleXML to build your document, more complex, but you'll be less prone to simple errors like mixing up a closing tag name (see </NAME>).


答:
By creating a big array up front, then using Array.Copy, we can achieve very reasonable speeds for concatenating, even with a very large number of arrays:

```<code>public static T[] ConcatArrays<T>(params T[][] p)
{
    var position = 0;
    var outputArray = new T[p.Sum(a => a.Length)];
    foreach (var curr in p)
    {
        Array.Copy(curr, 0, outputArray, position, curr.Length);
        position += curr.Length;
    }
    return outputArray;
}
</code>```

So, now we can either:

```<code>string bigArray = ConcatArrays(arrayOne, arrayTwo, arrayThree)
</code>```

or

```<code>string[][] arrays = new[]{arrayOne, arrayTwo, arrayThree};
string bigArray = ConcatArrays(arrays);
</code>```

Title: c# A better way to Copy/Merge multiple arrays into one array

Body:
By creating a big array up front, then using Array.Copy, we can achieve very reasonable speeds for concatenating, even with a very large number of arrays:

public static T[] ConcatArrays<T>(params T[][] p)
{
    var position = 0;
    var outputArray = new T[p.Sum(a => a.Length)];
    foreach (var curr in p)
    {
        Array.Copy(curr, 0, outputArray, position, curr.Length);
        position += curr.Length;
    }
    return outputArray;
}

So, now we can either:

string bigArray = ConcatArrays(arrayOne, arrayTwo, arrayThree)

or

string[][] arrays = new[]{arrayOne, arrayTwo, arrayThree};
string bigArray = ConcatArrays(arrays);


问:
Use NumberFormat.getCurrency in Kotlin Android
I need call this

```<code>{private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();}
</code>```

in Android Application, but I using Kotlin and I don't know how to do that in Kotlin. How can I do this in Kotlin?

答:
use as follows: </p>

```<code>private val currencyFormat = NumberFormat.getCurrencyInstance()
</code>```

Body:
I need call this

{private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();}

in Android Application, but I using Kotlin and I don't know how to do that in Kotlin. How can I do this in Kotlin?

Body:
use as follows:

private val currencyFormat = NumberFormat.getCurrencyInstance()


问:
Dynamic allocation array difference in C++
Today I came across a new type of allocation in cpp which I never heard of any I tried to search google but didn't find any related answer.

```<code>long int *a=new long int[N+1]();
</code>```

I know long int *a = new long int[N+1];

But what is the difference between the two above?

答:
```<code>long int *a = new long int[N+1]();
                               ^^
</code>```

Allocate memory, and initialize them to the default state of the type (for built-in types, zero). It's the standard way to initialize objects allocated by new so they do not contain indeterminate values (no UB, though). In C++11, you can also use curly brackets:

```<code>long int *a = new long int[N+1]{};
                               ^^
</code>```

Body:
Today I came across a new type of allocation in cpp which I never heard of any I tried to search google but didn't find any related answer.

long int *a=new long int[N+1]();

I know long int *a = new long int[N+1];

But what is the difference between the two above?

Body:
long int *a = new long int[N+1]();
                               ^^

Allocate memory, and initialize them to the default state of the type (for built-in types, zero). It's the standard way to initialize objects allocated by new so they do not contain indeterminate values (no UB, though). In C++11, you can also use curly brackets:

long int *a = new long int[N+1]{};
                               ^^


答:
You can use anchor tags in HTML to do this.

```<code><a href = " "> </a>
</code>```

As HTML convention, while defining a section, you can give each section an ID for identifiers :

```<code><section id= "id1" ></section>
</code>```

And you can redirect to the section by just mentioning them in the anchor tags :

```<code><a href = "#id1"> </a>
</code>```

https://jsfiddle.net/ybhh3jpx/

Title: How do I make it so that when I click on a button in Html How do I make it so the web page redirects itself to the place its supposed to go

Body:
 <!DOCTYPE html>

    <title>______</title>
    <button class="btn about">About</button>
    <button class="btn socialmedia">Social Media</button></button>
    <button class="btn profile">Profile</button>
    <button class="btn contact">Contact</button>
    <button class="btn homepage">Homepage</button>

I want it to be that when they click on contact it brings them to a page that I make that has all the contact info on it.  Please explain in the simplist way possible.

Body:
You can use anchor tags in HTML to do this.

<a href = " "> </a>

As HTML convention, while defining a section, you can give each section an ID for identifiers :

<section id= "id1" ></section>

And you can redirect to the section by just mentioning them in the anchor tags :

<a href = "#id1"> </a>

https://jsfiddle.net/ybhh3jpx/


问:
How to randomly select values for a list?
I'm using Python 2.7

To be clear, I don't want to randomize the items in the list. I want to make it so it's possible for certain strings not to show up at all. For example:

```<code>    r = "red"
    b = "blue"
    y = "yellow"
    rc = random colour
    myColours = [rc,rc,rc]
    print myColours
</code>```

Obviously the code above wouldn't work, but I'm not sure how to proceed. It would also help if I could change how likely a certain string would be selected, like 50% odds of red, 30% odds of blue, and 20% odds of yellow.

答:
Although it will not help the OP using Python 2.7, for those using Python 3.6, random.choices is simple, includes weights and is part of the standard library.

Return a k sized list of elements chosen from the population with replacement.

Given

```<code>import random

r = "red"
b = "blue"
y = "yellow"

iterable = r, b, y
size = 3
wts = [.5, .3, .2]
</code>```

Code

```<code>random.choices(iterable, k=size)
# ['red', 'yellow', 'yellow']

random.choices(iterable, weights=wts, k=size)
# ['red', 'red', 'red']
</code>```

Body:
I'm using Python 2.7

To be clear, I don't want to randomize the items in the list. I want to make it so it's possible for certain strings not to show up at all. For example:

    r = "red"
    b = "blue"
    y = "yellow"
    rc = random colour
    myColours = [rc,rc,rc]
    print myColours

Obviously the code above wouldn't work, but I'm not sure how to proceed. It would also help if I could change how likely a certain string would be selected, like 50% odds of red, 30% odds of blue, and 20% odds of yellow.

Body:
Although it will not help the OP using Python 2.7, for those using Python 3.6, random.choices is simple, includes weights and is part of the standard library.

Return a k sized list of elements chosen from the population with replacement.

Given

import random

r = "red"
b = "blue"
y = "yellow"

iterable = r, b, y
size = 3
wts = [.5, .3, .2]

Code

random.choices(iterable, k=size)
# ['red', 'yellow', 'yellow']

random.choices(iterable, weights=wts, k=size)
# ['red', 'red', 'red']


问:
How to avoid "SQL Server automatically uses the new inserted value as the current identity value."
I'm using SQL Server 2008

as per microsoft, http://msdn.microsoft.com/en-us/library/ms188059.aspx

when I execute the following

```<code>set identity_insert on
//insert statements here
set identity_insert off
</code>```

the identity of the column is set to the maximum value. Can I avoid this?

Consider the following scenario,

my table has 2 rows as follows

```<code>id, name  comm
1,  John, 232.43
2,  Alex, 353.52
</code>```

now using the above code, when I insert

```<code>10, Smith, 334.23
</code>```

as per the above link, SQL Server automatically sets the identity to 10. So for newly inserted records (without using identity_insert on), id automatically starts with 11.

I want the identity value to be 3, after using identity_insert on/off

please help.

答: Another way to get around the "planted bug" dilemma is to create your own identity generator procedure and tracking table. The table includes a tablename and value that the next ID should be. This way you can reset it any value at any time. The procedure would include logic to check to see if the next generated key exists and if it does exist it will increment the key till it finds an ID that does not exist in the table and pass that back out to you. This would have to be implemented on all inserts to work correctly. Which is possible with a trigger. The downside is more processing overhead than using a negative number like Damien_The_Unbeliever suggests.</p>

Body:
I'm using SQL Server 2008

as per microsoft, http://msdn.microsoft.com/en-us/library/ms188059.aspx

when I execute the following

set identity_insert on
//insert statements here
set identity_insert off

the identity of the column is set to the maximum value. Can I avoid this?

Consider the following scenario,

my table has 2 rows as follows

id, name  comm
1,  John, 232.43
2,  Alex, 353.52

now using the above code, when I insert

10, Smith, 334.23

as per the above link, SQL Server automatically sets the identity to 10. So for newly inserted records (without using identity_insert on), id automatically starts with 11.

I want the identity value to be 3, after using identity_insert on/off

please help.


问:
linear regression lines cannot show on time series plot in r
I am new in plotting time series. I downloaded a time series data and calculated a linear equation and I would like to add it in the time series plot. I want to show the year in the plot so I used index(stk) as x-axis input.

code:

```<code>library(quantmod)

stk <- suppressWarnings(getSymbols("AAPL", auto.assign = FALSE,
                                   src = "yahoo", periodicity = "daily"))
stk <- na.omit(stk)

stk.lm1 <- lm(log(Cl(stk)) ~ c(1:nrow(stk)), data = stk)
plot(index(stk), log(Cl(stk)), type = "l", lwd = 3, las = 1)
abline(coefficients(stk.lm1)[1], coefficients(stk.lm1)[2], col="blue")
</code>```

I know it is the plot using index(stk), how can I do to keep the x axis of plot in date and can I use plot.xts or other like ggplot2 to do the same things? Please advise, thank you very much.

答:
It isn't dificult to do the plot that you want in base r plot or ggplot2 here is what you what:

```<code>plot(index(stk), log(Cl(stk)), type="l", lwd=3, las=1)
lines(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values,col = "blue")
</code>```

for the base r plot I added a line with the fitted values of the linear regression that I extracted with the $ signed and the dates of theme. Take into account that lm respect the structure of the data so the results are xts

```<code>library(ggplot2)
ggplot(stk, aes(x = index(stk), y = as.numeric(log(Cl(stk)))))+geom_line(lwd=1)+
  geom_line(aes(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values),col = "blue")+
  labs(x = "Date", y = "Log Price")
</code>```

For ggplot2 is quite similar. First you have to initiate the plot with ggplot where you defined the data and aesthetics (aes), then you add a line with geom_line and for the extra line I used the this command and define the new line in a new aes the same way I did it with the base r function.

Body:
I am new in plotting time series. I downloaded a time series data and calculated a linear equation and I would like to add it in the time series plot. I want to show the year in the plot so I used index(stk) as x-axis input.

code:

library(quantmod)

stk <- suppressWarnings(getSymbols("AAPL", auto.assign = FALSE,
                                   src = "yahoo", periodicity = "daily"))
stk <- na.omit(stk)

stk.lm1 <- lm(log(Cl(stk)) ~ c(1:nrow(stk)), data = stk)
plot(index(stk), log(Cl(stk)), type = "l", lwd = 3, las = 1)
abline(coefficients(stk.lm1)[1], coefficients(stk.lm1)[2], col="blue")

I know it is the plot using index(stk), how can I do to keep the x axis of plot in date and can I use plot.xts or other like ggplot2 to do the same things? Please advise, thank you very much.

Body:
It isn't dificult to do the plot that you want in base r plot or ggplot2 here is what you what:

plot(index(stk), log(Cl(stk)), type="l", lwd=3, las=1)
lines(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values,col = "blue")

for the base r plot I added a line with the fitted values of the linear regression that I extracted with the $ signed and the dates of theme. Take into account that lm respect the structure of the data so the results are xts

library(ggplot2)
ggplot(stk, aes(x = index(stk), y = as.numeric(log(Cl(stk)))))+geom_line(lwd=1)+
  geom_line(aes(x = index(stk.lm1$fitted.values), y = stk.lm1$fitted.values),col = "blue")+
  labs(x = "Date", y = "Log Price")

For ggplot2 is quite similar. First you have to initiate the plot with ggplot where you defined the data and aesthetics (aes), then you add a line with geom_line and for the extra line I used the this command and define the new line in a new aes the same way I did it with the base r function.


问:
I need help understanding this iteration of two, two tuples in Python3
I need help trying to understand why this function returns forenames surnames instead of names. It's the first for loop that's got me confused I believe. For some background, the paths in the first for loop are just text files that list different names, one per line. Why are we returning forenames and surnames when each name from the files are being appended into the names variable? Please help, and let me know if more information is needed.

```<code>import random

def get_forenames_and_surnames():
    forenames = []
    surnames = []
    for names, filename in ((forenames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/forenames.txt"),
                        (surnames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/surnames.txt")):
        with open(filename, encoding="utf8") as file:
            for name in file:
                names.append(name.rstrip())
    return forenames, surnames

forenames, surnames = get_forenames_and_surnames()
with open("test-names1.txt", "w", encoding="utf8") as file:
    for i in range(100):
        line = "{0} {1}\n".format(random.choice(forenames),
                                  random.choice(surnames))
        file.write(line)
</code>```

The file for with list of forenames looks like:

```<code>Ailish
Cayden
Cohen
Maison
Becky
Dodou
Nickie
Zachary
Climate
</code>```

The file with a list of surnames is the same but with different names.

答:
understand why this function returns forenames surnames instead of names

Well... return forenames, surnames is why it does. And the formatting at the bottom requires two separate lists. (And return names would actually return surnames)

The loop is doing tuple-unpacking. Each iteration, you unpack one tuple and assign names, filename. Since the names is a list reference, names.append() will operate the same as forenames.append(), or surnames.append() depending on the iteration.

FWIW, you could rewrite the first function to use two explicit loops per file.

```<code>def get_forenames_and_surnames():
    forenames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/forenames.txt", encoding="utf8")]
    surnames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/surnames.txt", encoding="utf8")]
    return forenames, surnames
</code>```

If you wanted to use one list, take a look at the zip() function.

Body:
I need help trying to understand why this function returns forenames surnames instead of names. It's the first for loop that's got me confused I believe. For some background, the paths in the first for loop are just text files that list different names, one per line. Why are we returning forenames and surnames when each name from the files are being appended into the names variable? Please help, and let me know if more information is needed.

import random

def get_forenames_and_surnames():
    forenames = []
    surnames = []
    for names, filename in ((forenames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/forenames.txt"),
                        (surnames, "/home/mmelv/eclipse-
                                workspace/py30eg/data/surnames.txt")):
        with open(filename, encoding="utf8") as file:
            for name in file:
                names.append(name.rstrip())
    return forenames, surnames

forenames, surnames = get_forenames_and_surnames()
with open("test-names1.txt", "w", encoding="utf8") as file:
    for i in range(100):
        line = "{0} {1}\n".format(random.choice(forenames),
                                  random.choice(surnames))
        file.write(line)

The file for with list of forenames looks like:

Ailish
Cayden
Cohen
Maison
Becky
Dodou
Nickie
Zachary
Climate

The file with a list of surnames is the same but with different names.

Body:
understand why this function returns forenames surnames instead of names

Well... return forenames, surnames is why it does. And the formatting at the bottom requires two separate lists. (And return names would actually return surnames)

The loop is doing tuple-unpacking. Each iteration, you unpack one tuple and assign names, filename. Since the names is a list reference, names.append() will operate the same as forenames.append(), or surnames.append() depending on the iteration.

FWIW, you could rewrite the first function to use two explicit loops per file.

def get_forenames_and_surnames():
    forenames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/forenames.txt", encoding="utf8")]
    surnames = [line.rstrip() for line in open("/home/mmelv/eclipse-workspace/py30eg/data/surnames.txt", encoding="utf8")]
    return forenames, surnames

If you wanted to use one list, take a look at the zip() function.


答: Do you have to use arrays? Use lists and AddRange(). If you need to have an array eventually then just call ToArray() in the end.</p>

Body:
Would anyone be able to advise if there's a better way to copy multiple arrays into a single array? The resulting array must have the elements in the same order such as arrayOne values first then arraySecond values next etc.

Following is a mockup of what I'm currently executing which working as expected. Looking for a smarter way of doing this.

// Initialise the first array.
string[] arrayOne = new string[5];
arrayOne[0] = "arrayOneValue[0]";
arrayOne[1] = "arrayOneValue[1]";
arrayOne[2] = "arrayOneValue[2]";
arrayOne[3] = "arrayOneValue[3]";
arrayOne[4] = "arrayOneValue[4]";

// Initialise the second array.
string[] arrayTwo = new string[6];
arrayTwo[0] = "arrayTwoValue[0]";
arrayTwo[1] = "arrayTwoValue[1]";
arrayTwo[2] = "arrayTwoValue[2]";
arrayTwo[3] = "arrayTwoValue[3]";
arrayTwo[4] = "arrayTwoValue[4]";
arrayTwo[5] = "arrayTwoValue[5]";

// Initialise the third array.
string[] arrayThree = new string[3];
arrayThree[0] = "arrayThreeValue[0]";
arrayThree[1] = "arrayThreeValue[1]";
arrayThree[2] = "arrayThreeValue[2]";

// string[] arrayN = new string[n]
//.
//.
//.

// Initialise the target array.
string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length];
// ArrayN - string[] finalArray = new string[arrayOne.Length + arrayTwo.Length + arrayThree.Length + arrayN.Length];

// Copy/merge the three arrays into the target array.
Array.Copy(arrayOne, 0, finalArray, 0, arrayOne.Length);
Array.Copy(arrayTwo, 0, finalArray, arrayOne.Length, arrayTwo.Length);
Array.Copy(arrayThree, 0, finalArray, (arrayOne.Length + arrayTwo.Length), arrayThree.Length);
//.
//.
//.
//.
// ArrayN - Array.Copy(arrayN, 0, finalArray, (arrayOne.Length + arrayTwo.Length + arrayN), arrayN.Length) ?;

As you can see for arrayN the code can get longer. I have a maximum of 5 arrays I'm trying to copy into one array, therefore, it's manageable. I'm using this technique as part of a WebAPI where a collection of oracle parameter objects are consolidated based on business rules to be passed to several Oracle stored procedures. Any advise here is appreciated. Thanks in advance.
Result

Console output
/*--- Destination array -
arrayOneValue[0]
arrayOneValue[1]
arrayOneValue[2]
arrayOneValue[3]
arrayOneValue[4]
arrayTwoValue[0]
arrayTwoValue[1]
arrayTwoValue[2]
arrayTwoValue[3]
arrayTwoValue[4]
arrayTwoValue[5]
arrayThreeValue[0]
arrayThreeValue[1]
arrayThreeValue[2]*/


问:
Azure AD B2C - Using ADFS as an Identity Provider
The client we are attempting to integrate with has ADFS as their IDP. The customer is trying to use Azure AD B2C as their IDP.

The error is that Azure AD B2C tries to connect to their SAML endpoint directly which is not open to the public, so it fails.

Is there a way to upload their Federation.xml file into Azure AD B2C so that it doesn't try to connect to the URL?

答:
You can embed a SAML IDP's metadata in the custom policy directly by setting the the value of the PartnerEntity item within the ClaimProvider's Metadata to have a <![CDATA element.

<ClaimsProvider>
  <Domain>mysamlidp</Domain>
  <DisplayName>My SAML IdP</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="MySamlIdP">
      <DisplayName>My SAML IdP</DisplayName>
      <Description></Description>
      <Protocol Name="SAML2" />
      <Metadata>
        <Item Key="RequestsSigned">false</Item>
        <Item Key="WantsEncryptedAssertions">false</Item>
        <Item Key="PartnerEntity"><![CDATA[

<EntityDescriptor Id="..."></EntityDescriptor>

                    ]]></Item>
      </Metadata>
      <CryptographicKeys>

```

Body:
You can embed a SAML IDP's metadata in the custom policy directly by setting the the value of the PartnerEntity item within the ClaimProvider's Metadata to have a <![CDATA element.

<ClaimsProvider>
  <Domain>mysamlidp</Domain>
  <DisplayName>My SAML IdP</DisplayName>
  <TechnicalProfiles>
    <TechnicalProfile Id="MySamlIdP">
      <DisplayName>My SAML IdP</DisplayName>
      <Description></Description>
      <Protocol Name="SAML2" />
      <Metadata>
        <Item Key="RequestsSigned">false</Item>
        <Item Key="WantsEncryptedAssertions">false</Item>
        <Item Key="PartnerEntity"><![CDATA[
<!-- REPLACE THIS WITH YOUR METADATA XML -->
<EntityDescriptor Id="..."><!-- ... --></EntityDescriptor>
<!-- REPLACE THIS WITH YOUR METADATA XML -->
                    ]]></Item>
      </Metadata>
      <CryptographicKeys>
      <!-- ... etc ... -->


问:
Local repository directories disappeared?
I'm pretty new to Git, and recently started to use branches, but I don't think I have the concepts down, and now I'm running into problems.

Basically, I created a devel branch, and am creating feature branches to merge small changes into devel. I deleted some files in the feature branches, and thus in devel, but now I realized I want them again. They presumably are still in master, as I can see them online on GitHub, but when I ran the command "git checkout master", many directories and files have disappeared. I really have no clue why this has happened. How do I fix the problem?

EDIT: Is it possible for changes in other branches to cause problems when I switch back to the master branch? I feel like the master branch should have remained the same as before.

EDIT 2: It looks like the deletions happened when I was working on a feature branch and did "git checkout devel" - I was in a deep subdirectory when I ran this command, and for whatever reason there were a bunch of "D ... file" lines outputted, ending with "Switched to branch 'devel'" In fact, this continues to happen as I switch between branches.

答:
If you want to reset.

You can see all of your commits and from there you can know your last good commit where everything was ok, by invoking the command

```<code>git log
</code>```

After that you can reset to your known good commit by invoking

```<code>git reset --hard commit_number
</code>```

But be careful it will remove all current files created after that commit.

Body:
If you want to reset.

You can see all of your commits and from there you can know your last good commit where everything was ok, by invoking the command

git log

After that you can reset to your known good commit by invoking

git reset --hard commit_number

But be careful it will remove all current files created after that commit.


问:
Reference variable with new name in same function
Is it possible to reference an existing variable using a different name to identify it.  The reason I would like to do this is to clean up my code...

Example

Currently I have to do something like the example below...

```<code>private void Main()
{
    MyComplexObjectClass myComplicatedObject = new MyComplexObjectClass();
    myComplicatedObject.subobj.subobj2.subobj3 = "test start";

    TestFunction(ref myComplicatedObject);
}

private void TestFunction(ref myComplicatedObject)
{
    myComplicatedObject.subobj.subobj2.subobj3 = "test 1";
    //tons more code
    myComplicatedObject.subobj.subobj2.subobj3 = "test 2";
    //tons more code
    myComplicatedObject.subobj.subobj2.subobj3 = "test 3";
}
</code>```

I would much rather make it more clean like the example below.  The issue is when I do this then come out of the function the referenced myComplicatedObject does not have a subobj3 set to "test 3" it's "test start" instead (the starting value).  I'm sure this is because the object I'm creating subobj3 is a NEW object and not one that references the existing one.  How can I make it work?

```<code>private void TestFunction(ref myComplicatedObject)
{
    MySubObjectClass subobj3 = myComplicatedObject.subobj.subobj2.subobj3;
    subobj3 = "test 1";
    subobj3 = "test 2";
    subobj3 = "test 3";
}
</code>```

答:
Yes, you can do this if the thing you're assigning to the temp variable is a reference type (an instance of a class, not a struct or a primitive).

The key is that in order for it to work, you still have to be assigning to a property on the new variable, so the piece you "break off" to store in a variable needs to come from one level higher up (subobj2).

If you assign directly to the new variable (like you're doing in the second code snippet in your question), you will just be overwriting the variable within your method and nowhere else.

Try this:

```<code>private void TestFunction(ref myComplicatedObject)
{
    MySubObjectClass subobj2 = myComplicatedObject.subobj.subobj2;
    subobj2.subobj3 = "test 1";
    subobj2.subobj3 = "test 2";
    subobj2.subobj3 = "test 3";
}
</code>```

FYI there's no need for myComplicatedObject to be a ref parameter here. You should remove the ref.

Body:
Is it possible to reference an existing variable using a different name to identify it.  The reason I would like to do this is to clean up my code...

Example

Currently I have to do something like the example below...

private void Main()
{
    MyComplexObjectClass myComplicatedObject = new MyComplexObjectClass();
    myComplicatedObject.subobj.subobj2.subobj3 = "test start";

    TestFunction(ref myComplicatedObject);
}

private void TestFunction(ref myComplicatedObject)
{
    myComplicatedObject.subobj.subobj2.subobj3 = "test 1";
    //tons more code
    myComplicatedObject.subobj.subobj2.subobj3 = "test 2";
    //tons more code
    myComplicatedObject.subobj.subobj2.subobj3 = "test 3";
}

I would much rather make it more clean like the example below.  The issue is when I do this then come out of the function the referenced myComplicatedObject does not have a subobj3 set to "test 3" it's "test start" instead (the starting value).  I'm sure this is because the object I'm creating subobj3 is a NEW object and not one that references the existing one.  How can I make it work?

private void TestFunction(ref myComplicatedObject)
{
    MySubObjectClass subobj3 = myComplicatedObject.subobj.subobj2.subobj3;
    subobj3 = "test 1";
    subobj3 = "test 2";
    subobj3 = "test 3";
}

Body:
Yes, you can do this if the thing you're assigning to the temp variable is a reference type (an instance of a class, not a struct or a primitive).

The key is that in order for it to work, you still have to be assigning to a property on the new variable, so the piece you "break off" to store in a variable needs to come from one level higher up (subobj2).

If you assign directly to the new variable (like you're doing in the second code snippet in your question), you will just be overwriting the variable within your method and nowhere else.

Try this:

private void TestFunction(ref myComplicatedObject)
{
    MySubObjectClass subobj2 = myComplicatedObject.subobj.subobj2;
    subobj2.subobj3 = "test 1";
    subobj2.subobj3 = "test 2";
    subobj2.subobj3 = "test 3";
}

FYI there's no need for myComplicatedObject to be a ref parameter here. You should remove the ref.


问:
Time complexity of %in% in R; is there a way to make it O(1) like with sets in Python?
The %in% operator in R checks if something is in something else, kind of obviously.  But I'm curious about the performance.  In Python, searching for an item a set or dict keys is O(1) because the set is hash table, I think.  But searching for an item in a list in Python could be O(n) with an n-length list, because it will search element-by-element.  So how is %in% working behind the scenes for different datatypes in R?  It seems to take 5 times longer to search for something in a factor dtype in R as opposed to a vector, but it seems like %in% searches a vector linearly.  At first I thought a factor datatype might be like a set in Python, since they both reduce something to it's unique values, but not at all: https://www.tutorialspoint.com/r/r_data_types.htm.  Here is some example code so you can see what I mean with the runtimes:

```<code>library(microbenchmark)
s <- seq(5000)
microbenchmark(1 %in% s, times = 100000)
# searching for a term further in the list takes longer
microbenchmark(4999 %in% s, times = 100000)
s <- as.factor(s)
# searching for something in a factor takes way longer than a vector
# I think because everything is converted to a character dtype
microbenchmark(4999 %in% s, times = 100000)
</code>```

My main question is this: is there a way to make %in% O(1) in R?  A related question: is there an equivalent (in R) of the set() datatype in Python?

答:
As we discussed in the comments, there is an inherent set-like mechanism in R, though it is admittedly a little hackish and perhaps not quite what was intended. (Some of the limitations of this hack are documented in the hashmap package.)

Environments in R are internally hashed. This can be used for storage of arbitary objects with random access (both read and write). To check some benchmarks, I'll generate a few types of vectors to substantiate your initial concern and show the improvement using environments can make.

We'll first generate some similar data, ordered in various fashions to highlight an issue you brought up:

```<code>library(microbenchmark)
set.seed(2)
s1 <- seq(5000)
s2 <- rev(s1) # to highlight the bias you highlighted, since the vector is sorted
s3 <- sample(s1) # to shake things up a little
s4 <- as.character(s3) # comparison with character-based named in 'l' and 'e'

l <- list()
e <- new.env(parent = emptyenv())
for (i in s4) {
  assign(i, TRUE, envir = e)
  l[[i]] <- TRUE
}
head(names(l)) # unordered
# [1] "925"  "3512" "2866" "840"  "4716" "4713"
</code>```

The list does have ordinality within its objects, which supports the assumption that its objects are not hashed:

```<code>which(names(l) == "1")
# [1] 2291
</code>```

Environments do not have this:

```<code>e[[1]]
# Error in e[[1]] : wrong arguments for subsetting an environment
</code>```

Some quick membership testing: I used a logical for the value, though that is completely arbitary. Anything other than NULL would suffice for our needs here. We'll use a simple !is.null(e[[...]]) to test for specific membership:

```<code>!is.null(e[["1"]])
# [1] TRUE
!is.null(e[["10000"]])
# [1] FALSE
!is.null(l[["1"]])
# [1] TRUE
!is.null(l[["10000"]])
# [1] FALSE

microbenchmark(
  vec1 =  1  %in% s1,
  vec2 =  1  %in% s2,
  vec3 =  1  %in% s3,
  vec4 = "1" %in% s4,
  lst = is.null(l[["1"]]),
  env = is.null(e[["1"]]),
  times = 1000
)
# Warning in microbenchmark(vec1 = 1 %in% s1, vec2 = 1 %in% s2, vec3 = 1 %in%  :
#   Could not measure a positive execution time for 6 evaluations.
# Unit: nanoseconds
#  expr   min    lq     mean median    uq     max neval
#  vec1  5835  6929 12493.25   7294  9482 3214588  1000
#  vec2  9117  9847 16660.73  10212 12764 4081050  1000
#  vec3  7294  8388 19983.63   8752 10576 3274759  1000
#  vec4 11670 12400 15423.03  12764 14223   74394  1000
#   lst 20787 21517 24561.72  21881 22975  143317  1000
#   env     0     1   461.25    365   366   18235  1000
</code>```

Not surprisingly, the list does not perform well, though it seems to do better than the vectors (in the max case, relatively meaningless). Also not surprisingly, based on our claim that the environment uses an internal has, it performs quite well. Is it O(1)?

```<code>microbenchmark(
     samp5 = sapply(as.character(sample(5000, size =    5)), function(a) is.null(e[[a]])),
    samp50 = sapply(as.character(sample(5000, size =   50)), function(a) is.null(e[[a]])),
   samp500 = sapply(as.character(sample(5000, size =  500)), function(a) is.null(e[[a]])),
  samp5000 = sapply(as.character(sample(5000, size = 5000)), function(a) is.null(e[[a]]))
)
# Unit: microseconds
#      expr      min         lq        mean     median         uq       max neval
#     samp5   25.893    32.4565    49.58154    40.4795    58.3485   169.573   100
#    samp50  108.309   119.4310   156.45244   135.8410   167.3850   681.938   100
#   samp500  935.750  1023.2715  1265.29732  1073.9610  1172.6055  6841.985   100
#  samp5000 9410.008 10337.5520 11137.82968 10650.0765 11280.0485 15455.548   100
</code>```

The first one, samp5, appears to take a bit longer. This isn't too surprising, since there is overhead associated with sapply, sampling, and other things. However, the remaining rows seem to scale somewhat well with the numbers of samples done. This suggests it is indeed O(1) for some basic set operations.

NB: I had to use the whole sapply(...) trick because, unlike vectors and lists, R's environments do not allow subsetting with a vector.

```<code>e[[c("1")]]
# [1] TRUE
e[[c("1","10")]]
# Error in e[[c("1", "10")]] :
#   wrong arguments for subsetting an environment
</code>```

This is one of the claims made by (and fixed by) hashmap.

Extra credit: in order to facilitate using an environment as a set, you could use simple adders and deleters:

```<code>newset <- function() new.env(parent = emptyenv())
setadd <- function(set, n) set[[n]] <- TRUE
setdel <- function(set, n) set[[n]] <- NULL
setcontains <- function(set, n) !is.null(set[[n]])
setmembers <- function(set) names(set)

e <- newset()
setcontains(e, "a")
# [1] FALSE
setadd(e, "a")
setcontains(e, "a")
# [1] TRUE
setmembers(e)
# [1] "a"
setdel(e, "a")
setcontains(e, "a")
# [1] FALSE
</code>```

(There is a similar but much more extensive blog post on this by Jeffrey Horner here: http://jeffreyhorner.tumblr.com/post/114524915928/hash-table-performance-in-r-part-i.)

Body:
The %in% operator in R checks if something is in something else, kind of obviously.  But I'm curious about the performance.  In Python, searching for an item a set or dict keys is O(1) because the set is hash table, I think.  But searching for an item in a list in Python could be O(n) with an n-length list, because it will search element-by-element.  So how is %in% working behind the scenes for different datatypes in R?  It seems to take 5 times longer to search for something in a factor dtype in R as opposed to a vector, but it seems like %in% searches a vector linearly.  At first I thought a factor datatype might be like a set in Python, since they both reduce something to it's unique values, but not at all: https://www.tutorialspoint.com/r/r_data_types.htm.  Here is some example code so you can see what I mean with the runtimes:

library(microbenchmark)
s <- seq(5000)
microbenchmark(1 %in% s, times = 100000)
# searching for a term further in the list takes longer
microbenchmark(4999 %in% s, times = 100000)
s <- as.factor(s)
# searching for something in a factor takes way longer than a vector
# I think because everything is converted to a character dtype
microbenchmark(4999 %in% s, times = 100000)

My main question is this: is there a way to make %in% O(1) in R?  A related question: is there an equivalent (in R) of the set() datatype in Python?

Body:
As we discussed in the comments, there is an inherent set-like mechanism in R, though it is admittedly a little hackish and perhaps not quite what was intended. (Some of the limitations of this hack are documented in the hashmap package.)

Environments in R are internally hashed. This can be used for storage of arbitary objects with random access (both read and write). To check some benchmarks, I'll generate a few types of vectors to substantiate your initial concern and show the improvement using environments can make.

We'll first generate some similar data, ordered in various fashions to highlight an issue you brought up:

library(microbenchmark)
set.seed(2)
s1 <- seq(5000)
s2 <- rev(s1) # to highlight the bias you highlighted, since the vector is sorted
s3 <- sample(s1) # to shake things up a little
s4 <- as.character(s3) # comparison with character-based named in 'l' and 'e'

l <- list()
e <- new.env(parent = emptyenv())
for (i in s4) {
  assign(i, TRUE, envir = e)
  l[[i]] <- TRUE
}
head(names(l)) # unordered
# [1] "925"  "3512" "2866" "840"  "4716" "4713"

The list does have ordinality within its objects, which supports the assumption that its objects are not hashed:

which(names(l) == "1")
# [1] 2291

Environments do not have this:

e[[1]]
# Error in e[[1]] : wrong arguments for subsetting an environment

Some quick membership testing: I used a logical for the value, though that is completely arbitary. Anything other than NULL would suffice for our needs here. We'll use a simple !is.null(e[[...]]) to test for specific membership:

!is.null(e[["1"]])
# [1] TRUE
!is.null(e[["10000"]])
# [1] FALSE
!is.null(l[["1"]])
# [1] TRUE
!is.null(l[["10000"]])
# [1] FALSE

microbenchmark(
  vec1 =  1  %in% s1,
  vec2 =  1  %in% s2,
  vec3 =  1  %in% s3,
  vec4 = "1" %in% s4,
  lst = is.null(l[["1"]]),
  env = is.null(e[["1"]]),
  times = 1000
)
# Warning in microbenchmark(vec1 = 1 %in% s1, vec2 = 1 %in% s2, vec3 = 1 %in%  :
#   Could not measure a positive execution time for 6 evaluations.
# Unit: nanoseconds
#  expr   min    lq     mean median    uq     max neval
#  vec1  5835  6929 12493.25   7294  9482 3214588  1000
#  vec2  9117  9847 16660.73  10212 12764 4081050  1000
#  vec3  7294  8388 19983.63   8752 10576 3274759  1000
#  vec4 11670 12400 15423.03  12764 14223   74394  1000
#   lst 20787 21517 24561.72  21881 22975  143317  1000
#   env     0     1   461.25    365   366   18235  1000

Not surprisingly, the list does not perform well, though it seems to do better than the vectors (in the max case, relatively meaningless). Also not surprisingly, based on our claim that the environment uses an internal has, it performs quite well. Is it O(1)?

microbenchmark(
     samp5 = sapply(as.character(sample(5000, size =    5)), function(a) is.null(e[[a]])),
    samp50 = sapply(as.character(sample(5000, size =   50)), function(a) is.null(e[[a]])),
   samp500 = sapply(as.character(sample(5000, size =  500)), function(a) is.null(e[[a]])),
  samp5000 = sapply(as.character(sample(5000, size = 5000)), function(a) is.null(e[[a]]))
)
# Unit: microseconds
#      expr      min         lq        mean     median         uq       max neval
#     samp5   25.893    32.4565    49.58154    40.4795    58.3485   169.573   100
#    samp50  108.309   119.4310   156.45244   135.8410   167.3850   681.938   100
#   samp500  935.750  1023.2715  1265.29732  1073.9610  1172.6055  6841.985   100
#  samp5000 9410.008 10337.5520 11137.82968 10650.0765 11280.0485 15455.548   100

The first one, samp5, appears to take a bit longer. This isn't too surprising, since there is overhead associated with sapply, sampling, and other things. However, the remaining rows seem to scale somewhat well with the numbers of samples done. This suggests it is indeed O(1) for some basic set operations.

NB: I had to use the whole sapply(...) trick because, unlike vectors and lists, R's environments do not allow subsetting with a vector.

e[[c("1")]]
# [1] TRUE
e[[c("1","10")]]
# Error in e[[c("1", "10")]] :
#   wrong arguments for subsetting an environment

This is one of the claims made by (and fixed by) hashmap.

Extra credit: in order to facilitate using an environment as a set, you could use simple adders and deleters:

newset <- function() new.env(parent = emptyenv())
setadd <- function(set, n) set[[n]] <- TRUE
setdel <- function(set, n) set[[n]] <- NULL
setcontains <- function(set, n) !is.null(set[[n]])
setmembers <- function(set) names(set)

e <- newset()
setcontains(e, "a")
# [1] FALSE
setadd(e, "a")
setcontains(e, "a")
# [1] TRUE
setmembers(e)
# [1] "a"
setdel(e, "a")
setcontains(e, "a")
# [1] FALSE

(There is a similar but much more extensive blog post on this by Jeffrey Horner here: http://jeffreyhorner.tumblr.com/post/114524915928/hash-table-performance-in-r-part-i.)


答:
It can be performed via:</p>

```<code>val currencyFormat = NumberFormat.getCurrencyInstance();
</code>```

Title: Use NumberFormat.getCurrency in Kotlin Android

Body:
I need call this

{private static final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance();}

in Android Application, but I using Kotlin and I don't know how to do that in Kotlin. How can I do this in Kotlin?

Body:
It can be performed via:

val currencyFormat = NumberFormat.getCurrencyInstance();


问:
How to achieve 'media does not exist' like whatsapp?
What is the best way to achieve "media does not exist" with blur effect on original image which is already deleted (like WhatAapp),

And if WhatsApp store it in physical path (because you can also able to see it in offline mode), then where it exists?

答: You have to store image in database once delete should be blur effect on imageview</p>


问:
trying to modify the js function so that it gives the same output as it was when called the other js function
I am exporting the content on the webpage to the PDF file, for this i have used jsPDF API and i could able to get it work but now i want to use html2PDF as it resolves few issues which were faced when using jsPDF API.

I have written the function $scope.exportUsingJSPDF which is called when the button Export Using JSPDF is clicked. Similarly i want to implement the function $scope.exportUsingHTML2PDF which uses html2PDF API but could not succeed. Any inputs on how to modify  $scope.exportUsingHTML2PDF so that it iterates the divs and shows the div content as shown when invoked using  $scope.exportUsingJSPDF by clicking Export using JSPDF API.

Complete online example: https://plnkr.co/edit/454HUFF3rmLlkXLCQkbx?p=preview

js code:

```<code>    //trying to implement the below function same as $scope.exportUsingJSPDF, so
// that when user click on Export using HTML2PDF button, it exports the content to the PDF and generaes the PDF.
         $scope.exportUsingHTML2PDF = function(){
          var pdf = new jsPDF('l', 'pt', 'a4');
            var pdfName = 'test.pdf';

         pdf.canvas.height = 72 * 11;
         pdf.canvas.width = 72 * 8.5;
         html2pdf(document.getElementByClassName("myDivClass"), pdf, function(pdf){
             pdf.save(pdfName);
         });
         }

        $scope.exportUsingJSPDF = function() {
              var pdf = new jsPDF('p','pt','a4');
                var pdfName = 'test.pdf';

                var options = {   pagesplit: true};

                var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
                var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
                var currentRecursion=0;

                //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
                function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
                    //Once we have done all the divs save the pdf
                    if(currentRecursion==totalRecursions){
                        pdf.save(pdfName);
                    }else{
                        currentRecursion++;
                        pdf.addPage();
                        //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
                        //addHtml requires an html element. Not a string like fromHtml.
                        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                            console.log(currentRecursion);
                            recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                        });
                    }
                }

                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
                });
            }
</code>```

PS: I was trying to modify $scope.exportUsingHTML2PDF so that it gives the same output as generated when clicked on "Export using JSPDF" button which calls the function $scope.exportUsingJSPDF.

答:
The problem lies with your function using exportUsingHTML2PDF, the error is that you need to pass in the html to the function of html2PDF. Manage the page css on the basis of your need.

EDIT: You have wrong library. Please check html2pdf.js library within the plunker

Working plunker: html2pdf

```<code>    $scope.exportUsingHTML2PDF = function() {
    var element = document.getElementById('element-to-print');
    html2pdf(element, {
        margin: 1,
        filename: 'myfile.pdf',
        image: {
            type: 'jpeg',
            quality: 0.98
        },
        html2canvas: {
            dpi: 192,
            letterRendering: true
        },
        jsPDF: {
            unit: 'in',
            format: 'letter',
            orientation: 'portrait'
        }
    });
}
</code>```

Body:
I am exporting the content on the webpage to the PDF file, for this i have used jsPDF API and i could able to get it work but now i want to use html2PDF as it resolves few issues which were faced when using jsPDF API.

I have written the function $scope.exportUsingJSPDF which is called when the button Export Using JSPDF is clicked. Similarly i want to implement the function $scope.exportUsingHTML2PDF which uses html2PDF API but could not succeed. Any inputs on how to modify  $scope.exportUsingHTML2PDF so that it iterates the divs and shows the div content as shown when invoked using  $scope.exportUsingJSPDF by clicking Export using JSPDF API.

Complete online example: https://plnkr.co/edit/454HUFF3rmLlkXLCQkbx?p=preview

js code:

    //trying to implement the below function same as $scope.exportUsingJSPDF, so
// that when user click on Export using HTML2PDF button, it exports the content to the PDF and generaes the PDF.
         $scope.exportUsingHTML2PDF = function(){
          var pdf = new jsPDF('l', 'pt', 'a4');
            var pdfName = 'test.pdf';

         pdf.canvas.height = 72 * 11;
         pdf.canvas.width = 72 * 8.5;
         html2pdf(document.getElementByClassName("myDivClass"), pdf, function(pdf){
             pdf.save(pdfName);
         });
         }

        $scope.exportUsingJSPDF = function() {
              var pdf = new jsPDF('p','pt','a4');
                var pdfName = 'test.pdf';

                var options = {   pagesplit: true};

                var $divs = $('.myDivClass')                //jQuery object of all the myDivClass divs
                var numRecursionsNeeded = $divs.length -1;     //the number of times we need to call addHtml (once per div)
                var currentRecursion=0;

                //Found a trick for using addHtml more than once per pdf. Call addHtml in the callback function of addHtml recursively.
                function recursiveAddHtmlAndSave(currentRecursion, totalRecursions){
                    //Once we have done all the divs save the pdf
                    if(currentRecursion==totalRecursions){
                        pdf.save(pdfName);
                    }else{
                        currentRecursion++;
                        pdf.addPage();
                        //$('.myDivClass')[currentRecursion] selects one of the divs out of the jquery collection as a html element
                        //addHtml requires an html element. Not a string like fromHtml.
                        pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                            console.log(currentRecursion);
                            recursiveAddHtmlAndSave(currentRecursion, totalRecursions)
                        });
                    }
                }

                pdf.fromHTML($('.myDivClass')[currentRecursion], 15, 20, options, function(){
                    recursiveAddHtmlAndSave(currentRecursion, numRecursionsNeeded);
                });
            }

PS: I was trying to modify $scope.exportUsingHTML2PDF so that it gives the same output as generated when clicked on "Export using JSPDF" button which calls the function $scope.exportUsingJSPDF.

Body:
The problem lies with your function using exportUsingHTML2PDF, the error is that you need to pass in the html to the function of html2PDF. Manage the page css on the basis of your need.

EDIT: You have wrong library. Please check html2pdf.js library within the plunker

Working plunker: html2pdf

    $scope.exportUsingHTML2PDF = function() {
    var element = document.getElementById('element-to-print');
    html2pdf(element, {
        margin: 1,
        filename: 'myfile.pdf',
        image: {
            type: 'jpeg',
            quality: 0.98
        },
        html2canvas: {
            dpi: 192,
            letterRendering: true
        },
        jsPDF: {
            unit: 'in',
            format: 'letter',
            orientation: 'portrait'
        }
    });
}


问:
Replace Square-Expression in Maple
Given a maple expression like

```<code>f := (y + 5)^2 + x^2
</code>```

How can I replace all occurrences of the square function with a custom function? The result I want to have would be

```<code>square(y + 5) + square(x)
</code>```

I tried something like

```<code>subs({x^2 = square(x)}, f)
</code>```

However, that only replaces the x^2 expression. I could of course list explicitly the (y + 5) term as well, but I want to replace any occurrence of (.)^2 without listing everything explicitly.

How can I do this in Maple?

Title: Replace Square-Expression in Maple

Body:
Given a maple expression like

f := (y + 5)^2 + x^2

How can I replace all occurrences of the square function with a custom function? The result I want to have would be

square(y + 5) + square(x)

I tried something like

subs({x^2 = square(x)}, f)

However, that only replaces the x^2 expression. I could of course list explicitly the (y + 5) term as well, but I want to replace any occurrence of (.)^2 without listing everything explicitly.

How can I do this in Maple?

Body:
You can accomplish this using either subsindets or applyrule.

expression:=(y-5)^2+3+sin(((z-1/3)^2/(t-(y-s)^2)))+F(f(17+p^2)^2);

                                   /         2  \
                                   |  /    1\   |
                                   |  |z - -|   |    /          2\
                        2          |  \    3/   |    | / 2     \ |
   expression := (y - 5)  + 3 + sin|------------| + F\f\p  + 17/ /
                                   |           2|
                                   \t - (y - s) /

applyrule(_a::anything^2=square(_a), expression);

                           /        /    1\  \
                           |  square|z - -|  |
                           |        \    3/  |
    square(y - 5) + 3 + sin|-----------------| + F(square(f(square(p) + 17)))
                           \t - square(y - s)/

subsindets(expression, '`^`'(anything,2), u->square(op(1,u)));

                           /        /    1\  \
                           |  square|z - -|  |
                           |        \    3/  |
    square(y - 5) + 3 + sin|-----------------| + F(square(f(square(p) + 17)))
                           \t - square(y - s)/


问:
What is it called when JS is used to show only a certain part of a png?
Let's say you have a png and it contains all of the icons that are to be used on one page, what is the process of using JS to select and display on a certain icon in that image? I've always seen it being done, but it seems to evade me what it is, and how to do it.

答:
You would use CSS and if you want it to be a really painless experience use this website below.

http://www.spritebox.net/

It will take care of generating the picture and also making generating the CSS you will need to output the icons.


问:
When i resize my webpage the section expands vertically adding unwanted background

When the webpage is on the big screen everything is perfect. All 3 blocks of text are inline and the white footer comes right after the background picture.
But when I resize the window webpage automatically adds space after the picture.
 Not sure what I should do: have my picture repeated? But that won't look good. Leave it as it is? Not sure what to do? What is a good solution for this?

答:
If the background is an image(tag), through jquery set the height to window height in resize function.(jquery).

```<code>$(window).resize(function(){
    $(".img").height($(window).height());
});
</code>```

Here img is the class used for image tag.
Hopefully this solves your problem

Body:
If the background is an image(tag), through jquery set the height to window height in resize function.(jquery).

$(window).resize(function(){
    $(".img").height($(window).height());
});

Here img is the class used for image tag.
Hopefully this solves your problem