问:
Student, automating email to an admin on creation of a new user powershell
trying to send an email upon the creation of a new user to the admin.
This appears to work the first time but then fails to run a second time.
I think its an issue with me creating a new object the second time, but am unfamiliar with PScredential, and how to call it a second time instead of creating it again, I'm assuming it would be some form of if statement, but I don't know what to call in the if.

here is my Code

```<code>$password = ConvertTo-SecureString “Password” -AsPlainText -Force

$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")

Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'

</code>```

and this is the error message

```<code>New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:3 char:9
+ $Cred = New-Object System.Management.Automation.PSCredential('38da1ca ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
</code>```

答:
So lets see the documentation
https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.pscredential?view=pscore-6.2.0

We can see there are 2 constructors

```<code>PSCredential(PSObject)
</code>```

or

```<code>PSCredential(String, SecureString)
</code>```

It looks like in the post example PSCredential(String, SecureString) was trying to be used.

In the example

```<code>$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")
</code>```

Because "$Password" was put in quotes it has turned the SecureString into a regular String.

The Fix is to remove the qoutes "

Here is a working copy

```<code>$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',$password)
Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'
</code>```

Body:
trying to send an email upon the creation of a new user to the admin.
This appears to work the first time but then fails to run a second time.
I think its an issue with me creating a new object the second time, but am unfamiliar with PScredential, and how to call it a second time instead of creating it again, I'm assuming it would be some form of if statement, but I don't know what to call in the if.

here is my Code

$password = ConvertTo-SecureString “Password” -AsPlainText -Force

$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")

Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'

and this is the error message

New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:3 char:9
+ $Cred = New-Object System.Management.Automation.PSCredential('38da1ca ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Body:
So lets see the documentation
https://learn.microsoft.com/en-us/dotnet/api/system.management.automation.pscredential?view=pscore-6.2.0

We can see there are 2 constructors

PSCredential(PSObject)

or

PSCredential(String, SecureString)

It looks like in the post example PSCredential(String, SecureString) was trying to be used.

In the example

$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',"$password")

Because "$Password" was put in quotes it has turned the SecureString into a regular String.

The Fix is to remove the qoutes "

Here is a working copy

$password = ConvertTo-SecureString “Password” -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('38da1ca9daf082',$password)
Send-MailMessage -SmtpServer 'smtp.mailtrap.io' -Credential $cred -UseSsl -From 'server@gmail.com' -To 'admin@gmail.com' -Subject 'TEST'


来源: stackexchange

问:
Is it possible to get a deadlock with ConcurrentHashMap in this circumstance?
I'm reading the source code of ConcurrentHashMap in JDK8, notice that TreeBin uses a 'read-write' lock to prevent concurrent read and write.

Read threads will go through TreeNodes if there's no concurrent write thread trying to modify the tree structure. When the 'find' operation is done, read thread may:

(1)'CAS' the lockState and 'unpark' the waiter(writer) thread if it exists.

Following is the 'find()' method in source code.

final Node<K,V> find(int h, Object k) {
            if (k != null) {
                for (Node<K,V> e = first; e != null; ) {
                    int s; K ek;
                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
                        if (e.hash == h &&
                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
                            return e;
                        e = e.next;
                    }
                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
                                                 s + READER)) {
                        TreeNode<K,V> r, p;
                        try {
                            p = ((r = root) == null ? null :
                                 r.findTreeNode(h, k, null));
                        } finally {
                            Thread w;
                            // (1)if no more readers, try to unpark the waiter if it exists
                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
                                (READER|WAITER) && (w = waiter) != null)
                                LockSupport.unpark(w);
                        }
                        return p;
                    }
                }
            }
            return null;
        }
```

<p>on the other hand, writer thread may:</p>

<ul>
<li><p>(2) adding the <code>WAITER</code> state to <code>lockState</code> with 'CAS' operation.</p></li>
<li><p>(3) set itself to <code>waiter</code> variable.</p></li>
<li><p>(4) 'park' itself.</p></li>
</ul>

<p>here's the writer's code:</p>

<pre class="lang-java prettyprint-override"><code>        private final void contendedLock() {
            boolean waiting = false;
            for (int s;;) {
                if (((s = lockState) & ~WAITER) == 0) {
                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
                        if (waiting)
                            waiter = null;
                        return;
                    }
                }
                else if ((s & WAITER) == 0) {
                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
                        waiting = true;
                        waiter = Thread.currentThread();
                    }
                }
                else if (waiting)
                    LockSupport.park(this);
            }
        }
</code>```

HERE IS MY CONFUSION:

If the four operation above run in this order (2) (1) (3) (4), the operation (1) won't unpark anything because 'waiter' was null at that moment.

Then the waiter will park forever without anyone who can unpark it.

The subsequent writes will be all blocked on the intrinsic lock held by the 'parked' thread.

IS THIS A CHANCE OF DEADLOCK ?

I'm really confused about this. I think perhaps I've missed something in the source code. Need your help if you are familiar with it.

答:
The question is more than one year old. But it's such a nice puzzle. Here's the answer:

After (2) (1) (3) execution in contendedLock() continues as follows:

if (((s = lockState) & ~WAITER) == 0) is true because (1) was executed

if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) is also true, because (3) was executed before (s = lockState) and not after it

Since waiting was set to true before the execution of (3) the third if statements is also true. Therefore waiter is set to null and we exit the loop. (4) is never executed.

To sum it up:
After (2) (1) (3) operation (4) will never be executed. So there is no chance of deadlock and we can all continue to use ConcurrentHashMap without qualms ;-)

ContentLicense: CC BY-SA 4.0

Body:
I'm reading the source code of ConcurrentHashMap in JDK8, notice that TreeBin uses a 'read-write' lock to prevent concurrent read and write.

Read threads will go through TreeNodes if there's no concurrent write thread trying to modify the tree structure. When the 'find' operation is done, read thread may:

(1)'CAS' the lockState and 'unpark' the waiter(writer) thread if it exists.

Following is the 'find()' method in source code.

final Node<K,V> find(int h, Object k) {
            if (k != null) {
                for (Node<K,V> e = first; e != null; ) {
                    int s; K ek;
                    if (((s = lockState) & (WAITER|WRITER)) != 0) {
                        if (e.hash == h &&
                            ((ek = e.key) == k || (ek != null && k.equals(ek))))
                            return e;
                        e = e.next;
                    }
                    else if (U.compareAndSwapInt(this, LOCKSTATE, s,
                                                 s + READER)) {
                        TreeNode<K,V> r, p;
                        try {
                            p = ((r = root) == null ? null :
                                 r.findTreeNode(h, k, null));
                        } finally {
                            Thread w;
                            // (1)if no more readers, try to unpark the waiter if it exists
                            if (U.getAndAddInt(this, LOCKSTATE, -READER) ==
                                (READER|WAITER) && (w = waiter) != null)
                                LockSupport.unpark(w);
                        }
                        return p;
                    }
                }
            }
            return null;
        }

on the other hand, writer thread may:

(2) adding the WAITER state to lockState with 'CAS' operation.

(3) set itself to waiter variable.

(4) 'park' itself.

here's the writer's code:

        private final void contendedLock() {
            boolean waiting = false;
            for (int s;;) {
                if (((s = lockState) & ~WAITER) == 0) {
                    if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
                        if (waiting)
                            waiter = null;
                        return;
                    }
                }
                else if ((s & WAITER) == 0) {
                    if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
                        waiting = true;
                        waiter = Thread.currentThread();
                    }
                }
                else if (waiting)
                    LockSupport.park(this);
            }
        }

HERE IS MY CONFUSION:

If the four operation above run in this order (2) (1) (3) (4), the operation (1) won't unpark anything because 'waiter' was null at that moment.

Then the waiter will park forever without anyone who can unpark it.

The subsequent writes will be all blocked on the intrinsic lock held by the 'parked' thread.

IS THIS A CHANCE OF DEADLOCK ?

I'm really confused about this. I think perhaps I've missed something in the source code. Need your help if you are familiar with it.


问:
Accurate method to add months in PHP 5.1?
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

```<code>date('Y-m-d',strtotime( '+1 month', strtotime('now')));
</code>```

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

答:
You could argue that PHP is doing the right thing, and MySQL the wrong one:

MySQL is clamping the value down back to the last valid date that fits into the year/month definition. PHP is adjust upwards, moving forward to the first proper date that matches the specified day (31-30 = 1 day past, so 2011-06-30 + 1 day = 2011-07-01).

ContentLicense: CC BY-SA 3.0

Body:
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

date('Y-m-d',strtotime( '+1 month', strtotime('now')));

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?


问:
Angular/Typescript - This expression is not constructable. Type 'MoveDataClass' has no construct signatures
I am doing a class with 3 methods to create new instances of that class, but when i try to that , the following error appears :

"Angular/Typescript - This expression is not constructable. Type 'MoveDataClass' has no construct signatures."

What i am doing wrong?

The class:

```<code>export class MoveDataClass {

    power;
    stab;
    efect;

    constructor(power,stab,efect) {
        this.power= power;
        this.stab =stab;
        this.efect= efect;

    }

}

</code>```

What i do to create the new class :

```<code> this.pokemonMovesCalculated[0] =  new this.moveData(type);

</code>```

The error appears on the "this.moveData" in red

答:
To use a new instance of your class:

```<code>import { MoveDataClass} from './move.data'; // relative path
...
this.pokemonMovesCalculated[0] =  new MoveDataClass('one', 'two', 'three');
</code>```

this is a short form of your class with default values:

```<code>export class MoveDataClass {

  constructor(
    public power = '',
    public stab = '',
    public efect = '') {
  }
}
</code>```

This form can be used:

```<code>new MoveDataClass();
// or:
new MoveDataClass('one');
// or:
new MoveDataClass('one', 'two');
// or:
new MoveDataClass('one', 'two', 'three');
</code>```

Body:
I am doing a class with 3 methods to create new instances of that class, but when i try to that , the following error appears :

"Angular/Typescript - This expression is not constructable. Type 'MoveDataClass' has no construct signatures."

What i am doing wrong?

The class:

export class MoveDataClass {

    power;
    stab;
    efect;

    constructor(power,stab,efect) {
        this.power= power;
        this.stab =stab;
        this.efect= efect;

    }

}

What i do to create the new class :

 this.pokemonMovesCalculated[0] =  new this.moveData(type);

The error appears on the "this.moveData" in red

Body:
To use a new instance of your class:

import { MoveDataClass} from './move.data'; // relative path
...
this.pokemonMovesCalculated[0] =  new MoveDataClass('one', 'two', 'three');

this is a short form of your class with default values:

export class MoveDataClass {

  constructor(
    public power = '',
    public stab = '',
    public efect = '') {
  }
}

This form can be used:

new MoveDataClass();
// or:
new MoveDataClass('one');
// or:
new MoveDataClass('one', 'two');
// or:
new MoveDataClass('one', 'two', 'three');


问:
Jackson: How to edit existing property to the JSON without modifying the POJO?
I need to edit the name of "existing field" in POJO instead of adding "extra_field". Is it possible with the approach referenced link below?

Please note I do not want to use @JsonProperty annotation.

Requirement is, I have a POJO and want to use different field name every time without change in POJO. For example I have a field c_id in POJO and some times it need to write as cust_id and another time it would be my_id.

Also note I cannot change implementation of POJO as it is already used in several modules and have generic implementation.

POJO Example:

```<code>class MyPojo {
    String id;
    // getter and setters
}
</code>```

Expected output can be the following: (name of field can be changed)

{"cust_id": "123"}

{"my_id": "123"}

答:
Mixins

The easiest way to modify the output of Jackson without adding annotations to the original POJO is using mixins.

Just define a mixin-class with the necessary annotations and indicate to Jackson that you want to use the mixin when serializing the original object.

```<code>private static class MyPojoMixin {
    @JsonProperty("cust_id")
    private String id;
}

public String serializeWithMixin(MyPojo p) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(MyPojo.class, MyPojoMixin.class);

    return mapper.writeValueAsString(p);
}
</code>```

Custom property naming strategy

If you need to programmatically change the field-name, you might not be able to use the mixin solution. You could then use a custom PropertyNamingStrategy:

```<code>public class IdRenamingStrategy extends PropertyNamingStrategy {
    private final PropertyNamingStrategy inner;
    private final String newIdPropertyName;

    public IdRenamingStrategy(String newIdPropertyName) {
        this(PropertyNamingStrategy.LOWER_CAMEL_CASE, newIdPropertyName);
    }

    public IdRenamingStrategy(PropertyNamingStrategy inner, String newIdPropertyName) {
        this.inner = inner;
        this.newIdPropertyName = newIdPropertyName;
    }

    private String translate(String propertyName) {
        if ("id".equals(propertyName)) {
            return newIdPropertyName;
        } else {
            return propertyName;
        }
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        return inner.nameForField(config, field, translate(defaultName));
    }

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return inner.nameForGetterMethod(config, method, translate(defaultName));
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return inner.nameForSetterMethod(config, method, translate(defaultName));
    }

    @Override
    public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam, String defaultName) {
        return inner.nameForConstructorParameter(config, ctorParam, translate(defaultName));
    }
}
</code>```

This can be used like this:

```<code>public String serializeWithPropertyNamingStrategy(MyPojo p) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(new IdRenamingStrategy("cust_id"));

    return mapper.writeValueAsString(p));
}
</code>```

Body:
I need to edit the name of "existing field" in POJO instead of adding "extra_field". Is it possible with the approach referenced link below?

Please note I do not want to use @JsonProperty annotation.

Requirement is, I have a POJO and want to use different field name every time without change in POJO. For example I have a field c_id in POJO and some times it need to write as cust_id and another time it would be my_id.

Also note I cannot change implementation of POJO as it is already used in several modules and have generic implementation.

POJO Example:

class MyPojo {
    String id;
    // getter and setters
}

Expected output can be the following: (name of field can be changed)

{"cust_id": "123"}

{"my_id": "123"}

Body:
Mixins

The easiest way to modify the output of Jackson without adding annotations to the original POJO is using mixins.

Just define a mixin-class with the necessary annotations and indicate to Jackson that you want to use the mixin when serializing the original object.

private static class MyPojoMixin {
    @JsonProperty("cust_id")
    private String id;
}

public String serializeWithMixin(MyPojo p) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(MyPojo.class, MyPojoMixin.class);

    return mapper.writeValueAsString(p);
}

Custom property naming strategy

If you need to programmatically change the field-name, you might not be able to use the mixin solution. You could then use a custom PropertyNamingStrategy:

public class IdRenamingStrategy extends PropertyNamingStrategy {
    private final PropertyNamingStrategy inner;
    private final String newIdPropertyName;

    public IdRenamingStrategy(String newIdPropertyName) {
        this(PropertyNamingStrategy.LOWER_CAMEL_CASE, newIdPropertyName);
    }

    public IdRenamingStrategy(PropertyNamingStrategy inner, String newIdPropertyName) {
        this.inner = inner;
        this.newIdPropertyName = newIdPropertyName;
    }

