问:
Context menu for TreeViewer based on selected node - SWT
I need to create a context menu for a TreeViewer in an Eclipse plugin project. But, the menu should not contain constant items, they should vary depending on the type of the node that is selected. For example, my treeViewer has the following hierarchy:

```<code>Node A
 |
 --Node B
  |
   --Node C
</code>```

For node A - I want to show a menu with an action, but for nodes B and C I don't want to show anything (no menu).
I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected. My code looks like:

```<code>treeViewer.addSelectionChangedListener(
            new ISelectionChangedListener(){
                public void selectionChanged(SelectionChangedEvent event) {
                    if(event.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
                        Object o = selection.getFirstElement();

                        MenuManager menuMgr = new MenuManager();

                        if (o instanceof NodeA){

                            Menu menu = menuMgr.createContextMenu(treeViewer.getControl());
                            treeViewer.getControl().setMenu(menu);
                            getSite().registerContextMenu(menuMgr, treeViewer);

                            menuMgr.add(new SomeAction());

                        }else {
                            //what ?
                        }
                    }

                }
            }
    );
</code>```

On the else branch I tried to call dispose(),removeAll() on the MenuManager...nothing works!

Any help is appreciated, thanks.

答:
Just use single Menu Manager.
Do not make Menu Manager dynamically.

in theory, It's possible you tried, but it's inefficient and it's not general way.

Just make a Menu Manager and add all actions which you needs.

when selection has been changed, call Action#setVisible(true|false)to hide or show menu items.
You can also use Action#setEnable to enable/disable menu item.

ps.
Menu Manager is not a menu GUI(likes TreeViewer is a not tree)

It contributes Actions(business logic) to Menu(SWT). And It also manage visibility and enablement. We call this Contribution Manager. We can create a SWT menu very easy with this. (even we don't know about SWT, we just have to know only our business logic:Action) It's fundamental idea in JFace.

When you add an action into manu manager, action will be wrapped with ActionContributionItem. It hooks action's state to update UI(visibility, enablement for menu, button, toolbar and so on). It also hooks UI to launch action when it pressed.

If you are new to eclipse, It is easy to confuse role of SWT and JFace.

Body:
I need to create a context menu for a TreeViewer in an Eclipse plugin project. But, the menu should not contain constant items, they should vary depending on the type of the node that is selected. For example, my treeViewer has the following hierarchy:

Node A
 |
 --Node B
  |
   --Node C

For node A - I want to show a menu with an action, but for nodes B and C I don't want to show anything (no menu).
I managed to create the menu for node A, but then I can't get rid of it when some other type of node is selected. My code looks like:

treeViewer.addSelectionChangedListener(
            new ISelectionChangedListener(){
                public void selectionChanged(SelectionChangedEvent event) {
                    if(event.getSelection() instanceof IStructuredSelection) {
                        IStructuredSelection selection = (IStructuredSelection)event.getSelection();
                        Object o = selection.getFirstElement();

                        MenuManager menuMgr = new MenuManager();

                        if (o instanceof NodeA){

                            Menu menu = menuMgr.createContextMenu(treeViewer.getControl());
                            treeViewer.getControl().setMenu(menu);
                            getSite().registerContextMenu(menuMgr, treeViewer);

                            menuMgr.add(new SomeAction());

                        }else {
                            //what ?
                        }
                    }

                }
            }
    );

On the else branch I tried to call dispose(),removeAll() on the MenuManager...nothing works!

Any help is appreciated, thanks.


来源: stackexchange

问:
How to make Azure AD authentication work outside localhost
I created a blazor server app like this:

That works fine on my local machine. However, when deploying the website to azure I get the following error message: AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application

In the azure portal I navigated to the enterprise application that was automatically created during the project creation in visual studio. However, the "Homepage URL" is readonly.

How can I make this work?

答:
Method 1:

Instead of Enterprise application go to App registration click on Authentication under Manage group, in Authentication Menu you can specify redirect URL.

Method 2:

You can modify application manifest for redirect URL and save it after modification.

Considering AAD application is created using your own account you should be owner of this application and can be able to modify it.

Let me know for any question, happy to help!

ContentLicense: CC BY-SA 4.0


问:
Seqkit - manipulate regex for parsing ID
I am trying to use seqkit rmdup to remove duplicated sequences from my protein fasta files. However, it's only the accession numbers which are duplicated and not the description or sequences. See example below.

```<code>Host_331002_c0_seq1 95 1381 2 +
Host_331002_c0_seq1 1873 2112 1 +
</code>```

So basically I want to set a flag which will stop at the first tab when searching the identifiers (stop after Host_331002_c0_seq1) otherwise I won't get any duplicates in my output file. This flag would fix it but I am not sure how to manipulate regex.

```<code>--id-regexp string                regular expression for parsing ID (default "^(\\S+)\\s?")
</code>```

Could you assist with this issue?

I just started learning all the programming languages and I am not certain how to change that.

答:
Regex to match any zero or more characters up to the first tab excluding tab is

```<code>^[^\t]*
</code>```

See proof.

Body:
I am trying to use seqkit rmdup to remove duplicated sequences from my protein fasta files. However, it's only the accession numbers which are duplicated and not the description or sequences. See example below.

Host_331002_c0_seq1 95 1381 2 +
Host_331002_c0_seq1 1873 2112 1 +

So basically I want to set a flag which will stop at the first tab when searching the identifiers (stop after Host_331002_c0_seq1) otherwise I won't get any duplicates in my output file. This flag would fix it but I am not sure how to manipulate regex.

--id-regexp string                regular expression for parsing ID (default "^(\\S+)\\s?")

Could you assist with this issue?

I just started learning all the programming languages and I am not certain how to change that.

Body:
Regex to match any zero or more characters up to the first tab excluding tab is

^[^\t]*

See proof.


问:
Parsing a value with a dimension in Android
What is the proper way to parse a value with a dimension in Android? For example, I would want to get an int with a value of 20 from any of these strings: 20px, 20mm, 20dp.

Trying Integer.parseInt() doesn't get me very far because it throws an exception on non-numeric characters.

答:
If you start with an AttributeSet, you can obtain a TypedArray through a Context and eventually use getDimension or a related function.

If you just want to pass a string to parseInt without throwing an exception try this:

```<code>Integer.parseInt( someString.replaceFirst( "[^0-9].*" , "" ) );
</code>```

The regular expression truncates the string starting at the first character that is not a digit.  Which implies that the string must start with a digit.

ContentLicense: CC BY-SA 2.5

Body:
If you start with an AttributeSet, you can obtain a TypedArray through a Context and eventually use getDimension or a related function.

If you just want to pass a string to parseInt without throwing an exception try this:

Integer.parseInt( someString.replaceFirst( "[^0-9].*" , "" ) );

The regular expression truncates the string starting at the first character that is not a digit.  Which implies that the string must start with a digit.

ContentLicense: CC BY-SA 3.0


问:
How should I make a prepared statement here?
I am trying to execute that query using mysql2:

```<code>const [[questions]] =
  await db.promise().execute(
    'SELECT * FROM `questions` WHERE `questions`.`topic` LIKE ?',
    ['%' + text + '%']
  );
</code>```

but get nothing from database.

Then I tried this:

```<code>const [[questions]] =
  await db.promise().execute(
    "SELECT * FROM `questions` WHERE `questions`.`topic` LIKE '?'",
    ['%' + text + '%']
  );
</code>```

and still nothing.

How should I make prepared statement here?

答:
try this way : </p>

```<code>let query = `SELECT * FROM questions WHERE questions.topic LIKE '%${text}%'`;

const data = await db.promise().execute(query);
console.log('data ==>',data);
</code>```

Body:
I am trying to execute that query using mysql2:

const [[questions]] =
  await db.promise().execute(
    'SELECT * FROM `questions` WHERE `questions`.`topic` LIKE ?',
    ['%' + text + '%']
  );

but get nothing from database.

Then I tried this:

const [[questions]] =
  await db.promise().execute(
    "SELECT * FROM `questions` WHERE `questions`.`topic` LIKE '?'",
    ['%' + text + '%']
  );

and still nothing.

How should I make prepared statement here?

Body:
try this way :

let query = `SELECT * FROM questions WHERE questions.topic LIKE '%${text}%'`;

const data = await db.promise().execute(query);
console.log('data ==>',data);


问:
Test if notebook is running on Google Colab
How can I test if my notebook is running on Google Colab?

I need this test as obtaining / unzipping my training data is different if running on my laptop or on Colab.

答:
you can check environment variable like this:

```<code>import os
if 'COLAB_GPU' in os.environ:
   print("I'm running on Colab")
</code>```

actually you can print out os.environ to check what's associated with colab and then check the key

Body:
you can check environment variable like this:

import os
if 'COLAB_GPU' in os.environ:
   print("I'm running on Colab")

actually you can print out os.environ to check what's associated with colab and then check the key


问:
How to export database with diagrams in SQL Server?
I have tried to export a SQL Server database to a <code>.bacpac</code> file, but when I import the file, the database diagrams were not there. </p>

答: The diagrams are stored as data in a table (sysdiagrams), so I guess you'll need a .dacpac </p>

Body: I have tried to export a SQL Server database to a .bacpac file, but when I import the file, the database diagrams were not there.


问:
Sending data to Azure IoT hub using REST
I am trying to learn the Azure IoT hub, but I am unable to send data to my IoT hub using Postman.
I did the following:

Create Azure IoT hub

Create a device using Azure Portal CLI

Copied the text where it said "primary key" on the Device page

My request looks as follows:

POST https://myhub.azure-devices.net/devices/MyDevice/messages/events?api-version=2020-03-13

I have added the authorization header, which has the value:
SharedAccessSignature=SharedAccessSignature sr=myhub.azure-devices.net%2Fdevices%2FMyDevice&sig=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Where the key is the copied text from the "primary key" field from the device page.

Content-type is set to application/json. But the body is currently empty.

I am getting the following response:

"Message": "ErrorCode:ServerError;InternalServerError",

Note: Hub and device name are not the same as stated here.

答: You need to calculate the auth header based on your primary key, not just put it into the header. See here for examples how to do this, for instance by using CLI az iot hub generate-sas-token


问:
Zooming an item in Listbox/SurfaceListbox WPF
I am working on SurfaceListbox but I think the logic would apply to normal WPF listbox also.

I have the surfacelistbox with horizontal scroll enabled. It contains close to 20 items. The surfacelistbox is going to be placed in the center of the screen. Now when the user scrolls the listbox, the items move horizontally and based on the size of each item in the listbox, I have seen generally 3 items are visible at any given time on the screen.

Now what I want to do is, when the user stops scrolling and the 3 items are visible, I want to zoom in the center item i.e. basically enlarge it to highlight it.

Any pointers on how to implement such functionality in WPF would be great. Since the user doesnt make a selection when scrolling I could not use the selectionchanged event to know which one is the center item.

答:
Got useful information from these two links

http://social.msdn.microsoft.com/Forums/en-US/surfaceappdevelopment/thread/290f18c3-9579-4578-b215-45e6eb702470

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5d486826-9a72-4769-bd09-ff6977e16c30


问:
Change all negative values to 0
I would like to set every negative value in a column of integers to 0. That is, set it to 0 IN THE SAME CELL. Of course, I could just use MAX(cell,0) if I wanted a new column.

I think Format Cells -> Format Code may do this, as it appears to support some kind of regex, but how do I replace any generic negative value with 0?

I don't know the syntax and can't find any documentation on it. This is a custom format I tried:

```<code>#,##0.00;"0.00"
</code>```

The problem is, it just masks the negative values as "0.00". It doesn't replace the VALUE with 0. Calculations assume that cell still contains the negative value.

答:
```<code>=if(A1-A2<0; 0; A1-A2)
</code>```

If A1-A2 is less than 0, show 0, otherwise show A1-A2.

OR...

You can use conditional formatting!

Highlight the cells then, at the top, open Format > Conditional Formatting.
Cell value is, less than, 0
Then hit New Style, name it Zero (or whatever),
Open the Numbers tab.  At the bottom where it says Format code, change whatever is in there to "0.00" (include the quotes).
Hit OK. Make sure Cell Style is Zero. Hit OK. Done.

Hope that helps

Title: Change all negative values to 0

Body:
I would like to set every negative value in a column of integers to 0. That is, set it to 0 IN THE SAME CELL. Of course, I could just use MAX(cell,0) if I wanted a new column.

I think Format Cells -> Format Code may do this, as it appears to support some kind of regex, but how do I replace any generic negative value with 0?

I don't know the syntax and can't find any documentation on it. This is a custom format I tried:

#,##0.00;"0.00"

The problem is, it just masks the negative values as "0.00". It doesn't replace the VALUE with 0. Calculations assume that cell still contains the negative value.

Body:
=if(A1-A2<0; 0; A1-A2)

If A1-A2 is less than 0, show 0, otherwise show A1-A2.

OR...

You can use conditional formatting!

Highlight the cells then, at the top, open Format > Conditional Formatting.
Cell value is, less than, 0
Then hit New Style, name it Zero (or whatever),
Open the Numbers tab.  At the bottom where it says Format code, change whatever is in there to "0.00" (include the quotes).
Hit OK. Make sure Cell Style is Zero. Hit OK. Done.

Hope that helps


问:
How to manage resources that cannot be deep-copied in C++
I am creating a class that manages a resource that should not be "deep copied", that is, there can only ever be one instance of the underlying resource, even if multiple objects have access this same resource.

However, allowing multiple objects to access this resource is also dangerous, as one object could go out of scope, and self-destruct, which will also destroy the resource. In this case, is it reasonable to only define a move constructor (without allowing for shallow copies)? Or is there some way to support shallow copies, so that multiple objects can reference the same resource, but the resource will not be destroyed if at least one object still has access to the resource?

For context, the resource being managed is an OpenGL shader, and each object has the ID of this shader as one of it's members, which it uses to tell OpenGL to delete the shader when necessary.

答:
I think that you are looking for std::shared_ptr or parallel solution; std::shared_ptr is used to share pointers to a single object, which is destroyed only after all of the shared pointers are cleared. Thus, while we still have a reference to the object, it remains valid.

Even if you are not looking to use shared_ptr, the idea behind it is to use a reference counter, which is shared by all objects that refer to the same resource - each time you call a constructor/copy constructor/copy-assignment, you increase the shared counter by 1, and in the destructor, you decrease it by 1, and if (and only if) it reaches 0 then you release the underlying resource.

Also, for completeness of the answer, I should add that for std::shared_ptr, there is in addition std::weak_ptr, which denotes access without shared ownership - it allows one to access a resource held by a std::shared_ptr while it is alive, but can be reset automatically if all of the std::shared_ptr that refer to the resource are destroyed. It is rare to see usage of it, but it is possible to use it, nevertheless.


问:
Re-launching the docker container from same state from where it failed?
I am running some Machine Learning python code in one docker container and suppose it fails due to whatever reason and i want to launch a new container from the same state where the old one left computation of my code?Is there any way to do it?Like can we store the state or something like that and re-run it?</p>

答: You can't do that in docker. Containers are isolated from each other. You can start and run multiple containers of the same image but they don't interfere each other. So when you will start a new container, it will be totally a new instance of your application.</p>


问:
How to extend the return type of a function passing the parameter type?
I'm trying to define an interface extending properties from the return type of an existing function.
But the function has its return type defined by a parameter type. Something like the code below:

function doSomething<T: any>(myParameter: T): { myProperty: T };
```

<pre class="lang-js prettyprint-override"><code>interface MyInterface<A> extends ReturnType<typeof doSomething<A>> {
  newProperty1: boolean;
  newProperty2: boolean;
}
</code>```

Then, when I use the interface, I would like to infer the function's parameter type, like

let something: MyInterface<number>;
```

<p>resulting in a type like</p>

<pre class="lang-js prettyprint-override"><code>{
  myProperty: number,
  newProperty1: boolean,
  newProperty2: boolean,
}
</code>```

How can I achieve this?

答:
Sadly, I don't think you can reuse the signature of doSomething. As a workaround, you could re-define it by using an interface.

```<code>interface MyCallSignature<T> {
  (myParameter: T): {
    myParameter: T
  }
}

interface MyInterface<T> extends ReturnType<MyCallSignature<T>> {
  newProperty1: boolean;
  newProperty2: boolean;
}

declare let something: MyInterface<number>;

something.myProperty; // number
something.newProperty1; // boolean
something.newProperty2; // boolean
</code>```

Body:
I'm trying to define an interface extending properties from the return type of an existing function.
But the function has its return type defined by a parameter type. Something like the code below:

function doSomething<T: any>(myParameter: T): { myProperty: T };

interface MyInterface extends ReturnType<typeof doSomething> {
  newProperty1: boolean;
  newProperty2: boolean;
}

Then, when I use the interface, I would like to infer the function's parameter type, like

let something: MyInterface<number>;

resulting in a type like

{
  myProperty: number,
  newProperty1: boolean,
  newProperty2: boolean,
}

How can I achieve this?

Body:
Sadly, I don't think you can reuse the signature of doSomething. As a workaround, you could re-define it by using an interface.

interface MyCallSignature<T> {
  (myParameter: T): {
    myParameter: T
  }
}

interface MyInterface<T> extends ReturnType<MyCallSignature<T>> {
  newProperty1: boolean;
  newProperty2: boolean;
}

declare let something: MyInterface<number>;

something.myProperty; // number
something.newProperty1; // boolean
something.newProperty2; // boolean


问:
ViewFactory iphone
Has anyone successfully used this class to load custom tableViewCells. I have tried to create a singleton of the viewFactory class and load the cells using the shared instance but I get the following error...

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ViewFactory sharedMyClassName]: unrecognized selector sent to class 0x32a24'

