答:
The reasons for this outcome are like you state, and are explained in Is floating point math broken? and many other similar Q&A.

When you know the number of decimals of numerator and denominator, a more reliable way is to multiply those numbers first so they can treated as integers, and then perform integer division on them:

So in your case 1//0.01 should be converted first to 1*100//(0.01*100) which is 100.

In more extreme cases you can still get "unexpected" results. It might be necessary to add a round call to numerator and denominator before performing the integer division:

```<code>1 * 100000000000 // round(0.00000000001 * 100000000000)
</code>```

But, if this is about working with fixed decimals (money, cents), then consider working with cents as unit, so that all arithmetic can be done as integer arithmetic, and only convert to/from the main monetary unit (dollar) when doing I/O.

Or alternatively, use a library for decimals, like decimal, which:

...provides support for fast correctly-rounded decimal floating point arithmetic.

```<code>from decimal import Decimal
cent = Decimal(1) / Decimal(100) # Contrary to floating point, this is exactly 0.01
print (Decimal(1) // cent) # 100
</code>```

Title: Why 1//0.01 == 99 in Python?

Body:
I imagine this is a classic floating point precision question, but I am trying to wrap my head around this result, running 1//0.01 in Python 3.7.5 yields 99.

I imagine it is an expected result, but is there any way to decide when it is safer to use int(1/f) rather than 1//f ?

Body:
The reasons for this outcome are like you state, and are explained in Is floating point math broken? and many other similar Q&A.

When you know the number of decimals of numerator and denominator, a more reliable way is to multiply those numbers first so they can treated as integers, and then perform integer division on them:

So in your case 1//0.01 should be converted first to 1*100//(0.01*100) which is 100.

In more extreme cases you can still get "unexpected" results. It might be necessary to add a round call to numerator and denominator before performing the integer division:

1 * 100000000000 // round(0.00000000001 * 100000000000)

But, if this is about working with fixed decimals (money, cents), then consider working with cents as unit, so that all arithmetic can be done as integer arithmetic, and only convert to/from the main monetary unit (dollar) when doing I/O.

Or alternatively, use a library for decimals, like decimal, which:

...provides support for fast correctly-rounded decimal floating point arithmetic.