    private String translate(String propertyName) {
        if ("id".equals(propertyName)) {
            return newIdPropertyName;
        } else {
            return propertyName;
        }
    }

    @Override
    public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
        return inner.nameForField(config, field, translate(defaultName));
    }

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return inner.nameForGetterMethod(config, method, translate(defaultName));
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return inner.nameForSetterMethod(config, method, translate(defaultName));
    }

    @Override
    public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam, String defaultName) {
        return inner.nameForConstructorParameter(config, ctorParam, translate(defaultName));
    }
}

This can be used like this:

public String serializeWithPropertyNamingStrategy(MyPojo p) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(new IdRenamingStrategy("cust_id"));

    return mapper.writeValueAsString(p));
}


问:
need assistance with css layout

  I am having css layout issues.  I am attempting to align the Required! message to the right of the input elements

Keeping the flow:

Species:

input element    error-message

Breed:

input element    error-message

I tried various nested divs with-out success.

Link:

http://jsfiddle.net/d0773d/BpqyT/

答:
You've got too many unnecessary tags (list tags) in there please have a look at this, I think this will help:

```<code><div style="float:left;">
<select>
    <option>testing</option>
</select>
    <span>Required</span>
</div>
<div style="float:left;">
<select>
    <option>testing</option>
</select>
    <span>Required</span>
</div>
</code>```

working example:

http://jsfiddle.net/BpqyT/7/

Title: need assistance with css layout

Body:
You've got too many unnecessary tags (list tags) in there please have a look at this, I think this will help:

<div style="float:left;">
<select>
    <option>testing</option>
</select>
    <span>Required</span>
</div>
<div style="float:left;">
<select>
    <option>testing</option>
</select>
    <span>Required</span>
</div>

working example:

http://jsfiddle.net/BpqyT/7/


问:
TypeError: The view function did not return a valid response
Im looking at the SO post but the answer isnt working.

This is my flask app code, where there is a button on into the HTML to browse for the csv file. Ultimately process the CSV file in pandas and print the highest value found in a column called kW

```<code>from flask import Flask, make_response, request
from werkzeug.utils import secure_filename
import pandas as pd

app = Flask(__name__)

@app.route('/')
def form():
    return """
        <html>
            <body>
                <h1>Analysis</h1>

                <form action="/transform" method="post" enctype="multipart/form-data">
                    <input type="file" name="data_file" />
                    <input type="submit" />
                </form>
            </body>
        </html>
    """

@app.route('/transform', methods=["POST"])
def transform_view():
    # data_file is the name of the file upload field
    f = request.files['data_file']

    # for security - stops a hacker e.g. trying to overwrite system files
    filename = secure_filename(f.filename)

    # save a copy of the uploaded file
    f.save(filename)

    # And then use it ...
    df = pd.read_csv(filename, index_col='Date', parse_dates=True)

    maxy = df.kW.max()
    print(maxy)
</code>```

This is the simple.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}
</body>
</html>
</code>```

Any tips greatly appreciated... When I run the code (flask works) this will throw an error when the file is selected during the browse process.

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

Full traceback:

```<code>File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__

return self.wsgi_app(environ, start_response)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app

response = self.handle_exception(e)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception

reraise(exc_type, exc_value, tb)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise

raise value

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app

response = self.full_dispatch_request()

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1816, in full_dispatch_request

return self.finalize_request(rv)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1831, in finalize_request

 [Open an interactive python shell in this frame] response = self.make_response(rv)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1957, in make_response

'The view function did not return a valid response. The'
</code>```

答:
This is happening because your route \transform did return a valid response. This route must have a return statement. I am assuming that you want to load simple.html when this route is called, you can do the following things:

Import render_template:

from flask import render_template
```

<ol start="2">
<li>Use the return statement, in the route, like below:</li>
</ol>

<pre class="lang-py prettyprint-override"><code>return render_template('simple.html')
</code>```

Or just for dummy purpose you want this route to be executed without any error, then you can return like below:

return 'Transformed!'
```

Note: This depends, what you actually want to return or what you want to render, when this route is executed. You can read the docs.

Body:
Im looking at the SO post but the answer isnt working.

This is my flask app code, where there is a button on into the HTML to browse for the csv file. Ultimately process the CSV file in pandas and print the highest value found in a column called kW

from flask import Flask, make_response, request
from werkzeug.utils import secure_filename
import pandas as pd

app = Flask(__name__)

@app.route('/')
def form():
    return """

Analysis

                <form action="/transform" method="post" enctype="multipart/form-data">
                    <input type="file" name="data_file" />
                    <input type="submit" />
                </form>

    """

@app.route('/transform', methods=["POST"])
def transform_view():
    # data_file is the name of the file upload field
    f = request.files['data_file']

    # for security - stops a hacker e.g. trying to overwrite system files
    filename = secure_filename(f.filename)

    # save a copy of the uploaded file
    f.save(filename)

    # And then use it ...
    df = pd.read_csv(filename, index_col='Date', parse_dates=True)

    maxy = df.kW.max()
    print(maxy)

This is the simple.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

{% for table in tables %}
            {{titles[loop.index]}}
            {{ table|safe }}
{% endfor %}

Any tips greatly appreciated... When I run the code (flask works) this will throw an error when the file is selected during the browse process.

TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

Full traceback:

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__

return self.wsgi_app(environ, start_response)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app

response = self.handle_exception(e)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception

reraise(exc_type, exc_value, tb)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise

raise value

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app

response = self.full_dispatch_request()

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1816, in full_dispatch_request

return self.finalize_request(rv)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1831, in finalize_request

 [Open an interactive python shell in this frame] response = self.make_response(rv)

File "C:\Users\benb\AppData\Local\Continuum\anaconda3\lib\site-packages\flask\app.py", line 1957, in make_response

'The view function did not return a valid response. The'

Body:
This is happening because your route \transform did return a valid response. This route must have a return statement. I am assuming that you want to load simple.html when this route is called, you can do the following things:

Import render_template:

from flask import render_template

Use the return statement, in the route, like below:

return render_template('simple.html')

Or just for dummy purpose you want this route to be executed without any error, then you can return like below:

return 'Transformed!'

Note: This depends, what you actually want to return or what you want to render, when this route is executed. You can read the docs.


问:
How to access specific element in json and compare the values
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

```<code>input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.
</code>```

答:
```<code>import json
input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)
print(var)
# >>> {u'code': u'ABB', u'data': 47.8, u'ID': u'03'}
if var["data"] < 50:
    print(var["data"])
</code>```

The above code will work for the input you mentioned. If you have multiple such rows, just iterate over it and use the part as specified.

Also, there were multiple errors in your code, as follows:

You are iterating over one entry.

After json.loads(...), you are not using var, instead, you were using input.

The variable name input should not be used as it is an inbuilt function.

Hope this helps!

Body:
I am new to json and coding. I want to read a json file and flag the value in "data" to check if the value is below 50 (in python). I do not know how to access specific values and convert them to int.

Below is my code and error:

input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)

for row in var:
    if input["data"] < 50:
        print(input["data"])

Error:
TypeError: string indices must be integers.

Body:
import json
input = '{"data": 47.8,"code": "ABB","ID": "03"}'

var = json.loads(input)
print(var)
# >>> {u'code': u'ABB', u'data': 47.8, u'ID': u'03'}
if var["data"] < 50:
    print(var["data"])

The above code will work for the input you mentioned. If you have multiple such rows, just iterate over it and use the part as specified.

Also, there were multiple errors in your code, as follows:

You are iterating over one entry.

After json.loads(...), you are not using var, instead, you were using input.

The variable name input should not be used as it is an inbuilt function.

Hope this helps!