I am using this macro to create the singleton, and following the tutorial here Anyone had any experience with this before? I realise this may be a longshot but if anyone has ever used it then please let me know.

Many thanks

Jules

答:
The only reason that ViewFactory class is a singleton is so that you can access it globally. It would be trivial to take the bit of code in ViewFactory that does useful work and incorporate it into your own table view controller subclass. That would eliminate the singleton, make it easier to use separate nibs for each table, and (IMO) make your code simpler.

Another approach that works well is to put each type of cell in its own nib and use -loadNibNamed:owner:options: to load the cells as needed. The technique is described in Loading Custom Table-View Cells From Nib Files. It's not difficult, and although the example in that section uses only one type of custom cell it's easy to extrapolate to multiple custom cells.

Title: ViewFactory iphone


问:
Counting zeros in a rolling - numpy array (including NaNs)
I am trying to find a way of Counting zeros in a rolling using numpy array ?

Using pandas I can get it using:

```<code>df['demand'].apply(lambda x: (x == 0).rolling(7).sum()).fillna(0))
</code>```

or

```<code>df['demand'].transform(lambda x: x.rolling(7).apply(lambda x: 7 - np.count _nonzero(x))).fillna(0)
</code>```

In numpy, using the code from Here

```<code>def rolling_window(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    print(shape)
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])

np.count_nonzero(rolling_window(arr==0, 7), axis=1)

Output:
    array([2, 3])
</code>```

However, I need the first 6 NaNs as well, and fill it with zeros:

Expected output:

```<code>array([0, 0, 0, 0, 0, 0, 2, 3])
</code>```

答:
Think an efficient one would be with 1D convolution -

```<code>def sum_occurences_windowed(arr, W):
    K = np.ones(W, dtype=int)
    out = np.convolve(arr==0,K)[:len(arr)]
    out[:W-1] = 0
    return out
</code>```

Sample run -

```<code>In [42]: arr
Out[42]: array([10, 20, 30,  5,  6,  0,  0,  0])

In [43]: sum_occurences_windowed(arr,W=7)
Out[43]: array([0, 0, 0, 0, 0, 0, 2, 3])
</code>```

Timings on varying length arrays and window of 7

Including count_rolling from @Quang Hoang's post.

Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

```<code>import benchit
funcs = [sum_occurences_windowed, count_rolling]
in_ = {n:(np.random.randint(0,5,(n)),7) for n in [10,20,50,100,200,500,1000,2000,5000]}
t = benchit.timings(funcs, in_, multivar=True, input_name='Length')
t.plot(logx=True, save='timings.png')
</code>```