from decimal import Decimal
cent = Decimal(1) / Decimal(100) # Contrary to floating point, this is exactly 0.01
print (Decimal(1) // cent) # 100


来源: stackexchange

问:
How to extract an enumerable datatable from database when column names and count may vary?
How do I extract data from a data table in a sql server database, knowing that the table could have different column names/column count depending on the request?

I would usually use a SqlDataAdapter and then do: da.Fill(dt) but this is not an option as I cannot enumerate through a dataTable in a razor view. I wish to reproduce that table in a view using Razor Pages.

Here is an example of what I might normally do, but it involves knowing exactly what the column names will be and how many there will be. What can I put in the while to return all of the table data in a type that is enumerable?:

```<code>SqlConnection connectionCalc = new SqlConnection("<connectionString>");

                    if (connectionCalc.State.Equals(ConnectionState.Closed))
                        connectionCalc.Open();

                    using (var command = connectionCalc.CreateCommand())
                    {
                        command.CommandText = $@"SELECT * FROM {tableName}";

                        SqlDataReader reader = command.ExecuteReader();
                        column = new Dictionary<string, string>();
                        int FATUidSingle = -999;

                        while (reader.Read())
                        {
                            TableUid.Add(reader[SelectedCalculation + "TABLE_UID"].ToString());
                            FATUid.Add(Convert.ToInt32(reader["FAT_UID"]));
                            ScheduledDate.Add(Convert.ToDateTime(reader["SOME_DATE"]));
                            TableStatusUid.Add(reader[SelectedCalculation + "ST_UID"].ToString());
                            StartDate.Add(Convert.ToDateTime(reader["ANOTHER_DATE"]));
                            EndDate.Add(Convert.ToDateTime(reader["OTHER_DATE"]));
                            Progress.Add(reader["PROGRESS"].ToString());
                        }
</code>```

答:
Run a command like this first to get the field names, then you will know which fields to expect.  You could use it to build SQL and set ordinals to point to the column you want

```<code>    SELECT TABLE_NAME, COLUMN_NAME FROM
            INFORMATION_SCHEMA.COLUMNS
                    where table_name = 'EmployeeDetail'
</code>```

when you make your enumerable list, make a list of 'tuples' of string and object perhaps, where the string is the field name and the object is the value

ContentLicense: CC BY-SA 4.0

Body:
How do I extract data from a data table in a sql server database, knowing that the table could have different column names/column count depending on the request?

I would usually use a SqlDataAdapter and then do: da.Fill(dt) but this is not an option as I cannot enumerate through a dataTable in a razor view. I wish to reproduce that table in a view using Razor Pages.

Here is an example of what I might normally do, but it involves knowing exactly what the column names will be and how many there will be. What can I put in the while to return all of the table data in a type that is enumerable?:

SqlConnection connectionCalc = new SqlConnection("<connectionString>");

                    if (connectionCalc.State.Equals(ConnectionState.Closed))
                        connectionCalc.Open();

                    using (var command = connectionCalc.CreateCommand())
                    {
                        command.CommandText = $@"SELECT * FROM {tableName}";

                        SqlDataReader reader = command.ExecuteReader();
                        column = new Dictionary<string, string>();
                        int FATUidSingle = -999;

                        while (reader.Read())
                        {
                            TableUid.Add(reader[SelectedCalculation + "TABLE_UID"].ToString());
                            FATUid.Add(Convert.ToInt32(reader["FAT_UID"]));
                            ScheduledDate.Add(Convert.ToDateTime(reader["SOME_DATE"]));
                            TableStatusUid.Add(reader[SelectedCalculation + "ST_UID"].ToString());
                            StartDate.Add(Convert.ToDateTime(reader["ANOTHER_DATE"]));
                            EndDate.Add(Convert.ToDateTime(reader["OTHER_DATE"]));
                            Progress.Add(reader["PROGRESS"].ToString());
                        }

Body:
Run a command like this first to get the field names, then you will know which fields to expect.  You could use it to build SQL and set ordinals to point to the column you want

    SELECT TABLE_NAME, COLUMN_NAME FROM
            INFORMATION_SCHEMA.COLUMNS
                    where table_name = 'EmployeeDetail'

when you make your enumerable list, make a list of 'tuples' of string and object perhaps, where the string is the field name and the object is the value


问:
Why does aiohttp need await to get body?
I found aiohttp server should use await keyword to get Request Body

```<code>async def handler(request):
  body = await request.json(). # or text(), read()
</code>```

I think when the handler is called, the request body is already in server side memory and I don't think it is I/O intensive work, needing asynchronous operation.

Any missing point?

答:
With a very large request message-body, you might not have received the complete body when the handler is called. HTTP1/1 states that the server might answer before the end of the request (from RFC 2616):

An HTTP/1.1 (or later) client sending a message-body SHOULD monitor the network connection for an error status while it is transmitting the request. If the client sees an error status, it SHOULD immediately cease transmitting the body.

So you could for example reply with an 4xx Client error code immediately if you do not accept the request (e.g. 401 Unauthorized if the token is invalid) before receiving the whole request message-body.

Body:
I found aiohttp server should use await keyword to get Request Body

async def handler(request):
  body = await request.json(). # or text(), read()

I think when the handler is called, the request body is already in server side memory and I don't think it is I/O intensive work, needing asynchronous operation.

Any missing point?


问:
Unsupported get request. Object with ID 'me' does not exist
```<code>        $fb = new \Facebook\Facebook([
            'app_id' => config('config.fb_app_id'),
            'app_secret' => config('config.fb_app_secret'),
            'default_graph_version' => 'v3.0',
        ]);
        // User info
        $fb->setDefaultAccessToken($access_token);
        $request = $fb->request('GET', '/me?fields=id,name');
        $response = $fb->getClient()->sendRequest($request)->getDecodedBody();
</code>```

The above code doesn't work and it says "Unsupported get request. Object with ID 'me' does not exist".

Really strange!! This was working fine few days back and suddenly it started throwing Errors. Whats wrong with this code?

答:
Had the same problem.
Didn't notice facebook app was in developer mode.
Was working for me because I was configured as an admin in the app.

You need to add testers for the app

Body:
        $fb = new \Facebook\Facebook([
            'app_id' => config('config.fb_app_id'),
            'app_secret' => config('config.fb_app_secret'),
            'default_graph_version' => 'v3.0',
        ]);
        // User info
        $fb->setDefaultAccessToken($access_token);
        $request = $fb->request('GET', '/me?fields=id,name');
        $response = $fb->getClient()->sendRequest($request)->getDecodedBody();

The above code doesn't work and it says "Unsupported get request. Object with ID 'me' does not exist".

Really strange!! This was working fine few days back and suddenly it started throwing Errors. Whats wrong with this code?


问:
how to bind a php session to user SSL certificate
I read a paper in the php manual about session vulnerability. I learned that I need to bind my session to the user SSL certificate, and verify that on every page. I don't quite know what this means.

My site has SSL on every page, there is never any switch and the user can neve access it without https.

Do I need to take measures, in my code, to protect my sessions?

答:
If you're talking of client-certificate authentication (by which the client presents a certificate to authenticate to the server), you're probably use the server's authentication layer to provide you with an ID. Assuming Apache Httpd, that can be done with SSLOptions +FakeBasicAuth for example. From PHP's point of view, it's not much different to using HTTP Basic authentication after this (and you could bind a PHP session to this form of authentication).

If you're not talking about client-certificates, but in SSL/TLS session IDs, the notion of an SSL/TLS session is completely different from the PHP session. The SSL/TLS session may legitimately change during a PHP session, for a number of reason (including connection loss, time out, parallel connection to download multiple items on the page at the same time, ...). The effect of such a change will be completely transparent to the HTTP layer. There is no link between the two kinds of sessions, and using the SSL/TLS session ID as a basis for the PHP session ID is more likely to create trouble than anything else.

ContentLicense: CC BY-SA 3.0


问:
excel, check if string contains a character a-z or A-Z
I have a column with unstructured data. I need to detect if the string has an alphabetical character meaning a-z or A-Z. I am not sure how to do this in excel with a formula or other. I am thinking this could be a long countif and sumproduct. Or maybe regex in excel. I will post an attempt try once I try this out more. But I am looking for some advice. While searching online, I could not find a formula to do this. Thanks for your help. Please see below screenshot for sample data.

答:
Note that SEARCH is case-insensitive, so you can use:

```<code>    =IF(OR(ISNUMBER(SEARCH({"A";"B";"C";"D";"E";"F";"G";"H";"I";"J";"K";"L";"M";"N";"O";"P";"Q";"R";"S";"T";"U";"V";"W";"X";"Y";"Z"},A8))),"Yes","No")
</code>```

If you have a later version of O365 with the SEQUENCE function, you can use:

```<code>=IF(OR(ISNUMBER(SEARCH(CHAR(SEQUENCE(26,,65,1)),A1))),"Yes","No")
</code>```

Body:
Note that SEARCH is case-insensitive, so you can use:

    =IF(OR(ISNUMBER(SEARCH({"A";"B";"C";"D";"E";"F";"G";"H";"I";"J";"K";"L";"M";"N";"O";"P";"Q";"R";"S";"T";"U";"V";"W";"X";"Y";"Z"},A8))),"Yes","No")

If you have a later version of O365 with the SEQUENCE function, you can use:

=IF(OR(ISNUMBER(SEARCH(CHAR(SEQUENCE(26,,65,1)),A1))),"Yes","No")


问:
Sort by number of apearances
for example, I am given a word and I have to sort its letters by the number of occurrences in that word, if 2 letters appear the same number of times it will be sorted by the lexicographic minimum.
For now, I have started to see how many times a letter appears in a word but from here I do not know exactly how to do it.
The problem requires me to use BufferedReader and BufferedWriter.

```<code>import java.util.*;

public class Main {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Map<Character, Integer> m = new HashMap<>();
    String s = sc.nextLine();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (m.containsKey(c))
            m.put(c, m.get(c) + 1);
        else
            m.put(c, 1);
    }
    for (char letter = 'a'; letter <= 'z'; ++letter)
        if (m.containsKey(letter))
            System.out.println(letter + ": " + m.get(letter));
}
</code>```

For the moment I am posting what letters appear most often in the word, but I do not know how to sort them by the number of occurrences and in case there are two letters that appear at the same number of times with the minimum lexicographic.

答:
To count letters in word, you can use much simpler method:

define array with 26 zeros, scan input line and increase appropriate index in this array, so if you meet 'a' (or 'A' - which is the same letter, but different symbol) - you will increase value at index 0, b - index 1, etc

during this scan you can also compute most occurred symbol, like this:

```<code>public static void main(final String[] args) throws IOException {
    char maxSymbol = 0;
    int maxCount = 0;

    final int[] counts = new int[26]; // number of times each letter (a-z) appears in string
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        final String s = br.readLine().toLowerCase(); // calculate case-insensitive counts
        for (final char c : s.toCharArray()) {
            final int idx = c - 'a'; // convert form ASCII code to 0-based index
            counts[idx]++;

            if (counts[idx] > maxCount) {
                maxSymbol = c; // we found most occurred symbol for the current moment
                maxCount = counts[idx];
            } else if (counts[idx] == maxCount) { // we found 2nd most occurred symbol for the current moment, need to check which one is minimal in lexicographical order
                if (c < maxSymbol) {
                    maxSymbol = c;
                }
            }
        }
    }

    if (maxSymbol > 0) {
        System.out.println("Most frequent symbol " + maxSymbol + " occurred " + maxCount);
    }
}
</code>```

I've used buffered reader to get data from stdin, but I have no idea where to put buffered writer here, maybe to print result?

Title: Sort by number of apearances

Body:
for example, I am given a word and I have to sort its letters by the number of occurrences in that word, if 2 letters appear the same number of times it will be sorted by the lexicographic minimum.
For now, I have started to see how many times a letter appears in a word but from here I do not know exactly how to do it.
The problem requires me to use BufferedReader and BufferedWriter.

import java.util.*;

public class Main {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Map<Character, Integer> m = new HashMap<>();
    String s = sc.nextLine();
    for (int i = 0; i < s.length(); ++i) {
        char c = s.charAt(i);
        if (m.containsKey(c))
            m.put(c, m.get(c) + 1);
        else
            m.put(c, 1);
    }
    for (char letter = 'a'; letter <= 'z'; ++letter)
        if (m.containsKey(letter))
            System.out.println(letter + ": " + m.get(letter));
}

For the moment I am posting what letters appear most often in the word, but I do not know how to sort them by the number of occurrences and in case there are two letters that appear at the same number of times with the minimum lexicographic.

Body:
To count letters in word, you can use much simpler method:

define array with 26 zeros, scan input line and increase appropriate index in this array, so if you meet 'a' (or 'A' - which is the same letter, but different symbol) - you will increase value at index 0, b - index 1, etc

during this scan you can also compute most occurred symbol, like this:

public static void main(final String[] args) throws IOException {
    char maxSymbol = 0;
    int maxCount = 0;

    final int[] counts = new int[26]; // number of times each letter (a-z) appears in string
    try (final BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        final String s = br.readLine().toLowerCase(); // calculate case-insensitive counts
        for (final char c : s.toCharArray()) {
            final int idx = c - 'a'; // convert form ASCII code to 0-based index
            counts[idx]++;

            if (counts[idx] > maxCount) {
                maxSymbol = c; // we found most occurred symbol for the current moment
                maxCount = counts[idx];
            } else if (counts[idx] == maxCount) { // we found 2nd most occurred symbol for the current moment, need to check which one is minimal in lexicographical order
                if (c < maxSymbol) {
                    maxSymbol = c;
                }
            }
        }
    }

    if (maxSymbol > 0) {
        System.out.println("Most frequent symbol " + maxSymbol + " occurred " + maxCount);
    }
}

I've used buffered reader to get data from stdin, but I have no idea where to put buffered writer here, maybe to print result?


问:
Match value of variable to object array
i'm trying to match the value of variable to an object array. the last if statement is what i'm struggling with. anything helps thanks in advance.</p>

```<code>function getPage(){
    let pageActual = window.location.href;
    console.log(pageActual);

    let pageName = /500(.*)/;
    let EventName = pageName.exec(pageActual); // this creates the event name based on the event url you're currently on.
    console.log(EventName[1]);
const events2020v2 = [

{event:"example1", Date:'February 19, 2020'},
{event:"test2.html", Date:'February 11, 2020'},
{event:"example3", Date:'February 19, 2020'},
{event:"/test2.html", Date:'February 19, 2020'},
{event:"example4", Date:'February 19, 2020'}

];
// below im attempting to match the eventName to a value in the object above.
if(events2020v2.event.indexOf(EventName.value)){
         console.log('something')
     }
</code>```

答:
So .indexOf() works a bit differently. I suggest for this scenario .find() instead.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

Take a look at my example for your case:

const EventName = {
  value: 'test2.html'
};

const events2020v2 = [
   {event:"example1", Date:'February 19, 2020'},
   {event:"test2.html", Date:'February 11, 2020'},
   {event:"example3", Date:'February 19, 2020'},
   {event:"/test2.html", Date:'February 19, 2020'},
   {event:"example4", Date:'February 19, 2020'}
];

const found = events2020v2.find(e => e.event === EventName.value);

if (found) {
  console.log('found', found);
}```

I hope that helps!

Title: Match value of variable to object array

Body:
i'm trying to match the value of variable to an object array. the last if statement is what i'm struggling with. anything helps thanks in advance.

function getPage(){
    let pageActual = window.location.href;
    console.log(pageActual);

    let pageName = /500(.*)/;
    let EventName = pageName.exec(pageActual); // this creates the event name based on the event url you're currently on.
    console.log(EventName[1]);
const events2020v2 = [

{event:"example1", Date:'February 19, 2020'},
{event:"test2.html", Date:'February 11, 2020'},
{event:"example3", Date:'February 19, 2020'},
{event:"/test2.html", Date:'February 19, 2020'},
{event:"example4", Date:'February 19, 2020'}

];
// below im attempting to match the eventName to a value in the object above.
if(events2020v2.event.indexOf(EventName.value)){
         console.log('something')
     }

Body:
So .indexOf() works a bit differently. I suggest for this scenario .find() instead.

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.

Take a look at my example for your case:

const EventName = {
  value: 'test2.html'
};

const events2020v2 = [
   {event:"example1", Date:'February 19, 2020'},
   {event:"test2.html", Date:'February 11, 2020'},
   {event:"example3", Date:'February 19, 2020'},
   {event:"/test2.html", Date:'February 19, 2020'},
   {event:"example4", Date:'February 19, 2020'}
];

const found = events2020v2.find(e => e.event === EventName.value);

if (found) {
  console.log('found', found);
}

I hope that helps!


问:
How to pass arguments to animation.FuncAnimation()?
How to pass arguments to animation.FuncAnimation()? I tried, but didn't work. The signature of animation.FuncAnimation() is

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)                 Bases: matplotlib.animation.TimedAnimation

I have pasted my code below. Which changes I have to make?

```<code>import matplotlib.pyplot as plt
import matplotlib.animation as animation

def animate(i,argu):
    print argu

    graph_data = open('example.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
        ax1.clear()
        ax1.plot(xs, ys)
        plt.grid()

ani = animation.FuncAnimation(fig,animate,fargs = 5,interval = 100)
plt.show()
</code>```

答:
Intro

Below you will find an example of code how to pass an argument properly to the animation.funcAnimation function.

If you save all the code parts below as a single .py file you can call the script as follow in your terminal:
$python3 scriptLiveUpdateGraph.py -d data.csv
where data.csv is your data file containing data you want to display live.

The usual modules import

Below is my script starting:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import time
import os

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
</code>```

Some function

Here I declare the function that will be called later by the animation.funcAnimation function.

```<code>def animate(i, pathToMeas):
    pullData = open(pathToMeas,'r').read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    colunmNames = dataArray[0].split(',')
    # my data file had this structure:
    #col1, col2
    #100, 500
    #95, 488
    #90, 456
    #...
    # and this data file can be updated when the script is running
    for eachLine in dataArray[1:]:
        if len(eachLine) > 1:
           x, y = eachLine.split(',')
           xar.append(float(x))
           yar.append(float(y))

   # convert list to array
   xar = np.asarray(xar)
   yar = np.asarray(yar)

   # sort the data on the x, I do that for the problem I was trying to solve.
   index_sort_ = np.argsort(xar)
   xar = xar[index_sort_]
   yar = yar[index_sort_]

   ax1.clear()
   ax1.plot(xar, yar,'-+')
   ax1.set_xlim(0,np.max(xar))
   ax1.set_ylim(0,np.max(yar))
</code>```

Process the input parameters

To make the script more interactive I have added the possibility to read input file with argparse:

```<code>parser = argparse.ArgumentParser()
parser.add_argument("-d","--data",
                help="data path to the data to be displayed.",
                type=str)

args = parser.parse_args()
</code>```

Call the function to do the animation

And know we are answering the main question of this thread:

```<code>ani = animation.FuncAnimation(fig, animate, fargs=(args.data,), interval=1000 )
plt.show()
</code>```

Body:
How to pass arguments to animation.FuncAnimation()? I tried, but didn't work. The signature of animation.FuncAnimation() is

class matplotlib.animation.FuncAnimation(fig, func, frames=None, init_func=None, fargs=None, save_count=None, **kwargs)                 Bases: matplotlib.animation.TimedAnimation

I have pasted my code below. Which changes I have to make?

import matplotlib.pyplot as plt
import matplotlib.animation as animation

def animate(i,argu):
    print argu

    graph_data = open('example.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
        ax1.clear()
        ax1.plot(xs, ys)
        plt.grid()

ani = animation.FuncAnimation(fig,animate,fargs = 5,interval = 100)
plt.show()

Body:
Intro

Below you will find an example of code how to pass an argument properly to the animation.funcAnimation function.

If you save all the code parts below as a single .py file you can call the script as follow in your terminal:
$python3 scriptLiveUpdateGraph.py -d data.csv
where data.csv is your data file containing data you want to display live.

The usual modules import

Below is my script starting:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import time
import os

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

Some function

Here I declare the function that will be called later by the animation.funcAnimation function.

def animate(i, pathToMeas):
    pullData = open(pathToMeas,'r').read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []
    colunmNames = dataArray[0].split(',')
    # my data file had this structure:
    #col1, col2
    #100, 500
    #95, 488
    #90, 456
    #...
    # and this data file can be updated when the script is running
    for eachLine in dataArray[1:]:
        if len(eachLine) > 1:
           x, y = eachLine.split(',')
           xar.append(float(x))
           yar.append(float(y))

   # convert list to array
   xar = np.asarray(xar)
   yar = np.asarray(yar)

   # sort the data on the x, I do that for the problem I was trying to solve.
   index_sort_ = np.argsort(xar)
   xar = xar[index_sort_]
   yar = yar[index_sort_]

   ax1.clear()
   ax1.plot(xar, yar,'-+')
   ax1.set_xlim(0,np.max(xar))
   ax1.set_ylim(0,np.max(yar))

Process the input parameters

To make the script more interactive I have added the possibility to read input file with argparse:

parser = argparse.ArgumentParser()
parser.add_argument("-d","--data",
                help="data path to the data to be displayed.",
                type=str)

args = parser.parse_args()

Call the function to do the animation

And know we are answering the main question of this thread:

ani = animation.FuncAnimation(fig, animate, fargs=(args.data,), interval=1000 )
plt.show()


问:
VBA - Date-Time String Replace/Substitute
I have a column which has date and time of emails from outlook. Some dates are in format - January 2, 2020 4:15 PM, January-14-20 12:44 PM, December-24-19 20:15 PM.

I have tried to use Replace and Substitute functions, Replace does work as defined but from the string time is removed. I would like to have all dates as 2019-12-27 3:02 PM.

```<code>sub Replace()
 Dim sString, searchString as String
 dim i, LastCell as Long

 LastCell = Range("C" & Rows.Count).End(xlUp).Row
 Set searchRng = Range("C3:C" & lastCell)

 For Each c In searchRng
   sString = c
   searchString = "-"

   If InStr(1, sString, searchString, vbTextCompare) > 0 Then
      i = InStr(1, sString, SearchString, vbTextCompare)
      i = InStr(i + 1, sString, SearchString, vbTextCompare)
      c.Offset(0, 1) = WorksheetFunction.Replace(sString, i, "19", " 2020")
   End If
 Next c
End Sub
</code>```

答:
I still think you could do this easier:

```<code>'
'
'
 LastCell = Range("C" & Rows.Count).End(xlUp).Row
With Range("C3:C" & lastCell).Offset(0, 1)
    .FormulaR1C1 = "=TEXT(RC[-1],""yyyy-mm-dd hh:mm AM/PM"")"
    .Value = .Value
End With
</code>```

NOTE: yyyy-mm-dd hh:mm AM/PM will work according to your regional settings, so if Excel is not in english, translate it. My excel is spanish, and this code would not work for me unless I type aaaa-mm-dd hh:mm AM/PM instead of yyyy-mm-dd hh:mm AM/PM

Convert all dates at once.

Range

Body:
I have a column which has date and time of emails from outlook. Some dates are in format - January 2, 2020 4:15 PM, January-14-20 12:44 PM, December-24-19 20:15 PM.

I have tried to use Replace and Substitute functions, Replace does work as defined but from the string time is removed. I would like to have all dates as 2019-12-27 3:02 PM.

sub Replace()
 Dim sString, searchString as String
 dim i, LastCell as Long

 LastCell = Range("C" & Rows.Count).End(xlUp).Row
 Set searchRng = Range("C3:C" & lastCell)

 For Each c In searchRng
   sString = c
   searchString = "-"

   If InStr(1, sString, searchString, vbTextCompare) > 0 Then
      i = InStr(1, sString, SearchString, vbTextCompare)
      i = InStr(i + 1, sString, SearchString, vbTextCompare)
      c.Offset(0, 1) = WorksheetFunction.Replace(sString, i, "19", " 2020")
   End If
 Next c
End Sub

Body:
I still think you could do this easier:

'
'
'
 LastCell = Range("C" & Rows.Count).End(xlUp).Row
With Range("C3:C" & lastCell).Offset(0, 1)
    .FormulaR1C1 = "=TEXT(RC[-1],""yyyy-mm-dd hh:mm AM/PM"")"
    .Value = .Value
End With

NOTE: yyyy-mm-dd hh:mm AM/PM will work according to your regional settings, so if Excel is not in english, translate it. My excel is spanish, and this code would not work for me unless I type aaaa-mm-dd hh:mm AM/PM instead of yyyy-mm-dd hh:mm AM/PM

Convert all dates at once.

Range


问:
Implement ImagePicker to Set Image From Gallery or Camera?
I created a class ImagePickerManager using following Code:

```<code>    import Foundation
    import UIKit
    class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var picker = UIImagePickerController();
        var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
        var viewController: UIViewController?
        var pickImageCallback : ((UIImage) -> ())?;

        override init(){
            super.init()
        }

        func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {
            pickImageCallback = callback;
            self.viewController = viewController;

            let cameraAction = UIAlertAction(title: "Camera", style: .default){
                UIAlertAction in
                self.openCamera()
            }
            let galleryAction = UIAlertAction(title: "Gallery", style: .default){
                UIAlertAction in
                self.openGallery()
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){
                UIAlertAction in
            }

            // Add the actions
            picker.delegate = self
            alert.addAction(cameraAction)
            alert.addAction(galleryAction)
            alert.addAction(cancelAction)
            alert.popoverPresentationController?.sourceView = self.viewController!.view
            viewController.present(alert, animated: true, completion: nil)
        }
        func openCamera(){
            alert.dismiss(animated: true, completion: nil)
            if(UIImagePickerController .isSourceTypeAvailable(.camera)){
                picker.sourceType = .camera
                self.viewController!.present(picker, animated: true, completion: nil)
            } else {
                let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil,
cancelButtonTitle:"OK", otherButtonTitles:"")
                alertWarning.show()
            }
        }
        func openGallery(){
            alert.dismiss(animated: true, completion: nil)
            picker.sourceType = .photoLibrary
            self.viewController!.present(picker, animated: true, completion: nil)
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true, completion: nil)
        }
        //for swift below 4.2
        //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String
: Any]) {
        //    picker.dismiss(animated: true, completion: nil)
        //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //    pickImageCallback?(image)
        //}

        // For Swift 4.2+
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:
[UIImagePickerController.InfoKey : Any]) {
            picker.dismiss(animated: true, completion: nil)
            guard let image = info[.originalImage] as? UIImage else {
                fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
            }
            pickImageCallback?(image)
        }
    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) {
        }
    }'
</code>```

答:
```<code>@IBAction func btnProfileImgClicked(_ sender: UIButton) {
        ImagePickerManager().pickImage(self){ image in
            self.btnProfile.setImage(image, for: .normal)
            self.imgP = image
        }
}
</code>```

Body:
I created a class ImagePickerManager using following Code:

    import Foundation
    import UIKit
    class ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

        var picker = UIImagePickerController();
        var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
        var viewController: UIViewController?
        var pickImageCallback : ((UIImage) -> ())?;

        override init(){
            super.init()
        }

        func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {
            pickImageCallback = callback;
            self.viewController = viewController;

            let cameraAction = UIAlertAction(title: "Camera", style: .default){
                UIAlertAction in
                self.openCamera()
            }
            let galleryAction = UIAlertAction(title: "Gallery", style: .default){
                UIAlertAction in
                self.openGallery()
            }
            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){
                UIAlertAction in
            }

            // Add the actions
            picker.delegate = self
            alert.addAction(cameraAction)
            alert.addAction(galleryAction)
            alert.addAction(cancelAction)
            alert.popoverPresentationController?.sourceView = self.viewController!.view
            viewController.present(alert, animated: true, completion: nil)
        }
        func openCamera(){
            alert.dismiss(animated: true, completion: nil)
            if(UIImagePickerController .isSourceTypeAvailable(.camera)){
                picker.sourceType = .camera
                self.viewController!.present(picker, animated: true, completion: nil)
            } else {
                let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil,
cancelButtonTitle:"OK", otherButtonTitles:"")
                alertWarning.show()
            }
        }
        func openGallery(){
            alert.dismiss(animated: true, completion: nil)
            picker.sourceType = .photoLibrary
            self.viewController!.present(picker, animated: true, completion: nil)
        }

        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true, completion: nil)
        }
        //for swift below 4.2
        //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String