问:
How to Dynamically Add Elements in Vue.JS?
I am having a little trouble figuring out how to dynamically add elements in Vue. I tried using the V-for as a for loop, however, the output is just the second item in the array. My goal is to create a new box for each of the array items.

The first block is my script code containing my two arrays. The second block is the template or HTML. I tried to loop through each of the numbs array and create a new box in each instance, however, I am having trouble creating new boxes for each element in the array.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div class="body">

  <div class="box"
  v-for="(demo, index) in numbs"
  :key="index">
    <div class="heading">
      {{demo}}
    </div>
    <button class="info"><router-link to = "/viewapp">View</router-link></button>
    <button class="edit"><router-link to = "/editapp">Edit</router-link></button>
    <img class ="place" src="../images/imageinsert.jpg" />
    <div class ="summary"
      v-for="(apps, index) of applications"
      :key="index">
      Application Version {{apps.ver}}
      {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}
    </div>
    </div>

</div>
</template></code>```

Here is an image of how the code currently runs. It prints out the last element of both arrays

Any help is greatly appreciated!!

答:
To loop through an array and create an element for each item, you use the v-for directive. You use it like so:

```<code><div class="summary" v-for="(apps, index) in applications" :key="index">
   Application Version {{apps.ver}}
   {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}
</div>
</code>```

You have v-for=(apps, index) for applications" (it should be in not for)

Also, you are using the index variable in both the inner and outer for loops. That's bound to cause an issue.

Body:
I am having a little trouble figuring out how to dynamically add elements in Vue. I tried using the V-for as a for loop, however, the output is just the second item in the array. My goal is to create a new box for each of the array items.

The first block is my script code containing my two arrays. The second block is the template or HTML. I tried to loop through each of the numbs array and create a new box in each instance, however, I am having trouble creating new boxes for each element in the array.

<template>

      {{demo}}

    <button class="info"><router-link to = "/viewapp">View</router-link></button>
    <button class="edit"><router-link to = "/editapp">Edit</router-link></button>

      Application Version {{apps.ver}}
      {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}

</template>

Here is an image of how the code currently runs. It prints out the last element of both arrays

Any help is greatly appreciated!!

Body:
To loop through an array and create an element for each item, you use the v-for directive. You use it like so:

<div class="summary" v-for="(apps, index) in applications" :key="index">
   Application Version {{apps.ver}}
   {{apps.status}}, {{apps.deploymentD}}, {{apps.deploymentC}}
</div>

You have v-for=(apps, index) for applications" (it should be in not for)

Also, you are using the index variable in both the inner and outer for loops. That's bound to cause an issue.


问:
need help understanding this code
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

```<code>$('#addFilterButton').click( function() {
    var filterItem = $('<div>')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});
</code>```

答:
It allows you to trigger, or run, an event. For instance if you wanted the code to mimic the clicking of a button, you could write....

```<code>$("#myButton").trigger('click');
</code>```

This would then run exactly as if you had clicked the button yourself.

'adjustName' is a custom event. So the trigger function is running that custom event. The custom event is assigned using the jQuery bind function.

```<code>$("#someElement").bind('adjustName', function() {/* Some Code */});
</code>```

You might create a customer event for clarity. Perhaps your application opens a document, so you might want an event called 'openDocument' and 'closeDocument' assigned to the element containing the document.

Title: need help understanding this code

Body:
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

$('#addFilterButton').click( function() {
    var filterItem = $('
')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});

Body:
It allows you to trigger, or run, an event. For instance if you wanted the code to mimic the clicking of a button, you could write....

$("#myButton").trigger('click');

This would then run exactly as if you had clicked the button yourself.

'adjustName' is a custom event. So the trigger function is running that custom event. The custom event is assigned using the jQuery bind function.

$("#someElement").bind('adjustName', function() {/* Some Code */});

You might create a customer event for clarity. Perhaps your application opens a document, so you might want an event called 'openDocument' and 'closeDocument' assigned to the element containing the document.


问:
how to clear local storage of react-native-webview?
how to clear localStorage of react-native-webview and

what is the best way to clear localstorage of webview

答:
we can use injectedJavaScript to clear localstorage. we can call this.clearLocalStorage(); to clear localStorage

```<code>clearLocalStorage = () => {
    this.setState({ isCookieClear: true }, () => {
      setTimeout(() => {
        this.setState({ isCookieClear: false });
      }, 2000);
    });
  };
</code>```

```<code>const {isCookieClear}=this.state;

let myInjectedJs = `(function(){
  ${isCookieClear?`window.localStorage.clear(); `:''}
})();`

return (
<WebView
 ref="webview"
 javaScriptEnabled={true}
 domStorageEnabled={true}
 injectedJavaScript={myInjectedJs}
 useWebKit={true}
 />
)
</code>```

Body:
we can use injectedJavaScript to clear localstorage. we can call this.clearLocalStorage(); to clear localStorage

clearLocalStorage = () => {
    this.setState({ isCookieClear: true }, () => {
      setTimeout(() => {
        this.setState({ isCookieClear: false });
      }, 2000);
    });
  };

const {isCookieClear}=this.state;

let myInjectedJs = `(function(){
  ${isCookieClear?`window.localStorage.clear(); `:''}
})();`

return (
<WebView
 ref="webview"
 javaScriptEnabled={true}
 domStorageEnabled={true}
 injectedJavaScript={myInjectedJs}
 useWebKit={true}
 />
)


问:
Boostrap container overflow and not responsive (always displayed two columns)
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

```<code><div class="container flex-wrap pt-3 w-75 ml-auto mr-auto mt-auto mb-5">
  <div class="row">
    <div class="col">
      <b-card>
        <SeriesForm />
      </b-card>
    </div>
    <div class="col">
      <b-card :header="captions[1]">
        <SeriesForm :group="forms[1]" />
      </b-card>
    </div>
  </div>
  <div class="row">
    <div class="col text-center p-4">
      <b-button>Analyse</b-button>
    </div>
  </div>
</div>
</code>```

How can I make it two columns when there is enough space and single column otherwise?

答:
This is happening because of the flex display,

what you need to do is set the columns with below your row for each form :

use this
 instead of
 .. the spacing is a little bit tight so you might need to remove some of the margins and paddings

this will make each form take full width on big screens and below and will make them 50% width on xl screens

Body:
I have created a form with two columns. But when I decrease the browser width, two columns are preserved even when their content overflows. I have tried to change the code to plain DIV with container class, specify cols count, set width but it resists.

Here is the codepen: https://codesandbox.io/s/stoic-goldberg-4ugt6

and the source code of the parent container:

        <SeriesForm />

        <SeriesForm :group="forms[1]" />

      Analyse

How can I make it two columns when there is enough space and single column otherwise?

Body:
This is happening because of the flex display,

what you need to do is set the columns with below your row for each form :

use this <div class='col-12 col-xl-6'> instead of <div class='col'> .. the spacing is a little bit tight so you might need to remove some of the margins and paddings

this will make each form take full width on big screens and below and will make them 50% width on xl screens


问:
Adding a custom 'Add' button to createMaterialBottomTabNavigator in react navigation 5
I'm making a project (react native, expo, react navigation 5) where I wanted to add a custom 'add' button to the bottom tabs, but since...

A navigator can only contain 'Screen' components as its direct
  children

...I needed to find a way to pass my custom component.

Seemed easy enough, I mean there are docs:

https://reactnavigation.org/docs/material-bottom-tab-navigator

https://reactnavigation.org/docs/bottom-tab-navigator

https://reactnavigation.org/docs/custom-navigators/

...but in looking at these and the questions from others I either only found muy complicado examples or examples of how to achieve this in earlier versions.

In the end I found a simple solution that so far works like a charm (fully grateful to any suggestions as to why this might be a terrible idea).

Figured I post my solution if anyone is in a similar pickle. See answer below.

答:
I had the same problem, I needed to add a custom component, not related with a screen, to the tab navigator and everything I tried it failed. In my case I was trying with createMaterialTopTabNavigator.

Documentation of React Navigation 5 is a little rough and there isn't a lot of examples of React Navigation 5, but after many attempts I could create a custom component and style it myself so I can mix the tabs created by the routes and the custom buttons embedded in the tab navigator.

```<code>import * as React from 'react';
import { View } from 'react-native'
import {
  NavigationHelpersContext,
  useNavigationBuilder,
  TabRouter,
  TabActions,
  createNavigatorFactory,
} from '@react-navigation/native';
import styled from 'styled-components'
import Colors from '../constants/Colors';

