问:
SQL db inserting to table works with 1 item but not multiple
I have a sql database Im trying to write too via a python script. That python script parses DC switches then spits it out into results_list. I then filter for the below 2 items description and interface.

The front end of the app is a flask page I have buttons assigned that will query x cabinet and do all the above. I want to send all of below data to a sql database. I also want to prevent duplicates / update table if item has changed.

right now when i run the query if the working params gets passed on to sql and the rest of the flask script is processed. When I pass params with multiple items I get the following error.

```<code>OperationalError: (1241, 'Operand should contain 1 column(s)')
</code>```

working params:

```<code>params = ([('TECH2_5750',)], [('Gi1/0/7',)], [(u'10.210.44.5',)])
</code>```

not working params:

```<code>params = ([('TECH2_5252',), ('TECH2_5261',), ('TECH2_5857',), ('TECH2_5278',), ('TECH2_5855',), ('TECH2_5207',), ('TECH2_6539',), ('TECH2_6363',), ('TECH2_5253',), ('TECH2_5030',), ('TECH2_6575',), ('TECH2_5839',), ('TECH2_6953',), ('TECH2_6133',), ('TECH2_5046',), ('TECH2_6152',), ('TECH2_5267',), ('TECH2_5847',), ('TECH2_5748',), ('TECH2_5104',), ('TECH2_5649',), ('TECH2_5103',)], [('Gi2/0/11',), ('Gi1/0/11',), ('Gi2/0/7',), ('Gi3/0/27',), ('Gi1/0/7',), ('Gi2/0/9',), ('Gi3/0/7',), ('Gi2/0/27',), ('Gi1/0/29',), ('Gi3/0/25',), ('Gi2/0/25',), ('Gi2/0/29',), ('Gi2/0/31',), ('Gi1/0/31',), ('Gi2/0/5',), ('Gi1/0/25',), ('Gi1/0/5',), ('Gi3/0/5',), ('Gi1/0/9',), ('Gi1/0/35',), ('Gi1/0/27',), ('Gi1/0/33',)], [(u'10.210.45.5',)])
</code>```

code:

```<code>local1 = []
device1 = []
items = len(filtered_interface)
for item in range(0, items):
    t = filtered_tech[item].split(' ')
    hostname = t[1]
    device1.append((hostname,))
    t = filtered_interface[item].split(' ')
    interfacelocal = t[1]
    local1.append((interfacelocal,))
cab1 = []
cab1.append((cab,))
params = (device1,  local1, cab1,)
connection1 = MySQLdb.connect(user="user", passwd="password", db="db",host="127.0.0.1")
mycursor = connection1.cursor()
sql = """
        INSERT INTO devices (hostname, localint, cab) VALUES (%s, %s, %s)"""
mycursor.execute(sql, params)
        connection1.commit()
</code>```

答:
mycursur.execute() requires that params have the same number of elements as you have placeholders in the query. Since you have 3 placeholders, params must have 3 elements.

If you want to insert multiple rows, you need to use mycursor.executemany. This will execute the query repeatedly for each element of the parameter sequence. params should then be a 2-dimensional sequence, with each element of the top-level sequence being a sequence of 3 parameters to fill in the placeholders.

```<code>params = [('TECH2_5252', 'Gi1/0/7', u'10.210.44.5'),
          ('TECH2_5261', 'Gi1/0/11', u'10.210.45.5'),
          ('TECH2_5857', 'Gi2/0/7', u'10.210.45.5'),
          ...]
sql = """
        INSERT INTO devices (hostname, localint, cab) VALUES (%s, %s, %s)"""
mycursor.executemany(sql, params)
</code>```

Body:
I have a sql database Im trying to write too via a python script. That python script parses DC switches then spits it out into results_list. I then filter for the below 2 items description and interface.

The front end of the app is a flask page I have buttons assigned that will query x cabinet and do all the above. I want to send all of below data to a sql database. I also want to prevent duplicates / update table if item has changed.

right now when i run the query if the working params gets passed on to sql and the rest of the flask script is processed. When I pass params with multiple items I get the following error.

OperationalError: (1241, 'Operand should contain 1 column(s)')

working params:

params = ([('TECH2_5750',)], [('Gi1/0/7',)], [(u'10.210.44.5',)])

not working params:

params = ([('TECH2_5252',), ('TECH2_5261',), ('TECH2_5857',), ('TECH2_5278',), ('TECH2_5855',), ('TECH2_5207',), ('TECH2_6539',), ('TECH2_6363',), ('TECH2_5253',), ('TECH2_5030',), ('TECH2_6575',), ('TECH2_5839',), ('TECH2_6953',), ('TECH2_6133',), ('TECH2_5046',), ('TECH2_6152',), ('TECH2_5267',), ('TECH2_5847',), ('TECH2_5748',), ('TECH2_5104',), ('TECH2_5649',), ('TECH2_5103',)], [('Gi2/0/11',), ('Gi1/0/11',), ('Gi2/0/7',), ('Gi3/0/27',), ('Gi1/0/7',), ('Gi2/0/9',), ('Gi3/0/7',), ('Gi2/0/27',), ('Gi1/0/29',), ('Gi3/0/25',), ('Gi2/0/25',), ('Gi2/0/29',), ('Gi2/0/31',), ('Gi1/0/31',), ('Gi2/0/5',), ('Gi1/0/25',), ('Gi1/0/5',), ('Gi3/0/5',), ('Gi1/0/9',), ('Gi1/0/35',), ('Gi1/0/27',), ('Gi1/0/33',)], [(u'10.210.45.5',)])

code:

local1 = []
device1 = []
items = len(filtered_interface)
for item in range(0, items):
    t = filtered_tech[item].split(' ')
    hostname = t[1]
    device1.append((hostname,))
    t = filtered_interface[item].split(' ')
    interfacelocal = t[1]
    local1.append((interfacelocal,))
cab1 = []
cab1.append((cab,))
params = (device1,  local1, cab1,)
connection1 = MySQLdb.connect(user="user", passwd="password", db="db",host="127.0.0.1")
mycursor = connection1.cursor()
sql = """
        INSERT INTO devices (hostname, localint, cab) VALUES (%s, %s, %s)"""
mycursor.execute(sql, params)
        connection1.commit()

Body:
mycursur.execute() requires that params have the same number of elements as you have placeholders in the query. Since you have 3 placeholders, params must have 3 elements.

If you want to insert multiple rows, you need to use mycursor.executemany. This will execute the query repeatedly for each element of the parameter sequence. params should then be a 2-dimensional sequence, with each element of the top-level sequence being a sequence of 3 parameters to fill in the placeholders.

params = [('TECH2_5252', 'Gi1/0/7', u'10.210.44.5'),
          ('TECH2_5261', 'Gi1/0/11', u'10.210.45.5'),
          ('TECH2_5857', 'Gi2/0/7', u'10.210.45.5'),
          ...]
sql = """
        INSERT INTO devices (hostname, localint, cab) VALUES (%s, %s, %s)"""
mycursor.executemany(sql, params)


来源: stackexchange

问:
Reading through a .m File and Python keeps reading a character in the .m File as a line?
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.

I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.

# Example of what I did
with open('MyFile.m') as f:
   for line in f:
       text = f.readline()
       if text.startswith('%'):
         continue
       else:
          my_string = text.strip("=")
          my_list.append(my_string)
```

This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e  S t r i n g"

答:
Without your input file I've had to make some guesses here

Input file:

```<code>%
The
%
String
%
</code>```

Solution:

my_list = []

with open('MyFile.m') as f:
    for line in f:
        if not line.startswith('%'):
            my_list.append(line.strip("=").strip())
print(' '.join(my_list))
```

The readLine() call was unnecessary as the for loop already gets you the line.  The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.

I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.

# Example of what I did
with open('MyFile.m') as f:
   for line in f:
       text = f.readline()
       if text.startswith('%'):
         continue
       else:
          my_string = text.strip("=")
          my_list.append(my_string)

This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e  S t r i n g"

Body:
Without your input file I've had to make some guesses here

Input file:

%
The
%
String
%

Solution:

my_list = []

with open('MyFile.m') as f:
    for line in f:
        if not line.startswith('%'):
            my_list.append(line.strip("=").strip())
print(' '.join(my_list))

The readLine() call was unnecessary as the for loop already gets you the line.  The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.


问:
How can connect jupyter notebook in desired environment in Anaconda in server computer by using Putty?
I'm trying to connect to server computer from my desktop computer via Putty to use capacity and source of powerful server remotely via Tunneling and applying localhost address and port. The problem is I have successfully installed Anaconda in server and created environment([CR7]) and installed Keras and tensorflow and already tested them via python but when I call jupyter notebook and import tensorflow in my environment [CR7], I face ModuleNotFoundError: No module named 'tensorflow' which is ridiculous as following picture:

Why it's the case and how can I fix that?

Should I install TF nad Keras in root environment in Anaconda?

Any help would be greatly appreciated.

Update I've just installed TF & Keras in root in server and it works but still I can't access my already built environment via Jupyter notebook and run TF & Keras!!! I don;t want to work in root environments due to some consequences!

BTW Python version is 3.7.1

答:
I could find a solution based on Anaconda documentation Using Jupyter Notebook extensions. Basically I should have installed Notebook Conda Kernels (nb_conda_kernels) in my desired environment via:

```<code>conda install nb_conda_kernels
</code>```

After installing, there would be the option in Jupyter Notebook to Change kernel from the 'Kernel' menu in the Jupyter Notebook.

Body:
I could find a solution based on Anaconda documentation Using Jupyter Notebook extensions. Basically I should have installed Notebook Conda Kernels (nb_conda_kernels) in my desired environment via:

conda install nb_conda_kernels

After installing, there would be the option in Jupyter Notebook to Change kernel from the 'Kernel' menu in the Jupyter Notebook.


问:
Loop over pages when requesting API
I request an API and I have to loop over the different 'pages' (nearly 5000 'pages') using start_page and count attributes. I would like to store fetched data into a mySQL database.
How I can do to loop over the 'pages' and store data into the database synchronously?
I'm a newbie with promises and other asynchronous techniques.

Thanks for your help!

The loop looks like:

```<code>for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {
    listOfPromises.push(
        new Promise(function(resolve, reject) {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) {
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else {
                    //On résoud la promesse :
                    resolve(data);
                }
            })
        }));
    }
</code>```

And I created a recursive function like that:

```<code>// Recursive function
function handlePromises(promises, cb, data = {
    dataSchedules: new Array(),
    dataExceptions: new Array()
}) {
    // If there is no more promises
    // break the function
    if (promises.length == 0) {
        cb(data);
    } else {
        // Shift remove the first elemn in array
        // and remove it from the array
        let promise = promises.shift()
        promise.then((promiseData) => {
            // do what you want with data
            return handlePromises(promises, cb, data)
        }).catch(function(err) {
            console.error(err);
        });
    }
}
</code>```

答:
Here's what I think you need:</p>

```<code>async function init() {
    for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {

        await new Promise((resolve, reject) => {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) {
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else {
                    //On résoud la promesse :
                    resolve(data);
                }
        })
    });
}

init();
</code>```

Title: Loop over pages when requesting API

Body:
I request an API and I have to loop over the different 'pages' (nearly 5000 'pages') using start_page and count attributes. I would like to store fetched data into a mySQL database.
How I can do to loop over the 'pages' and store data into the database synchronously?
I'm a newbie with promises and other asynchronous techniques.

Thanks for your help!

The loop looks like:

for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {
    listOfPromises.push(
        new Promise(function(resolve, reject) {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) {
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else {
                    //On résoud la promesse :
                    resolve(data);
                }
            })
        }));
    }

And I created a recursive function like that:

// Recursive function
function handlePromises(promises, cb, data = {
    dataSchedules: new Array(),
    dataExceptions: new Array()
}) {
    // If there is no more promises
    // break the function
    if (promises.length == 0) {
        cb(data);
    } else {
        // Shift remove the first elemn in array
        // and remove it from the array
        let promise = promises.shift()
        promise.then((promiseData) => {
            // do what you want with data
            return handlePromises(promises, cb, data)
        }).catch(function(err) {
            console.error(err);
        });
    }
}

Body:
Here's what I think you need:

async function init() {
    for (var i = Math.floor(body.pagination.total_result / body.pagination.items_per_page); i >= 0; i--) {

        await new Promise((resolve, reject) => {
            request(schedulesURL + 'start_page=' + i + '&count=' + _COUNT, { json: true }, function(err, response, body) {
                if (err) {
                    console.log('Erreur et i = ' + i);
                    reject(err);
                } else {
                    //On résoud la promesse :
                    resolve(data);
                }
        })
    });
}

init();


问:
Use jQuery to detect which font Browser selected
The font-family attribute in CSS accepts lists of font names to provide backup options in case the user does not have the 1st, 2nd, etc. font on their computer. Is there a way using jQuery to detect which of the fonts listed the browser is using?

For example if my CSS is:

```<code>body {
    font-family: 'SuperCoolFont', 'Foo', 'Bar', 'Arial', 'Comic Sans MS';
}
</code>```

I want to know which option the browser settled on. If the user didn't have the first 3 options I want the resulting answer to be 'Arial'. Is this possible with jQuery?

A simple test of $('body').css('font-family'); returns the whole list of fonts.

答:
It's a little complicated to do.

DetectFont accepts an element to check and uses getComputedStyle to get a list of the fonts. It compares the widths of the fonts in getComputedStyle using canvas and the measureText method to figure out which one is actually being rendered on the client.

Body:
The font-family attribute in CSS accepts lists of font names to provide backup options in case the user does not have the 1st, 2nd, etc. font on their computer. Is there a way using jQuery to detect which of the fonts listed the browser is using?

For example if my CSS is:

body {
    font-family: 'SuperCoolFont', 'Foo', 'Bar', 'Arial', 'Comic Sans MS';
}

I want to know which option the browser settled on. If the user didn't have the first 3 options I want the resulting answer to be 'Arial'. Is this possible with jQuery?

A simple test of $('body').css('font-family'); returns the whole list of fonts.


问:
Disable tooltip hint in Visual Studio Code
How can I disable the default tooltip hint message in VSCode? It's annoying sometimes.

答: Simple way that no one here has mentioned: Code → Preferences → Settings. Search for "hover". Uncheck the checkbox where it says "Editor > Hover: Enabled".</p>


问:
C# Custom Marshaling - ICustomMarshaler implementation not supplied with zero IntPtr values
I've implemented a very simple custom marshaler for an API:

Custom Marshaler:

```<code>  private sealed class JuliaWrapperMarshaller : ICustomMarshaler
  {
      object ICustomMarshaler.MarshalNativeToManaged(IntPtr pNativeData) => (JuliaWrapper)pNativeData;

     [other methods removed]
  }
</code>```

API:

```<code>    [DllImport(@"libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(JuliaWrapperMarshaller))]
    public static extern JuliaWrapper jl_eval_string(string str);
</code>```

And this works fine when the jl_eval_string method returns a non-zero IntPtr. I can convert it to my return object JuliaWrapper and all is well.

The problem comes when I execute jl_eval_string with invalid parameters and it returns a zero IntPtr.

I want to handle this in my JuliaWrapper object and automatically call 'get last error'. However I don't get the chance to, because the ICustomMarshaler.MarshalNativeToManaged method is never invoked when the jl_eval_string method returns 0x0000

Is there a way of telling the custom marshaler to provide me with 0 IntPtr values?

Are there any hacks to work around this?

Is there a better way of working?

答:
Based on Hans' comment, this isn't possible.

In order to achieve similar functionality, I created public/private shadow functions which return my wrapper class.

The implicit operator function receives the IntPtr which is 0 or otherwise, and calls the constructor of my wrapper class, which I then have code in to handle calling 'GetLastError' if the IntPtr is 0.

Body:
I've implemented a very simple custom marshaler for an API:

Custom Marshaler:

  private sealed class JuliaWrapperMarshaller : ICustomMarshaler
  {
      object ICustomMarshaler.MarshalNativeToManaged(IntPtr pNativeData) => (JuliaWrapper)pNativeData;

     [other methods removed]
  }

API:

    [DllImport(@"libjulia.dll", CallingConvention = CallingConvention.Cdecl)]
    [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(JuliaWrapperMarshaller))]
    public static extern JuliaWrapper jl_eval_string(string str);

And this works fine when the jl_eval_string method returns a non-zero IntPtr. I can convert it to my return object JuliaWrapper and all is well.

The problem comes when I execute jl_eval_string with invalid parameters and it returns a zero IntPtr.

I want to handle this in my JuliaWrapper object and automatically call 'get last error'. However I don't get the chance to, because the ICustomMarshaler.MarshalNativeToManaged method is never invoked when the jl_eval_string method returns 0x0000

Is there a way of telling the custom marshaler to provide me with 0 IntPtr values?

Are there any hacks to work around this?

Is there a better way of working?


问:
Effective-Date-Range One-Hot-Encode groupby
Starting with this sample data...

```<code>import pandas as pd

start_data = {"person_id": [1, 1, 1, 1, 2], "nid": [1, 2, 3, 4, 1],
              "beg": ["Jan 1 2018", "Jan 5 2018", "Jan 10 2018", "Feb 5 2018", "Jan 25 2018"],
              "end": ["Feb 1 2018", "Mar 4 2018", "", "Oct 18 2018", "Nov 10 2018"]}
df = pd.DataFrame(start_data)
df["beg"] = pd.to_datetime(df["beg"])
df["end"] = pd.to_datetime(df["end"])
</code>```

Starting point:

```<code>   person_id  nid        beg        end
0          1    1 2018-01-01 2018-02-01
1          1    2 2018-01-05 2018-03-04
2          1    3 2018-01-10        NaT
3          1    4 2018-02-05 2018-10-18
4          2    1 2018-01-25 2018-11-10
</code>```

Goal output:

```<code>person_id date       1 2 3 4
        1 2018-01-01 1 0 0 0
        1 2018-01-05 1 1 0 0
        1 2018-01-10 1 1 1 0
        1 2018-02-01 0 1 1 0
        1 2018-02-05 0 1 1 1
        1 2018-03-04 0 0 1 1
        1 2018-10-18 0 0 1 0
        2 2018-01-25 1 0 0 0
        2 2018-11-10 0 0 0 0
</code>```

I am trying to tie all active nid's to the associated person_id This will then be joined to another dataframe based on the latest date less than a dated activity column. And finally this will be part of the input into a predictive model.

Doing something like pd.get_dummies(df["nid"]) get's this output:

```<code>   1  2  3  4
0  1  0  0  0
1  0  1  0  0
2  0  0  1  0
3  0  0  0  1
4  1  0  0  0
</code>```

So this needs to be moved to a different index representing effective date, grouped by person_id, and then aggregated to match the goal output.

Special bonus to anyone who can come up with an approach that would properly leverage Dask. This is what we are using for other parts of the pipeline due to the scalability. This may be a pipe-dream but I thought I would send it out to see what comes back.

答:
The question is hard , I can only think of numpy broadcast to speed up the for loop

```<code>s=df.set_index('person_id')[['beg','end']].stack()
l=[]
for x , y in df.groupby('person_id'):
    y=y.fillna({'end':y.end.max()})
    s1=y.beg.values
    s2=y.end.values
    t=s.loc[x].values
    l.append(pd.DataFrame(((s1-t[:,None]).astype(float)<=0)&((s2-t[:,None]).astype(float)>0),columns=y.nid,index=s.loc[[x]].index))
s=pd.concat([s,pd.concat(l).fillna(0).astype(int)],1).reset_index(level=0).sort_values(['person_id',0])
s
Out[401]:
     person_id          0  1  2  3  4
beg          1 2018-01-01  1  0  0  0
beg          1 2018-01-05  1  1  0  0
beg          1 2018-01-10  1  1  1  0
end          1 2018-02-01  0  1  1  0
beg          1 2018-02-05  0  1  1  1
end          1 2018-03-04  0  0  1  1
end          1 2018-10-18  0  0  0  0
beg          2 2018-01-25  1  0  0  0
end          2 2018-11-10  0  0  0  0
</code>```

Body:
Starting with this sample data...

import pandas as pd