: Any]) {
        //    picker.dismiss(animated: true, completion: nil)
        //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //    pickImageCallback?(image)
        //}

        // For Swift 4.2+
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:
[UIImagePickerController.InfoKey : Any]) {
            picker.dismiss(animated: true, completion: nil)
            guard let image = info[.originalImage] as? UIImage else {
                fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
            }
            pickImageCallback?(image)
        }
    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) {
        }
    }'


问:
How to check if an object is a Vue component?
Is there a reliable way to check if an object is a Vue.js component?</p>

答:
The simplest way to check if a an object is a Vue component, as in 2020l, is probably the _isVue property of the component, which, in case of the given object being a Vue.js component, exists as key-value at the root of the object and returns true.

```<code>Const isVueComponent = [VUE_COMPONENT_OBJECT]._isVue
</code>```

Body:
The simplest way to check if a an object is a Vue component, as in 2020l, is probably the _isVue property of the component, which, in case of the given object being a Vue.js component, exists as key-value at the root of the object and returns true.

Const isVueComponent = [VUE_COMPONENT_OBJECT]._isVue


问:
jquery- stop auto refreshing onClick
I'm running a jquery autorefresh code which get active soon the page is loaded. I've set timeinterval to 1second.which means that for every 1 sec page gets refreshed.
I want to know is there any method to stop auto refreshing onclick?