const customTabNavigator = ({
  initialRouteName,
  children,
  screenOptions,
  tabContainerStyle,
  contentStyle,
  leftIcon,
  rightIcon
}) => {
  const { state, navigation, descriptors } = useNavigationBuilder(TabRouter, {
    children,
    screenOptions,
    initialRouteName,
  });

  return (
    <NavigationHelpersContext.Provider value={navigation}>
      <OuterWrapper style={tabContainerStyle}>
        { leftIcon }
        <TabWrapper>
          {state.routes.map((route, i) => {
            return (
              <Tab
                key={route.key}
                onPress={() => {
                  const event = navigation.emit({
                    type: 'tabPress',
                    target: route.key,
                    canPreventDefault: true,
                  });

                  if (!event.defaultPrevented) {
                    navigation.dispatch({
                      ...TabActions.jumpTo(route.name),
                      target: state.key,
                    });
                  }
                }}
                style={descriptors[route.key].options.tabStyle}
              >
                { descriptors[route.key].options.label ?? <Label active={state.index === i}>{descriptors[route.key].options.title || route.name}</Label> }
              </Tab>
            )
          })}
        </TabWrapper>
        { rightIcon }
      </OuterWrapper>
      <View style={[{ flex: 1 }, contentStyle]}>
        {descriptors[state.routes[state.index].key].render()}
      </View>
    </NavigationHelpersContext.Provider>
  );
}

const OuterWrapper = styled.View`
  height: 55px;
  flex-direction: row;
  justify-content: space-between;
  background-color: ${Colors.grey1};
`
const TabWrapper = styled.View`
  flex: 1;
  flex-direction: row;
  justify-content: space-evenly;
`
const Tab = styled.TouchableOpacity`
  padding: 0 24px;
  justify-content: center;
  height: 100%;
`
const Label = styled.Text`
  font-family: Futura-Medium;
  font-size: 26px;
  color: ${({ active }) => active ? Colors.grey6 : Colors.grey3};
`

export default createNavigatorFactory(customTabNavigator)
</code>```

```<code>import customTabNavigator from './customTabNavigator'
import * as React from 'react';
import { View, Image } from 'react-native'

import {
  ProjectsScreen,
  RenderScreen,
  EventsScreen,
  CameraScreen
} from '../screens';

import Colors from '../constants/Colors'

import logo from '../assets/images/icon.png'
import { Ionicons } from '@expo/vector-icons';
import { TouchableOpacity } from 'react-native-gesture-handler';

const TopTab = customTabNavigator();
const INITIAL_ROUTE_NAME = 'Home';

export default function MainNavigator({ navigation, route }) {

  navigation.setOptions({ headerTitle: getHeaderTitle(route) });
  return (
      <TopTab.Navigator
        initialRouteName={INITIAL_ROUTE_NAME}
        leftIcon={(
          <TouchableOpacity style={{ height: "100%", justifyContent: "center" }} onPress={() => alert("Whatever")}>
            <Image source={logo} style={{ resizeMode: "center", width: 70, height: 40 }} />
          </TouchableOpacity>
        )}
      >
        <TopTab.Screen
          name="Home"
          component={ProjectsScreen}
          options={{
            title: 'Proyectos',
          }}
        />
        <TopTab.Screen
          name="Preview"
          component={EventsScreen}
          options={{
            title: 'Eventos',
          }}
        />
        <TopTab.Screen
          name="Render"
          component={RenderScreen}
          options={{
            title: 'Mi cuenta',
          }}
        />
        <TopTab.Screen
          name="Camera"
          component={CameraScreen}
          options={{
            title: "Camera",
            label: (
              <View style={{ width: 36, height: 32, backgroundColor: Colors.grey3, borderRadius: 3, alignItems: "center", justifyContent: "center" }}>
                <Ionicons name="md-camera" style={{ color: Colors.grey5 }} size={25} />
              </View>
            ),
            tabStyle: { flexDirection: "row", alignItems: "center", justifyContent: "flex-end", flex: 1  }
          }}
        />
      </TopTab.Navigator>
  );
}

function getHeaderTitle(route) {
  const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;

  switch (routeName) {
    case 'Home':
      return 'Montar vídeo';
    case 'Preview':
      return 'Previsualizar vídeo';
    case 'Render':
      return 'Renderizar';
    case 'Gallery':
      return 'Galería'
    case 'Camera':
      return 'Camera'
  }
}
</code>```

To the example of https://reactnavigation.org/docs/custom-navigators I added a different styling and two new props, leftIcon and rightIcon. This props receive a component for render it to the corresponding side of the tab wrapper. And this components can be TouchableWhatevers with a custom onPress not related with a screen :P

I hope it helps, I almost throw myself through the window until I made it work, haha

Body:
I had the same problem, I needed to add a custom component, not related with a screen, to the tab navigator and everything I tried it failed. In my case I was trying with createMaterialTopTabNavigator.

Documentation of React Navigation 5 is a little rough and there isn't a lot of examples of React Navigation 5, but after many attempts I could create a custom component and style it myself so I can mix the tabs created by the routes and the custom buttons embedded in the tab navigator.

import * as React from 'react';
import { View } from 'react-native'
import {
  NavigationHelpersContext,
  useNavigationBuilder,
  TabRouter,
  TabActions,
  createNavigatorFactory,
} from '@react-navigation/native';
import styled from 'styled-components'
import Colors from '../constants/Colors';

const customTabNavigator = ({
  initialRouteName,
  children,
  screenOptions,
  tabContainerStyle,
  contentStyle,
  leftIcon,
  rightIcon
}) => {
  const { state, navigation, descriptors } = useNavigationBuilder(TabRouter, {
    children,
    screenOptions,
    initialRouteName,
  });

  return (
    <NavigationHelpersContext.Provider value={navigation}>
      <OuterWrapper style={tabContainerStyle}>
        { leftIcon }
        <TabWrapper>
          {state.routes.map((route, i) => {
            return (
              <Tab
                key={route.key}
                onPress={() => {
                  const event = navigation.emit({
                    type: 'tabPress',
                    target: route.key,
                    canPreventDefault: true,
                  });

                  if (!event.defaultPrevented) {
                    navigation.dispatch({
                      ...TabActions.jumpTo(route.name),
                      target: state.key,
                    });
                  }
                }}
                style={descriptors[route.key].options.tabStyle}
              >
                { descriptors[route.key].options.label ?? <Label active={state.index === i}>{descriptors[route.key].options.title || route.name}</Label> }
              </Tab>
            )
          })}
        </TabWrapper>
        { rightIcon }
      </OuterWrapper>
      <View style={[{ flex: 1 }, contentStyle]}>
        {descriptors[state.routes[state.index].key].render()}
      </View>
    </NavigationHelpersContext.Provider>
  );
}

const OuterWrapper = styled.View`
  height: 55px;
  flex-direction: row;
  justify-content: space-between;
  background-color: ${Colors.grey1};