start_data = {"person_id": [1, 1, 1, 1, 2], "nid": [1, 2, 3, 4, 1],
              "beg": ["Jan 1 2018", "Jan 5 2018", "Jan 10 2018", "Feb 5 2018", "Jan 25 2018"],
              "end": ["Feb 1 2018", "Mar 4 2018", "", "Oct 18 2018", "Nov 10 2018"]}
df = pd.DataFrame(start_data)
df["beg"] = pd.to_datetime(df["beg"])
df["end"] = pd.to_datetime(df["end"])

Starting point:

   person_id  nid        beg        end
0          1    1 2018-01-01 2018-02-01
1          1    2 2018-01-05 2018-03-04
2          1    3 2018-01-10        NaT
3          1    4 2018-02-05 2018-10-18
4          2    1 2018-01-25 2018-11-10

Goal output:

person_id date       1 2 3 4
        1 2018-01-01 1 0 0 0
        1 2018-01-05 1 1 0 0
        1 2018-01-10 1 1 1 0
        1 2018-02-01 0 1 1 0
        1 2018-02-05 0 1 1 1
        1 2018-03-04 0 0 1 1
        1 2018-10-18 0 0 1 0
        2 2018-01-25 1 0 0 0
        2 2018-11-10 0 0 0 0

I am trying to tie all active nid's to the associated person_id This will then be joined to another dataframe based on the latest date less than a dated activity column. And finally this will be part of the input into a predictive model.

Doing something like pd.get_dummies(df["nid"]) get's this output:

   1  2  3  4
0  1  0  0  0
1  0  1  0  0
2  0  0  1  0
3  0  0  0  1
4  1  0  0  0

So this needs to be moved to a different index representing effective date, grouped by person_id, and then aggregated to match the goal output.

Special bonus to anyone who can come up with an approach that would properly leverage Dask. This is what we are using for other parts of the pipeline due to the scalability. This may be a pipe-dream but I thought I would send it out to see what comes back.

Body:
The question is hard , I can only think of numpy broadcast to speed up the for loop

s=df.set_index('person_id')[['beg','end']].stack()
l=[]
for x , y in df.groupby('person_id'):
    y=y.fillna({'end':y.end.max()})
    s1=y.beg.values
    s2=y.end.values
    t=s.loc[x].values
    l.append(pd.DataFrame(((s1-t[:,None]).astype(float)<=0)&((s2-t[:,None]).astype(float)>0),columns=y.nid,index=s.loc[[x]].index))
s=pd.concat([s,pd.concat(l).fillna(0).astype(int)],1).reset_index(level=0).sort_values(['person_id',0])
s
Out[401]:
     person_id          0  1  2  3  4
beg          1 2018-01-01  1  0  0  0
beg          1 2018-01-05  1  1  0  0
beg          1 2018-01-10  1  1  1  0
end          1 2018-02-01  0  1  1  0
beg          1 2018-02-05  0  1  1  1
end          1 2018-03-04  0  0  1  1
end          1 2018-10-18  0  0  0  0
beg          2 2018-01-25  1  0  0  0
end          2 2018-11-10  0  0  0  0


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
If you're dealing with long strings that are likely to have duplicate letters, stopping ASAP may help.

```<code>INPUT: for (@input) {
   my %seen;
   while (/(.)/sg) {
      next INPUT if $seen{$1}++;
   }
   say;
}
</code>```

I'd go with the simplest solution unless the performance is found to be really unacceptable.

```<code>my @output = grep !/(.).*?\1/s, @input;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
If you're dealing with long strings that are likely to have duplicate letters, stopping ASAP may help.

INPUT: for (@input) {
   my %seen;
   while (/(.)/sg) {
      next INPUT if $seen{$1}++;
   }
   say;
}

I'd go with the simplest solution unless the performance is found to be really unacceptable.

my @output = grep !/(.).*?\1/s, @input;


问:
Datatables- Omitting Certain Rows from Footer Calculation
I have a table which calculates the total of all the rows in the footer.  My question is, can I omit certain rows based on criteria.

For instance, I have season stats for a baseball player with their career total calculated at in the footer.
This particular player played for two different teams in the 2018 season. This is indicated by TOTAL in the league LEAGUE field in which I have added his combined stats for each team that season.
So looking at the table heres what you should notice:

He had 1 HITS for the 2017 season for STL

He had 15 HITS for the 2018 season (5 for LAD and 10 for BAL)

Given this, you should see that his career total in the footer was not counted correctly. He should have 16 career his, not 31.
So in order to straighten this out I would like to omit all rows tha have a TOTAL in the LEAGUE column from being counted in the footer total. How would I do this? Any help here would be greatly appreciated. Thanks.

```<code>YEAR    Name        AGE  TEAM   LEAGUE   HITS
2017    John Smith  25   STL    NL       1
2018    John Smith  26          TOTAL    15
2018    John Smith  26   LAD    NL       5
2018    John Smith  26   BAL    AL       10
        Career Total                     31
</code>```

Here's my code

```<code><div align="center">
         <table id = 'battingtbl' class="display compact nowrap">
        <thead>
            <tr>
                <th>YEAR</th>
                <th>NAME</th>
                <th>AGE</th>
                <th>TEAM</th>
                <th>LEAGUE</th>
                <th>HITS</th>
            </tr>
        </thead>
        <tbody>
        {% for stat in playerdata.bbhittingstatsmstr_set.all %}
            <tr>
                <td>{{ stat.year }}</td>
                <td>{{ stat.name }}</td>
                <td>{{ stat.age }}</td>
                <td>{{ stat.team }}</td>
                <td>{{ stat.league }}</td>
                <td>{{ stat.hits }}</td>
            </tr>
        {% endfor %}
        </tbody>
             <tfoot>
                    <tr>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                        <th></th>
                    </tr>
             </tfoot>
        </table>
                <script>
                    $(document).ready(function () {
                        $('#battingtbl').DataTable({
                            "searching": true,
                            "pageLength": 40,
                            "scrollX": true,
                            "paging": false,
                            "info": false,
                            drawCallback: () => {
                                const table = $('#battingtbl').DataTable();
                                const tableData = table.rows({
                                        search: 'applied'
                                    }).data().toArray();
                                const totals = tableData.reduce((total, rowData) => {
                                        total[0] += parseFloat(rowData[5]);          <!--HITS -->
                                        return total;
                                    }, [0,0,0,0,0,0]);
                                $(table.column(5).footer()).text(totals[0]);         <!--HITS -->
                            }
                        })
                    });
                </script>
</code>```

答:
Add an if statement into the tableData.reduce call:

```<code>const totals = tableData.reduce((total, rowData) => {
    if (rowData[4] !== 'TOTAL') {
        total[0] += parseFloat(rowData[5]);          <!--HITS -->
    }
    return total;
}, [0,0,0,0,0,0]);

$(table.column(5).footer()).text(totals[0]);         <!--HITS -->
</code>```

Also you can simplify the initial value of the reduce call (the 3rd argument):

```<code>// totals is a Number not an Array
const totals = tableData.reduce((total, rowData) => {
    if (rowData[4] !== 'TOTAL') {
        total += parseFloat(rowData[5]);          <!--HITS -->
    }
    return total;
}, 0);