Code:

```<code>$(document).ready(function(){
    setTimeout("dummy()",500);
});
function dummy(){
    setTimeout("checkalerts()",50);
}
function checkalerts() {
    var url="includes/adda/hangouts/display_all_hangouts.php";
    $.post(url,function(data){
        $("#print").html(data).show();
        setTimeout("dummy()",1000);
    });
}
</code>```

答:
After further reviewing your code, I'm a little baffled. I don't understand why you need so many timers. You essentially have one timer that calls dummy() every half a second, and that function creates a new timer (every half a second, a new timer is created) every 50 millisecond.

And when posting you're calling dummy again every second. This is some serious WTF code!

Anyway, updated code, this snippet should work

```<code>var timer;

$( document ).ready(function(){
    timer = setTimeout( "checkalerts()", 1000);
});

function checkalerts()
{
    var url="includes/adda/hangouts/display_all_hangouts.php";

    $.post( url, function( data )
    {
        $("#print").html(data).show();
    });
}

$( '#my-button' ).click( function()
{
    clearTimeout( timer );
});
</code>```

Title: jquery- stop auto refreshing onClick

Body:
I'm running a jquery autorefresh code which get active soon the page is loaded. I've set timeinterval to 1second.which means that for every 1 sec page gets refreshed.
I want to know is there any method to stop auto refreshing onclick?

Code:

$(document).ready(function(){
    setTimeout("dummy()",500);
});
function dummy(){
    setTimeout("checkalerts()",50);
}
function checkalerts() {
    var url="includes/adda/hangouts/display_all_hangouts.php";
    $.post(url,function(data){
        $("#print").html(data).show();
        setTimeout("dummy()",1000);
    });
}

Body:
After further reviewing your code, I'm a little baffled. I don't understand why you need so many timers. You essentially have one timer that calls dummy() every half a second, and that function creates a new timer (every half a second, a new timer is created) every 50 millisecond.

And when posting you're calling dummy again every second. This is some serious WTF code!

Anyway, updated code, this snippet should work

var timer;

$( document ).ready(function(){
    timer = setTimeout( "checkalerts()", 1000);
});

function checkalerts()
{
    var url="includes/adda/hangouts/display_all_hangouts.php";

    $.post( url, function( data )
    {
        $("#print").html(data).show();
    });
}

$( '#my-button' ).click( function()
{
    clearTimeout( timer );
});


问:
Saving fragment state in Activity
I'm getting the below error when I try to save the state of my fragments in my main activity:

```<code>java.lang.IllegalStateException: Fragment MarketviewFragment{c5e0f0d} is not currently in the FragmentManager
    at androidx.fragment.app.FragmentManagerImpl.putFragment(FragmentManager.java:923)
    at com.shoob.capstone.android.crypfolio.MainActivity.onSaveInstanceState(MainActivity.java:308)
    at android.app.Activity.performSaveInstanceState(Activity.java:1608)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1443)
    at android.app.ActivityThread.callActivityOnSaveInstanceState(ActivityThread.java:5038)
    at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4372)
    at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4986)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4922)
    at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6986)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
</code>```

In my main activity, I have 4 possible fragments that get displayed only one at a time.  I keep a reference to the fragments in the main activity and display them as needed:

```<code>private MarketviewFragment marketviewFragment;
private WatchlistFragment watchlistFragment;
private PortfolioFragment portfolioFragment;
private DetailsFragment detailsFragment;
</code>```

I set the current displayed fragment with the below code (only one fragment displayed at a time):

```<code>//fragment is an instance of one of the 4 types of fragments above
private void setFragment(Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();

    if (fm.findFragmentById(R.id.frag_main) != null) {
        fm.beginTransaction()
                .replace(R.id.frag_main, fragment)
                .commit();
    } else {
        fm.beginTransaction()
                .add(R.id.frag_main, fragment)
                .commit();
    }
}
</code>```

This is how I set each fragment (one example, same for the other types):

```<code>private void setPortfolioFragment() {
    if (portfolioFragment == null) {
        portfolioFragment = PortfolioFragment.newInstance();
    }
    setFragment(portfolioFragment);
}
</code>```

Now for my question.  How do I save the state of all these fragments?  I want to save them all in a Bundle so I can restore them on recreation of the Main Activity (like on rotation).

The way I'm doing it now doesn't seem to work, what is the correct way to do this?

Saving state:

```<code>@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (marketviewFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_MARKETVIEW_FRAGMENT, marketviewFragment);
    }
    if (watchlistFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_WATCHLIST_FRAGMENT, watchlistFragment);
    }
    if (portfolioFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_PORTFOLIO_FRAGMENT, portfolioFragment);
    }
    if (detailsFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_DETAILS_FRAGMENT, detailsFragment);
    }

}
</code>```