Extending to generic n-dim arrays

```<code>from scipy.ndimage.filters import convolve1d

def sum_occurences_windowed_ndim(arr, W, axis=-1):
    K = np.ones(W, dtype=int)
    out = convolve1d((arr==0).astype(int),K,axis=axis,origin=-(W//2))
    out.swapaxes(axis,0)[:W-1] = 0
    return out
</code>```

So, on a 2D array, for counting along each row, use axis=1 and for cols, axis=0 and so on.

Sample run -

```<code>In [155]: np.random.seed(0)

In [156]: a = np.random.randint(0,3,(3,10))

In [157]: a
Out[157]:
array([[0, 1, 0, 1, 1, 2, 0, 2, 0, 0],
       [0, 2, 1, 2, 2, 0, 1, 1, 1, 1],
       [0, 1, 0, 0, 1, 2, 0, 2, 0, 1]])

In [158]: sum_occurences_windowed_ndim(a, W=7)
Out[158]:
array([[0, 0, 0, 0, 0, 0, 3, 2, 3, 3],
       [0, 0, 0, 0, 0, 0, 2, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 4, 3, 4, 3]])

# Verify with earlier 1D solution
In [159]: np.vstack([sum_occurences_windowed(i,7) for i in a])
Out[159]:
array([[0, 0, 0, 0, 0, 0, 3, 2, 3, 3],
       [0, 0, 0, 0, 0, 0, 2, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 4, 3, 4, 3]])
</code>```

Let's test out our original 1D input array -

```<code>In [187]: arr
Out[187]: array([10, 20, 30,  5,  6,  0,  0,  0])

In [188]: sum_occurences_windowed_ndim(arr, W=7)
Out[188]: array([0, 0, 0, 0, 0, 0, 2, 3])
</code>```

Body:
I am trying to find a way of Counting zeros in a rolling using numpy array ?

Using pandas I can get it using:

df['demand'].apply(lambda x: (x == 0).rolling(7).sum()).fillna(0))

or

df['demand'].transform(lambda x: x.rolling(7).apply(lambda x: 7 - np.count _nonzero(x))).fillna(0)

In numpy, using the code from Here

def rolling_window(a, window_size):
    shape = (a.shape[0] - window_size + 1, window_size) + a.shape[1:]
    print(shape)
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

arr = np.asarray([10, 20, 30, 5, 6, 0, 0, 0])

np.count_nonzero(rolling_window(arr==0, 7), axis=1)

Output:
    array([2, 3])

However, I need the first 6 NaNs as well, and fill it with zeros:

Expected output:

array([0, 0, 0, 0, 0, 0, 2, 3])

Body:
Think an efficient one would be with 1D convolution -

def sum_occurences_windowed(arr, W):
    K = np.ones(W, dtype=int)
    out = np.convolve(arr==0,K)[:len(arr)]
    out[:W-1] = 0
    return out

Sample run -

In [42]: arr
Out[42]: array([10, 20, 30,  5,  6,  0,  0,  0])

In [43]: sum_occurences_windowed(arr,W=7)
Out[43]: array([0, 0, 0, 0, 0, 0, 2, 3])

Timings on varying length arrays and window of 7

Including count_rolling from @Quang Hoang's post.

Using benchit package (few benchmarking tools packaged together; disclaimer: I am its author) to benchmark proposed solutions.

import benchit
funcs = [sum_occurences_windowed, count_rolling]
in_ = {n:(np.random.randint(0,5,(n)),7) for n in [10,20,50,100,200,500,1000,2000,5000]}
t = benchit.timings(funcs, in_, multivar=True, input_name='Length')
t.plot(logx=True, save='timings.png')

Extending to generic n-dim arrays

from scipy.ndimage.filters import convolve1d

def sum_occurences_windowed_ndim(arr, W, axis=-1):
    K = np.ones(W, dtype=int)
    out = convolve1d((arr==0).astype(int),K,axis=axis,origin=-(W//2))
    out.swapaxes(axis,0)[:W-1] = 0
    return out

So, on a 2D array, for counting along each row, use axis=1 and for cols, axis=0 and so on.

Sample run -

In [155]: np.random.seed(0)

In [156]: a = np.random.randint(0,3,(3,10))

In [157]: a
Out[157]:
array([[0, 1, 0, 1, 1, 2, 0, 2, 0, 0],
       [0, 2, 1, 2, 2, 0, 1, 1, 1, 1],
       [0, 1, 0, 0, 1, 2, 0, 2, 0, 1]])

In [158]: sum_occurences_windowed_ndim(a, W=7)
Out[158]:
array([[0, 0, 0, 0, 0, 0, 3, 2, 3, 3],
       [0, 0, 0, 0, 0, 0, 2, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 4, 3, 4, 3]])

# Verify with earlier 1D solution
In [159]: np.vstack([sum_occurences_windowed(i,7) for i in a])
Out[159]:
array([[0, 0, 0, 0, 0, 0, 3, 2, 3, 3],
       [0, 0, 0, 0, 0, 0, 2, 1, 1, 1],
       [0, 0, 0, 0, 0, 0, 4, 3, 4, 3]])

Let's test out our original 1D input array -

In [187]: arr
Out[187]: array([10, 20, 30,  5,  6,  0,  0,  0])

In [188]: sum_occurences_windowed_ndim(arr, W=7)
Out[188]: array([0, 0, 0, 0, 0, 0, 2, 3])


问:
Change the starting value of a serial - Postgresql
I've a little problem with serial : From a file, I filled my database in which I have a client ID (it is a serial and it is my primary key). I have 300 clients so 300 client ID (1 to 300). Now my problem is, I've a form for new clients.I cannot add them because when I add a client, my program adds the client with ID 1 or the ID 1 is already assigned to another client.

So my question is : is it possible to change the starting value of a serial for to resolve this problem ?

答:
The solutions above did not work for what I needed.

I needed a serial id to use as a primary key that started from 1000, rather than 1.

In order to do this, I created a standard serial column:

```<code>ALTER table my_table ADD COLUMN new_id SERIAL PRIMARY KEY;
</code>```

and then updated that column:

```<code>UPDATE my_table set new_id = new_id + 1000;
</code>```

I then joined that table to the table with existing non-consecutive id numbers under 1000.

Body:
The solutions above did not work for what I needed.

I needed a serial id to use as a primary key that started from 1000, rather than 1.

In order to do this, I created a standard serial column:

ALTER table my_table ADD COLUMN new_id SERIAL PRIMARY KEY;

and then updated that column:

UPDATE my_table set new_id = new_id + 1000;

I then joined that table to the table with existing non-consecutive id numbers under 1000.


问:
AWS DMS replication instance unable to connect local machine SQL Server test endpoint
I am trying to migrate & replicate on-premise SQL Server DB to Aurora DB in AWS. From the AWS docs., it seems it is possible. However, when I tried to implement I faced few problems as below:

What server name should I provide while setting up the source endpoint (i.e., SQL Server)? Should I specify 'My-Public-IP\DB-Instance-Name'?

I tried that but got 'Test Endpoint Failed' error when trying to test the endpoint.

PS: Same as this - Connectivity Issue from AWS DMS to local SQL Server

答:
Yes you can migrate the data from on prem sql server to Aurora.

While setting up your source endpoint you should provide IP address of sql server instance in server name field.

After this if you are getting timeout error then check NACL ,security group or on-prem sql server instance firewall if any of them is blocking ips


问:
How can I update the Application Loader on MAC OS Catalina 10.15.5?
If i check this link https://help.apple.com/itc/apploader/ this is the showed me:

But if i check my Application Loader this is showed me:

Someone knows what is the problem?

答: Application Loader has been replaced.  Use Transporter instead.</p>


问:
Loopback 4 authorization allowing access to all type of users
I am following this article for implementing authorization in my app. The user with the admin role can perform certain operations that other users can't.

But it is not working. The controllers are accessible to all type of users

Here is the code

Thank you in advance

user model has a property called role

```<code>  @property({
    type: 'string',
  })
  role?: string;
</code>```

authorizer.ts

```<code>import {AuthorizationContext, AuthorizationDecision, AuthorizationMetadata} from '@loopback/authorization';
import {securityId, UserProfile} from '@loopback/security';
import _ from 'lodash';

// Instance level authorizer
// Can be also registered as an authorizer, depends on users' need.
export async function basicAuthorization(
  authorizationCtx: AuthorizationContext,
  metadata: AuthorizationMetadata,

): Promise<AuthorizationDecision> {

  //console.log(authorizationCtx.principals[0])
  //console.log(authorizationCtx.roles)
  // No access if authorization details are missing
  let currentUser: UserProfile;
  if (authorizationCtx.principals.length > 0) {
    const user = _.pick(authorizationCtx.principals[0], [
      'id',
      'name',
      'role', // propety role
    ]);
    //console.log(user)
    currentUser = {[securityId]: user.id, name: user.name, roles: user.role};

    console.log(currentUser)

  } else {
    return AuthorizationDecision.DENY;
  }

  if (!currentUser.roles) {
    return AuthorizationDecision.DENY;
  }

  // Authorize everything that does not have a allowedRoles property
  if (!metadata.allowedRoles) {
    return AuthorizationDecision.ALLOW;
  }

  let roleIsAllowed = false;
  const role = currentUser.roles
  // for (const role of currentUser.roles) {
  if (metadata.allowedRoles!.includes(role)) {
    roleIsAllowed = true;
    // }
  }

  if (!roleIsAllowed) {
    return AuthorizationDecision.DENY;
  }

  // Admin and support accounts bypass id verification
  if (
    currentUser.roles.includes('admin') ||
    currentUser.roles.includes('support')
  ) {
    return AuthorizationDecision.ALLOW;
  }

  /**
   * Allow access only to model owners, using route as source of truth
   *
   * eg. @post('/users/{userId}/orders', ...) returns `userId` as args[0]
   */
  if (currentUser[securityId] === authorizationCtx.invocationContext.args[0]) {
    return AuthorizationDecision.ALLOW;
  }

  return AuthorizationDecision.DENY;
}
</code>```

application.ts

```<code>   //Other imports
        import {MyAuthorizationProvider} from './services/try';
        import {AuthorizationComponent, AuthorizationDecision, AuthorizationOptions, AuthorizationTags} from '@loopback/authorization';

       constructor(options: ApplicationConfig = {}) {
       super(options);
      // other code
        let app = new Application()
    const data: AuthorizationOptions = {
      precedence: AuthorizationDecision.DENY,
      defaultDecision: AuthorizationDecision.DENY,
    };

    const binding = app.component(AuthorizationComponent);
    app.configure(binding.key).to(data);

    app
      .bind('authorizationProviders.my-authorizer-provider')
      .toProvider(MyAuthorizationProvider)
      .tag(AuthorizationTags.AUTHORIZER);
}
</code>```

user.controller.ts

```<code>  @get('/users/count', {
    responses: {
      '200': {
        description: 'User model count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })

  @authenticate('jwt')
  @authorize({allowedRoles: ['admin']})

  async count(
    @param.where(User) where?: Where<User>,
  ): Promise<Count> {
    return this.userRepository.count(where);
  }
</code>```

答:
The actual problem was while generating the token, property role wasn't included in TokenService from @loopback/authentication.

So I created custom-token service implementing this TokenService and added a property role while token-generation.

So later loopback-authentication sends this role to loopback-authorization. You can access it in AuthorizationContext.principals[0]

Here is the code

custom-toekn.service.ts

```<code>import {TokenService} from '@loopback/authentication';
import {inject} from '@loopback/context';
import {HttpErrors} from '@loopback/rest';
import {securityId, UserProfile} from '@loopback/security';
import {promisify} from 'util';
import {TokenServiceBindings} from '../keys';

const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);

export class JWTService implements TokenService {
  constructor(
    @inject(TokenServiceBindings.TOKEN_SECRET)
    private jwtSecret: string,
    @inject(TokenServiceBindings.TOKEN_EXPIRES_IN)
    private jwtExpiresIn: string,
  ) {}

  async verifyToken(token: string): Promise<UserProfile> {
    if (!token) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : 'token' is null`,
      );
    }

    let userProfile: UserProfile;

    try {
      // decode user profile from token
      const decodedToken = await verifyAsync(token, this.jwtSecret);
      // don't copy over  token field 'iat' and 'exp', nor 'email' to user profile
      userProfile = Object.assign(
        {[securityId]: '', name: ''},
        {
          [securityId]: decodedToken.id,
          name: decodedToken.name,
          id: decodedToken.id,
          role: decodedToken.role,
        },
      );
    } catch (error) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : ${error.message}`,
      );
    }
    return userProfile;
  }

  async generateToken(userProfile: UserProfile): Promise<string> {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      role: userProfile.role,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
    }

    return token;
  }
}
</code>```