$(table.column(5).footer()).text(totals);
</code>```

Body:
I have a table which calculates the total of all the rows in the footer.  My question is, can I omit certain rows based on criteria.

For instance, I have season stats for a baseball player with their career total calculated at in the footer.
This particular player played for two different teams in the 2018 season. This is indicated by TOTAL in the league LEAGUE field in which I have added his combined stats for each team that season.
So looking at the table heres what you should notice:

He had 1 HITS for the 2017 season for STL

He had 15 HITS for the 2018 season (5 for LAD and 10 for BAL)

Given this, you should see that his career total in the footer was not counted correctly. He should have 16 career his, not 31.
So in order to straighten this out I would like to omit all rows tha have a TOTAL in the LEAGUE column from being counted in the footer total. How would I do this? Any help here would be greatly appreciated. Thanks.

YEAR    Name        AGE  TEAM   LEAGUE   HITS
2017    John Smith  25   STL    NL       1
2018    John Smith  26          TOTAL    15
2018    John Smith  26   LAD    NL       5
2018    John Smith  26   BAL    AL       10
        Career Total                     31

Here's my code

                YEAR
                NAME
                AGE
                TEAM
                LEAGUE
                HITS

        {% for stat in playerdata.bbhittingstatsmstr_set.all %}

                {{ stat.year }}
                {{ stat.name }}
                {{ stat.age }}
                {{ stat.team }}
                {{ stat.league }}
                {{ stat.hits }}

        {% endfor %}

Body:
Add an if statement into the tableData.reduce call:

const totals = tableData.reduce((total, rowData) => {
    if (rowData[4] !== 'TOTAL') {
        total[0] += parseFloat(rowData[5]);          <!--HITS -->
    }
    return total;
}, [0,0,0,0,0,0]);

$(table.column(5).footer()).text(totals[0]);         <!--HITS -->

Also you can simplify the initial value of the reduce call (the 3rd argument):

// totals is a Number not an Array
const totals = tableData.reduce((total, rowData) => {
    if (rowData[4] !== 'TOTAL') {
        total += parseFloat(rowData[5]);          <!--HITS -->
    }
    return total;
}, 0);

$(table.column(5).footer()).text(totals);


问:
Given an integer array and a value N. Represent N as a sum of minimum number of elements of the array. How to approach this problem?
Suppose, given an array A = {1, 3, 10, 11, 20} and a value N. Now, my task is to represent N as a sum of minimum number of elements of the array A.

Note: There might be one or more occurrence of an element of the array in the representation. But, the total length of the representation must be minimum.

Let N = 5. Here the answer would be {1, 1, 3}. Here the length of the representation is 3. There is no way I can get shorter length representation. So, it is the answer for N = 5.

Another example: If N = 8 then the shortest representation is {1, 1, 3, 3}.

I think this problem should be solved using Dynamic Programming. But, I can't come up with any idea. How should I approach this?

答:
This looks like homework, so I won't give the whole answer away, but here's a strategy one can use.

This problem is a bit like making change when you want to give back the minimum number of coins.

For example, if you have an infinite number of {1¢, 5¢, 25¢} coins and you want to give 37¢ in change, you'd do that by providing 25¢ + 5¢ + 5¢ + 1¢ + 1¢, for a total of 5 coins.

Now, what if you also had 7¢ coins available, so that your selection was from {1¢, 5¢, 7¢, 25¢}? Now you can do 25¢ + 7¢ + 5¢, for a total of 3 coins.

This might suggest that we can work backwards from the biggest coin size to the smallest one. But that's not correct. Consider what happens if we have {1¢, 3¢, 4¢} and we want to represent 6¢. We'd provide 4¢ + 1¢ + 1¢ for a total of 3 coins — but the shortest answer is actually 3¢ + 3¢.

So the naive/greedy approach won't always get us the right answer here; we'll need to use something like dynamic programming.

A dynamic programming approach could take a number of forms, but it needs to use two key insights:

Optimal substructure: The way you make change for x¢ is useful for understanding the way you make change for x¢ + n¢.

Overlapping subproblems: The way you make change for x¢ might be computed a number of different times when considering values larger than x¢. Can you reuse those calculations to avoid doing the work more than once?

One approach is outlined here if you're stuck. Hope that helps!


问:
SNS with file attachment
I have SNS notification for a S3 bucket. I wanted to push that SNS notification with attachment

We have a S3 bucket namely like SDD-XXX-YYY. Once if any file is getting arrived in that bucket, we have configured SNS to receive email notification.

Now we need email notification with content of the file which we are receiving in S3 or as attachment in our email.

Example: We are receiving some "error.log" file S3, here we need to push the error.log in email or else content of error.log file.

Please help me to achieve it.

Do we need to write lambda here? or we can manage it in SNS itself?

答:
The SNS S3 notification will only give you information about the newly created object.

You can see the structure of the event in Event Message Structure.

If you want to send the file via email you will have to write this logic in a Lambda function: you will use the information from the event (bucket and key) to download the object and then send it via email.

This function could subscribe to SNS or directly to S3.

Title: SNS with file attachment


问:
Trouble with Task.WhenAny
I am using .NET framework to create a server, which listens on two ports on localhost.  It is a simple console application.

It works when I keep connecting to one of the ports, but after I connect to first, another does not respond.  First still is alive.

Here is my code:

```<code>    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            while (true)
            {
                Socket socket = AcceptAnyConnection(listeners).Result;
                NetworkStream stream = new NetworkStream(socket);
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);
                //stream.Close();
                socket.Close();
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }

    private static async Task<Socket> AcceptAnyConnection(List<TcpListener> listeners)
    {
        List<Task<Socket>> tasks = new List<Task<Socket>>();
        foreach (TcpListener listener in listeners)
        {
            tasks.Add(AcceptConnection(listener));
        }
        Task<Socket> completedTask = await Task.WhenAny(tasks);
        return await completedTask;
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }
</code>```

await Task.WhenAny() blocks if I connect to another port.

I must be doing something wrong, but I am not sure what.

BTW, I did try the same with .NET Core console application, and it works fine.

Thanks

答:
Here is my code, after I followed a suggestion by canton7 to move the task list outside of loop and move add and remove tasks "as we go". Probably, I will have to look at it to clean it up, but the idea works:</p>

```<code>    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        ProcessConnections(listeners).Wait();
    }

    private async static Task SendData(Socket socket)
    {
        NetworkStream stream = new NetworkStream(socket);
        byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
        await stream.WriteAsync(bytes, 0, bytes.Length);
        socket.Close();
    }

    private static async Task ProcessConnections(List<TcpListener> listeners)
    {
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            List<Task<Socket>> tasks = new List<Task<Socket>>();
            foreach (TcpListener listener in listeners)
            {
                tasks.Add(AcceptConnection(listener));
            }
            while (true)
            {
                int i = Task.WaitAny(tasks.ToArray());
                Socket socket = await tasks[i];
                await SendData(socket);
                tasks.RemoveAt(i);
                tasks.Insert(i, AcceptConnection(listeners[i]));
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }
</code>```

Title: Trouble with Task.WhenAny

Body:
I am using .NET framework to create a server, which listens on two ports on localhost.  It is a simple console application.

It works when I keep connecting to one of the ports, but after I connect to first, another does not respond.  First still is alive.

Here is my code:

    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            while (true)
            {
                Socket socket = AcceptAnyConnection(listeners).Result;
                NetworkStream stream = new NetworkStream(socket);
                byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
                stream.Write(bytes, 0, bytes.Length);
                //stream.Close();
                socket.Close();
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }

    private static async Task<Socket> AcceptAnyConnection(List<TcpListener> listeners)
    {
        List<Task<Socket>> tasks = new List<Task<Socket>>();
        foreach (TcpListener listener in listeners)
        {
            tasks.Add(AcceptConnection(listener));
        }
        Task<Socket> completedTask = await Task.WhenAny(tasks);
        return await completedTask;
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }

await Task.WhenAny() blocks if I connect to another port.

I must be doing something wrong, but I am not sure what.

BTW, I did try the same with .NET Core console application, and it works fine.

Thanks

Body:
Here is my code, after I followed a suggestion by canton7 to move the task list outside of loop and move add and remove tasks "as we go". Probably, I will have to look at it to clean it up, but the idea works:

    static void Main(string[] args)
    {
        IPAddress hostIP = Dns.GetHostAddresses("127.0.0.1")[0];
        List<TcpListener> listeners = new List<TcpListener>()
        {
            new TcpListener(hostIP, 6060),
            new TcpListener(hostIP, 6061)
        };
        ProcessConnections(listeners).Wait();
    }

    private async static Task SendData(Socket socket)
    {
        NetworkStream stream = new NetworkStream(socket);
        byte[] bytes = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
        await stream.WriteAsync(bytes, 0, bytes.Length);
        socket.Close();
    }

    private static async Task ProcessConnections(List<TcpListener> listeners)
    {
        foreach (TcpListener listener in listeners)
        {
            listener.Start();
        }
        try
        {
            List<Task<Socket>> tasks = new List<Task<Socket>>();
            foreach (TcpListener listener in listeners)
            {
                tasks.Add(AcceptConnection(listener));
            }
            while (true)
            {
                int i = Task.WaitAny(tasks.ToArray());
                Socket socket = await tasks[i];
                await SendData(socket);
                tasks.RemoveAt(i);
                tasks.Insert(i, AcceptConnection(listeners[i]));
            }
        }
        finally
        {
            foreach (TcpListener listener in listeners)
            {
                listener.Stop();
            }
        }
    }
    private static async Task<Socket> AcceptConnection(TcpListener listener)
    {
        Socket socket = await listener.AcceptSocketAsync();
        return socket;
    }


问:
Powershell Get -ChildItem: filtering csv files and -Recurse not working
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

```<code>    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}
</code>```

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

答:
LotPings beat me to this by 10 minutes with a virtually identical answer, but I'm leaving this for the 'passing an empty file to the pipeline' bit that I have. I also realize after the fact that you don't need a pipeline variable for that same reason, as you only need it if you pass things through the pipeline within the loop.

If all you want to do is change the encoding I would use a ForEach($x in $y){} loop, or a ForEach-Object{} loop with a PipelineVariable on the Get-ChildItem. I'll show that since I think pipeline variables are under used. I would also not read the file and pipe it to something, since if the file is empty you won't create a new file as nothing is passed down the pipeline.

```<code>Get-ChildItem *.csv -Recurse -PipelineVariable File | ForEach-Object{
    Set-Content -Value (Get-Content $File.FullName -Encoding Unicode) -Path {Join-Path $File.Directory "UTF8$($File.Name)"} -Encoding UTF8
}
</code>```

Body:
I created a short powershell script to convert csv files from Unicode to UTF-8 encoding. My script outputs new files with the the original file name preceded by UTF8. I'm running into two issues:

I'm trying to only run the powershell script on csv files. Currently the script runs on every file in the directory, including the powershell script (it outputs a new file called UTF8pshell_script if the powershell script was called pshell_script for example). The other methods where I've tried to only run the script on csv files just end up making the script not do anything.

I'm trying to run the script on sub-directories. The first issue is that output files created from csv files in subdirectories have no content inside them whatsoever. If the script is ran in the same directory as the csv file this problem does not arise. This is not crucial but I am also uncertain how to get output files created from those in subdirectories to be outputted in the same subdirectories (currently they are outputted in the main directory where the powershell script is).
as

    Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8
    Get-ChildItem -Recurse | ForEach-Object {Get-Content -Encoding Unicode $_ | Out-File -Encoding UTF8 "UTF8$_"}

The desired output is the powershell script running on only csv files, and outputting files to the same subdirectories where the files they were created form are.

Body:
LotPings beat me to this by 10 minutes with a virtually identical answer, but I'm leaving this for the 'passing an empty file to the pipeline' bit that I have. I also realize after the fact that you don't need a pipeline variable for that same reason, as you only need it if you pass things through the pipeline within the loop.

If all you want to do is change the encoding I would use a ForEach($x in $y){} loop, or a ForEach-Object{} loop with a PipelineVariable on the Get-ChildItem. I'll show that since I think pipeline variables are under used. I would also not read the file and pipe it to something, since if the file is empty you won't create a new file as nothing is passed down the pipeline.

Get-ChildItem *.csv -Recurse -PipelineVariable File | ForEach-Object{
    Set-Content -Value (Get-Content $File.FullName -Encoding Unicode) -Path {Join-Path $File.Directory "UTF8$($File.Name)"} -Encoding UTF8
}


问:
Exceptions for Entity Framework Code First Migrations
I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.

The database context:

```<code>public class MyAppContext : DbContext
{
   public DbSet<Branch> Branches { get; set; }

   public MyAppContext()
   { }
}
</code>```

The entity:

```<code>public class Branch : IEntity<Guid>
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool Active { get; set; }
 }