Restoring state:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        marketviewFragment = (MarketviewFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_MARKETVIEW_FRAGMENT);
        watchlistFragment = (WatchlistFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_WATCHLIST_FRAGMENT);
        portfolioFragment = (PortfolioFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_PORTFOLIO_FRAGMENT);
        detailsFragment = (DetailsFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_DETAILS_FRAGMENT);

    }
}
</code>```

答:
Your activity should not be handling saving state for each fragment. You should let each fragment handle storing its own state by overriding onSaveInstanceState() in each fragment class:

```<code>@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    // save fragment state here
}
</code>```

Also, keeping hard references to all your fragments in your activity is not a great idea.

Edit: After looking at your question again, I understand more what you're trying to do. You're trying to save and restore the actual instances of your fragments. The Android OS will do this automatically for you and you're trying to get in the way of this process. Again, the fact that you are storing the fragments as instance variables is part of the problem and is making you do something you normally wouldn't need to do.

Title: Saving fragment state in Activity

Body:
I'm getting the below error when I try to save the state of my fragments in my main activity:

java.lang.IllegalStateException: Fragment MarketviewFragment{c5e0f0d} is not currently in the FragmentManager
    at androidx.fragment.app.FragmentManagerImpl.putFragment(FragmentManager.java:923)
    at com.shoob.capstone.android.crypfolio.MainActivity.onSaveInstanceState(MainActivity.java:308)
    at android.app.Activity.performSaveInstanceState(Activity.java:1608)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1443)
    at android.app.ActivityThread.callActivityOnSaveInstanceState(ActivityThread.java:5038)
    at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4372)
    at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:4986)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4922)
    at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:69)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6986)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

In my main activity, I have 4 possible fragments that get displayed only one at a time.  I keep a reference to the fragments in the main activity and display them as needed:

private MarketviewFragment marketviewFragment;
private WatchlistFragment watchlistFragment;
private PortfolioFragment portfolioFragment;
private DetailsFragment detailsFragment;

I set the current displayed fragment with the below code (only one fragment displayed at a time):

//fragment is an instance of one of the 4 types of fragments above
private void setFragment(Fragment fragment) {
    FragmentManager fm = getSupportFragmentManager();

    if (fm.findFragmentById(R.id.frag_main) != null) {
        fm.beginTransaction()
                .replace(R.id.frag_main, fragment)
                .commit();
    } else {
        fm.beginTransaction()
                .add(R.id.frag_main, fragment)
                .commit();
    }
}

This is how I set each fragment (one example, same for the other types):

private void setPortfolioFragment() {
    if (portfolioFragment == null) {
        portfolioFragment = PortfolioFragment.newInstance();
    }
    setFragment(portfolioFragment);
}

Now for my question.  How do I save the state of all these fragments?  I want to save them all in a Bundle so I can restore them on recreation of the Main Activity (like on rotation).

The way I'm doing it now doesn't seem to work, what is the correct way to do this?

Saving state:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    if (marketviewFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_MARKETVIEW_FRAGMENT, marketviewFragment);
    }
    if (watchlistFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_WATCHLIST_FRAGMENT, watchlistFragment);
    }
    if (portfolioFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_PORTFOLIO_FRAGMENT, portfolioFragment);
    }
    if (detailsFragment != null) {
        getSupportFragmentManager().putFragment(outState, KEY_BUNDLE_DETAILS_FRAGMENT, detailsFragment);
    }

}

Restoring state:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        marketviewFragment = (MarketviewFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_MARKETVIEW_FRAGMENT);
        watchlistFragment = (WatchlistFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_WATCHLIST_FRAGMENT);
        portfolioFragment = (PortfolioFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_PORTFOLIO_FRAGMENT);
        detailsFragment = (DetailsFragment)getSupportFragmentManager().getFragment(savedInstanceState, KEY_BUNDLE_DETAILS_FRAGMENT);

    }
}

Body:
Your activity should not be handling saving state for each fragment. You should let each fragment handle storing its own state by overriding onSaveInstanceState() in each fragment class:

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    // save fragment state here
}

Also, keeping hard references to all your fragments in your activity is not a great idea.

Edit: After looking at your question again, I understand more what you're trying to do. You're trying to save and restore the actual instances of your fragments. The Android OS will do this automatically for you and you're trying to get in the way of this process. Again, the fact that you are storing the fragments as instance variables is part of the problem and is making you do something you normally wouldn't need to do.


问:
Swift tabBar doesnt refresh view when navigated to
So im new to the Swift and Xcode world.

The expected usage:

The app has an tabBar with 3 tabs.

I go to the tab "search" and i click a row in a tableView, this writes an Int to a userDefault

I now click on the home tab that reloads and reads that userDefault and gets data from an api again like the first start of the app

The problem:

When i start the app it gets the key from userDefaults and read the data but when i then go to the search tab and change the userDefaults and click the home tab again its just going back on the backstack so no reload.

Ive searched and searched and only found weird solutions with notifications and stuff...

How do i call like the code below that reloads a fragment in android in Swift?

```<code>FragmantClass rSum = new FragmantClass(); getSupportFragmentManager().beginTransaction().remove(rSum).commit();
</code>```

Yes i want the whole viewDidLoad() to run again...

答: The view controllers are not being recreated, so viewDidLoad will not run again. Look at viewWillAppear instead.

Body:
So im new to the Swift and Xcode world.

The expected usage:

The app has an tabBar with 3 tabs.

I go to the tab "search" and i click a row in a tableView, this writes an Int to a userDefault

I now click on the home tab that reloads and reads that userDefault and gets data from an api again like the first start of the app

The problem:

When i start the app it gets the key from userDefaults and read the data but when i then go to the search tab and change the userDefaults and click the home tab again its just going back on the backstack so no reload.

Ive searched and searched and only found weird solutions with notifications and stuff...

How do i call like the code below that reloads a fragment in android in Swift?

FragmantClass rSum = new FragmantClass(); getSupportFragmentManager().beginTransaction().remove(rSum).commit();

Yes i want the whole viewDidLoad() to run again...


问:
Select columns using pandas dataframe.query()
The documentation on dataframe.query() is very terse http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html .    I was also unable to find examples of projections by web search.

So I tried simply providing the column names: that gave a syntax error. Likewise for typing select and then the column names.  So .. how to do this?

答:
How about

df_new = df.query('col1==1 & col2=="x" ')[['col1', 'col3']]
```

Would filter rows where col1 equals 1 and col2 equals "X" and return only columns 1 and 3.

but you would need to filter for rows otherwise it doesn't work.

for filtering columns only better use .loc or .iloc

Body:
How about

df_new = df.query('col1==1 & col2=="x" ')[['col1', 'col3']]

Would filter rows where col1 equals 1 and col2 equals "X" and return only columns 1 and 3.

but you would need to filter for rows otherwise it doesn't work.

for filtering columns only better use .loc or .iloc


问:
GGPlot within loop in Flexdashboard
Using Flexdashboard, I want to put some text and a plot inside a loop - it should loop through variables, and I don't know how many there will be. But the plots appear side by side, not down the page, and the text is lost.

Example:

```<code>---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(ggplot2)

data(cars)

for(var in names(cars)) {
 htmltools::tags$p(var)
 print(ggplot(cars, aes_string(var)) +
   geom_histogram())
}

```
</code>```

Gives me:

If I don't loop, and instead just run the code for each variable:

```<code>---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(ggplot2)
data(cars)

var <- "speed"
  htmltools::tags$p(var)
  print(ggplot(cars, aes_string(var)) +
   geom_histogram())

var <- "dist"
  htmltools::tags$p(var)
  print(ggplot(cars, aes_string(var)) +
   geom_histogram())

```
</code>```

I get what I expect:

Which is what I expect.

is there a way to get (something like) the second page, using the first code.

答:
I'm having trouble getting the look to be exactly the same, but if you're ok with the name of the variable being indented along with the chart, this can work:

```<code>---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(tidyverse)
data(cars)

car_plots <- names(cars) %>%
  set_names() %>%
  map(~ ggplot(cars, aes(!! sym(.x))) + geom_histogram() + ggtitle(.x))

walk(names(cars), ~ print(car_plots[[.x]]))
```
</code>```

In this case, the variable name is showing as a title to the chart, which is why it ends up being indented.

Title: GGPlot within loop in Flexdashboard

Body:
Using Flexdashboard, I want to put some text and a plot inside a loop - it should loop through variables, and I don't know how many there will be. But the plots appear side by side, not down the page, and the text is lost.

Example:

---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(ggplot2)

data(cars)

for(var in names(cars)) {
 htmltools::tags$p(var)
 print(ggplot(cars, aes_string(var)) +
   geom_histogram())
}

```

Gives me:

If I don't loop, and instead just run the code for each variable:

---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(ggplot2)
data(cars)

var <- "speed"
  htmltools::tags$p(var)
  print(ggplot(cars, aes_string(var)) +
   geom_histogram())

var <- "dist"
  htmltools::tags$p(var)
  print(ggplot(cars, aes_string(var)) +
   geom_histogram())

```

I get what I expect:

Which is what I expect.

is there a way to get (something like) the second page, using the first code.

Body:
I'm having trouble getting the look to be exactly the same, but if you're ok with the name of the variable being indented along with the chart, this can work:

---
title: "Cars Test"
output: flexdashboard::flex_dashboard
---

```{r}
library(tidyverse)
data(cars)

car_plots <- names(cars) %>%
  set_names() %>%
  map(~ ggplot(cars, aes(!! sym(.x))) + geom_histogram() + ggtitle(.x))

walk(names(cars), ~ print(car_plots[[.x]]))
```

In this case, the variable name is showing as a title to the chart, which is why it ends up being indented.


问:
Justify last line of UITextView
I am working on a book like project. Where there are list of paragraphs on multiple pages that you can scroll through. I create separate UITextView for every single page and set it as justified to create that book-like experience. Unfortunately last line of UITextView is not justified (because I am using new UITextView for every single page). So in fact UITextView is behaving correctly. But as my paragraph continue on next page, I would like it to express that by justifying the last line. I am using UITextView to provide user an option to select and copy parts of text.

This is how it looks now.

This is what is expected.

答:
I added a category on UITextView to perform the calculations we need for the last line. This can either be separate .h/.m files or placed at the top of the .m file where you need to use it. Note that this operates on the attributedText and textContainer properties. The attributedText property is set (as of iOS7) even when you only set the text property on the UITextView. The textContainer property defines the size of the area where the UITextView will render its text, but you may need this be a little different, if you are using constrains to lay out the UITextView.

```<code>@interface UITextView (LastLineRange)

- (NSRange) lastLineRange;

@end

@implementation UITextView (LastLineRange)

- (NSRange)lastLineRange
{
    // calculate the bounds for the text rendered in the UITextView
    CGSize textSize = [self.attributedText boundingRectWithSize:self.textContainer.size
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                        context:nil].size;

    // we care about the last line, so get the start and end points along the bottom of the bounds
    UITextPosition* start = [self characterRangeAtPoint:CGPointMake(0, textSize.height)].start;
    UITextPosition* end = [self characterRangeAtPoint:CGPointMake(textSize.width, textSize.height)].end;

    // turn the text positions into indices we can make a range with
    NSInteger startLoc = [self offsetFromPosition:self.beginningOfDocument
                                       toPosition:start];

    // this should not be 'endOfDocument', but the end that we calculated above,
    // since this represents the end of the visible text
    NSInteger endLoc = [self offsetFromPosition:start
                                     toPosition:end];

    return NSMakeRange(startLoc, endLoc);
}