keys.ts

```<code>import {TokenService} from '@loopback/authentication';

export namespace TokenServiceConstants {
  export const TOKEN_SECRET_VALUE = 'myjwts3cr3t';
  export const TOKEN_EXPIRES_IN_VALUE = '600';
}

export namespace TokenServiceBindings {
  export const TOKEN_SECRET = BindingKey.create<string>(
    'authentication.jwt.secret',
  );
  export const TOKEN_EXPIRES_IN = BindingKey.create<string>(
    'authentication.jwt.expires.in.seconds',
  );
  export const TOKEN_SERVICE = BindingKey.create<TokenService>(
    'services.authentication.jwt.tokenservice',
  );
}
</code>```

Then you have to bind this token-service in application.ts

application.ts

```<code>import {JWTService} from './services/token-service';
import {TokenServiceBindings, TokenServiceConstants} from './keys';

this.bind(TokenServiceBindings.TOKEN_SECRET).to(
      TokenServiceConstants.TOKEN_SECRET_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_EXPIRES_IN).to(
      TokenServiceConstants.TOKEN_EXPIRES_IN_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_SERVICE).toClass(JWTService);
</code>```

controller.ts

```<code>import {authenticate, TokenService, UserService} from '@loopback/authentication';
import {Credentials, OPERATION_SECURITY_SPEC, TokenServiceBindings, UserServiceBindings} from '@loopback/authentication-jwt';
import {authorize} from '@loopback/authorization';

export class UserController {
  constructor(
    @repository(UserRepository)
    public userRepository: UserRepository,

    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: UserService<User, Credentials>,
    @inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,

  ) {}

@authenticate('jwt')
  @authorize({allowedRoles: ['admin'], voters: [basicAuthorization]})

aasync fund(){}

}
</code>```

Body:
I am following this article for implementing authorization in my app. The user with the admin role can perform certain operations that other users can't.

But it is not working. The controllers are accessible to all type of users

Here is the code

Thank you in advance

user model has a property called role

  @property({
    type: 'string',
  })
  role?: string;

authorizer.ts

import {AuthorizationContext, AuthorizationDecision, AuthorizationMetadata} from '@loopback/authorization';
import {securityId, UserProfile} from '@loopback/security';
import _ from 'lodash';

// Instance level authorizer
// Can be also registered as an authorizer, depends on users' need.
export async function basicAuthorization(
  authorizationCtx: AuthorizationContext,
  metadata: AuthorizationMetadata,

): Promise<AuthorizationDecision> {

  //console.log(authorizationCtx.principals[0])
  //console.log(authorizationCtx.roles)
  // No access if authorization details are missing
  let currentUser: UserProfile;
  if (authorizationCtx.principals.length > 0) {
    const user = _.pick(authorizationCtx.principals[0], [
      'id',
      'name',
      'role', // propety role
    ]);
    //console.log(user)
    currentUser = {[securityId]: user.id, name: user.name, roles: user.role};

    console.log(currentUser)

  } else {
    return AuthorizationDecision.DENY;
  }

  if (!currentUser.roles) {
    return AuthorizationDecision.DENY;
  }

  // Authorize everything that does not have a allowedRoles property
  if (!metadata.allowedRoles) {
    return AuthorizationDecision.ALLOW;
  }

  let roleIsAllowed = false;
  const role = currentUser.roles
  // for (const role of currentUser.roles) {
  if (metadata.allowedRoles!.includes(role)) {
    roleIsAllowed = true;
    // }
  }

  if (!roleIsAllowed) {
    return AuthorizationDecision.DENY;
  }

  // Admin and support accounts bypass id verification
  if (
    currentUser.roles.includes('admin') ||
    currentUser.roles.includes('support')
  ) {
    return AuthorizationDecision.ALLOW;
  }

  /**
   * Allow access only to model owners, using route as source of truth
   *
   * eg. @post('/users/{userId}/orders', ...) returns `userId` as args[0]
   */
  if (currentUser[securityId] === authorizationCtx.invocationContext.args[0]) {
    return AuthorizationDecision.ALLOW;
  }

  return AuthorizationDecision.DENY;
}

application.ts

   //Other imports
        import {MyAuthorizationProvider} from './services/try';
        import {AuthorizationComponent, AuthorizationDecision, AuthorizationOptions, AuthorizationTags} from '@loopback/authorization';

       constructor(options: ApplicationConfig = {}) {
       super(options);
      // other code
        let app = new Application()
    const data: AuthorizationOptions = {
      precedence: AuthorizationDecision.DENY,
      defaultDecision: AuthorizationDecision.DENY,
    };

    const binding = app.component(AuthorizationComponent);
    app.configure(binding.key).to(data);

    app
      .bind('authorizationProviders.my-authorizer-provider')
      .toProvider(MyAuthorizationProvider)
      .tag(AuthorizationTags.AUTHORIZER);
}