`
const TabWrapper = styled.View`
  flex: 1;
  flex-direction: row;
  justify-content: space-evenly;
`
const Tab = styled.TouchableOpacity`
  padding: 0 24px;
  justify-content: center;
  height: 100%;
`
const Label = styled.Text`
  font-family: Futura-Medium;
  font-size: 26px;
  color: ${({ active }) => active ? Colors.grey6 : Colors.grey3};
`

export default createNavigatorFactory(customTabNavigator)

import customTabNavigator from './customTabNavigator'
import * as React from 'react';
import { View, Image } from 'react-native'

import {
  ProjectsScreen,
  RenderScreen,
  EventsScreen,
  CameraScreen
} from '../screens';

import Colors from '../constants/Colors'

import logo from '../assets/images/icon.png'
import { Ionicons } from '@expo/vector-icons';
import { TouchableOpacity } from 'react-native-gesture-handler';

const TopTab = customTabNavigator();
const INITIAL_ROUTE_NAME = 'Home';

export default function MainNavigator({ navigation, route }) {

  navigation.setOptions({ headerTitle: getHeaderTitle(route) });
  return (
      <TopTab.Navigator
        initialRouteName={INITIAL_ROUTE_NAME}
        leftIcon={(
          <TouchableOpacity style={{ height: "100%", justifyContent: "center" }} onPress={() => alert("Whatever")}>
            <Image source={logo} style={{ resizeMode: "center", width: 70, height: 40 }} />
          </TouchableOpacity>
        )}
      >
        <TopTab.Screen
          name="Home"
          component={ProjectsScreen}
          options={{
            title: 'Proyectos',
          }}
        />
        <TopTab.Screen
          name="Preview"
          component={EventsScreen}
          options={{
            title: 'Eventos',
          }}
        />
        <TopTab.Screen
          name="Render"
          component={RenderScreen}
          options={{
            title: 'Mi cuenta',
          }}
        />
        <TopTab.Screen
          name="Camera"
          component={CameraScreen}
          options={{
            title: "Camera",
            label: (
              <View style={{ width: 36, height: 32, backgroundColor: Colors.grey3, borderRadius: 3, alignItems: "center", justifyContent: "center" }}>
                <Ionicons name="md-camera" style={{ color: Colors.grey5 }} size={25} />
              </View>
            ),
            tabStyle: { flexDirection: "row", alignItems: "center", justifyContent: "flex-end", flex: 1  }
          }}
        />
      </TopTab.Navigator>
  );
}

function getHeaderTitle(route) {
  const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;

  switch (routeName) {
    case 'Home':
      return 'Montar vídeo';
    case 'Preview':
      return 'Previsualizar vídeo';
    case 'Render':
      return 'Renderizar';
    case 'Gallery':
      return 'Galería'
    case 'Camera':
      return 'Camera'
  }
}

To the example of https://reactnavigation.org/docs/custom-navigators I added a different styling and two new props, leftIcon and rightIcon. This props receive a component for render it to the corresponding side of the tab wrapper. And this components can be TouchableWhatevers with a custom onPress not related with a screen :P

I hope it helps, I almost throw myself through the window until I made it work, haha


问:
How to extract CN from X509Certificate in Java?
I am using a SslServerSocket and client certificates and want to extract the CN from the SubjectDN from the client's X509Certificate.

At the moment I call cert.getSubjectX500Principal().getName() but this of course gives me the total formatted DN of the client. For some reason I am just interested in the CN=theclient part of the DN. Is there a way to extract this part of the DN without parsing the String myself?

答:
One more way to do with plain Java :

public static String getCommonName(X509Certificate certificate) {
    String name = certificate.getSubjectX500Principal().getName();
    int start = name.indexOf("CN=");
    int end = name.indexOf(",", start);
    if (end == -1) {
        end = name.length();
    }
    return name.substring(start + 3, end);
}
```


问:
How to extract the text from the selected item on the listView
I have a listview with some items. I would like to get the text from the selected item.

Here is my list adapter and the onItemClickListener:

```<code>ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
??????
    }});
        }
</code>```

Could you tell me please how to get the String from the selected item.

the method ((TextView) view).getText() does not work, i have a

```<code>ClassCastException: android.widget.LinearLayout
</code>```

I have found the solution, maybe somebody will need it:

```<code>ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            String text = textView.getText().toString();
            System.out.println("Choosen Country = : " + text);

    }});
</code>```

答:
This worked for me. I had tried some solutions here but they hadn't worked. Hope this helps.</p>

```<code>ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myFamily);

    listViewDemo.setAdapter(arrayAdapter);

    listViewDemo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //String nameSelectedfromList = arrayAdapter.getItem(position).toString();
            String nameSelectedfromList = listViewDemo.getItemAtPosition(position).toString();

            Log.i("Clicked Item", nameSelectedfromList);

        }
    });
</code>```

Body:
I have a listview with some items. I would like to get the text from the selected item.

Here is my list adapter and the onItemClickListener:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
??????
    }});
        }

Could you tell me please how to get the String from the selected item.

the method ((TextView) view).getText() does not work, i have a

ClassCastException: android.widget.LinearLayout

I have found the solution, maybe somebody will need it:

ListView lv = (ListView)findViewById(R.id.listView1);
    lv.setAdapter(new ArrayAdapter<Country>(
            this,R.layout.list_black_text,R.id.list_content, values));

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
            TextView textView = (TextView) view.findViewById(R.id.list_content);
            String text = textView.getText().toString();
            System.out.println("Choosen Country = : " + text);

    }});

Body:
This worked for me. I had tried some solutions here but they hadn't worked. Hope this helps.

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myFamily);

    listViewDemo.setAdapter(arrayAdapter);

    listViewDemo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            //String nameSelectedfromList = arrayAdapter.getItem(position).toString();
            String nameSelectedfromList = listViewDemo.getItemAtPosition(position).toString();

            Log.i("Clicked Item", nameSelectedfromList);

        }
    });


问:
Order each column of dataframe and print to .csv file
I have a dataframe in which I want to order each column in descending order, and write the result as a .csv file.

For example

```<code>> mtcars$car <- rownames(mtcars)
> head(mtcars,3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb           car
 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1     Datsun 710
</code>```

For example, the ranks of the wt column would be one .txt file

```<code>      > head(sorted_mtcars,5)
      wt                 car
   5.424 Lincoln Continental
   5.345   Chrysler Imperial
   5.250  Cadillac Fleetwood
   4.070          Merc 450SE
   3.845    Pontiac Firebird
</code>```

And the ranks of the qsec column:

```<code>> head(sorted_mtcars,5)
   qsec            car
  22.90       Merc 230
  20.22        Valiant
  20.01  Toyota Corona
  20.00      Merc 240D
  19.90 Toyota Corolla
</code>```

How can I do this for the entire dataframe?

答:
Using a for loop:</p>

```<code># for each column except "car"
for(col in setdiff(names(mtcars), "car")) {
  # write a csv
  write.csv(
    #  ordered by the column
    #  selecting the column and the "car" column
    x = mtcars[order(mtcars[[col]], decreasing = TRUE), c(col, "car")],
    # give it a nice filename
    file = paste0("mtcars_sorted_", col, ".csv")
  )
}
</code>```

Body:
I have a dataframe in which I want to order each column in descending order, and write the result as a .csv file.

For example