</code>```

The database initializer:

```<code>public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
   protected override void Seed(MyAppContext context)
   {
      context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
      context.SaveChanges();
   }
}
</code>```

I installed Entity Framework 4.3 to my DAL project and MVC project using:

Install-Package EntityFramework

I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:

PM> Enable-Migrations -Verbose

Using NuGet project 'Ckms.KeyManagement.Managers'.
  Error while searching for context type (specify -Verbose to see exception details).
  System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.    at
  System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
  runner)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()

  at
  System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable()
  Edit the generated Configuration class to specify the context to
  enable migrations for.
  Code First Migrations enabled for project Ckms.KeyManagement.Managers.

A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:

```<code>internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
   public Configuration()
   {
      AutomaticMigrationsEnabled = true;
   }

   protected override void Seed(MyAppContext context)
   { }
}
</code>```

These exceptions are thrown for the Add-Migration and Update-Database commands:

PM> Add-Migration TestEFMigrationsColumn -Verbose

Using NuGet project
  'Ckms.KeyManagement.Managers'. Using StartUp project ''.
  System.Reflection.TargetInvocationException: Exception has been thrown
  by the target of an invocation. ---> System.ArgumentException: The
  parameter is incorrect. (Exception from HRESULT: 0x80070057
  (E_INVALIDARG))    --- End of inner exception stack trace ---    at
  System.RuntimeType.InvokeDispMethod(String name, BindingFlags
  invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
  Int32 culture, String[] namedParameters)    at
  System.RuntimeType.InvokeMember(String name, BindingFlags
  bindingFlags, Binder binder, Object target, Object[] providedArgs,
  ParameterModifier[] modifiers, CultureInfo culture, String[]
  namedParams)    at
  System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
  Object[] arguments) Exception has been thrown by the target of an
  invocation.

Update-Database:

PM> Update-Database -Verbose

Using NuGet project
  'Ckms.KeyManagement.Managers'. Using StartUp project ''.
  System.Reflection.TargetInvocationException: Exception has been thrown
  by the target of an invocation. ---> System.ArgumentException: The
  parameter is incorrect. (Exception from HRESULT: 0x80070057
  (E_INVALIDARG))    --- End of inner exception stack trace ---    at
  System.RuntimeType.InvokeDispMethod(String name, BindingFlags
  invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
  Int32 culture, String[] namedParameters)    at
  System.RuntimeType.InvokeMember(String name, BindingFlags
  bindingFlags, Binder binder, Object target, Object[] providedArgs,
  ParameterModifier[] modifiers, CultureInfo culture, String[]
  namedParams)    at
  System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
  Object[] arguments) Exception has been thrown by the target of an
  invocation.

Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.

答: You must be having two connection strings in your web. Config files. Just delete one</p>

Body:
I'm getting several unhandled exceptions while using Code First Migrations of Entity Framework 4.3.

The database context:

public class MyAppContext : DbContext
{
   public DbSet<Branch> Branches { get; set; }

   public MyAppContext()
   { }
}

The entity:

public class Branch : IEntity<Guid>
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool Active { get; set; }
 }

The database initializer:

public class MyAppInitializer : CreateDatabaseIfNotExists<MyAppContext>
{
   protected override void Seed(MyAppContext context)
   {
      context.Branches.Add(new Branch() { Id = branchId, Name = "Acme", Description = "Acme", Active = true });
      context.SaveChanges();
   }
}

I installed Entity Framework 4.3 to my DAL project and MVC project using:

Install-Package EntityFramework

I have set the MVC project as the startup project and executed the following command to the DAL project with the database context and initializer:

PM> Enable-Migrations -Verbose

Using NuGet project 'Ckms.KeyManagement.Managers'.
  Error while searching for context type (specify -Verbose to see exception details).
  System.Data.Entity.Migrations.Design.ToolingException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.    at
  System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner
  runner)    at
  System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypes()

  at
  System.Data.Entity.Migrations.MigrationsCommands.FindContextToEnable()
  Edit the generated Configuration class to specify the context to
  enable migrations for.
  Code First Migrations enabled for project Ckms.KeyManagement.Managers.

A DbMigrationsConfiguration child class is added to the DAL project. If I add the type of the DbContext manually and enable Automatic Migrations:

internal sealed class Configuration : DbMigrationsConfiguration<MyAppContext>
{
   public Configuration()
   {
      AutomaticMigrationsEnabled = true;
   }

   protected override void Seed(MyAppContext context)
   { }
}

These exceptions are thrown for the Add-Migration and Update-Database commands:

PM> Add-Migration TestEFMigrationsColumn -Verbose

Using NuGet project
  'Ckms.KeyManagement.Managers'. Using StartUp project ''.
  System.Reflection.TargetInvocationException: Exception has been thrown
  by the target of an invocation. ---> System.ArgumentException: The
  parameter is incorrect. (Exception from HRESULT: 0x80070057
  (E_INVALIDARG))    --- End of inner exception stack trace ---    at
  System.RuntimeType.InvokeDispMethod(String name, BindingFlags
  invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
  Int32 culture, String[] namedParameters)    at
  System.RuntimeType.InvokeMember(String name, BindingFlags
  bindingFlags, Binder binder, Object target, Object[] providedArgs,
  ParameterModifier[] modifiers, CultureInfo culture, String[]
  namedParams)    at
  System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
  Object[] arguments) Exception has been thrown by the target of an
  invocation.

Update-Database:

PM> Update-Database -Verbose

Using NuGet project
  'Ckms.KeyManagement.Managers'. Using StartUp project ''.
  System.Reflection.TargetInvocationException: Exception has been thrown
  by the target of an invocation. ---> System.ArgumentException: The
  parameter is incorrect. (Exception from HRESULT: 0x80070057
  (E_INVALIDARG))    --- End of inner exception stack trace ---    at
  System.RuntimeType.InvokeDispMethod(String name, BindingFlags
  invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers,
  Int32 culture, String[] namedParameters)    at
  System.RuntimeType.InvokeMember(String name, BindingFlags
  bindingFlags, Binder binder, Object target, Object[] providedArgs,
  ParameterModifier[] modifiers, CultureInfo culture, String[]
  namedParams)    at
  System.Management.Automation.ComMethod.InvokeMethod(PSMethod method,
  Object[] arguments) Exception has been thrown by the target of an
  invocation.

Any ideas? The error messages are not really helpful. I have tried the Nuget commands with and without an existing database.


问:
ALTER USER in Oracle
I need to expire and lock accounts that have never been logged into EXCEPT SYS and RMAN (and accounts that begin with RMAN/SYS)

```<code>SELECT USERNAME
FROM DBA_USERS
WHERE (LAST_LOGIN IS NULL)
AND not REGEXP_LIKE(USERNAME, '^SYS')
ORDER BY LAST_LOGIN ASC;
</code>```

This query returns rows that begin with SYS (yes I know I didn't specify RMAN but I am trying to figure out how to exclude SYS first)

答:
You could use:</p>

```<code>SELECT USERNAME
FROM DBA_USERS
WHERE (LAST_LOGIN IS NULL)
  AND USERNAME NOT LIKE 'SYS%'
ORDER BY LAST_LOGIN ASC;
</code>```

Title: ALTER USER in Oracle

Body:
I need to expire and lock accounts that have never been logged into EXCEPT SYS and RMAN (and accounts that begin with RMAN/SYS)

SELECT USERNAME
FROM DBA_USERS
WHERE (LAST_LOGIN IS NULL)
AND not REGEXP_LIKE(USERNAME, '^SYS')
ORDER BY LAST_LOGIN ASC;

This query returns rows that begin with SYS (yes I know I didn't specify RMAN but I am trying to figure out how to exclude SYS first)

Body:
You could use:

SELECT USERNAME
FROM DBA_USERS
WHERE (LAST_LOGIN IS NULL)
  AND USERNAME NOT LIKE 'SYS%'
ORDER BY LAST_LOGIN ASC;


问:
Sorting lines and removing all but one line based on the last string?
searching for a solution to my problem I found this thread: Sorting on the last field of a line

I used some solutions for sorting using sed and awk and they work, one more thing I need is to delete all but one line based on last string in a line.

Example, I have:

```<code>www.site.com/324242_1234
www.site.com/233_1234
www.site.com/45357_1234
www.site.com/6545_2345
www.site.com/5433_2345
www.site.com/87745_456
www.site.com/453209_456
www.site.com/1345_456
</code>```

Need this result:

```<code>www.site.com/324242_1234
www.site.com/6545_2345
www.site.com/87745_456
</code>```

So I need to keep only one line that contains that last string, in this example they are separated by underline. I appreciate help.

答:
How about this?

```<code>cat file | sed -e 's/_/\t/gi' | sort -uk 2,2 | sed -e 's/\t/_/gi'
</code>```

Where file has the strings

Body:
searching for a solution to my problem I found this thread: Sorting on the last field of a line

I used some solutions for sorting using sed and awk and they work, one more thing I need is to delete all but one line based on last string in a line.

Example, I have:

www.site.com/324242_1234
www.site.com/233_1234
www.site.com/45357_1234
www.site.com/6545_2345
www.site.com/5433_2345
www.site.com/87745_456
www.site.com/453209_456
www.site.com/1345_456

Need this result:

www.site.com/324242_1234
www.site.com/6545_2345
www.site.com/87745_456

So I need to keep only one line that contains that last string, in this example they are separated by underline. I appreciate help.

Body:
How about this?

cat file | sed -e 's/_/\t/gi' | sort -uk 2,2 | sed -e 's/\t/_/gi'

Where file has the strings


问:
Bluetooth pairing dialog not showing up in Screen Pinning mode
I'm writing an enterprise inspired app based on Device Policy Manager. The app will enable kiosk mode on the device so only one app will be in the foreground & the user won't be able to get out of the app.

My app whitelists the particular app that's going to be in the foreground. Everything so far is working great except that when the device is in Kiosk mode, the system dialogs, for example, Bluetooth device pairing dialog and USB accessory permission dialog don't appear on top of the pinned app.

I couldn't find any api that would enable such system dialogs to appear while kiosk mode is in action.

Google added some new apis in Android 9 that let you know that but since my app will be running on devices <= Android Oreo, I can't utilize those apis.

Following api is using to whitelist an app to go in Kiosk Mode,

```<code>public void setLockTaskPackages (ComponentName admin,
                String[] packages)