user.controller.ts

  @get('/users/count', {
    responses: {
      '200': {
        description: 'User model count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })

  @authenticate('jwt')
  @authorize({allowedRoles: ['admin']})

  async count(
    @param.where(User) where?: Where<User>,
  ): Promise<Count> {
    return this.userRepository.count(where);
  }

Body:
The actual problem was while generating the token, property role wasn't included in TokenService from @loopback/authentication.

So I created custom-token service implementing this TokenService and added a property role while token-generation.

So later loopback-authentication sends this role to loopback-authorization. You can access it in AuthorizationContext.principals[0]

Here is the code

custom-toekn.service.ts

import {TokenService} from '@loopback/authentication';
import {inject} from '@loopback/context';
import {HttpErrors} from '@loopback/rest';
import {securityId, UserProfile} from '@loopback/security';
import {promisify} from 'util';
import {TokenServiceBindings} from '../keys';

const jwt = require('jsonwebtoken');
const signAsync = promisify(jwt.sign);
const verifyAsync = promisify(jwt.verify);

export class JWTService implements TokenService {
  constructor(
    @inject(TokenServiceBindings.TOKEN_SECRET)
    private jwtSecret: string,
    @inject(TokenServiceBindings.TOKEN_EXPIRES_IN)
    private jwtExpiresIn: string,
  ) {}

  async verifyToken(token: string): Promise<UserProfile> {
    if (!token) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : 'token' is null`,
      );
    }

    let userProfile: UserProfile;

    try {
      // decode user profile from token
      const decodedToken = await verifyAsync(token, this.jwtSecret);
      // don't copy over  token field 'iat' and 'exp', nor 'email' to user profile
      userProfile = Object.assign(
        {[securityId]: '', name: ''},
        {
          [securityId]: decodedToken.id,
          name: decodedToken.name,
          id: decodedToken.id,
          role: decodedToken.role,
        },
      );
    } catch (error) {
      throw new HttpErrors.Unauthorized(
        `Error verifying token : ${error.message}`,
      );
    }
    return userProfile;
  }

  async generateToken(userProfile: UserProfile): Promise<string> {
    if (!userProfile) {
      throw new HttpErrors.Unauthorized(
        'Error generating token : userProfile is null',
      );
    }
    const userInfoForToken = {
      id: userProfile[securityId],
      name: userProfile.name,
      role: userProfile.role,
    };
    // Generate a JSON Web Token
    let token: string;
    try {
      token = await signAsync(userInfoForToken, this.jwtSecret, {
        expiresIn: Number(this.jwtExpiresIn),
      });
    } catch (error) {
      throw new HttpErrors.Unauthorized(`Error encoding token : ${error}`);
    }

    return token;
  }
}

keys.ts

import {TokenService} from '@loopback/authentication';

export namespace TokenServiceConstants {
  export const TOKEN_SECRET_VALUE = 'myjwts3cr3t';
  export const TOKEN_EXPIRES_IN_VALUE = '600';
}

export namespace TokenServiceBindings {
  export const TOKEN_SECRET = BindingKey.create<string>(
    'authentication.jwt.secret',
  );
  export const TOKEN_EXPIRES_IN = BindingKey.create<string>(
    'authentication.jwt.expires.in.seconds',
  );
  export const TOKEN_SERVICE = BindingKey.create<TokenService>(
    'services.authentication.jwt.tokenservice',
  );
}

Then you have to bind this token-service in application.ts

application.ts

import {JWTService} from './services/token-service';
import {TokenServiceBindings, TokenServiceConstants} from './keys';

this.bind(TokenServiceBindings.TOKEN_SECRET).to(
      TokenServiceConstants.TOKEN_SECRET_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_EXPIRES_IN).to(
      TokenServiceConstants.TOKEN_EXPIRES_IN_VALUE,
    );

    this.bind(TokenServiceBindings.TOKEN_SERVICE).toClass(JWTService);

controller.ts

import {authenticate, TokenService, UserService} from '@loopback/authentication';
import {Credentials, OPERATION_SECURITY_SPEC, TokenServiceBindings, UserServiceBindings} from '@loopback/authentication-jwt';
import {authorize} from '@loopback/authorization';

export class UserController {
  constructor(
    @repository(UserRepository)
    public userRepository: UserRepository,

    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: UserService<User, Credentials>,
    @inject(SecurityBindings.USER, {optional: true})
    public users: UserProfile,

  ) {}

@authenticate('jwt')
  @authorize({allowedRoles: ['admin'], voters: [basicAuthorization]})

aasync fund(){}

}


问:
Getting error "Insufficient privileges to complete the operation" while pulling application list using azure-python-sdk
I'm using a service principle with permissions Application.Read.All and Directory.Read.All of Application type to authenticate to Azure and using following code to pull list of Applications in the tenant.

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
from config import app

credentials = ServicePrincipalCredentials(
    client_id = app["CLIENT"],
    secret = app["KEY"],
    tenant = app["TENANT_ID"],
    resource="https://graph.windows.net"
)

graphrbac_client = GraphRbacManagementClient(credentials, app["TENANT"])

for app in graphrbac_client.applications.list():
    print("\nApp:")
    print(app)
print("******\n")
</code>```

Any help is much appreciated

答: Application.Read.All and Directory.Read.All these 2 permissions requires Global Administrator consent for your directory. I would suggest to ask your Global Administrator to provide consent to your service principal. </p>

Body:
I'm using a service principle with permissions Application.Read.All and Directory.Read.All of Application type to authenticate to Azure and using following code to pull list of Applications in the tenant.

from azure.common.credentials import ServicePrincipalCredentials
from azure.graphrbac import GraphRbacManagementClient
from config import app

credentials = ServicePrincipalCredentials(
    client_id = app["CLIENT"],
    secret = app["KEY"],
    tenant = app["TENANT_ID"],
    resource="https://graph.windows.net"
)

graphrbac_client = GraphRbacManagementClient(credentials, app["TENANT"])

for app in graphrbac_client.applications.list():
    print("\nApp:")
    print(app)
print("******\n")

Any help is much appreciated


问:
Running into error "Access to the path 'C:\Users\Work & School\Documents\My Music' is denied." C#-App console
i am learning from the tutorial from microsoft "https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-enumerate-directories-and-files"

Specifically, this one:

```<code>using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Set a variable to the My Documents path.
            string docPath =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        from line in File.ReadLines(file)
                        where line.Contains("Microsoft")
                        select new
                        {
                            File = file,
                            Line = line
                        };

            foreach (var f in files)
            {
                Console.WriteLine($"{f.File}\t{f.Line}");
            }
            Console.WriteLine($"{files.Count().ToString()} files found.");
        }
        catch (UnauthorizedAccessException uAEx)
        {
            Console.WriteLine(uAEx.Message);
        }
        catch (PathTooLongException pathEx)
        {
            Console.WriteLine(pathEx.Message);
        }
    }
}
</code>```

However, when I run this file, I run into the error:

Access to the path 'C:\Users\Work & School\Documents\My Music' is denied.

Im wondering, why is it accessing the My Music folder in the first place, when all it should be doing is going to Documents? Furthermore, I also tried deleting the Music folder from a separate folder but i still end up getting the same error. I also put two text files in the document folder, both specifying "Microsoft" so they will return the values from the lines. How would I get rid of the error?

*for the text files, I also turned off the readonly attribute

答:
why is it accessing the My Music folder in the first place?

Because of your SearchOption. SeachOption.AllDirectories searches file in current directory as well as all its subdirectories.

If you want to search only in current directory not in its subdirectories then, change SearchOption to SeachOption.TopDirectoryOnly

Your updated code should look like,

```<code> var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.TopDirectoryOnly)
           from line in File.ReadLines(file)
           where line.Contains("Microsoft")
           select new
           {
                 File = file,
                 Line = line
           };
</code>```

SearchOption Enum (From MSDN)

Body:
i am learning from the tutorial from microsoft "https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-enumerate-directories-and-files"

Specifically, this one:

using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Set a variable to the My Documents path.
            string docPath =
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.AllDirectories)
                        from line in File.ReadLines(file)
                        where line.Contains("Microsoft")
                        select new
                        {
                            File = file,
                            Line = line
                        };

            foreach (var f in files)
            {
                Console.WriteLine($"{f.File}\t{f.Line}");
            }
            Console.WriteLine($"{files.Count().ToString()} files found.");
        }
        catch (UnauthorizedAccessException uAEx)
        {
            Console.WriteLine(uAEx.Message);
        }
        catch (PathTooLongException pathEx)
        {
            Console.WriteLine(pathEx.Message);
        }
    }
}

However, when I run this file, I run into the error:

Access to the path 'C:\Users\Work & School\Documents\My Music' is denied.

Im wondering, why is it accessing the My Music folder in the first place, when all it should be doing is going to Documents? Furthermore, I also tried deleting the Music folder from a separate folder but i still end up getting the same error. I also put two text files in the document folder, both specifying "Microsoft" so they will return the values from the lines. How would I get rid of the error?

*for the text files, I also turned off the readonly attribute

Body:
why is it accessing the My Music folder in the first place?

Because of your SearchOption. SeachOption.AllDirectories searches file in current directory as well as all its subdirectories.

If you want to search only in current directory not in its subdirectories then, change SearchOption to SeachOption.TopDirectoryOnly

Your updated code should look like,

 var files = from file in Directory.EnumerateFiles(docPath, "*.txt", SearchOption.TopDirectoryOnly)
           from line in File.ReadLines(file)
           where line.Contains("Microsoft")
           select new
           {
                 File = file,
                 Line = line
           };

SearchOption Enum (From MSDN)


问:
ReactJS JSX Use Shorthand to Perform Multiple Executions
I understand a shorthand can be used to return a single execution, but is there a way to make a shorthand return multiple executions?

Take the following example (working):

```<code>import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && console.log("one")}</div>
  )
}

export default CompName;
</code>```

Output:
one

Now I want to execute two console logs if the condition is true:

```<code>import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && (console.log("one") && console.log("two"))}</div>
  )
}

export default CompName;
</code>```

Output:
one

Expected Output:
one
two

Anyone have any idea on the syntax I should be using to get the expected output?

答:
I think i got it working. I needed to use the OR instead of the AND.

change:

```<code> condition && (console.log("one") && console.log("two"))
</code>```

to:

```<code> condition && (console.log("one") || console.log("two"))
</code>```

I believe the reason for this was the shorthand is looking for a true/false return value. And a function call returning nothing is falsey, therefor the 2nd execution never takes place.

I'll leave this up here in case anyone else runs into this.

Edit:

Although the above works, shorthand's should NEVER BE USED this way.

The reason is lets say those two executions are function calls, and the first execution is changed to return true. This means the 2nd execution will never happen.

This means later down the road you can introduce a bug that will become very hard to trace.

Ultimately, it's just better to use the following when you have MORE THAN ONE execution needing to perform:

```<code>if(condition){console.log("foo"); console.log("bar");}
</code>```

This becomes much easier to find in the code, if the bug is ever introduced.

Body:
I understand a shorthand can be used to return a single execution, but is there a way to make a shorthand return multiple executions?

Take the following example (working):

import React from 'react';

const CompName = () => {
  const condition = true;
  return (

{condition && console.log("one")}

  )
}

export default CompName;

Output:
one

Now I want to execute two console logs if the condition is true:

import React from 'react';

const CompName = () => {
  const condition = true;
  return (

{condition && (console.log("one") && console.log("two"))}

  )
}

export default CompName;

Output:
one

Expected Output:
one
two

Anyone have any idea on the syntax I should be using to get the expected output?

Body:
I think i got it working. I needed to use the OR instead of the AND.

change:

 condition && (console.log("one") && console.log("two"))

to:

 condition && (console.log("one") || console.log("two"))

I believe the reason for this was the shorthand is looking for a true/false return value. And a function call returning nothing is falsey, therefor the 2nd execution never takes place.

I'll leave this up here in case anyone else runs into this.

Edit:

Although the above works, shorthand's should NEVER BE USED this way.

The reason is lets say those two executions are function calls, and the first execution is changed to return true. This means the 2nd execution will never happen.

This means later down the road you can introduce a bug that will become very hard to trace.

Ultimately, it's just better to use the following when you have MORE THAN ONE execution needing to perform:

if(condition){console.log("foo"); console.log("bar");}

This becomes much easier to find in the code, if the bug is ever introduced.


问:
Traefik v2: 404 while routing HTTP traffic globally to HTTPS
I have the problem that I can route HTTPS traffic but I can not globally redirect the HTTP traffic to HTTPS. In my case I only want HTTPS traffic, so that I want to redirect all the incoming traffic.

Currently I get an 404 error while I try to serve my URLs over HTTP.
I already enabled DEBUG logs in Treafik, but I can not see any problems or unnormal stuff in the logs.

Additionally I saw a pretty similar topic here on Stackoverflow, but we found out, that his error was not the same to mine: How to redirect http to https with Traefik 2.0 and Docker Compose labels?

The following setup is based on the blog entry here: https://blog.containo.us/traefik-2-0-docker-101-fc2893944b9d

My setup

I configured Traefik in my swarm like this:

```<code>global:
  checkNewVersion: false
  sendAnonymousUsage: false
api:
  dashboard: true
entryPoints:
  web:
    address: :80
  websecure:
    address: :443
providers:
  providersThrottleDuration: 2s
docker:
  watch: true
  endpoint: unix:///var/run/docker.sock
  swarmMode: true
  swarmModeRefreshSeconds: 15s
  exposedByDefault: false
  network: webgateway
log:
  level: DEBUG
accessLog: {}
certificatesResolvers:
  default:
    acme:
    email: {email}
    storage: /etc/traefik/acme/acme.json
    httpChallenge:
      entryPoint: web
</code>```

And started Traefik with the following docker-compose file

```<code>version: '3'

services:
proxy:
    image: traefik:latest
    ports:
    - "80:80"
    - "443:443"
    volumes:
    - /var/run/docker.sock:/var/run/docker.sock
    - /data/docker_data/traefik/traefik-2.yml:/etc/traefik/traefik.yml
    - /data/docker_data/traefik/acme-2.json:/etc/traefik/acme/acme.json
    labels:
    # redirect
    - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
    - "traefik.http.routers.redirs.rule=hostregexp(`{host:.+}`)"
    - "traefik.http.routers.redirs.entrypoints=web"
    - "traefik.http.routers.redirs.middlewares=redirect-to-https"
</code>```

My services are configured with the following labels:

```<code>traefik.http.routers.myapp.rule=Host(`myapp.ch`)
traefik.http.routers.myapp.service=myapp
traefik.http.routers.myapp.entrypoints=websecure
# I don't think that the following one is required here...
# traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https
traefik.http.routers.myapp.tls.certresolver=default
traefik.http.services.myapp.loadbalancer.server.port=3000
traefik.http.routers.myapp.tls=true
traefik.enable=true
</code>```

Any ideas why this is not working?

答:
This is for those who are trying Global HTTP to HTTPS redirection on Traefik 2. Some of you might be getting 404 on the http endpoints. After literal hours spending on the different forums. This works for me. This applies for people who want to use pre-signed ssl certificates as well.

As most of us are using config provided in the traefik blogs and many dont contain the command section of traefik container where we declared for security purpose

"--providers.docker.exposedbydefault=false"

This prevents the global https redirector to work if we dont give

"traefik.enable=true"

here is the full file

```<code>version: "3.8"
services:
  traefik:
    image: "traefik:v2.2.1"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--providers.docker.watch=true"
      - "--providers.file.directory=/conf/"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
    ports:
      - "80:80"
      - "443:443"
    networks:
      - somenetwork
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - ./certs:/certs
      - ./conf:/conf
    labels:
      # this is needed as we did the --providers.docker.exposedbydefault=false
      - "traefik.enable=true"
      # middleware redirect
      - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
      # global redirect to https
      - "traefik.http.routers.http-catchall.rule=hostregexp(`{host:.+}`)"
      - "traefik.http.routers.http-catchall.entrypoints=web"
      - "traefik.http.routers.http-catchall.middlewares=redirect-to-https"
  whoami:
    image: "containous/whoami"
    container_name: "simple-service"
    networks:
      - somenetwork
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami-secure.entrypoints=websecure"
      - "traefik.http.routers.whoami-secure.tls=true"
      - "traefik.http.routers.whoami-secure.rule=Host(`test.traefik.localhost`)"
</code>```

I am also adding the certificates.toml inside conf directory. If you are working on localhost then you can add this using mkcert openssl etc. For production you need to need to get this from certificate providers. And you need to add the certificates in the certs folder.

```<code>[[tls.certificates]] #first certificate
   certFile = "/certs/_wildcard.traefik.localhost.pem"
   keyFile = "/certs/_wildcard.traefik.localhost-key.pem"
</code>```

And of course you can use lets encrypt. There are a lot of blogs on that topic.

Hope this saves your times. :)

Body:
I have the problem that I can route HTTPS traffic but I can not globally redirect the HTTP traffic to HTTPS. In my case I only want HTTPS traffic, so that I want to redirect all the incoming traffic.

Currently I get an 404 error while I try to serve my URLs over HTTP.
I already enabled DEBUG logs in Treafik, but I can not see any problems or unnormal stuff in the logs.

Additionally I saw a pretty similar topic here on Stackoverflow, but we found out, that his error was not the same to mine: How to redirect http to https with Traefik 2.0 and Docker Compose labels?

The following setup is based on the blog entry here: https://blog.containo.us/traefik-2-0-docker-101-fc2893944b9d

My setup

I configured Traefik in my swarm like this:

global:
  checkNewVersion: false
  sendAnonymousUsage: false
api:
  dashboard: true
entryPoints:
  web:
    address: :80
  websecure:
    address: :443
providers:
  providersThrottleDuration: 2s
docker:
  watch: true
  endpoint: unix:///var/run/docker.sock
  swarmMode: true
  swarmModeRefreshSeconds: 15s
  exposedByDefault: false
  network: webgateway
log:
  level: DEBUG
accessLog: {}
certificatesResolvers:
  default:
    acme:
    email: {email}
    storage: /etc/traefik/acme/acme.json
    httpChallenge:
      entryPoint: web

And started Traefik with the following docker-compose file

version: '3'

services:
proxy:
    image: traefik:latest
    ports:
    - "80:80"
    - "443:443"
    volumes:
    - /var/run/docker.sock:/var/run/docker.sock
    - /data/docker_data/traefik/traefik-2.yml:/etc/traefik/traefik.yml
    - /data/docker_data/traefik/acme-2.json:/etc/traefik/acme/acme.json
    labels:
    # redirect
    - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
    - "traefik.http.routers.redirs.rule=hostregexp(`{host:.+}`)"
    - "traefik.http.routers.redirs.entrypoints=web"
    - "traefik.http.routers.redirs.middlewares=redirect-to-https"

My services are configured with the following labels:

traefik.http.routers.myapp.rule=Host(`myapp.ch`)
traefik.http.routers.myapp.service=myapp
traefik.http.routers.myapp.entrypoints=websecure
# I don't think that the following one is required here...
# traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https
traefik.http.routers.myapp.tls.certresolver=default
traefik.http.services.myapp.loadbalancer.server.port=3000
traefik.http.routers.myapp.tls=true
traefik.enable=true

Any ideas why this is not working?

Body:
This is for those who are trying Global HTTP to HTTPS redirection on Traefik 2. Some of you might be getting 404 on the http endpoints. After literal hours spending on the different forums. This works for me. This applies for people who want to use pre-signed ssl certificates as well.

As most of us are using config provided in the traefik blogs and many dont contain the command section of traefik container where we declared for security purpose

"--providers.docker.exposedbydefault=false"

This prevents the global https redirector to work if we dont give

"traefik.enable=true"

here is the full file

version: "3.8"
services:
  traefik:
    image: "traefik:v2.2.1"
    container_name: "traefik"
    command:
      - "--log.level=DEBUG"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false"
      - "--providers.docker.watch=true"
      - "--providers.file.directory=/conf/"
      - "--entrypoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
    ports:
      - "80:80"
      - "443:443"
    networks:
      - somenetwork
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro"
      - ./certs:/certs
      - ./conf:/conf
    labels:
      # this is needed as we did the --providers.docker.exposedbydefault=false
      - "traefik.enable=true"
      # middleware redirect
      - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
      # global redirect to https
      - "traefik.http.routers.http-catchall.rule=hostregexp(`{host:.+}`)"
      - "traefik.http.routers.http-catchall.entrypoints=web"
      - "traefik.http.routers.http-catchall.middlewares=redirect-to-https"
  whoami:
    image: "containous/whoami"
    container_name: "simple-service"
    networks:
      - somenetwork
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.whoami-secure.entrypoints=websecure"
      - "traefik.http.routers.whoami-secure.tls=true"
      - "traefik.http.routers.whoami-secure.rule=Host(`test.traefik.localhost`)"

I am also adding the certificates.toml inside conf directory. If you are working on localhost then you can add this using mkcert openssl etc. For production you need to need to get this from certificate providers. And you need to add the certificates in the certs folder.

[[tls.certificates]] #first certificate
   certFile = "/certs/_wildcard.traefik.localhost.pem"
   keyFile = "/certs/_wildcard.traefik.localhost-key.pem"

And of course you can use lets encrypt. There are a lot of blogs on that topic.

Hope this saves your times. :)