> mtcars$car <- rownames(mtcars)
> head(mtcars,3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb           car
 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4      Mazda RX4
 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  Mazda RX4 Wag
 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1     Datsun 710

For example, the ranks of the wt column would be one .txt file

      > head(sorted_mtcars,5)
      wt                 car
   5.424 Lincoln Continental
   5.345   Chrysler Imperial
   5.250  Cadillac Fleetwood
   4.070          Merc 450SE
   3.845    Pontiac Firebird

And the ranks of the qsec column:

> head(sorted_mtcars,5)
   qsec            car
  22.90       Merc 230
  20.22        Valiant
  20.01  Toyota Corona
  20.00      Merc 240D
  19.90 Toyota Corolla

How can I do this for the entire dataframe?

Body:
Using a for loop:

# for each column except "car"
for(col in setdiff(names(mtcars), "car")) {
  # write a csv
  write.csv(
    #  ordered by the column
    #  selecting the column and the "car" column
    x = mtcars[order(mtcars[[col]], decreasing = TRUE), c(col, "car")],
    # give it a nice filename
    file = paste0("mtcars_sorted_", col, ".csv")
  )
}


问:
Remove orphan identities in TFS 2010
I am in the process of moving a TFS 2010 installation from one machine to another.

I found that is possible remap identities using TFSConfig Identities /change command but I didn't find a way to remove orphan user identities that I don't need anymore.

I know that probably I can leave them there, but I am fussy and I like keeping things in order. Do you have any idea how to safely remove unused identities?

答: Don't clean them up. They are inactive so think of them as tombstones. If you get rid of them, you may experience dangling users (in Access Control Entries or File History for example).</p>

Title: Remove orphan identities in TFS 2010


问:
How to make image from internet responsive on Android layout?
I have an Imageview on my layout which I fill with a .jpg that I download from the web. The thing is that I am trying to make the image container responsive to the screen size since in larger phones the image is seen small.

```<code>    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
    }

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String imageUrl="https:url";

        new DownloadImageTask((ImageView) findViewById(R.id.imvAd))
                .execute(imageUrl);
    }
    }
</code>```

I do not want to give fixed values.

Any help or suggestions on what to look for would be great

This is the layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".startActivities.LoginActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imvLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@mipmap/logo"
                tools:ignore="ContentDescription" />

            <LinearLayout
                android:id="@+id/lytProgressBarLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <ProgressBar
                    android:id="@+id/pgbLogin"
                    style="?android:attr/progressBarStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView
                    android:id="@+id/txtwelcome"
                    style="@style/styleTextview1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/welcome" />

                <EditText
                    android:id="@+id/edtPwdworker"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="@string/password"
                    android:inputType="numberPassword" />

                <Button
                    android:id="@+id/btnLogin"
                    style="@style/styleButtonConsult"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="@string/login" />
            </LinearLayout>

            <TextView
                android:id="@+id/txtInfoRoute"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="10dp"
                android:layout_weight="90"
                android:gravity="center" />

            <TextView
                android:id="@+id/txtPinDeviceLogin"
                style="@style/styleTextviewsubTitlebold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:text="@string/pinDevice" />

            <ImageView
                android:id="@+id/imvAd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                tools:ignore="ContentDescription" />
        </LinearLayout>

    </ScrollView>

    <TextView
        android:id="@+id/txtVersionLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="95"
        android:gravity="center" />

</LinearLayout>
</code>```

答:
If your ImageView is fixed you can scale the image by setting ScaleType to CENTER_CROP or other relevant scale types to make the image scale as your ImageView does.

```<code><ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />
</code>```

Also don't use wrap_content instead you may use match_parent to fit the layout.
or use 0dp ( in ConstraintLayout ) and constraint the ImageView between two other views.

but if you want your ImageView's size changes with respect to the screen's size
you can use a Constraintlayout as the parent and use layout_constraintDimensionRatio like this.

```<code><androidx.constraintlayout.widget.ConstraintLayout>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Besides that, I suggest using an image loader library such as Glide.
It's more efficient than loading the image yourself and also you can set the scale type directly from there.

Body:
I have an Imageview on my layout which I fill with a .jpg that I download from the web. The thing is that I am trying to make the image container responsive to the screen size since in larger phones the image is seen small.

    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
    }

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String imageUrl="https:url";

        new DownloadImageTask((ImageView) findViewById(R.id.imvAd))
                .execute(imageUrl);
    }
    }

I do not want to give fixed values.

Any help or suggestions on what to look for would be great

This is the layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".startActivities.LoginActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imvLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@mipmap/logo"
                tools:ignore="ContentDescription" />

            <LinearLayout
                android:id="@+id/lytProgressBarLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <ProgressBar
                    android:id="@+id/pgbLogin"
                    style="?android:attr/progressBarStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView
                    android:id="@+id/txtwelcome"
                    style="@style/styleTextview1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/welcome" />

                <EditText
                    android:id="@+id/edtPwdworker"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="@string/password"
                    android:inputType="numberPassword" />

                <Button
                    android:id="@+id/btnLogin"
                    style="@style/styleButtonConsult"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="@string/login" />
            </LinearLayout>

            <TextView
                android:id="@+id/txtInfoRoute"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="10dp"
                android:layout_weight="90"
                android:gravity="center" />

            <TextView
                android:id="@+id/txtPinDeviceLogin"
                style="@style/styleTextviewsubTitlebold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:text="@string/pinDevice" />

            <ImageView
                android:id="@+id/imvAd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                tools:ignore="ContentDescription" />
        </LinearLayout>

    </ScrollView>

    <TextView
        android:id="@+id/txtVersionLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="95"
        android:gravity="center" />

</LinearLayout>

Body:
If your ImageView is fixed you can scale the image by setting ScaleType to CENTER_CROP or other relevant scale types to make the image scale as your ImageView does.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />

Also don't use wrap_content instead you may use match_parent to fit the layout.
or use 0dp ( in ConstraintLayout ) and constraint the ImageView between two other views.

but if you want your ImageView's size changes with respect to the screen's size
you can use a Constraintlayout as the parent and use layout_constraintDimensionRatio like this.

<androidx.constraintlayout.widget.ConstraintLayout>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1" />
</androidx.constraintlayout.widget.ConstraintLayout>

Besides that, I suggest using an image loader library such as Glide.
It's more efficient than loading the image yourself and also you can set the scale type directly from there.


问:
Android App context null in Activity.onCreate()
This code in Activity

```<code>public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}
</code>```

sometimes produces a NullPointerException.

This is the custom App class:

```<code>public class App extends Application
{
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext()
    {
        return context;
    }
}
</code>```

How can the NullPointerException be fixed?

答:
Replace:

```<code>DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics();
</code>```

with:

```<code>DisplayMetrics metrics = getResources().getDisplayMetrics();
</code>```

Not only do you not need the Application here, anything GUI-related should be using an Activity anyway.

Body:
This code in Activity

public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics(); //crash
}

sometimes produces a NullPointerException.

This is the custom App class:

public class App extends Application
{
    private static Context context;

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    public static Context getAppContext()
    {
        return context;
    }
}

How can the NullPointerException be fixed?

Body:
Replace:

DisplayMetrics metrics = App.getAppContext().getResources().getDisplayMetrics();

with:

DisplayMetrics metrics = getResources().getDisplayMetrics();

Not only do you not need the Application here, anything GUI-related should be using an Activity anyway.


问:
How can I do vertical align in a cell with multiple data
I want to add to my cell two links and place them on a bottom of my cell.
I've tried "vertical-align:bottom" but it doesn't work in my case:

```<code>// Append database data here
$.ajax({
    type: "GET",
    url: "/Home/JsonWeekEvents",
    dataType: "JSON",
    success: function (result) {
        $.each(result, function (i, val) {
            var trow = $('<tr/>').data("id", val.Id);
            //trow.append('<td>' + val.Id + " " + '</td>');
            trow.append('<td style="padding:5px; width:100px; height:70px"></td>');

            trow.append('<td valign="top" style="padding:2px; width:150px; height:100px">' +
                '<div class="ui-widget">' +
                '<input  size="10" maxlength="10" id="tagsW" class="tags" />' +
                '<input type="button" id="addBtn" class="addEvent" size="5" value="+" /><br/>' +
                '<div style="text-align:center" id="wedVal" class="desc_NumW">' + val.Wednesday + '</div >' +
                '<input type="hidden" class="idEvent" />' +
                '<div style="vertical-align:bottom;">' +
                '<a  href="#" style="float:left;text-align:left;">Details<a/>' + '<a href="#" style="float:right;text-align:right;">Clear<a />' +
                '</div >' +
                '</div >' +
                '</td>');
</code>```

How can I solve it?

答:
try set follow styles for your div instead vertical-align</p>

```<code>display:flex; align-items: flex-end;
</code>```

Body:
I want to add to my cell two links and place them on a bottom of my cell.
I've tried "vertical-align:bottom" but it doesn't work in my case:

// Append database data here
$.ajax({
    type: "GET",
    url: "/Home/JsonWeekEvents",
    dataType: "JSON",
    success: function (result) {
        $.each(result, function (i, val) {
            var trow = $('
').data("id", val.Id);
            //trow.append('' + val.Id + " " + '	');
            trow.append('	');

            trow.append('' +
                '
' +
                '<input  size="10" maxlength="10" id="tagsW" class="tags" />' +
                '<input type="button" id="addBtn" class="addEvent" size="5" value="+" />
' +
                '
' + val.Wednesday + '
' +
                '<input type="hidden" class="idEvent" />' +
                '
' +
                'Details' + 'Clear' +
                '
' +
                '
' +
                '	');

How can I solve it?

Body:
try set follow styles for your div instead vertical-align

display:flex; align-items: flex-end;


问:
How to import an existing S3 bucket exported by a stack, into another stack via CloudFormation YAML
Something like the below CloudformationYAML works. I end up with a lambda function that's getting triggered whenever a new object shows up on the S3 bucket.

```<code>Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref myS3BucketName
      AccessControl: Private
      VersioningConfiguration:
        Status: Enabled

LambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: main.handler
      CodeUri:
        Bucket: !Ref CodeBucketName
        Key: !Ref CodeKey
      Role: !GetAtt
        - LambdaRole
        - Arn
      Runtime: nodejs12.x
      Timeout: !Ref LambdaTimeOut
      MemorySize: !Ref LambdaMemory
      FunctionName: !Sub '${Environment}-${FunctionName}'
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketResource
            Events:
              - 's3:ObjectCreated:Put'

</code>```

However, what I need to do is to have the lambda function use an already existing S3 bucket, which was created by another stack. Note that in the above, the S3 bucket is getting created by the same CF template that's also creating the lambda.

I can't seem to just refer to the S3 buckets name in the Bucket property of the S3Event like below:

```<code>      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketName
            Events:
              - 's3:ObjectCreated:Put'
</code>```

So I'm thinking it's because it needed to be a resource rather than a string, at least based on the CF template above which works.

I read about Fn::ImportValue for importing something that's been exported by another stack -- which is the case for the S3 bucket I need to use. But I couldn't figure out how to specify that on the CF template.

Tried below, for example, but it's not working. With out without the Type: AWS::S3::Bucket line.

```<code>Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      Bucket:
        Fn::ImportValue: !Sub "${exportedS3Bucket}"
</code>```

Any lead would be appreciated. If there's a way to specify the Bucket without going through an import route, then that really would be best.

Thanks!

答:
Found this AWS doc => https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-s3.html

There's this:

```<code>Bucket
S3 bucket name. This bucket must exist in the same template.

Type: String

Required: Yes

AWS CloudFormation Compatibility: This property is similar to the BucketName property of an AWS::S3::Bucket. This is a required field in SAM. This field only accepts a reference to the S3 bucket created in this template
</code>```

And this YAML sample:

```<code>Events:
  S3Event:
    Type: S3
    Properties:
      Bucket:
        Ref: ImagesBucket     # This must be the name of an S3 bucket declared in the same template file
      Events: s3:ObjectCreated:*
      Filter:
        S3Key:
          Rules:
          - Name: prefix      # or "suffix"
            Value: value      # The value to search for in the S3 object key names
</code>```

The comment on the YAML indicates that the S3 bucket needs to be "declared in the same template file". While the bit about AWS CloudFormation Compatibility: in the Bucket section indicates "This field only accepts a reference to the S3 bucket created in this template".

Unless this AWS doc just needs updating, It doesn't look like there's a way to add a Lambda event trigger using an existing S3 bucket via CF. And that doesn't bode well for my use case.

Body:
Something like the below CloudformationYAML works. I end up with a lambda function that's getting triggered whenever a new object shows up on the S3 bucket.

Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref myS3BucketName
      AccessControl: Private
      VersioningConfiguration:
        Status: Enabled

LambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: main.handler
      CodeUri:
        Bucket: !Ref CodeBucketName
        Key: !Ref CodeKey
      Role: !GetAtt
        - LambdaRole
        - Arn
      Runtime: nodejs12.x
      Timeout: !Ref LambdaTimeOut
      MemorySize: !Ref LambdaMemory
      FunctionName: !Sub '${Environment}-${FunctionName}'
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketResource
            Events:
              - 's3:ObjectCreated:Put'

However, what I need to do is to have the lambda function use an already existing S3 bucket, which was created by another stack. Note that in the above, the S3 bucket is getting created by the same CF template that's also creating the lambda.

I can't seem to just refer to the S3 buckets name in the Bucket property of the S3Event like below:

      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketName
            Events:
              - 's3:ObjectCreated:Put'

So I'm thinking it's because it needed to be a resource rather than a string, at least based on the CF template above which works.

I read about Fn::ImportValue for importing something that's been exported by another stack -- which is the case for the S3 bucket I need to use. But I couldn't figure out how to specify that on the CF template.

Tried below, for example, but it's not working. With out without the Type: AWS::S3::Bucket line.

Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      Bucket:
        Fn::ImportValue: !Sub "${exportedS3Bucket}"

Any lead would be appreciated. If there's a way to specify the Bucket without going through an import route, then that really would be best.

Thanks!

Body:
Found this AWS doc => https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-function-s3.html

There's this:

Bucket
S3 bucket name. This bucket must exist in the same template.

Type: String

Required: Yes

AWS CloudFormation Compatibility: This property is similar to the BucketName property of an AWS::S3::Bucket. This is a required field in SAM. This field only accepts a reference to the S3 bucket created in this template

And this YAML sample:

Events:
  S3Event:
    Type: S3
    Properties:
      Bucket:
        Ref: ImagesBucket     # This must be the name of an S3 bucket declared in the same template file
      Events: s3:ObjectCreated:*
      Filter:
        S3Key:
          Rules:
          - Name: prefix      # or "suffix"
            Value: value      # The value to search for in the S3 object key names

The comment on the YAML indicates that the S3 bucket needs to be "declared in the same template file". While the bit about AWS CloudFormation Compatibility: in the Bucket section indicates "This field only accepts a reference to the S3 bucket created in this template".

Unless this AWS doc just needs updating, It doesn't look like there's a way to add a Lambda event trigger using an existing S3 bucket via CF. And that doesn't bode well for my use case.