@end
</code>```

This is how I used the category to get the last line and apply a right-aligned paragraph style to it. I've tried to add comments to make it clear what is happening. I just roughed out the actual UITextView, so it's not as pretty as your example, but should give you the idea.

```<code>- (void)viewDidLoad
{
    [super viewDidLoad];

    UIFont* font = [UIFont systemFontOfSize:20.0];

    // used for the main, left-aligned text
    NSMutableParagraphStyle* pStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    pStyle.lineBreakMode = NSLineBreakByWordWrapping;
    pStyle.alignment = NSTextAlignmentLeft;

    // used for the last line, which will be right-aligned
    NSMutableParagraphStyle* lastStyle = [pStyle mutableCopy];
    lastStyle.alignment = NSTextAlignmentRight;

    CGRect pageFrame = CGRectMake(self.view.frame.size.width / 4.0,
                                  50.0,
                                  self.view.frame.size.width / 2.0,
                                  self.view.frame.size.height / 2.0);

    UITextView* page = [[UITextView alloc] initWithFrame:pageFrame
                                            textContainer:nil];

    page.scrollEnabled = false;
    page.editable = false;

    // attributes for main text
    NSDictionary* lAlignedAttrs = @{
                                    NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : pStyle
                                   };

    // attributes for the last line of text
    NSDictionary* rAlignedAttrs = @{
                                    NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : lastStyle,
                                    // only added this to highlight the last line changes
                                    NSForegroundColorAttributeName : [UIColor redColor]
                                   };

    // needs to be mutable, so we can set attributes at certain ranges
    NSMutableAttributedString* text1 = [[NSMutableAttributedString alloc] initWithString:text
                                                                    attributes:lAlignedAttrs];

    // now set the attributed text as content for the UITextView, since
    // we will use the category for finding the last line
    page.attributedText = text1;

    // here, we ensure that the last line will be considered a new paragraph
    // so the paragraph style changes we make will take effect
    NSInteger insertionIndex = page.lastLineRange.location;
    if ( [text1.string characterAtIndex:insertionIndex] != '\n' )
    {
        [text1 insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]
                              atIndex:insertionIndex];
    }

    // apply right-aligned paragraph style over the range of the last line
    [text1 setAttributes:rAlignedAttrs
                   range:page.lastLineRange];

    // we have altered the attributed text, so need to set the new text
    // as the content for the UITextView
    page.attributedText = text1;

    [self.view addSubview:page];
}

@end
</code>```

Here is what I achieved with this:

Title: Justify last line of UITextView

Body:
I added a category on UITextView to perform the calculations we need for the last line. This can either be separate .h/.m files or placed at the top of the .m file where you need to use it. Note that this operates on the attributedText and textContainer properties. The attributedText property is set (as of iOS7) even when you only set the text property on the UITextView. The textContainer property defines the size of the area where the UITextView will render its text, but you may need this be a little different, if you are using constrains to lay out the UITextView.

@interface UITextView (LastLineRange)

- (NSRange) lastLineRange;

@end

@implementation UITextView (LastLineRange)

- (NSRange)lastLineRange
{
    // calculate the bounds for the text rendered in the UITextView
    CGSize textSize = [self.attributedText boundingRectWithSize:self.textContainer.size
                                                        options:NSStringDrawingUsesLineFragmentOrigin
                                                        context:nil].size;

    // we care about the last line, so get the start and end points along the bottom of the bounds
    UITextPosition* start = [self characterRangeAtPoint:CGPointMake(0, textSize.height)].start;
    UITextPosition* end = [self characterRangeAtPoint:CGPointMake(textSize.width, textSize.height)].end;

    // turn the text positions into indices we can make a range with
    NSInteger startLoc = [self offsetFromPosition:self.beginningOfDocument
                                       toPosition:start];

    // this should not be 'endOfDocument', but the end that we calculated above,
    // since this represents the end of the visible text
    NSInteger endLoc = [self offsetFromPosition:start
                                     toPosition:end];

    return NSMakeRange(startLoc, endLoc);
}

@end

This is how I used the category to get the last line and apply a right-aligned paragraph style to it. I've tried to add comments to make it clear what is happening. I just roughed out the actual UITextView, so it's not as pretty as your example, but should give you the idea.

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIFont* font = [UIFont systemFontOfSize:20.0];

    // used for the main, left-aligned text
    NSMutableParagraphStyle* pStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    pStyle.lineBreakMode = NSLineBreakByWordWrapping;
    pStyle.alignment = NSTextAlignmentLeft;

    // used for the last line, which will be right-aligned
    NSMutableParagraphStyle* lastStyle = [pStyle mutableCopy];
    lastStyle.alignment = NSTextAlignmentRight;

    CGRect pageFrame = CGRectMake(self.view.frame.size.width / 4.0,
                                  50.0,
                                  self.view.frame.size.width / 2.0,
                                  self.view.frame.size.height / 2.0);

    UITextView* page = [[UITextView alloc] initWithFrame:pageFrame
                                            textContainer:nil];

    page.scrollEnabled = false;
    page.editable = false;

    // attributes for main text
    NSDictionary* lAlignedAttrs = @{
                                    NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : pStyle
                                   };

    // attributes for the last line of text
    NSDictionary* rAlignedAttrs = @{
                                    NSFontAttributeName : font,
                                    NSParagraphStyleAttributeName : lastStyle,
                                    // only added this to highlight the last line changes
                                    NSForegroundColorAttributeName : [UIColor redColor]
                                   };

    // needs to be mutable, so we can set attributes at certain ranges
    NSMutableAttributedString* text1 = [[NSMutableAttributedString alloc] initWithString:text
                                                                    attributes:lAlignedAttrs];

    // now set the attributed text as content for the UITextView, since
    // we will use the category for finding the last line
    page.attributedText = text1;

    // here, we ensure that the last line will be considered a new paragraph
    // so the paragraph style changes we make will take effect
    NSInteger insertionIndex = page.lastLineRange.location;
    if ( [text1.string characterAtIndex:insertionIndex] != '\n' )
    {
        [text1 insertAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]
                              atIndex:insertionIndex];
    }

    // apply right-aligned paragraph style over the range of the last line
    [text1 setAttributes:rAlignedAttrs
                   range:page.lastLineRange];

    // we have altered the attributed text, so need to set the new text
    // as the content for the UITextView
    page.attributedText = text1;

    [self.view addSubview:page];
}

@end

Here is what I achieved with this:


问:
Daily Coding Problem 260 : Reconstruct a jumbled array - Intuition?
I'm going through the question below.

The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order is an array representing whether each number is larger or smaller than the last. Given this information, reconstruct an array that is consistent with it.

For example, given [None, +, +, -, +], you could return [1, 2, 3, 0, 4].

I went through the solution on this post but still unable to understand it as to why this solution works. I don't think I would be able to come up with the solution if I had this in front of me during an interview. Can anyone explain the intuition behind it? Thanks in advance!

答:
It works because all changes are sequential, either adding one or subtracting one, starting both the increasing and the decreasing sequences from the same place. That guarantees we have a sequential list overall. For example, given the arbitrary

```<code>[None, +, -, +, +, -]
</code>```

turned vertically for convenience, we can see

```<code>None   0
+      1
-     -1
+      2
+      3
-     -2
</code>```

Now just shift them up by two (to account for -2):

```<code>2 3 1 4 5 0
 + - + + -
</code>```

Body:
It works because all changes are sequential, either adding one or subtracting one, starting both the increasing and the decreasing sequences from the same place. That guarantees we have a sequential list overall. For example, given the arbitrary

[None, +, -, +, +, -]

turned vertically for convenience, we can see

None   0
+      1
-     -1
+      2
+      3
-     -2

Now just shift them up by two (to account for -2):

2 3 1 4 5 0
 + - + + -


问:
Javascript append is adding child to parent via console but not showing in dev tools elements or on page
I am attempting to add a child node to an existing container.  Looking at dev tools, after clicking the button, I see that in my console log my parent container (parking_container) indeed has the div appended.

In the elements section of dev tools, the parking container does not show the appended div.  On the page itself, I do not see the appended div.  If I edit the html in elements directly and add the div as shown in the console log, it does show as expected.

EDIT: Context:  I am attempting a hot-fix on a website built in drupal.  The page section I am trying to attempt to append the node to is a custom module.  I am able to add an "html" module, which is where I am inserting the code below.  Again, the button shows and runs the script as expected, and it appears that the append is adding the div via the console log, but not showing on the page.  I understand that the problem may be something a) out of my control with this method or b) not solvable without giving context that I can't give.

Just hoping someone maybe has an idea.  Thanks.

```<code><button onclick="addElement()">Click me</button>

<script>
function addElement (){
  var pContainer = document.getElementById("parking_container");

  var newDiv = document.createElement("div");
      newDiv.innerHTML="Temporary Filler";

  pContainer.appendChild(newDiv);

  console.log(pContainer);
 }

</script>
</code>```

答:
try this </p>

```<code>var node = document.createTextNode("Temporary Filler");
newDiv.appendChild(node);
pContainer.appendChild(newDiv);
</code>```

<p>instead of </p>

```<code>newDiv.innerHTML="Temporary Filler";
</code>```

Body:
I am attempting to add a child node to an existing container.  Looking at dev tools, after clicking the button, I see that in my console log my parent container (parking_container) indeed has the div appended.

In the elements section of dev tools, the parking container does not show the appended div.  On the page itself, I do not see the appended div.  If I edit the html in elements directly and add the div as shown in the console log, it does show as expected.

EDIT: Context:  I am attempting a hot-fix on a website built in drupal.  The page section I am trying to attempt to append the node to is a custom module.  I am able to add an "html" module, which is where I am inserting the code below.  Again, the button shows and runs the script as expected, and it appears that the append is adding the div via the console log, but not showing on the page.  I understand that the problem may be something a) out of my control with this method or b) not solvable without giving context that I can't give.

Just hoping someone maybe has an idea.  Thanks.

<button onclick="addElement()">Click me</button>

Body:
try this

var node = document.createTextNode("Temporary Filler");
newDiv.appendChild(node);
pContainer.appendChild(newDiv);

instead of

newDiv.innerHTML="Temporary Filler";


问:
If Statement not working, when using elif
No Clue why this doesn't work.

```<code>Script Below:
def dirpricker():
    prompt = '<>'
    print("Where do you want to install Deploy in the Current Dir?  (Y/n ")
    Userinput = input(prompt)
    print(Userinput)
    if Userinput == "Y" or "y":
        print("Not Ready Yet!")
    elif Userinput == "N" or "n":
        print("No")
    else:
        print("Please Choose either Yes Or No.")
        print(prompt)