问:
Redirecting command output in docker
I want to do some simple logging for my server which is a small Flask app running in a Docker container.

Here is the Dockerfile

```<code># Dockerfile
FROM dreen/flask
MAINTAINER dreen
WORKDIR /srv

# Get source
RUN mkdir -p /srv
COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz
RUN tar x -f perfektimprezy.tar.gz
RUN rm perfektimprezy.tar.gz

# Run server
EXPOSE 80
CMD ["python", "index.py", "1>server.log", "2>server.log"]
</code>```

As you can see on the last line I redirect stderr and stdout to a file. Now I run this container and shell into it

```<code>docker run -d -p 80:80 perfektimprezy
docker exec -it "... id of container ..." bash
</code>```

And observe the following things:

The server is running and the website working

There is no /srv/server.log

ps aux | grep python yields:

```<code>root         1  1.6  3.2  54172 16240 ?        Ss   13:43   0:00 python index.py 1>server.log 2>server.log
root        12  1.9  3.3 130388 16740 ?        Sl   13:43   0:00 /usr/bin/python index.py 1>server.log 2>server.log
root        32  0.0  0.0   8860   388 ?        R+   13:43   0:00 grep --color=auto python
</code>```

But there are no logs... HOWEVER, if I docker attach to the container I can see the app generating output in the console.

How do I properly redirect stdout/err to a file when using Docker?

答:
I personally use :

```<code>ENTRYPOINT ["python3"]
CMD ["-u", "-m", "swagger_server"]
</code>```

The "-u" is the key :)

Title: Redirecting command output in docker