</code>```

and then the screen pinned app calls startLockTask() to have full affect of kiosk mode but then system dialogs stop appearing as mentioned above.

Is there any other api that would let the system dialogs to show up? Any pointers/work arounds would be really appreciated

答:
I'm currently developing an enterprise app that has the same issue. My temporary solution has been to unlock the application while I'm expecting to receive the Bluetooth pairing dialog, and then lock the app once the connection has been set up.

So far, this is the only solution I've found to work. If you manage to find a solution, please let me know. It's been a frustrating couple of months trying to fix this.

Body:
I'm writing an enterprise inspired app based on Device Policy Manager. The app will enable kiosk mode on the device so only one app will be in the foreground & the user won't be able to get out of the app.

My app whitelists the particular app that's going to be in the foreground. Everything so far is working great except that when the device is in Kiosk mode, the system dialogs, for example, Bluetooth device pairing dialog and USB accessory permission dialog don't appear on top of the pinned app.

I couldn't find any api that would enable such system dialogs to appear while kiosk mode is in action.

Google added some new apis in Android 9 that let you know that but since my app will be running on devices <= Android Oreo, I can't utilize those apis.

Following api is using to whitelist an app to go in Kiosk Mode,

public void setLockTaskPackages (ComponentName admin,
                String[] packages)

and then the screen pinned app calls startLockTask() to have full affect of kiosk mode but then system dialogs stop appearing as mentioned above.

Is there any other api that would let the system dialogs to show up? Any pointers/work arounds would be really appreciated


问:
How can I make a static array with references to trait implementations in Rust?
I want to be able to iterate over an array of parsers trying to find a delegate parser from a main parsing function. The list of parsers is known at compile-time, so I want this to be a constant.

I've tried some varieties of this but I can't get it to work:

```<code>const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
</code>```

How can I achieve this?

Notes:

Parser is a trait.

CommentParser is a struct implementing Parser.

there are other implementations of Parser but they are not shown for simplicity.

even though all parser implementations are known at compile-time, I just want to avoid explicitly trying one by one as that would make the code worse than I think it should be.

The error I get currently:

|
11 | const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
   |                    ^^^^^^^^^^^^ the trait `parsers::Parser` cannot be made into an object
   |
   = note: method `parse` has generic type parameters
```

<p>I can't see any generics in the parse method:</p>

```pub trait Parser {
    fn opening_char(self: &Self) -> char;
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;
}
```

<h3>If I make the types values:</h3>

```const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
```

<p>The error becomes:</p>

<pre class="lang-none prettyprint-override"><code>11 | const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
|                    ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn parsers::Parser + 'static)`
</code>```

答:
Trait references need to be marked as &dyn, e.g. &dyn Parser:

```<code>trait Parser { }

struct CommentParser { }
impl Parser for CommentParser { }

const ALL_PARSERS: [&dyn Parser; 1] = [&CommentParser {}];

fn main() {
    for &parser in &ALL_PARSERS {
        // do something with parser
    }
}
</code>```

Link to playground example

Also, as this answer to a related question states, you can't have a generic parameter in your trait if you want to make a trait reference, so you'll need to either add a generic type to the trait itself, or use a trait reference instead of impl in your parser type:

```<code>// original (with error)
trait Parser {
    // impl ParserEnv is an implicit generic type
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;

    // same as:
    //   fn parser<E: ParserEnv>(&mut self, env: E) -> ParserResult;
}

// alternative 1, with trait generic type
trait Parser<E: ParserEnv> {
    fn parse(&mut self, env: E) -> ParseResult;
}