dirpricker()
</code>```

thanks, Matt

Output: Not Ready, Even after inputting No.

答:
Small mistake in your file, for every condition in the if you have to define what should be true to proceed so instead of if Userinput == "Y" or "y": change it to: if Userinput == "Y" or Userinput == "y":, or "y" is like asking if "y" which will evaluate to true.

```<code>def dirpricker():
    prompt = '>'
    print("Where do you want to install Deploy in the Current Dir?  (Y/n ")
    Userinput = input(prompt)
    print(Userinput)

    if Userinput == "Y" or Userinput == "y":
        print("Not Ready Yet!")
    elif Userinput == "N" or Userinput == "n":
        print("No")
    else:
        print("Please Choose either Yes Or No.")
        print(prompt)

dirpricker()
</code>```

Body:
No Clue why this doesn't work.

Script Below:
def dirpricker():
    prompt = '<>'
    print("Where do you want to install Deploy in the Current Dir?  (Y/n ")
    Userinput = input(prompt)
    print(Userinput)
    if Userinput == "Y" or "y":
        print("Not Ready Yet!")
    elif Userinput == "N" or "n":
        print("No")
    else:
        print("Please Choose either Yes Or No.")
        print(prompt)
dirpricker()

thanks, Matt

Output: Not Ready, Even after inputting No.

Body:
Small mistake in your file, for every condition in the if you have to define what should be true to proceed so instead of if Userinput == "Y" or "y": change it to: if Userinput == "Y" or Userinput == "y":, or "y" is like asking if "y" which will evaluate to true.

def dirpricker():
    prompt = '>'
    print("Where do you want to install Deploy in the Current Dir?  (Y/n ")
    Userinput = input(prompt)
    print(Userinput)

    if Userinput == "Y" or Userinput == "y":
        print("Not Ready Yet!")
    elif Userinput == "N" or Userinput == "n":
        print("No")
    else:
        print("Please Choose either Yes Or No.")
        print(prompt)

dirpricker()


问:
C# Active Directory Login
Ive written a program to manage our Active Directory in c# - windows forms.

I'm stuck at the following point:
For managing the Active Directory and Commiting Changes, you have to run the program as administrator.
I want to include a login button to verify as admin and be able to commit changes without starting the .exe directly as admin.

Something like:

```<code>group.Properties["member"].Add(distinguishedName);
group.CommitChanges();
</code>```

If this is not possible I was thinking it could maybe be possible to restart the program when the user has typed in his credentials and putting in the admin-credentials directly into the username and password field as parameters.

Is that possible? If not, do you have other suggestions?

答:
Your program does not need to run as admin. You just need to connect to Active Directory using credentials that have permissions to update that group. By default, it will use the credentials that the program is running with. So it sounds like whichever credentials you are using to run as admin also has permissions to update that group.

If it helps you, you can use alternate credentials for connecting to AD by using the constructor for DirectoryEntry that accepts credentials. For example:

var group = new DirectoryEntry($"LDAP://{groupDn}", "username", "password");
group.Properties["member"].Add(distinguishedName);
group.CommitChanges();
```

Title: C# Active Directory Login

Body:
Ive written a program to manage our Active Directory in c# - windows forms.

I'm stuck at the following point:
For managing the Active Directory and Commiting Changes, you have to run the program as administrator.
I want to include a login button to verify as admin and be able to commit changes without starting the .exe directly as admin.

Something like:

group.Properties["member"].Add(distinguishedName);
group.CommitChanges();

If this is not possible I was thinking it could maybe be possible to restart the program when the user has typed in his credentials and putting in the admin-credentials directly into the username and password field as parameters.

Is that possible? If not, do you have other suggestions?


问:
Restoring TextView's Text with android:freezestext not working
I am trying to retain the text of TextView on screen rotation. Following is a snippet of my code.

SampleActivity.java

```<code>public class SampleActivity extends AppCompatActivity {
    private static TextView mIntView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_layout.xml);

        mIntView = (TextView) findViewById(R.id.int_view);

        if (savedInstanceState == null) {
            mIntView.setText(String.valueOf(1));
        }

        Log.d("Test", mIntView.getText().toString());
    }

}
</code>```

sample_layout.xml

```<code><TextView
     android:id="@+id/int_view"
     android:background="@drawable/circle"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="top|center"
     android:layout_marginRight="20dp"
     android:gravity="center_vertical|center_horizontal"
     android:textSize="25sp"
     android:clickable="true"
     android:textColor="@color/blue"
     android:freezesText="true"/>
</code>```

android:freezesText="true" attribute should preserve the state of TextView. But still when I rotate my screen the Integer "1" is gone from the TextView. Am I doing something wrong here ?

答:
I am bit delayed in answering this, but I hope this helps.

No need of savedInstanceState when you are setting the textview property as android:freezesText="true". It is as simple as that.

Just create a landscape variation of the sample_layout.xml file. Make sure, the android:freezesText is set to true in both the portrait and landscape variation of the sample_layout.xml.

Body:
I am trying to retain the text of TextView on screen rotation. Following is a snippet of my code.

SampleActivity.java

public class SampleActivity extends AppCompatActivity {
    private static TextView mIntView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sample_layout.xml);

        mIntView = (TextView) findViewById(R.id.int_view);

        if (savedInstanceState == null) {
            mIntView.setText(String.valueOf(1));
        }

        Log.d("Test", mIntView.getText().toString());
    }

}

sample_layout.xml

<TextView
     android:id="@+id/int_view"
     android:background="@drawable/circle"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_gravity="top|center"
     android:layout_marginRight="20dp"
     android:gravity="center_vertical|center_horizontal"
     android:textSize="25sp"
     android:clickable="true"
     android:textColor="@color/blue"
     android:freezesText="true"/>

android:freezesText="true" attribute should preserve the state of TextView. But still when I rotate my screen the Integer "1" is gone from the TextView. Am I doing something wrong here ?


问:
Can I send array of parameter to store procedure?
I have User table, it has UserId uniqueidentifier, Name varchar and IsActive bit.

I want to create store procedure to set IsActive to false for many user, for example, if I want to deactive 2 users, I want to send Guid of those users to store procedure (prefer as array). I want to know how can I do it?

P.S. I'm working on Microsoft SQL Azure

答: Along the same lines than Elian, take a look at XML parameters. Generally speaking you should have a cleaner/safer implementation using xml than parsing a list of strings.  Click here for a code example </p>

OwnerDisplayName: Anonymous


问:
VBA and IE8 - enter value and search
I have an intranet based website at work that I'd like to input SKU's and scrape the data that comes up into an excel sheet using VBA and IE8. Currently waiting on Access license approvals and approval to gain access to our IBM as400 server. IE8 does not support getElementsByName, and the search bar has no ID, so most of the examples I've found online aren't relevant.

```<code>Sub scraper()

Dim item As Long

item = "10011" 'this will eventually be placed in a loop for multiple searches

Set objIE = CreateObject("InternetExplorer.Application")
  objIE.Visible = True
' navigate and download the web page
  objIE.Navigate "http://**********.aspx"
Do While objIE.ReadyState <> 4 Or objIE.Busy
    DoEvents
Loop

objIE.document.getElementsByName("input").Value = item

End Sub
</code>```

Here's a photo of the inspected element tree. As you can see, there is only a name (input) and class (st1), no ID. How can i get the search data input into this area? I am stuck with IE8, although I do have access to Chrome as well...

答:
Changing objIE.document.getElementsByName("input").Value = item to objIE.document.getElementsByTagName("input")(0).Value = item ended up resolving this issue.

getElementsByTagName is supported by IE8.

Title: VBA and IE8 - enter value and search

Body:
I have an intranet based website at work that I'd like to input SKU's and scrape the data that comes up into an excel sheet using VBA and IE8. Currently waiting on Access license approvals and approval to gain access to our IBM as400 server. IE8 does not support getElementsByName, and the search bar has no ID, so most of the examples I've found online aren't relevant.

Sub scraper()

Dim item As Long

item = "10011" 'this will eventually be placed in a loop for multiple searches

Set objIE = CreateObject("InternetExplorer.Application")
  objIE.Visible = True
' navigate and download the web page
  objIE.Navigate "http://**********.aspx"
Do While objIE.ReadyState <> 4 Or objIE.Busy
    DoEvents
Loop

objIE.document.getElementsByName("input").Value = item

End Sub

Here's a photo of the inspected element tree. As you can see, there is only a name (input) and class (st1), no ID. How can i get the search data input into this area? I am stuck with IE8, although I do have access to Chrome as well...


问:
For loop doesn’t accept array. How to work around for this Amibroker code?
The following code will calculate the high-low range in percentage of certain bars when an event occurred and calculate the average of the high-low range.

```<code>event_up = get_event_up();
event_down = get_event_low();
num_events_in_range = get_num_events_in_range();

sum_pct_updown_dist = 0;
for (i=1;i<num_events_in_range; i++) //for cannot accept array type
{
    event_up_high_i = ValueWhen(event_up, High, i);
    event_down_low_i = ValueWhen(event_down, Low, i);
    pct_updown_dist_i = (event_up_high_i-event_down_low_i)/event_up_high_i*100;
    sum_pct_updown_dist = sum_pct_updown_dist + pct_updown_dist_i;
}
avg_pct_updown_dist = sum_pct_updown_dist/num_events_in_range;
</code>```

The code doesn't work in Amibroker because of this line for (i=1;i<num_events_in_range; i++) which violates Amibroker syntax. For loop does not accept array type. num_events_in_range is an array.

How can this code be modified to work around this problem?

答:
The syntax of for loop is

```<code>for ( init-expression ; cond-expression ; loop-expression )
</code>```

In your code i < num_events_in_range is an invalid condition, since i is an integer and num_events_in_range is an array.

In place of num_events_in_range, use the length of num_events_in_range

Body:
The following code will calculate the high-low range in percentage of certain bars when an event occurred and calculate the average of the high-low range.

event_up = get_event_up();
event_down = get_event_low();
num_events_in_range = get_num_events_in_range();