Body:
I want to do some simple logging for my server which is a small Flask app running in a Docker container.

Here is the Dockerfile

# Dockerfile
FROM dreen/flask
MAINTAINER dreen
WORKDIR /srv

# Get source
RUN mkdir -p /srv
COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz
RUN tar x -f perfektimprezy.tar.gz
RUN rm perfektimprezy.tar.gz

# Run server
EXPOSE 80
CMD ["python", "index.py", "1>server.log", "2>server.log"]

As you can see on the last line I redirect stderr and stdout to a file. Now I run this container and shell into it

docker run -d -p 80:80 perfektimprezy
docker exec -it "... id of container ..." bash

And observe the following things:

The server is running and the website working

There is no /srv/server.log

ps aux | grep python yields:

root         1  1.6  3.2  54172 16240 ?        Ss   13:43   0:00 python index.py 1>server.log 2>server.log
root        12  1.9  3.3 130388 16740 ?        Sl   13:43   0:00 /usr/bin/python index.py 1>server.log 2>server.log
root        32  0.0  0.0   8860   388 ?        R+   13:43   0:00 grep --color=auto python

But there are no logs... HOWEVER, if I docker attach to the container I can see the app generating output in the console.

How do I properly redirect stdout/err to a file when using Docker?

Body:
I personally use :

ENTRYPOINT ["python3"]
CMD ["-u", "-m", "swagger_server"]

The "-u" is the key :)


问:
Jquery submit specific input with enter key
is it posible avoid submit with enter key(13) in all input except only input???

```<code>$('#ruc').keypress(function(event){
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13'){
    if ($('#ruc').val().length==11){
        //alert('ingreso DNI');
        mostrarDatosRUC($('#ruc').val());
      } else {
        alertify.error("El RUC debe tener 11 dígitos")
      }
    }
  });

});

$('form input'). keydown(function (e) {
  if (e. keyCode == 13) {
    e. preventDefault();
    return false;
  }
});
</code>```

With this, $('#ruc').keypress(function(event) not working.
Cheers

答:
It works if you adjust your second function to</p>

```<code> $('form input:not(#ruc)'). keydown(function (e) {
    if (e. keyCode == 13) {
       e. preventDefault();
       return false;
    }
 });
</code>```

Body:
is it posible avoid submit with enter key(13) in all input except only input???

$('#ruc').keypress(function(event){
  var keycode = (event.keyCode ? event.keyCode : event.which);
  if(keycode == '13'){
    if ($('#ruc').val().length==11){
        //alert('ingreso DNI');
        mostrarDatosRUC($('#ruc').val());
      } else {
        alertify.error("El RUC debe tener 11 dígitos")
      }
    }
  });

});

$('form input'). keydown(function (e) {
  if (e. keyCode == 13) {
    e. preventDefault();
    return false;
  }
});

With this, $('#ruc').keypress(function(event) not working.
Cheers

Body:
It works if you adjust your second function to

 $('form input:not(#ruc)'). keydown(function (e) {
    if (e. keyCode == 13) {
       e. preventDefault();
       return false;
    }
 });


问:
Minimize the impact on memory on generating and downloading a file
For testing purposes only, I created this controller, which generates a 100MB file and returns it to the client. The method is very fast. The content of the file does not matter. The file is generated on the fly, it is not saved to disk.

Is it possible to reduce the impact on memory, particularly on java heap? Thank you

```<code>    @GetMapping("/testDownload100MB")
    public ResponseEntity<Resource> download100MB() throws IOException {

        int sizeInBytes = 100 * 1024 * 1024;

        ByteArrayOutputStream outStream = new ByteArrayOutputStream(sizeInBytes);
        for (int i = 0; i < sizeInBytes; i++) {
            outStream.write(0);
        }
        Resource resource = new ByteArrayResource(outStream.toByteArray());

        return ResponseEntity.ok()
                .headers(utilities.getGenericHttpHeadersToDownloadFile())
                .contentLength(sizeInBytes)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
</code>```

The code of utilities.getGenericHttpHeadersToDownloadFile() is not relevant for the question, however I report it for completeness:

```<code>    public HttpHeaders getGenericHttpHeadersToDownloadFile() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=myfile");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return headers;
    }
</code>```

答:
Solved.

The code in my question throws a java.lang.OutOfMemoryError: Java heap space on my Spring Boot server. This new code solves the issue:

```<code>    @GetMapping("/testDownload100MB")
    public ResponseEntity<Resource> download100MB() throws IOException {

        int size1MB = 1 * 1024 * 1024; // size in bytes

        File tempFile = new File(System.getProperty("user.home") + File.separator + "tempFile" + System.currentTimeMillis());

        for (int i = 0; i < 100; i++) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(size1MB);
            for (int j = 0; j < size1MB; j++) {
                outStream.write(0);
            }
            FileUtils.writeByteArrayToFile(tempFile, outStream.toByteArray(), true); // append to the temp file
        }

        Resource resource = new FileSystemResource(tempFile);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // we can assume that the file can be safely deleted after five minutes
               tempFile.delete();
            }
        }, 1000 * 60 * 5);

        return ResponseEntity.ok()
                .headers(utilities.getGenericHttpHeadersToDownloadFile())
                .contentLength(tempFile.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
</code>```

Note that FileUtils must be imported with: import org.apache.commons.io.FileUtils;.

In this case, no objects exceeding 1 MB are placed in the java heap. In addition, FileSystemResource does not need to load the entire file into memory. On the other hand, I had to add a timer to delete the file: since this is a method for testing purposes, I can safely assume that after a few minutes the file is no longer needed.

If there are better solutions that do not require a temporary file, add your answer :)

Body:
For testing purposes only, I created this controller, which generates a 100MB file and returns it to the client. The method is very fast. The content of the file does not matter. The file is generated on the fly, it is not saved to disk.

Is it possible to reduce the impact on memory, particularly on java heap? Thank you

    @GetMapping("/testDownload100MB")
    public ResponseEntity<Resource> download100MB() throws IOException {

        int sizeInBytes = 100 * 1024 * 1024;

        ByteArrayOutputStream outStream = new ByteArrayOutputStream(sizeInBytes);
        for (int i = 0; i < sizeInBytes; i++) {
            outStream.write(0);
        }
        Resource resource = new ByteArrayResource(outStream.toByteArray());

        return ResponseEntity.ok()
                .headers(utilities.getGenericHttpHeadersToDownloadFile())
                .contentLength(sizeInBytes)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

The code of utilities.getGenericHttpHeadersToDownloadFile() is not relevant for the question, however I report it for completeness:

    public HttpHeaders getGenericHttpHeadersToDownloadFile() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=myfile");
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return headers;
    }

Body:
Solved.

The code in my question throws a java.lang.OutOfMemoryError: Java heap space on my Spring Boot server. This new code solves the issue:

    @GetMapping("/testDownload100MB")
    public ResponseEntity<Resource> download100MB() throws IOException {

        int size1MB = 1 * 1024 * 1024; // size in bytes

        File tempFile = new File(System.getProperty("user.home") + File.separator + "tempFile" + System.currentTimeMillis());

        for (int i = 0; i < 100; i++) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(size1MB);
            for (int j = 0; j < size1MB; j++) {
                outStream.write(0);
            }
            FileUtils.writeByteArrayToFile(tempFile, outStream.toByteArray(), true); // append to the temp file
        }

        Resource resource = new FileSystemResource(tempFile);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // we can assume that the file can be safely deleted after five minutes
               tempFile.delete();
            }
        }, 1000 * 60 * 5);

        return ResponseEntity.ok()
                .headers(utilities.getGenericHttpHeadersToDownloadFile())
                .contentLength(tempFile.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

Note that FileUtils must be imported with: import org.apache.commons.io.FileUtils;.

In this case, no objects exceeding 1 MB are placed in the java heap. In addition, FileSystemResource does not need to load the entire file into memory. On the other hand, I had to add a timer to delete the file: since this is a method for testing purposes, I can safely assume that after a few minutes the file is no longer needed.

If there are better solutions that do not require a temporary file, add your answer :)


问:
Changing Selenium driver for new URL
I used Selenium to navigate to a URL (i.e. URL_1) with a login/password and provided the login credentials.  I'm logged in and the URL (i.e. URL_2) has changed as expected.  I don't know how to navigate URL_2 because the driver still refers to URL_1.

Thanks in advance.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

user_name = 'xyz'
password = 'xyz'

def login_process():
    driver = webdriver.Firefox()
    driver.get("URL_1")
    #successfully navigated to URL_1

    elem = driver.find_element_by_name("username")
    elem.clear()
    elem.send_keys(user_name)

    elem = driver.find_element_by_name("password")
    elem.clear()
    elem.send_keys(password)
    driver.find_element_by_id("submit").click()
    #successfully entered URL_2

def query():
    HOW DO I CHANGE THE DRIVER TO URL_2?

    #elem = driver.find_element_by_class_name(ticker_box) #this doesn't work, references URL_1 driver
    #elem.clear()
    #elem.send_keys('xyz')
</code>```

答:
After navigating to the new page if you want to do something on that new page

```<code>newURl = driver.window_handles[0]