// alternative 2, with trait reference
trait Parser {
    fn parser(&mut self, env: &dyn ParserEnv) -> ParserResult;
    // may need &dyn mut ParserEnv if you want to modify env as well
}
</code>```

I think the second approach may be the best, since then you can store the parsers in the array without needing to assign a particular ParserEnv type to the parsers.

Body:
I want to be able to iterate over an array of parsers trying to find a delegate parser from a main parsing function. The list of parsers is known at compile-time, so I want this to be a constant.

I've tried some varieties of this but I can't get it to work:

const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];

How can I achieve this?

Notes:

Parser is a trait.

CommentParser is a struct implementing Parser.

there are other implementations of Parser but they are not shown for simplicity.

even though all parser implementations are known at compile-time, I just want to avoid explicitly trying one by one as that would make the code worse than I think it should be.

The error I get currently:

|
11 | const ALL_PARSERS: [&Parser; 1] = [&CommentParser {}];
   |                    ^^^^^^^^^^^^ the trait `parsers::Parser` cannot be made into an object
   |
   = note: method `parse` has generic type parameters

I can't see any generics in the parse method:

pub trait Parser {
    fn opening_char(self: &Self) -> char;
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;
}

If I make the types values:

const ALL_PARSERS: [Parser; 1] = [CommentParser {}];

The error becomes:

11 | const ALL_PARSERS: [Parser; 1] = [CommentParser {}];
|                    ^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `(dyn parsers::Parser + 'static)`

Body:
Trait references need to be marked as &dyn, e.g. &dyn Parser:

trait Parser { }

struct CommentParser { }
impl Parser for CommentParser { }

const ALL_PARSERS: [&dyn Parser; 1] = [&CommentParser {}];

fn main() {
    for &parser in &ALL_PARSERS {
        // do something with parser
    }
}

Link to playground example

Also, as this answer to a related question states, you can't have a generic parameter in your trait if you want to make a trait reference, so you'll need to either add a generic type to the trait itself, or use a trait reference instead of impl in your parser type:

// original (with error)
trait Parser {
    // impl ParserEnv is an implicit generic type
    fn parse(&mut self, env: impl ParserEnv) -> ParseResult;

    // same as:
    //   fn parser<E: ParserEnv>(&mut self, env: E) -> ParserResult;
}

// alternative 1, with trait generic type
trait Parser<E: ParserEnv> {
    fn parse(&mut self, env: E) -> ParseResult;
}

// alternative 2, with trait reference
trait Parser {
    fn parser(&mut self, env: &dyn ParserEnv) -> ParserResult;
    // may need &dyn mut ParserEnv if you want to modify env as well
}

I think the second approach may be the best, since then you can store the parsers in the array without needing to assign a particular ParserEnv type to the parsers.


问:
Is there a method to change the passwords new users receive via email in Wordpress?
I have a WordPress website with WooCommerce Subscriptions and Memberships.

New users on my website receive an email with their username and password. The password inside this email is 12 characters long and contains a mix of characters. Is there a way to do any of the following:

Change default password character length

Change default password to equal customer's lastname + 1 (e.g Hua1)

Change the default password to only contain (a-z, 0-9)

Any help would be greatly appreciated! Thank you.

答:
It sounds very likely that one of your plugins is overriding the default wp_new_user_notification() function with a less secure version.

If you look in wp-includes/pluggable.php, you'll note that in WP 4.3 the function was changed to remove the plaintext parameter, because (as Patrick noted) sending plaintext passwords was quite concerning to a lot of folks.
Documentation for the function is at https://developer.wordpress.org/reference/functions/wp_new_user_notification/

As of WP 4.9, it is also possible to change the email sent to the user with the wp_new_user_notification_email filter.

But, if a plugin is overriding wp_new_user_notification, then that's a moot point, and you need to either override it yourself (by copying the code from core), or by asking the plugin developer responsible to fix their outdated code.


问:
Filter an array of objects based on field name
Consider an object, Notification, with the following properties:

```<code>id: String
body: String
repeats: Bool
</code>```

and consider an array of Notifications, notifications:

```<code>let notifications = [Notification(id: "1", body: "body1", repeats: false),
                     Notification(id: "2", body: "body2", repeats: false),
                     Notification(id: "3", body: "body3", repeats: true)]
</code>```

How can I use the higher-order filter() function to retrieve an array of Strings corresponding to each id?

In other words, I would like to write a filter() closure to which I pass my notifications and the resulting output is:

```<code>["1", "2", "3"]
</code>```

Therefore, my filter comparison operator should be based on the property name. Is this achievable?

答:
filter is not the appropriate tool here. filter would be for returning a subset of the notifications based on some criteria (such as only repeating notifications, for example).

You want map which is used to transform data.

```<code>let idList = notifications.map { $0.id }
</code>```

You can combine these as needed. Let's say you wanted the list of ids for the repeating notifications.

```<code>let ids = notifications.filter { $0.repeats }.map { $0.id }
</code>```

Body:
Consider an object, Notification, with the following properties:

id: String
body: String
repeats: Bool

and consider an array of Notifications, notifications:

let notifications = [Notification(id: "1", body: "body1", repeats: false),
                     Notification(id: "2", body: "body2", repeats: false),
                     Notification(id: "3", body: "body3", repeats: true)]

How can I use the higher-order filter() function to retrieve an array of Strings corresponding to each id?

In other words, I would like to write a filter() closure to which I pass my notifications and the resulting output is:

["1", "2", "3"]

Therefore, my filter comparison operator should be based on the property name. Is this achievable?

Body:
filter is not the appropriate tool here. filter would be for returning a subset of the notifications based on some criteria (such as only repeating notifications, for example).

You want map which is used to transform data.

let idList = notifications.map { $0.id }

You can combine these as needed. Let's say you wanted the list of ids for the repeating notifications.

let ids = notifications.filter { $0.repeats }.map { $0.id }


答:
Create a temporary column (grp) that increments a counter each time column C is equal to 0 (the reset condition) and use this as a partitioning column for your cumulative sum.

```<code>import pyspark.sql.functions as f
from pyspark.sql import Window

x.withColumn(
    "grp",
    f.sum((f.col("C") == 0).cast("int")).over(Window.orderBy("A"))
).withColumn(
    "D",
    f.sum(f.col("C")).over(Window.partitionBy("grp").orderBy("A"))
).drop("grp").show()
#+---+----+---+---+
#|  A|   B|  C|  D|
#+---+----+---+---+
#|  0|null|  1|  1|
#|  1| 3.0|  0|  0|
#|  2| 7.0|  0|  0|
#|  3|null|  1|  1|
#|  4| 4.0|  0|  0|
#|  5| 3.0|  0|  0|
#|  6|null|  1|  1|
#|  7|null|  1|  2|
#|  8|null|  1|  3|
#|  9| 5.0|  0|  0|
#| 10| 2.0|  0|  0|
#| 11|null|  1|  1|
#+---+----+---+---+
</code>```

Title: Pyspark - Cumulative sum with reset condition

Body:
I have this dataframe

+---+----+---+
|  A|   B|  C|
+---+----+---+
|  0|null|  1|
|  1| 3.0|  0|
|  2| 7.0|  0|
|  3|null|  1|
|  4| 4.0|  0|
|  5| 3.0|  0|
|  6|null|  1|
|  7|null|  1|
|  8|null|  1|
|  9| 5.0|  0|
| 10| 2.0|  0|
| 11|null|  1|
+---+----+---+

What I need do is a cumulative sum of values from column C until the next value is zero.

Expected output:

+---+----+---+----+
|  A|   B|  C|   D|
+---+----+---+----+
|  0|null|  1|   1|
|  1| 3.0|  0|   0|
|  2| 7.0|  0|   0|
|  3|null|  1|   1|
|  4| 4.0|  0|   0|
|  5| 3.0|  0|   0|
|  6|null|  1|   1|
|  7|null|  1|   2|
|  8|null|  1|   3|
|  9| 5.0|  0|   0|
| 10| 2.0|  0|   0|
| 11|null|  1|   1|
+---+----+---+----+

To reproduce dataframe:

from pyspark.shell import sc
from pyspark.sql import Window
from pyspark.sql.functions import lag, when, sum

x = sc.parallelize([
    [0, None], [1, 3.], [2, 7.], [3, None], [4, 4.],
    [5, 3.], [6, None], [7, None], [8, None], [9, 5.], [10, 2.], [11, None]])
x = x.toDF(['A', 'B'])

# Transform null values into "1"
x = x.withColumn('C', when(x.B.isNull(), 1).otherwise(0))

Body:
Create a temporary column (grp) that increments a counter each time column C is equal to 0 (the reset condition) and use this as a partitioning column for your cumulative sum.

import pyspark.sql.functions as f
from pyspark.sql import Window

x.withColumn(
    "grp",
    f.sum((f.col("C") == 0).cast("int")).over(Window.orderBy("A"))
).withColumn(
    "D",
    f.sum(f.col("C")).over(Window.partitionBy("grp").orderBy("A"))
).drop("grp").show()
#+---+----+---+---+
#|  A|   B|  C|  D|
#+---+----+---+---+
#|  0|null|  1|  1|
#|  1| 3.0|  0|  0|
#|  2| 7.0|  0|  0|
#|  3|null|  1|  1|
#|  4| 4.0|  0|  0|
#|  5| 3.0|  0|  0|
#|  6|null|  1|  1|
#|  7|null|  1|  2|
#|  8|null|  1|  3|
#|  9| 5.0|  0|  0|
#| 10| 2.0|  0|  0|
#| 11|null|  1|  1|
#+---+----+---+---+


问:
Function returns True instead of False over iteration
I am doing some challenges on edabit and I came across a problem with my output. So i have to Create a function that takes in an array (slot machine outcome) and returns true if all elements in the array are identical, and false otherwise. The array will contain 4 elements. Can someone explain why my code isn't working the right way.

I have tried with other inputs and it's working fine.

```<code>   'use strict';

   function array_Validator(e1,e2,e3,e4)
   {
       let m_Array=[e1,e2,e3,e4];
       for(let i=0;i<m_Array.length-1;i++)
       {
           for(let x=i;x<m_Array.length-1;x++)
           {
               if(m_Array[i]!==m_Array[x+1])
               {
                   return false;
               }
               else
               return true;
           }
       }
   }

  let u_Result=array_Validator("SS","SS","Ss","Ss");

   console.log(u_Result);
</code>```

So when I input Ss it shoes true instead of false.

答:
For this you can use Rest Parameters ...args</p>

```<code>function array_Validator(...args) {
    for (let i = 1; i < args.length; i++) {
        if (args[0] !== args[i]) return false;
    }
    return true;
}
let u_Result = array_Validator("SS","SS","Ss","Ss");
console.log(u_Result);
</code>```

Body:
I am doing some challenges on edabit and I came across a problem with my output. So i have to Create a function that takes in an array (slot machine outcome) and returns true if all elements in the array are identical, and false otherwise. The array will contain 4 elements. Can someone explain why my code isn't working the right way.

I have tried with other inputs and it's working fine.

   'use strict';

   function array_Validator(e1,e2,e3,e4)
   {
       let m_Array=[e1,e2,e3,e4];
       for(let i=0;i<m_Array.length-1;i++)
       {
           for(let x=i;x<m_Array.length-1;x++)
           {
               if(m_Array[i]!==m_Array[x+1])
               {
                   return false;
               }
               else
               return true;
           }
       }
   }

  let u_Result=array_Validator("SS","SS","Ss","Ss");

   console.log(u_Result);

So when I input Ss it shoes true instead of false.

Body:
For this you can use Rest Parameters ...args

function array_Validator(...args) {
    for (let i = 1; i < args.length; i++) {
        if (args[0] !== args[i]) return false;
    }
    return true;
}
let u_Result = array_Validator("SS","SS","Ss","Ss");
console.log(u_Result);


问:
Why is my code getting a segmentation error
For the life of me I cannot understand at all why this program is getting a segmentation error. The issue is that it retrieves an object within the vector container uses a function within the menu class using the get_command() and for some reason after testing the main function line by line this one results in a segmentation fault:

menu->get_command()->execute();

I have tried changing the syntax to create a new command object that stores the returned object from get_command() and changed the index between 0 and -1 and still nothing fixes the error. I have spent at least a couple of hours trying to figure out why but I cannot seem to find a solution.

```<code>class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    Base* root;

public:
    Command() { this->root = nullptr; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<Command*> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() {
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() {
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() {
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(Command* cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.push_back(cmd);
        history_index++;
    }

    Command* get_command() {
        // Returns the command that the history_index is currently referring to
        return history[history_index];
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:
    Base* root;

public:
    InitialCommand(Base* b) { this->root = b; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

void main()
{
    Menu* menu = new Menu();
    InitialCommand* temp = new InitialCommand(new op(7));
    menu->add_command(temp);
    EXPECT_EQ(menu->get_command()->execute(), 7);

    system("PAUSE");

}
</code>```

答:
You're not doing inheritance right, as you are duplicating fields between Command and InitialCommand that lead to the error.

Both command classes have a Base *root member, and non-virtual execute methods.  When you construct a new InitialCommand object, the InitialCommand::root object points at the op that was created for it, while Command::root remains NULL because of the default constructor for Command.  Then, when you call menu->get_command(), it will call Command::execute because execute is non-virtual and menu is a Command *.  Command::execute will then dereference a NULL root, causing your segmentation error.

Remove the Base *root member from InitialCommand, and pass the parameter to a constructor in Command.  You probably want to make some methods like execute virtual.

Body:
For the life of me I cannot understand at all why this program is getting a segmentation error. The issue is that it retrieves an object within the vector container uses a function within the menu class using the get_command() and for some reason after testing the main function line by line this one results in a segmentation fault:

menu->get_command()->execute();

I have tried changing the syntax to create a new command object that stores the returned object from get_command() and changed the index between 0 and -1 and still nothing fixes the error. I have spent at least a couple of hours trying to figure out why but I cannot seem to find a solution.

class Base {
public:
    /* Constructors */
    Base() { };

    /* Pure Virtual Functions */
    virtual double evaluate() = 0;
    virtual std::string stringify() = 0;
};

class op : public Base
{
public:
    op() { };
    op(double op1) { operand = op1; }

    double evaluate() { return operand; }

    string stringify() {
        string value = to_string(operand);
        return value;
    }
private:
    double operand;
};

class Command {
protected:
    Base* root;

public:
    Command() { this->root = nullptr; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

class Menu {
private:
    int history_index; // Indexes which command was last executed, accounting for undo and redo functions
    std::vector<Command*> history; // Holds all the commands that have been executed until now

public:
    Menu() {
        // Constructor which initializes the internal members
        history_index = -1;
    }

    std::string execute() {
        // Returns the string converted evaluation of the current command
        return to_string(history[history_index - 1]->execute());
    }

    std::string stringify() {
        // Returns the stringified version of the current command
        return history[history_index]->stringify();
    }

    bool initialized() {
        // Returns if the history has an InitialCommand, which is necessary to start the calculation
        if (history[history_index] != nullptr)
            return true;
        else
            return false;
    }

    void add_command(Command* cmd) {
        // Adds a command to the history (does not execute it), this may require removal of some other commands depending on where history_index is
        history.push_back(cmd);
        history_index++;
    }

    Command* get_command() {
        // Returns the command that the history_index is currently referring to
        return history[history_index];
    }

    void undo() {
        // Move back one command (does not execute it) if there is a command to undo
        history_index--;
    }

    void redo() {
        // Moves forward one command (does not execute it) if there is a command to redo
        history_index++;
    }
};

class InitialCommand : public Command {
protected:
    Base* root;

public:
    InitialCommand(Base* b) { this->root = b; }
    double execute() { return root->evaluate(); }
    std::string stringify() { return root->stringify(); }
    Base* get_root() { return root; }
};

void main()
{
    Menu* menu = new Menu();
    InitialCommand* temp = new InitialCommand(new op(7));
    menu->add_command(temp);
    EXPECT_EQ(menu->get_command()->execute(), 7);

    system("PAUSE");

}


问:
Optimizing query that searches concatenated row values
I am working on some legacy SQL code, and am looking for some help trying to fix an odd query I have. It looks like this:

```<code>SELECT *
FROM   TA LEFT OUTER JOIN TB ON TA.a1 = TB.b3
WHERE  TA.a1 LIKE 'usersearch'
    OR TB.b1 + ':' + TB.b2 LIKE 'usersearch'
</code>```

usersearch is a user supplied regex that is unknown at the time of the query's creation.

The usersearch variable is the same in both LIKE sections. This is an insane bit of code, and takes forever to run, but I'm having a hard time figuring out how I can optimize it.

The terrible part is that it constructs a string to perform a regex on for every single line. However, I'm not really sure how to avoid this.

If anyone has any ideas I'd love to hear them!

答: Your where condition:  TB.b1 + ':' + TB.b2 LIKE 'usersearch' is non-sargable and will always result in a table scan.  You might want to consider making a computed column that is persisted so that you can index it.  That should improve performance.  However, your question indicated that 'usersearch' is a RegEx.  LIKE does not work with RegEx.  It does work with the % and _ wildcards.  I'm hoping that this was just a terminology mistake.  If it really is a RegEx, then you'll need a very different solution.  Regardless, the sargable issue still needs to be resolved.

Body:
I am working on some legacy SQL code, and am looking for some help trying to fix an odd query I have. It looks like this:

SELECT *
FROM   TA LEFT OUTER JOIN TB ON TA.a1 = TB.b3
WHERE  TA.a1 LIKE 'usersearch'
    OR TB.b1 + ':' + TB.b2 LIKE 'usersearch'

usersearch is a user supplied regex that is unknown at the time of the query's creation.

The usersearch variable is the same in both LIKE sections. This is an insane bit of code, and takes forever to run, but I'm having a hard time figuring out how I can optimize it.

The terrible part is that it constructs a string to perform a regex on for every single line. However, I'm not really sure how to avoid this.

If anyone has any ideas I'd love to hear them!


问:
Thread.sleep( ) with Espresso
Espresso claims that there is no need for Thread.sleep() but my code doesn't work unless I include it. I am connecting to an IP and, while connecting, a progress dialog is shown. I need a Thread.sleep() call to wait for the dialog to dismiss. This is my test code where I use it:

```<code>    IP.enterIP(); // fills out an IP dialog (this is done with espresso)

    //progress dialog is now shown
    Thread.sleep(1500);

    onView(withId(R.id.button).perform(click());
</code>```

I have tried this code without the Thread.sleep() call but it says R.id.Button doesn't exist. The only way I can get it to work is with the Thread.sleep() call.

Also, I have tried replacing Thread.sleep() with things like getInstrumentation().waitForIdleSync() and still no luck.

Is this the only way to do this? Or am I missing something?

答:
This is similar to this answer but uses a timeout instead of attempts and can be chained with other ViewInteractions:

```<code>/**
 * Wait for view to be visible
 */
fun ViewInteraction.waitUntilVisible(timeout: Long): ViewInteraction {
    val startTime = System.currentTimeMillis()
    val endTime = startTime + timeout

    do {
        try {
            check(matches(isDisplayed()))
            return this
        } catch (e: AssertionFailedError) {
            Thread.sleep(50)
        }
    } while (System.currentTimeMillis() < endTime)

    throw TimeoutException()
}
</code>```

Usage:

```<code>onView(withId(R.id.whatever))
    .waitUntilVisible(5000)
    .perform(click())
</code>```

Title: Thread.sleep( ) with Espresso

Body:
Espresso claims that there is no need for Thread.sleep() but my code doesn't work unless I include it. I am connecting to an IP and, while connecting, a progress dialog is shown. I need a Thread.sleep() call to wait for the dialog to dismiss. This is my test code where I use it:

    IP.enterIP(); // fills out an IP dialog (this is done with espresso)

    //progress dialog is now shown
    Thread.sleep(1500);

    onView(withId(R.id.button).perform(click());

I have tried this code without the Thread.sleep() call but it says R.id.Button doesn't exist. The only way I can get it to work is with the Thread.sleep() call.

Also, I have tried replacing Thread.sleep() with things like getInstrumentation().waitForIdleSync() and still no luck.

Is this the only way to do this? Or am I missing something?

Body:
This is similar to this answer but uses a timeout instead of attempts and can be chained with other ViewInteractions:

/**
 * Wait for view to be visible
 */
fun ViewInteraction.waitUntilVisible(timeout: Long): ViewInteraction {
    val startTime = System.currentTimeMillis()
    val endTime = startTime + timeout

    do {
        try {
            check(matches(isDisplayed()))
            return this
        } catch (e: AssertionFailedError) {
            Thread.sleep(50)
        }
    } while (System.currentTimeMillis() < endTime)

    throw TimeoutException()
}

Usage:

onView(withId(R.id.whatever))
    .waitUntilVisible(5000)
    .perform(click())


Title: Sorting lines and removing all but one line based on the last string?

Body:
awk -F[_/] '{print $NF,$(NF-1),$0}' input_file |sort -r -nk2,1   |awk '!a[$1]++{gsub($1FS$2,"");gsub(/^ /,"");print}'
www.site.com/87745_456
www.site.com/6545_2345
www.site.com/45357_1234


问:
SageMaker TensorFlow Estimator source code S3 upload path
I'm using the SageMaker TensorFlow estimator for training, and specifying an output path for my model artifacts with the output_path argument, with a value of s3://<bucket>/<prefix>/.

After model training, a directory named <training_job_name>/output is created in the specified output_path.

The issue I'm having is, the source code that's used for training is also uploaded to S3 by default, but instead of being placed in s3://<bucket>/<prefix>/<training_job_name>/source, it's placed in s3://<bucket>/<training_job_name>/source.

So how can I specify the S3 upload path for the training job's source code in order to make it use the bucket AND prefix name of output_path?

答:
I believe the code_location parameter shown by @user3458797 is the correct answer.

The output_path only configures the S3 location for saving the training result (model artifacts and output files).

https://sagemaker.readthedocs.io/en/stable/estimators.html

Your training script won't be saved in the "output_path" unless you move the file into /opt/ml/model during the training or you use the code_location parameter.

Please let me know if there is anything I can clarify.


问:
Accessing nginx-ingress-controller error log
I have set up one Kubernetes master node and 2 workers node. I deployed two web applications as a pod using kubectl. I deployed nginx-ingress-controller ( image: gcr.io/google_containers/nginx-ingress-controller:0.9.0-beta.6) and created a service for the same with nodeport option. How do I access the error logs of the nginx-ingress-controller? I'm able to see error.log under /var/log/nginx/, but it is link to /dev/stderr.

答:
TL;DR

```<code>kubectl logs -n <<ingress_namespace>> <<ingress_pod_name>>
</code>```

Check the namespace under which the Ingress controller is currently running.

```<code>$ kubectl get pods
NAME                                    READY   STATUS    RESTARTS   AGE
helloworld-deployment-7dc448d6b-5zvr8   1/1     Running   1          3d20h
helloworld-deployment-7dc448d6b-82dnt   1/1     Running   1          3d20h

$ kubectl get pods -n kube-system
NAME                                        READY   STATUS    RESTARTS   AGE
kube-apiserver-minikube                     1/1     Running   1          3d20h
nginx-ingress-controller-586cdc477c-rhj9z   1/1     Running   1          3d21h
</code>```

For me, it happens to be the kube-system namespace on the pod nginx-ingress-controller-586cdc477c-rhj9z.

Now, get the logs just like you would for any pod using

```<code> kubectl logs -n kube-system nginx-ingress-controller-586cdc477c-rhj9z
</code>```

Body:
TL;DR

kubectl logs -n <<ingress_namespace>> <<ingress_pod_name>>

Check the namespace under which the Ingress controller is currently running.

$ kubectl get pods
NAME                                    READY   STATUS    RESTARTS   AGE
helloworld-deployment-7dc448d6b-5zvr8   1/1     Running   1          3d20h
helloworld-deployment-7dc448d6b-82dnt   1/1     Running   1          3d20h

$ kubectl get pods -n kube-system
NAME                                        READY   STATUS    RESTARTS   AGE
kube-apiserver-minikube                     1/1     Running   1          3d20h
nginx-ingress-controller-586cdc477c-rhj9z   1/1     Running   1          3d21h

For me, it happens to be the kube-system namespace on the pod nginx-ingress-controller-586cdc477c-rhj9z.

Now, get the logs just like you would for any pod using

 kubectl logs -n kube-system nginx-ingress-controller-586cdc477c-rhj9z


问:
Conditional groupby sum
I would like to create a column that contains the sum of all amounts that occurred in a given hour. For example, if the row I am looking at has 0 under the column 0, I would like the volume column for that row to be the total volume for all amounts that occurred within that hour.

So:

```<code>dat.groupby('Hours')['Amount'].sum()
</code>```

by performing groupby hours and summing the amount, I get the total amount of transactions that where made in each hour.

```<code>Hours
0     257101.87
1     146105.69
2     108819.17
....
45    532181.83
46    448887.69
47    336343.60
Name: Amount, dtype: float64
</code>```

Problem is my database contains 1000s of rows and I can't simply create a new column with the values from the groupby, I would need a condition stipulating that if the value on the hour column is 0 then return the sum of all the amounts where the hour is 0.

So the desired result would be something like this

```<code>Hours      Amount      Total
 0           20         100
 0           20         100
 0           60         100
 1           10          20
 1           10          20
 2           50          50
</code>```

In this scenario I would want to create the total column and return the sum of all amounts that occurred in a given hour

答:
I would use the output of dat.groupby('Hours')['Amount'].sum(), and merge it with the original set on the Hours column:

```<code>totals = dat.groupby('Hours')['Amount'].sum()

dat_with_totals = dat.merge(totals, on='Hours')
</code>```

Title: Conditional groupby sum

Body:
I would like to create a column that contains the sum of all amounts that occurred in a given hour. For example, if the row I am looking at has 0 under the column 0, I would like the volume column for that row to be the total volume for all amounts that occurred within that hour.

So:

dat.groupby('Hours')['Amount'].sum()

by performing groupby hours and summing the amount, I get the total amount of transactions that where made in each hour.

Hours
0     257101.87
1     146105.69
2     108819.17
....
45    532181.83
46    448887.69
47    336343.60
Name: Amount, dtype: float64

Problem is my database contains 1000s of rows and I can't simply create a new column with the values from the groupby, I would need a condition stipulating that if the value on the hour column is 0 then return the sum of all the amounts where the hour is 0.

So the desired result would be something like this

Hours      Amount      Total
 0           20         100
 0           20         100
 0           60         100
 1           10          20
 1           10          20
 2           50          50

In this scenario I would want to create the total column and return the sum of all amounts that occurred in a given hour

Body:
I would use the output of dat.groupby('Hours')['Amount'].sum(), and merge it with the original set on the Hours column:

totals = dat.groupby('Hours')['Amount'].sum()

dat_with_totals = dat.merge(totals, on='Hours')