sum_pct_updown_dist = 0;
for (i=1;i<num_events_in_range; i++) //for cannot accept array type
{
    event_up_high_i = ValueWhen(event_up, High, i);
    event_down_low_i = ValueWhen(event_down, Low, i);
    pct_updown_dist_i = (event_up_high_i-event_down_low_i)/event_up_high_i*100;
    sum_pct_updown_dist = sum_pct_updown_dist + pct_updown_dist_i;
}
avg_pct_updown_dist = sum_pct_updown_dist/num_events_in_range;

The code doesn't work in Amibroker because of this line for (i=1;i<num_events_in_range; i++) which violates Amibroker syntax. For loop does not accept array type. num_events_in_range is an array.

How can this code be modified to work around this problem?

Body:
The syntax of for loop is

for ( init-expression ; cond-expression ; loop-expression )

In your code i < num_events_in_range is an invalid condition, since i is an integer and num_events_in_range is an array.

In place of num_events_in_range, use the length of num_events_in_range


问:
how to send binary file to server with Cypress using request
I need before the test to upload directly from Cypress API to server an excel-table (without any input[type="file"], just plain file submission) and then it will be requested back with some other data and used by the test.

So i tried in different ways to make Cypress to use the file by fixture, readfile with different data-encodings, but neigther was working.

As soon as file is received successfully some rest of the code must run.

```<code>  before(() => {

  cy.fixture("data/catalog.xlsx", "binary")
    .then(content => {

      cy.wrap(Cypress.Blob.binaryStringToBlob(content, "utf8"))
        .then(blob => {

          const file = new File([blob], "catalog-table", {type: "utf8"});

          cy.request("POST", "http://localhost:28080/app/admin/api/catalog/import/xlsx", file)
            .then(res => {debugger; expect(res.ok).to.be.true})
            .as("fileSend");

          cy.wait("@fileSend")
            .then(() => {some other code to be executed});
        })
    })
})
</code>```

also tried to add few more headers lines

```<code>          cy.request({
            method: "POST",
            url: "http://localhost:28080/app/admin/api/catalog/import/xlsx",
            headers: {
              contentType: false,
              processData: false,
            },
            cache: 'no-cache',
            body: file
          })
</code>```

答:
I found out that neither cy.request nor Cypress.$.ajax werent working at all with files.

My problem was hidden in two issues:

the way of handling the file before submission;

faulty native cypress request method

Here are some details to take into account:

Take a file to dispatch it from the local:

```<code>before(() => { //run before the tests
  cy.fixture(filePath, "binary")
</code>```

Prepare it as a binary one:

```<code>    .then(Cypress.Blob.binaryStringToBlob)
    .then(blob => {
      const file = new File([blob], fileName);
</code>```

Make it a part of data submitting:

```<code>      let data = new FormData();

      //settings for host server
      data.append("catalogName", fileName);
      data.append("xlsxFile", file);
</code>```

Request-workaround in spite of cy.request nor Cypress.$.ajax:

```<code>      cy.form_request(url, data)
        .then(response => { some other code})
    })
})

</code>```

Because
Cypress.$.ajax was illegaly invoked but in the web its difficult to find out the source of problem.
cypress crashed on formData preparation;
I found that out from Network section in Devtool there was no any XHR request because it failed from the start.

I found third way by native XHR workaround
and there is the custom request cy.form_reques placed in commands.js:

```<code>
Cypress.Commands.add("form_request", (url, formData) => {
  return cy
    .server()
    .route("POST", url)
    .as("formRequest")
    .window()
    .then(win => {
      var xhr = new win.XMLHttpRequest();
      xhr.open("POST", url);
      xhr.send(formData);
    })
    .wait("@formRequest");
});

</code>```

Body:
I need before the test to upload directly from Cypress API to server an excel-table (without any input[type="file"], just plain file submission) and then it will be requested back with some other data and used by the test.

So i tried in different ways to make Cypress to use the file by fixture, readfile with different data-encodings, but neigther was working.

As soon as file is received successfully some rest of the code must run.

  before(() => {

  cy.fixture("data/catalog.xlsx", "binary")
    .then(content => {

      cy.wrap(Cypress.Blob.binaryStringToBlob(content, "utf8"))
        .then(blob => {

          const file = new File([blob], "catalog-table", {type: "utf8"});

          cy.request("POST", "http://localhost:28080/app/admin/api/catalog/import/xlsx", file)
            .then(res => {debugger; expect(res.ok).to.be.true})
            .as("fileSend");

          cy.wait("@fileSend")
            .then(() => {some other code to be executed});
        })
    })
})

also tried to add few more headers lines

          cy.request({
            method: "POST",
            url: "http://localhost:28080/app/admin/api/catalog/import/xlsx",
            headers: {
              contentType: false,
              processData: false,
            },
            cache: 'no-cache',
            body: file
          })

Body:
I found out that neither cy.request nor Cypress.$.ajax werent working at all with files.

My problem was hidden in two issues:

the way of handling the file before submission;

faulty native cypress request method

Here are some details to take into account:

Take a file to dispatch it from the local:

before(() => { //run before the tests
  cy.fixture(filePath, "binary")

Prepare it as a binary one:

    .then(Cypress.Blob.binaryStringToBlob)
    .then(blob => {
      const file = new File([blob], fileName);

Make it a part of data submitting:

      let data = new FormData();

      //settings for host server
      data.append("catalogName", fileName);
      data.append("xlsxFile", file);

Request-workaround in spite of cy.request nor Cypress.$.ajax:

      cy.form_request(url, data)
        .then(response => { some other code})
    })
})

Because
Cypress.$.ajax was illegaly invoked but in the web its difficult to find out the source of problem.
cypress crashed on formData preparation;
I found that out from Network section in Devtool there was no any XHR request because it failed from the start.

I found third way by native XHR workaround
and there is the custom request cy.form_reques placed in commands.js:

Cypress.Commands.add("form_request", (url, formData) => {
  return cy
    .server()
    .route("POST", url)
    .as("formRequest")
    .window()
    .then(win => {
      var xhr = new win.XMLHttpRequest();
      xhr.open("POST", url);
      xhr.send(formData);
    })
    .wait("@formRequest");
});


问:
How to apply $arrayToObject to the array output by $push in mongodb aggreggation
The code below (with the two lines commented out)

```<code>    myComments.aggregate(
        { $sort: { createdAt: -1 } },
        { $match: query },
        { $group: {
            _id: {
                activity: "$activity",
                writer: "$writer"
            },
            summary: {
                // $arrayToObject: {
                    $push: {
                        "k": "$userID",
                        "v": "$commentText",
                    }
                // }
            },
        } },
        { $project: { _id: 0 } },
        ( err, data ) => {
            console.log( JSON.stringify( data || [] ) );
        }
    )
</code>```

produces "summary" arrays as expected:

```<code>    [ {"summary":[ {"k":183044,"v":"adf"}, {"k":184817,"v":"be"}, {"k":187252,"v":"c"} ]},
      {"summary":[ {"k":183044,"v":"146"}, {"k":184817,"v":"25"}, {"k":187252,"v":"3"} ]} ]
</code>```

However, when I remove the comments and allow $arrayToObject to act upon those arrays the output data is undefined.

Am I using one or both of these commands incorrectly? Is it incorrect to nest them this way?

答:
In $group when each documents is being iterated respective below object will be pushed into summary field, So at the end of group stage summary would be an array of objects.

```<code>{
    "k": "$userID",
    "v": "$commentText"
}
</code>```

Additionally you can not apply $arrayToObject to summary cause your keys (k's) are not strings. So if $userID is not a string you need to convert it to string in group stage. Try as below :

```<code>   myComments.aggregate(
    { $sort: { createdAt: -1 } },
    { $match: query },
    {
        $group: {
            _id: {
                activity: "$activity",
                writer: "$writer"
            },
            summary: {
                $push: {
                    "k": { $toString: "$userID" },
                    "v": "$commentText",
                }
            },
        }
    },
    {
        $project: {
            _id: 0,
            summary: {
                $arrayToObject: "$summary"
            }
        }
    },
    (err, data) => {
        console.log(JSON.stringify(data || []));
    }
)
</code>```

Body:
The code below (with the two lines commented out)

    myComments.aggregate(
        { $sort: { createdAt: -1 } },
        { $match: query },
        { $group: {
            _id: {
                activity: "$activity",
                writer: "$writer"
            },
            summary: {
                // $arrayToObject: {
                    $push: {
                        "k": "$userID",
                        "v": "$commentText",
                    }
                // }
            },
        } },
        { $project: { _id: 0 } },
        ( err, data ) => {
            console.log( JSON.stringify( data || [] ) );
        }
    )

produces "summary" arrays as expected:

    [ {"summary":[ {"k":183044,"v":"adf"}, {"k":184817,"v":"be"}, {"k":187252,"v":"c"} ]},
      {"summary":[ {"k":183044,"v":"146"}, {"k":184817,"v":"25"}, {"k":187252,"v":"3"} ]} ]

However, when I remove the comments and allow $arrayToObject to act upon those arrays the output data is undefined.

Am I using one or both of these commands incorrectly? Is it incorrect to nest them this way?

Body:
In $group when each documents is being iterated respective below object will be pushed into summary field, So at the end of group stage summary would be an array of objects.

{
    "k": "$userID",
    "v": "$commentText"
}

Additionally you can not apply $arrayToObject to summary cause your keys (k's) are not strings. So if $userID is not a string you need to convert it to string in group stage. Try as below :

   myComments.aggregate(
    { $sort: { createdAt: -1 } },
    { $match: query },
    {
        $group: {
            _id: {
                activity: "$activity",
                writer: "$writer"
            },
            summary: {
                $push: {
                    "k": { $toString: "$userID" },
                    "v": "$commentText",
                }
            },
        }
    },
    {
        $project: {
            _id: 0,
            summary: {
                $arrayToObject: "$summary"
            }
        }
    },
    (err, data) => {
        console.log(JSON.stringify(data || []));
    }
)