driver.switch_to.window(newURl)
</code>```

After doing this you can do something in the new url without getting "no such element exceptions"

Title: Changing Selenium driver for new URL

Body:
I used Selenium to navigate to a URL (i.e. URL_1) with a login/password and provided the login credentials.  I'm logged in and the URL (i.e. URL_2) has changed as expected.  I don't know how to navigate URL_2 because the driver still refers to URL_1.

Thanks in advance.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

user_name = 'xyz'
password = 'xyz'

def login_process():
    driver = webdriver.Firefox()
    driver.get("URL_1")
    #successfully navigated to URL_1

    elem = driver.find_element_by_name("username")
    elem.clear()
    elem.send_keys(user_name)

    elem = driver.find_element_by_name("password")
    elem.clear()
    elem.send_keys(password)
    driver.find_element_by_id("submit").click()
    #successfully entered URL_2

def query():
    HOW DO I CHANGE THE DRIVER TO URL_2?

    #elem = driver.find_element_by_class_name(ticker_box) #this doesn't work, references URL_1 driver
    #elem.clear()
    #elem.send_keys('xyz')

Body:
After navigating to the new page if you want to do something on that new page

newURl = driver.window_handles[0]

driver.switch_to.window(newURl)

After doing this you can do something in the new url without getting "no such element exceptions"


问:
IETester Question
I have been using IETester for a little while now and although I have read that sometimes it can be buggy and not completely accurate (http://stackoverflow.com/questions/5612170/web-testing-for-ie-how-accurate-is-ietester) when I emulate IE6 it always seems to render the box model correctly (which IE6 obviously wouldn't). I was wondering if anyone else has had this problem. The Developer Tools on IE8 and 9 do emulate the box model incorrectly for IE6 mode like it should, but I find that they are inconsistent with IETester too. I find myself constantly switching between IE developer tools and IETester trying to guess at what IE6 would really display.

Should I only be using one or the other, or perhaps a different tool altogether?

I would greatly appreciate any insight on this.

答:
I believe IE8 and IE9 don't even have an IE6 emulation mode (only IE7, I thought). But the best way to test for IE6, is to get a virtual machine up and running with IE6 installed. You could use IETester or one of the various stand-alone versions of IE6 to test it on your development PC (most things will work as expected, after all), and do a final test on the virtual machine.

To my knowledge there are no other tools that emulate every quirk of IE6 better.

Title: IETester Question


问:
Why will this URL not be created from this string in iOS using Swift and Xcode?
Converting String to URL is not working for this string:

https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

Here is my code:

```<code>print(directionsURLString)

let directionsURL = URL(string: directionsURLString)!
</code>```

Here is the debug window:

```<code>https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123
2020-05-29 14:08:52.570189-0500 Routes[1576:2052272] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123
</code>```

The code worked for this string which has one waypoint, unlike the string that gave an error, which has two waypoints.

https://maps.googleapis.com/maps/api/directions/json?origin=New%20Address&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

答:
The "|" character is the culprit, as it's not in the list of valid characters as per RFC 3986:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=
</code>```

Solution: replace it with its percent-encoded equvalent, %7c

Body:
Converting String to URL is not working for this string:

https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

Here is my code:

print(directionsURLString)

let directionsURL = URL(string: directionsURLString)!

Here is the debug window:

https://maps.googleapis.com/maps/api/directions/json?origin=3701%20Moores%20Ln,%20Texarkana,%20TX%2075503,%20USA&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA|5601%20Larry%20Dr,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123
2020-05-29 14:08:52.570189-0500 Routes[1576:2052272] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file /Users/shinehah/Documents/Xcode Projects/Routes folder/Routes 08/Routes/MapTasks.swift, line 123

The code worked for this string which has one waypoint, unlike the string that gave an error, which has two waypoints.

https://maps.googleapis.com/maps/api/directions/json?origin=New%20Address&destination=3%20Wisteria%20Dr,%20Texarkana,%20TX%2075503,%20USA&waypoints=optimize:true21%20Summer%20Ln,%20Texarkana,%20TX%2075503,%20USA&mode=driving&key=xxx

Body:
The "|" character is the culprit, as it's not in the list of valid characters as per RFC 3986:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Solution: replace it with its percent-encoded equvalent, %7c


问:
In SwiftUI, where are the control events, i.e. scrollViewDidScroll to detect the bottom of list data
In SwiftUI, does anyone know where are the control events such as scrollViewDidScroll to detect when a user reaches the bottom of a list causing an event to retrieve additional chunks of data? Or is there a new way to do this?

Seems like UIRefreshControl() is not there either...

答:
I tried the answer for this question and was getting the error Pattern matching in a condition requires the 'case' keyword like @C.Aglar .

I changed the code to check if the item that appears is the last of the list, it'll print/execute the clause. This condition will be true once you scroll and reach the last element of the list.

```<code>struct ContentView: View {
    @State var items = Array(1...30)

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text("\(item)")
                .onAppear {
                    if item == self.items.last {
                        print("last item")
                        fetchStuff()
                    }
                }
            }
        }
    }
}
</code>```

Body:
I tried the answer for this question and was getting the error Pattern matching in a condition requires the 'case' keyword like @C.Aglar .

I changed the code to check if the item that appears is the last of the list, it'll print/execute the clause. This condition will be true once you scroll and reach the last element of the list.

struct ContentView: View {
    @State var items = Array(1...30)

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text("\(item)")
                .onAppear {
                    if item == self.items.last {
                        print("last item")
                        fetchStuff()
                    }
                }
            }
        }
    }
}


问:
XSLT Transform to split a file by repeated elements
I have an xml file in the following format:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Feed xmlns="http://www.somecompany.com/xs/PRR/SomeFeed/14.7" encryptionKeyID="ENCRYPTION-KEY-ID-2020-05-01T18:00:17.324Z">
   <Interaction>
      <EncryptedEmailAddress></EncryptedEmailAddress>
      <UserID></UserID>
      <UserName></UserName>
      <TransactionDate></TransactionDate>
      <Locale></Locale>
      <DeploymentZone></DeploymentZone>
      <Products>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price></Price>
            <ImageUrl></ImageUrl>
         </Product>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price></Price>
            <ImageUrl></ImageUrl>
         </Product>
      </Products>
   </Interaction>
   <Interaction>
      <EncryptedEmailAddress></EncryptedEmailAddress>
      <UserID></UserID>
      <UserName></UserName>
      <TransactionDate></TransactionDate>
      <Locale></Locale>
      <DeploymentZone></DeploymentZone>
      <Products>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price>37</Price>
            <ImageUrl></ImageUrl>
         </Product>
      </Products>
   </Interaction>
</Feed>
</code>```

This feed can have millions of interactions. I want to create an xsl transformation to split files using 9000 interactions at a time. I need to have the Feed element in every split file.

I've tried the following but it doesn't work correctly.

```<code><xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/*">
    <xsl:for-each-group select="*" group-adjacent="(position()-1) idiv 9000">
      <xsl:result-document href="chunk{position()}.xml">
        <xsl:copy>
          <xsl:copy-of select="."/>
        </xsl:copy>
      </xsl:result-document>
    </xsl:for-each-group>
  </xsl:template>
</xsl:transform>
</code>```

This is not grouping properly and does not include the feed element in each file.

答:
Use

```<code><xsl:copy select="/*">
  <xsl:copy-of select="current-group()"/>
</xsl:copy>
</code>```

If you want to do with with Saxon EE and streaming I think the xsl:copy select="/*" will not work but you can use <xsl:element name="{name(..)}" namespace="{namespace-uri(..)}"> instead e.g.

```<code><xsl:template match="/*">
    <xsl:for-each-group select="*" group-adjacent="(position() - 1) idiv $chunk-size">
        <xsl:result-document href="split-{position()}.xml">
            <xsl:element name="{name(..)}" namespace="{namespace-uri(..)}">
                <xsl:copy-of select="current-group()"/>
            </xsl:element>
        </xsl:result-document>
    </xsl:for-each-group>
</xsl:template>
</code>```

Body:
I have an xml file in the following format:

<?xml version="1.0" encoding="UTF-8"?>
<Feed xmlns="http://www.somecompany.com/xs/PRR/SomeFeed/14.7" encryptionKeyID="ENCRYPTION-KEY-ID-2020-05-01T18:00:17.324Z">
   <Interaction>
      <EncryptedEmailAddress></EncryptedEmailAddress>
      <UserID></UserID>
      <UserName></UserName>
      <TransactionDate></TransactionDate>
      <Locale></Locale>
      <DeploymentZone></DeploymentZone>
      <Products>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price></Price>
            <ImageUrl></ImageUrl>
         </Product>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price></Price>
            <ImageUrl></ImageUrl>
         </Product>
      </Products>
   </Interaction>
   <Interaction>
      <EncryptedEmailAddress></EncryptedEmailAddress>
      <UserID></UserID>
      <UserName></UserName>
      <TransactionDate></TransactionDate>
      <Locale></Locale>
      <DeploymentZone></DeploymentZone>
      <Products>
         <Product>
            <ExternalId></ExternalId>
            <Name></Name>
            <Price>37</Price>
            <ImageUrl></ImageUrl>
         </Product>
      </Products>
   </Interaction>
</Feed>

This feed can have millions of interactions. I want to create an xsl transformation to split files using 9000 interactions at a time. I need to have the Feed element in every split file.

I've tried the following but it doesn't work correctly.

<xsl:transform version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/*">
    <xsl:for-each-group select="*" group-adjacent="(position()-1) idiv 9000">
      <xsl:result-document href="chunk{position()}.xml">
        <xsl:copy>
          <xsl:copy-of select="."/>
        </xsl:copy>
      </xsl:result-document>
    </xsl:for-each-group>
  </xsl:template>
</xsl:transform>

This is not grouping properly and does not include the feed element in each file.

Body:
Use

<xsl:copy select="/*">
  <xsl:copy-of select="current-group()"/>
</xsl:copy>

If you want to do with with Saxon EE and streaming I think the xsl:copy select="/*" will not work but you can use <xsl:element name="{name(..)}" namespace="{namespace-uri(..)}"> instead e.g.

<xsl:template match="/*">
    <xsl:for-each-group select="*" group-adjacent="(position() - 1) idiv $chunk-size">
        <xsl:result-document href="split-{position()}.xml">
            <xsl:element name="{name(..)}" namespace="{namespace-uri(..)}">
                <xsl:copy-of select="current-group()"/>
            </xsl:element>
        </xsl:result-document>
    </xsl:for-each-group>
</xsl:template>


问:
Installing Rails 3.1
I'm trying to install Rails 3.1.

It says to use 'gem install rails --pre' in the announcement blog post here:

http://weblog.rubyonrails.org/2011/5/22/rails-3-1-release-candidate

When I try

$ gem install rails --pre

I get the error:

ERROR:  While executing gem ... (NameError)
  uninitialized constant Syck::Syck

What to do?

答:
I googled this error message and found the following comment on the Riding Rails blog:

I’ve met the same

ERROR: While executing gem …
  (NameError) uninitialized constant
  Syck::Syck

issue with: gem install rails --pre

Get around with: gem install rails -v
  ”>=3.1.0rc”

Does this resolve the issue?

Title: Installing Rails 3.1