问:
Textarea remaining characters not working properly
I have a textarea with pre-filled value in it. Now, I have also installed a "character remaining" line underneath the text area.

I'm not been able to achieve the default count value, if you notice on load the word count stays at "250 characters remaining", also note that the value is pre-filled with some text already so the function should count the pre-filled text by default.

The text color changes to yellow once "100 characters are remaining" and to red once "0 characters are remaining". It seems like the color doesn't change back to default when I reach the yellow color and starts removing the text to more than 100 characters.

Can someone help?

document.addEventListener('keyup', function(event) {
  if (event.target.matches('textarea.minchar')) {
    let element = event.target;
    let value = element.value;
    let maxLength = element.maxLength;
    let rechar = element.nextElementSibling;

    rechar.innerText = `${maxLength - Number(value.length)} characters remaining`;

    if (maxLength - Number(value.length) == 0) {
      rechar.style.color = "#E01424";
    } else if (maxLength - Number(value.length) <= 100) {
      rechar.style.color = "#CF7721";
    }
  }
}, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-10 pl-0">
  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>
  <p class="rechar" id="test">250 characters remaining</p>
</div></code>```

答:
Add an else statement to the bottom and set color back to black like so:

```<code>if (maxLength - Number(value.length) <= 0) {
  rechar.style.color = "#E01424";
} else if (maxLength - Number(value.length) <= 100) {
  rechar.style.color = "#CF7721";
} else { // You can add an if statement here to check if the color is #000 yet to prevent re-renders
  rechar.style.color = "#000";
}
</code>```

Manually triggering event the first time:

```<code>var evnt = document.createEvent('HTMLEvents');
evnt.initEvent('keyup', true, true); // Deprecated but still works
$('textarea.minchar').dispatchEvent(evnt);
</code>```

Body:
I have a textarea with pre-filled value in it. Now, I have also installed a "character remaining" line underneath the text area.

I'm not been able to achieve the default count value, if you notice on load the word count stays at "250 characters remaining", also note that the value is pre-filled with some text already so the function should count the pre-filled text by default.

The text color changes to yellow once "100 characters are remaining" and to red once "0 characters are remaining". It seems like the color doesn't change back to default when I reach the yellow color and starts removing the text to more than 100 characters.

Can someone help?

document.addEventListener('keyup', function(event) {
  if (event.target.matches('textarea.minchar')) {
    let element = event.target;
    let value = element.value;
    let maxLength = element.maxLength;
    let rechar = element.nextElementSibling;

    rechar.innerText = `${maxLength - Number(value.length)} characters remaining`;

    if (maxLength - Number(value.length) == 0) {
      rechar.style.color = "#E01424";
    } else if (maxLength - Number(value.length) <= 100) {
      rechar.style.color = "#CF7721";
    }
  }
}, false);

  <textarea cols="15" rows="4" placeholder="Describe this Extra in brief for your guest" class="minchar" maxlength="250">Save time and return the vehicle at any fuel level. The price includes up to a full tank of petrol/diesel/charge.</textarea>

250 characters remaining

Body:
Add an else statement to the bottom and set color back to black like so:

if (maxLength - Number(value.length) <= 0) {
  rechar.style.color = "#E01424";
} else if (maxLength - Number(value.length) <= 100) {
  rechar.style.color = "#CF7721";
} else { // You can add an if statement here to check if the color is #000 yet to prevent re-renders
  rechar.style.color = "#000";
}

Manually triggering event the first time:

var evnt = document.createEvent('HTMLEvents');
evnt.initEvent('keyup', true, true); // Deprecated but still works
$('textarea.minchar').dispatchEvent(evnt);


来源: stackexchange

问:
Python: List Comprehension invalid syntax error
I'm trying to recreate this loop in one line:

```<code>results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]

for x in results:
  total = x + total

print(total)
</code>```

But when I do this:

```<code> y = [total = total + x for x in results]
</code>```

I get an error:

```<code>y = [total = total + x for x in results]
                   ^
SyntaxError: invalid syntax
</code>```

What am I missing? Thank you.

答:
The problem arises because a one-liner in python returns an array, it has not a clean way to refer to the objects it is creating itself.

You can't make a commutative sum, you could multiply the numbers (but each one of them)

```<code>In [2]: y = [x*x  for x in results]

In [3]: y
Out[3]: [22201, 0, 16384, 0, 0, 0, 1, 0, 0, 196, 0, 4]

</code>```

The best way to accomplish what you want is with its build in method sum

```<code>In [9]: sum(results)
Out[9]: 294
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to recreate this loop in one line:

results = [149, 0, 128, 0, 0, 0, 1, 0, 0, 14, 0, 2]

for x in results:
  total = x + total

print(total)

But when I do this:

 y = [total = total + x for x in results]

I get an error:

y = [total = total + x for x in results]
                   ^
SyntaxError: invalid syntax

What am I missing? Thank you.

Body:
The problem arises because a one-liner in python returns an array, it has not a clean way to refer to the objects it is creating itself.

You can't make a commutative sum, you could multiply the numbers (but each one of them)

In [2]: y = [x*x  for x in results]

In [3]: y
Out[3]: [22201, 0, 16384, 0, 0, 0, 1, 0, 0, 196, 0, 4]

The best way to accomplish what you want is with its build in method sum

In [9]: sum(results)
Out[9]: 294


问:
Iterating through a vector and cast enum to integer
I have a vector of enums that I want to cast to an integer value so I can do a numerical comparison.

I keep running into borrowing warnings "cannot move out of borrowed context"

I have tried various permutations of the following:

```<code>enum SomeEnum {
    A,
    B,
    C,
}

let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter() {
  let i = *val as i32;
  // if i < X do something
}
</code>```

答:
iter iterates through a collection using the references to the elements. into_iter, which causes a move, will give you access to the actual elements. If you're okay with the move, then this can help ease the cast of enums ordinal values:

```<code>for val in values.into_iter() {
    let i = val as i32;
    // if i < X do something
}
</code>```

Alternatively, if you want to be able to iterate the vector again, you can use clone:

```<code>#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}
</code>```

Which allows to cast after allocating a new instance of the enum value:

```<code>let values = vec![SomeEnum::A, SomeEnum::B];
for val in values.iter() {
    let i = (val.clone()) as i32;
    // if i < X do something
}
</code>```

Body:
I have a vector of enums that I want to cast to an integer value so I can do a numerical comparison.

I keep running into borrowing warnings "cannot move out of borrowed context"

I have tried various permutations of the following:

enum SomeEnum {
    A,
    B,
    C,
}

let values = vec![SomeEnum::A, SomeEnum::B];

for val in values.iter() {
  let i = *val as i32;
  // if i < X do something
}

Body:
iter iterates through a collection using the references to the elements. into_iter, which causes a move, will give you access to the actual elements. If you're okay with the move, then this can help ease the cast of enums ordinal values:

for val in values.into_iter() {
    let i = val as i32;
    // if i < X do something
}

Alternatively, if you want to be able to iterate the vector again, you can use clone:

#[derive(Clone)]
enum SomeEnum {
    A,
    B,
    C,
}

Which allows to cast after allocating a new instance of the enum value:

let values = vec![SomeEnum::A, SomeEnum::B];
for val in values.iter() {
    let i = (val.clone()) as i32;
    // if i < X do something
}


问:
"unsupported_grant_type" after publishing WebApi on Azure
I'm creating a WebApi that access a database hosted on Azure. After implementing Token Based Authentication it works perfectly locally, but after publishing it on Azure, when I try to get an access token I keep receiving the message: "error": "unsupported_grant_type" when testing it on Postman. Do I need to configure something else on Azure?

I'm requesting my token with the following parameters/settings:

```<code>"Content-Type", "application/x-www-form-urlencoded"
username: xxx
password: xxx
grant_type: password
</code>```

As I said, using these parameters I'm receiving my access token just fine locally (as seen below), the problem only occurs after deploying it to Azure.

```<code>{
    "access_token": "Daak3ZrEzMkcd-dCbEdN0FTjdc9QYexA5wfHtYBRQIdx0dJtX1RL3LR6rqXhKvr84J6qS0CyDwuVw3w3T-b6iXtVG3utqTda98EcQJUgDZjvnq6tgsml4tbkAQRYLX0BPYidk5JvdRHMLaoQkP3vYJYnCefWPN-jBPb9xdyyk-ZtgOxKVUcBECGeZeWKkSl2ZL7Mtg_opc5ryxedQbNcQkFAk1z4oBEuYSaUllGHJlswqq1lbZq-BUOTwroZFzae",
    "token_type": "bearer",
    "expires_in": 3599
}
</code>```

locally:
postman request made locally

after deploying to azure:
postman request made after deploy

So far I haven't made a request via code, only using postman

Has anyone faced a similar problem? Thanks!

答:
It seems you are trying to use Resource owner password credential (ROPC) to access your API. But this flow has little restriction on azure portal.

Please read the Important note carefully.

You could Use:

MatheusSchneider@YourTennant.onmicrosoft.com

But Not MatheusSchneider@outlook.com

Note: As Microsoft does not recommend this authentication flow this may be the cause after deployment on azure portal. I would
  suggest you to use some other authentication flow instead of this. You
  could check here

Body:
I'm creating a WebApi that access a database hosted on Azure. After implementing Token Based Authentication it works perfectly locally, but after publishing it on Azure, when I try to get an access token I keep receiving the message: "error": "unsupported_grant_type" when testing it on Postman. Do I need to configure something else on Azure?

I'm requesting my token with the following parameters/settings:

"Content-Type", "application/x-www-form-urlencoded"
username: xxx
password: xxx
grant_type: password

As I said, using these parameters I'm receiving my access token just fine locally (as seen below), the problem only occurs after deploying it to Azure.

{
    "access_token": "Daak3ZrEzMkcd-dCbEdN0FTjdc9QYexA5wfHtYBRQIdx0dJtX1RL3LR6rqXhKvr84J6qS0CyDwuVw3w3T-b6iXtVG3utqTda98EcQJUgDZjvnq6tgsml4tbkAQRYLX0BPYidk5JvdRHMLaoQkP3vYJYnCefWPN-jBPb9xdyyk-ZtgOxKVUcBECGeZeWKkSl2ZL7Mtg_opc5ryxedQbNcQkFAk1z4oBEuYSaUllGHJlswqq1lbZq-BUOTwroZFzae",
    "token_type": "bearer",
    "expires_in": 3599
}

locally:
postman request made locally

after deploying to azure:
postman request made after deploy

So far I haven't made a request via code, only using postman

Has anyone faced a similar problem? Thanks!


问:
Flask - Return the Same Form that was Submitted
How do I get Flask to return the user to the same page, filled out the same way, after he/she submits the form on the page? 'render_template' only seems to work if I know all the variables ahead of time. My form is dynamic, and the variables change depending on selections the user has made. See the psuedo-code below for what I'm thinking of. I know render_template doesn't work like this, but is there a way to just say "use the same form values that came in when rendering the template?"</p>

```<code>@app.route('./MyPage', methods=['GET', 'POST'])
def MyPage():

  if request.method == 'POST':
    # Do some stuff
    # return render_template('MyPage.html', context=request.form)
  else:
    # Do some other stuff
</code>```

答:
The simplest way to do a download in the way you are asking it to use target="_blank" on your form:

```<code><form action="/MyPage" method="POST" target="_blank">
  <ul>
  {% for input in form %}
    <li>{{ input.label }} {{ input }}</li>
  {% endfor %}
  </ul>
</form>
</code>```

Then your POST-handling method doesn't need to do anything else but return the CSV:

```<code>@app.route('/MyPage', methods=['GET', 'POST'])
def MyPage():
  if request.method == 'POST':
    # Turn `request.form` into a CSV
    # see https://stackoverflow.com/q/26997679/135978 for an example
    headers = {'Content-Disposition': 'attachment; filename=saved-form.csv', 'Content-Type': 'text/csv'}
    return form_as_csv, headers
  else:
    # Do some other stuff
</code>```

If you need multiple buttons on the form, then instead of setting target on the form, you can just set formtarget="_blank" on the button that triggers the CSV:

```<code><form action="/MyPage" method="POST">
  <ul><!-- ... snip ... --></ul>
  <button name="submit_action" value="SAVE_AS_CSV" formtarget="_blank">Save as CSV</button>
  <button name="submit_action" value="RUN_CALCULATION">Run Calculation</button>
</form>
</code>```

Then you just need to add a check for request.form['submit_action'] in your if request.method == 'POST' block and you're off to the races:

```<code>if request.method == 'POST':
    if request.form['submit_action'] == 'SAVE_AS_CSV':
        # Return the CSV response
    else:
        # Return the calculation response
</code>```

See also: Writing a CSV from Flask framework

Body:
How do I get Flask to return the user to the same page, filled out the same way, after he/she submits the form on the page? 'render_template' only seems to work if I know all the variables ahead of time. My form is dynamic, and the variables change depending on selections the user has made. See the psuedo-code below for what I'm thinking of. I know render_template doesn't work like this, but is there a way to just say "use the same form values that came in when rendering the template?"

@app.route('./MyPage', methods=['GET', 'POST'])
def MyPage():

  if request.method == 'POST':
    # Do some stuff
    # return render_template('MyPage.html', context=request.form)
  else:
    # Do some other stuff

Body:
The simplest way to do a download in the way you are asking it to use target="_blank" on your form:

<form action="/MyPage" method="POST" target="_blank">
  <ul>
  {% for input in form %}
    <li>{{ input.label }} {{ input }}</li>
  {% endfor %}
  </ul>
</form>

Then your POST-handling method doesn't need to do anything else but return the CSV:

@app.route('/MyPage', methods=['GET', 'POST'])
def MyPage():
  if request.method == 'POST':
    # Turn `request.form` into a CSV
    # see https://stackoverflow.com/q/26997679/135978 for an example
    headers = {'Content-Disposition': 'attachment; filename=saved-form.csv', 'Content-Type': 'text/csv'}
    return form_as_csv, headers
  else:
    # Do some other stuff

If you need multiple buttons on the form, then instead of setting target on the form, you can just set formtarget="_blank" on the button that triggers the CSV:

<form action="/MyPage" method="POST">
  <ul><!-- ... snip ... --></ul>
  <button name="submit_action" value="SAVE_AS_CSV" formtarget="_blank">Save as CSV</button>
  <button name="submit_action" value="RUN_CALCULATION">Run Calculation</button>
</form>

Then you just need to add a check for request.form['submit_action'] in your if request.method == 'POST' block and you're off to the races:

if request.method == 'POST':
    if request.form['submit_action'] == 'SAVE_AS_CSV':
        # Return the CSV response
    else:
        # Return the calculation response

See also: Writing a CSV from Flask framework


问:
Private variables inside DelegatingHandler mixing values from other requests
We have a DelegatingHandler implemented that has some private variables and 2 of them are getting values from different parallel requests than their own even though they are not static variables

```<code>public sealed class XYZProxyHandler:DelegatingHandler
{
    private string _var1;
    private string _var2;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = request.Headers.GetCookies().FirstOrDefault().Cookies.FirstOrDefault(x => x.Name.ToLower() == "access_token").Value;
        _var1 = GetVar1(token);
        _var2 = GetVar2(token);
</code>```

Tried to make it as simple of code while including an important piece of code.
In the above sample code, ideally _var1 and _var2 should get the values of its own request but for whatever reason, they sometimes get other request's values.
I have instances of _var1 getting the value of another request but _var2 gets the value of its own request and vice-versa.

I have run into this type of behaviour before when a static variable is shared across requests but these are not static variables and hence I am not sure how it can happen or if it is something to do with DelegatingHandler implementation.

I have tried to test it but did not reproduce it and am working on the same with more variations of test data and this happens 50 times in a month maybe so not very often.

I am not sure if I am being tunnel visioned and not seeing something obvious or glaring.

答:
The instance of DelegatingHandler-class is simultaneously consumed by all requests that the app receives so this behavior is predictable.

I would get rid of any local variables and pass the required values directly:

```<code>public sealed class XYZProxyHandler : DelegatingHandler
{
   // If needed some thread-safe service, repo, etc can be passed in the constructor.
    /*
    private readonly ISmth _smth;

    public XYZProxyHandler(ISmth smth)
    {
        _smth = smth;
    }
    */

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = request.Headers.GetCookies().FirstOrDefault().Cookies.FirstOrDefault(x => x.Name.ToLower() == "access_token").Value;
        var _var1 = GetVar1(token);
        var _var2 = GetVar2(token);

        SomeMethod(_var1, _var2);

        // ..
    }

    private void SomeMethod(string one, string two) {

    }
}
</code>```

Body:
We have a DelegatingHandler implemented that has some private variables and 2 of them are getting values from different parallel requests than their own even though they are not static variables

public sealed class XYZProxyHandler:DelegatingHandler
{
    private string _var1;
    private string _var2;

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = request.Headers.GetCookies().FirstOrDefault().Cookies.FirstOrDefault(x => x.Name.ToLower() == "access_token").Value;
        _var1 = GetVar1(token);
        _var2 = GetVar2(token);

Tried to make it as simple of code while including an important piece of code.
In the above sample code, ideally _var1 and _var2 should get the values of its own request but for whatever reason, they sometimes get other request's values.
I have instances of _var1 getting the value of another request but _var2 gets the value of its own request and vice-versa.

I have run into this type of behaviour before when a static variable is shared across requests but these are not static variables and hence I am not sure how it can happen or if it is something to do with DelegatingHandler implementation.

I have tried to test it but did not reproduce it and am working on the same with more variations of test data and this happens 50 times in a month maybe so not very often.

I am not sure if I am being tunnel visioned and not seeing something obvious or glaring.

Body:
The instance of DelegatingHandler-class is simultaneously consumed by all requests that the app receives so this behavior is predictable.

I would get rid of any local variables and pass the required values directly:

public sealed class XYZProxyHandler : DelegatingHandler
{
   // If needed some thread-safe service, repo, etc can be passed in the constructor.
    /*
    private readonly ISmth _smth;

    public XYZProxyHandler(ISmth smth)
    {
        _smth = smth;
    }
    */

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = request.Headers.GetCookies().FirstOrDefault().Cookies.FirstOrDefault(x => x.Name.ToLower() == "access_token").Value;
        var _var1 = GetVar1(token);
        var _var2 = GetVar2(token);

        SomeMethod(_var1, _var2);

        // ..
    }

    private void SomeMethod(string one, string two) {

    }
}


问:
finding out what is causing dreaded "The website encountered an unexpected error. Please try again later." message

while doing a drupal 6 to 7 upgrade I am getting the not so helpful message
"The website encountered an unexpected error. Please try again later." everytime I go to certain pages.
ex) /admin/config

What is the best way to find out what is causing the fatal error so that I can fix it?

All I can think of right now is to start disabling contributed modules until that page works or looking through the logs.

Thanks.

答:
In Drupal 8.7 you can do this in core/lib/Drupal/Core/EventSubscriber/FinalExceptionSubscriber.php line 126:</p>

```<code>$content = $this->t('The website encountered an  error. Please try again later.' . var_dump($error));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Drupal 8.7 you can do this in core/lib/Drupal/Core/EventSubscriber/FinalExceptionSubscriber.php line 126:

$content = $this->t('The website encountered an  error. Please try again later.' . var_dump($error));


问:
How do I save a value from an html input field into a database?
I know this seems like a very simple problem, but it's been really bothering me for a while. So pretty much, I have an input thing in html, then when the user clicks a button it's supposed to store the information they typed in the box into the database.

I already know the part that sends the info to the database works because I've tried it. But it's not echoing "works!" so its not recognizing any input in the input box.

```<code>$submit = @$_POST['test'];

$col= "";

$get_info = mysqli_query($connection, "SELECT col FROM users WHERE
username = '$username'");
$get_row = mysqli_fetch_assoc($get_info);
$db_col = $get_row['col'];

$col =  @$_POST['coly'];

if($submit){

    if($col){

        echo"works!";
        $update_col = mysqli_query($connection, "UPDATE users SET col
              =
            '$col' WHERE username = '$username'");
    }
}

<div class = "profileLeftSideContent">

    <form action = "edit.php" method="post">

        <input type="text" name="coly" size="25"
                 placeholder="School"
             /> <br /><br />

    </form>
</div>

<form class="budon" method="POST">

<input  type="submit" name="test" id="test" value="Save"/><br/>

</form>
</code>```

It should be sending the typed information to the database, but instead, it doesn't even echo "worked!" so it thinks that $col has nothing typed in it. It is giving me no errors and the button works fine. Thank you for any input you might have.

答:
It's not because $col has nothing, it's because $submit is empty since the form has no field named 'test' so $_POST['test'] returns nothing.

```<code>$submit = $_POST['test'];

$col= "";

$get_info = mysqli_query($connection, "SELECT col FROM users WHERE username = '$username'");
$get_row = mysqli_fetch_assoc($get_info);
$db_col = $get_row['col'];

$col =  $_POST['coly'];

if($submit){

    if($col){

        echo"works!";
        $update_col = mysqli_query($connection, "UPDATE users SET col = '$col' WHERE username = '$username'");
    }

}

<div class = "profileLeftSideContent">

    <form action = "edit.php" method="post">

        <input type="text" name="coly" size="25" placeholder="School"/>
        <br /><br />
        <input type="submit" name="test" value="Submit"/>

    </form>

</div>
</code>```

Body:
I know this seems like a very simple problem, but it's been really bothering me for a while. So pretty much, I have an input thing in html, then when the user clicks a button it's supposed to store the information they typed in the box into the database.

I already know the part that sends the info to the database works because I've tried it. But it's not echoing "works!" so its not recognizing any input in the input box.

$submit = @$_POST['test'];

$col= "";

$get_info = mysqli_query($connection, "SELECT col FROM users WHERE
username = '$username'");
$get_row = mysqli_fetch_assoc($get_info);
$db_col = $get_row['col'];

$col =  @$_POST['coly'];

if($submit){

    if($col){

        echo"works!";
        $update_col = mysqli_query($connection, "UPDATE users SET col
              =
            '$col' WHERE username = '$username'");
    }
}

    <form action = "edit.php" method="post">

        <input type="text" name="coly" size="25"
                 placeholder="School"
             />

    </form>

<form class="budon" method="POST">

<input  type="submit" name="test" id="test" value="Save"/>

</form>

It should be sending the typed information to the database, but instead, it doesn't even echo "worked!" so it thinks that $col has nothing typed in it. It is giving me no errors and the button works fine. Thank you for any input you might have.

Body:
It's not because $col has nothing, it's because $submit is empty since the form has no field named 'test' so $_POST['test'] returns nothing.

$submit = $_POST['test'];

$col= "";

$get_info = mysqli_query($connection, "SELECT col FROM users WHERE username = '$username'");
$get_row = mysqli_fetch_assoc($get_info);
$db_col = $get_row['col'];

$col =  $_POST['coly'];

if($submit){

    if($col){

        echo"works!";
        $update_col = mysqli_query($connection, "UPDATE users SET col = '$col' WHERE username = '$username'");
    }

}

<div class = "profileLeftSideContent">

    <form action = "edit.php" method="post">

        <input type="text" name="coly" size="25" placeholder="School"/>
        <br /><br />
        <input type="submit" name="test" value="Submit"/>

    </form>

</div>


问:
Using vue.js with semantic UI
I'm trying to use webpack + Semantic UI with Vue.js and I found this library https://vueui.github.io/

But there was problem compling:

```<code>ERROR in ./~/vue-ui/components/sidebar/sidebar.jade
Module parse failed: /Project/node_modules/vue-
ui/components/sidebar/sidebar.jade Unexpected token (1:24)
You may need an appropriate loader to handle this file type.
</code>```

So I installed jade(pug) but still no luck.

And there's comment in github for that lib:

WIP, do not use ( https://github.com/vueui/vue-ui )

I've managed to import semantic css in my templates like this:

```<code>@import './assets/libs/semantic/dist/semantic.min.css';
</code>```

But problem here is that I can't use semantic.js functions like dimmer and other stuff.

The thing is that I already have some old codebase written with semantic and it would be good not to use any other css framework (bootstrap or materialize).

Is there any elegant way to include semantic UI in my vue.js project?

答: If it happens everything else is working but your buttons make sure to add this .ui form to your form.

ContentLicense: CC BY-SA 3.0

Title: Using vue.js with semantic UI

Body:
I'm trying to use webpack + Semantic UI with Vue.js and I found this library https://vueui.github.io/

But there was problem compling:

ERROR in ./~/vue-ui/components/sidebar/sidebar.jade
Module parse failed: /Project/node_modules/vue-
ui/components/sidebar/sidebar.jade Unexpected token (1:24)
You may need an appropriate loader to handle this file type.

So I installed jade(pug) but still no luck.

And there's comment in github for that lib:

WIP, do not use ( https://github.com/vueui/vue-ui )

I've managed to import semantic css in my templates like this:

@import './assets/libs/semantic/dist/semantic.min.css';

But problem here is that I can't use semantic.js functions like dimmer and other stuff.

The thing is that I already have some old codebase written with semantic and it would be good not to use any other css framework (bootstrap or materialize).

Is there any elegant way to include semantic UI in my vue.js project?


问:
Does getting a synchronized collection from collections class synchronize a class?
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

```<code>HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);
</code>```

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.

答:
So did the above code just synchronized whole syncHashMap class or every method inside it?

Not sure what do you mean by synchronized whole syncHashMap class and every method inside it.

If you look into the source code of method Collections.synchronizedMap(hashMap), you will find it uses synchronized keyword to decorate every method of the original map. Which means for the decorated map object, you can only call one of its methods at one time. But the different maps, you can call them at one time.

You can find the usage of them in here. ConcurrentHashMap vs Synchronized HashMap

Body:
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.


问:
Missing operator in expression when compiling assembly file with masm
MASM is saying "missing operator in expression" but I see no problem with the assembly.

I'm trying to manually call windows syscalls in x86 asm, I've grabbed the syscall offset from fs for NtFlushInstructionCache from https://j00ru.vexillium.org/syscalls/nt/64/

C declaration:
extern "C" NTSTATUS NewNtFlushInstructionCache(HANDLE ProcessHandle, PVOID BaseAddress, ULONG NumberOfBytesToFlush);

Here's my asm:

```<code>.model flat
.486
.code

NewNtFlushInstructionCache PROC
    mov eax, 39h
    xor ecx, ecx
    lea edx, [esp + 4]
    call large DWORD PTR fs:[0C0h]
    add esp, 4
    ret 14h
NewNtFlushInstructionCache ENDP

END
</code>```

The error is "missing operator in expression" on this line: call large DWORD PTR fs:[0C0h]
Any help? Can fs not be accessed directly from assembly?

答:
The LARGE modifier for the memory operand is an artifact of the IDA/IDA Pro disassembler and not understood by MASM. In MASM it is simply done without specifying LARGE:

```<code>call DWORD PTR fs:[0C0h]
</code>```

LARGE is a memory model, and not a modifier for memory operands.

By default FS and GS are set to ASSUME FS:error so when those segment registers are used they will produce an Error A2183. ASSUME FS:nothing overrides the behaviour and allows you to use FS freely. Place ASSUME FS:nothing at some point before using FS like this:

```<code>ASSUME FS:nothing
call DWORD PTR fs:[0C0h]
</code>```

Body:
MASM is saying "missing operator in expression" but I see no problem with the assembly.

I'm trying to manually call windows syscalls in x86 asm, I've grabbed the syscall offset from fs for NtFlushInstructionCache from https://j00ru.vexillium.org/syscalls/nt/64/

C declaration:
extern "C" NTSTATUS NewNtFlushInstructionCache(HANDLE ProcessHandle, PVOID BaseAddress, ULONG NumberOfBytesToFlush);

Here's my asm:

.model flat
.486
.code

NewNtFlushInstructionCache PROC
    mov eax, 39h
    xor ecx, ecx
    lea edx, [esp + 4]
    call large DWORD PTR fs:[0C0h]
    add esp, 4
    ret 14h
NewNtFlushInstructionCache ENDP

END

The error is "missing operator in expression" on this line: call large DWORD PTR fs:[0C0h]
Any help? Can fs not be accessed directly from assembly?

Body:
The LARGE modifier for the memory operand is an artifact of the IDA/IDA Pro disassembler and not understood by MASM. In MASM it is simply done without specifying LARGE:

call DWORD PTR fs:[0C0h]

LARGE is a memory model, and not a modifier for memory operands.

By default FS and GS are set to ASSUME FS:error so when those segment registers are used they will produce an Error A2183. ASSUME FS:nothing overrides the behaviour and allows you to use FS freely. Place ASSUME FS:nothing at some point before using FS like this:

ASSUME FS:nothing
call DWORD PTR fs:[0C0h]


问:
Singletons in multi threaded environment
when using singletons, if the class has instance fields should you be careful when several threads might be using the singleton? (And the fields are mutable and their values can be changed)

I havn't tried but in theory it seems like the answer is yes and you would need synchronization (or skip the singleton)

答:
Yes you need to synchronize access to all fields of the singleton, otherwise you will wreak havoc with state of your object.

On the other hand, if you can avoid the singleton in a multi-threaded environment, you'll be better off.  Why don't you just pass around your object, instead of using the same instance.

You will still have to synch access if it is shared, even if you pass it around.

I'm just not really pro singleton, as they tend to lead for a need for more singletons which is inevitably what you should avoid.


问:
ASP.NET Core 2.2 Prevent Direct URL Access to Document/File
I have bunch of files stored in a directory. Those files have links stored in the database like

https://localhost:44325/Repositories/Aopdio/2019/05/QWNjb3VX0FNT1NUSElSRF9LTA==.pdf

When I log in to my application, I am able to access the files via the application. However, when I copy this link and paste it in another browser, the file still opens.

Is there a way to prevent this from happening? I'd like the content to only be served from the application.

This is my startup.cs

```<code>app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(RepositoryManager.GetBasePath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))),
    RequestPath = RepositoryManager.GetRequestPath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))
});
app.UseStaticFiles(
    new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources")),
        RequestPath = "/Resources"
    }
);
</code>```

This is the middleware that I have tried to implement:

In Startup.cs

```<code>app.UseRequestMiddleware();
</code>```

The Middleware

```<code>public class RequestMiddleware
{
    private readonly RequestDelegate next;

    public RequestMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context, Func<Task> next)
    {
        var test = context;
    }
}
</code>```

The extension that calls the middleware and is called in Startup.cs

```<code>public static class RequestMiddlewareExtension
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }
}
</code>```

However, I get this error:

```<code>InvalidOperationException: Unable to resolve service for type 'System.Func`1[System.Threading.Tasks.Task]' while attempting to Invoke middleware 'App.ClassLibrary.Middleware.RequestMiddleware'.
</code>```

答:
In the default configuration of app.UseStaticFiles(), only files under wwwroot are served. If the files outside that directory is served directly, then either you have enabled static files for the whole app from your root folder or you have enabled directory browsing on the IIS. You can check and disable them.

[Update]
When you serve the files using UseStaticFiles(), the request doesn't method does not comes through the normal middleware pipeline. So you can't have the regular middleware features like Authenticate/Authorize. Either you can have a Repositories Controller that returns FileResult or you can have a custom middleware like the one here.

Body:
I have bunch of files stored in a directory. Those files have links stored in the database like

https://localhost:44325/Repositories/Aopdio/2019/05/QWNjb3VX0FNT1NUSElSRF9LTA==.pdf

When I log in to my application, I am able to access the files via the application. However, when I copy this link and paste it in another browser, the file still opens.

Is there a way to prevent this from happening? I'd like the content to only be served from the application.

This is my startup.cs

app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(RepositoryManager.GetBasePath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))),
    RequestPath = RepositoryManager.GetRequestPath(Environment.GetEnvironmentVariable("APPONE_REPOSITORY"))
});
app.UseStaticFiles(
    new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources")),
        RequestPath = "/Resources"
    }
);

This is the middleware that I have tried to implement:

In Startup.cs

app.UseRequestMiddleware();

The Middleware

public class RequestMiddleware
{
    private readonly RequestDelegate next;

    public RequestMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context, Func<Task> next)
    {
        var test = context;
    }
}

The extension that calls the middleware and is called in Startup.cs

public static class RequestMiddlewareExtension
    {
        public static IApplicationBuilder UseRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestMiddleware>();
        }
    }
}

However, I get this error:

InvalidOperationException: Unable to resolve service for type 'System.Func`1[System.Threading.Tasks.Task]' while attempting to Invoke middleware 'App.ClassLibrary.Middleware.RequestMiddleware'.


问:
Is there a special configuration for using video (.mov, .mp4) locally and Webpack with 'file-loader'?
I am using webpack to build a basic site. Everything is working as far as images, sass, and loading of local fonts goes. I am now trying to load video from a local file however when i go to add it webpack is giving me a 404 error. Can anyone help me with my configuration since it seems I have it wrong for video. The video controls render but the video itself doesn't.

HTML code

```<code>    <video controls width="600">
      <source src="./assets/images/hero_vid_bg_1.mp4" type="video/mp4">
      Sorry, your browser doesn't support embedded videos.
    </video>
</code>```

Webpack Config file

```<code>module.exports = {
  entry: {
    main: "./src/index.js"
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: ["html-loader"]
      },
      {
        test: /\.(svg|png|jpg|gif|)$/,
        use: [{
          loader: "file-loader",
          options: {
            name: "[name].[hash].[ext]",
            outputPath: "./assets/images"
          }
        }]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        loader: "file-loader",
        options: {
          name: "[name].[hash].[ext]",
          outputPath: "./assets/fonts"
        }
      },
      {
        test: /\.(mov|mp4)$/,
        loader: "file-loader",
        options: {
          name: "[name].[hash].[ext]",
          publicPath: "./assets/images",
          outputPath: "./assets/videos"
        }
      }
    ]
  }
};

</code>```

Absolute path to video file is assets/images/hero_vid_bg.mp4

答:
The src specified in your source tag doesn’t have the hash part you configured in file-loader’s option，you should replace the path with an import statement:

import mp4 from path/to/video;

and use the variable mp4 as src in the source tag

Body:
I am using webpack to build a basic site. Everything is working as far as images, sass, and loading of local fonts goes. I am now trying to load video from a local file however when i go to add it webpack is giving me a 404 error. Can anyone help me with my configuration since it seems I have it wrong for video. The video controls render but the video itself doesn't.

HTML code

    <video controls width="600">
      <source src="./assets/images/hero_vid_bg_1.mp4" type="video/mp4">
      Sorry, your browser doesn't support embedded videos.
    </video>

Webpack Config file

module.exports = {
  entry: {
    main: "./src/index.js"
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: ["html-loader"]
      },
      {
        test: /\.(svg|png|jpg|gif|)$/,
        use: [{
          loader: "file-loader",
          options: {
            name: "[name].[hash].[ext]",
            outputPath: "./assets/images"
          }
        }]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        loader: "file-loader",
        options: {
          name: "[name].[hash].[ext]",
          outputPath: "./assets/fonts"
        }
      },
      {
        test: /\.(mov|mp4)$/,
        loader: "file-loader",
        options: {
          name: "[name].[hash].[ext]",
          publicPath: "./assets/images",
          outputPath: "./assets/videos"
        }
      }
    ]
  }
};

Absolute path to video file is assets/images/hero_vid_bg.mp4


问:
Only enable landscape in some specific ViewController
My app has many different ViewController, I want to allow some specific ViewController can rotate landscape. I have tried some way like using supportedInterfaceOrientations or shouldAutorotate, but it does not work.
Is there anyone have other ideas?</p>

答:
Update in your ViewController is not enough, you must update more in AppDelegate.

AppDelegate

```<code>var enableAllOrientation = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if enableAllOrientation {
        return .all
    }
    return .portrait
}
</code>```

Any ViewController that you want support landscape, just implement:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.enableAllOrientation = true
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.enableAllOrientation = false
}
</code>```

Body:
Update in your ViewController is not enough, you must update more in AppDelegate.

AppDelegate

var enableAllOrientation = false
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    if enableAllOrientation {
        return .all
    }
    return .portrait
}

Any ViewController that you want support landscape, just implement:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.enableAllOrientation = true
}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    let appDelegate = UIApplication.shared.delegate as? AppDelegate
    appDelegate?.enableAllOrientation = false
}


问:
How to Deny Access to specific folder in ASP.Net MVC 5
I have one "Upload" folder in my project directory where I upload files & images. To get access to these files only by authorized access, I created a authorize Downloads Controller & provides files by that way. But if someone tried http://domain_name/Upload/filename.ext then that file accessible in browser. I want to restrict this Upload folder access to anonymous users. For this I tried:
http://prideparrot.com/blog/archive/2012/6/authorizing_folders_using_routeexistingfiles
https://stackoverflow.com/a/18218084/5756211
But nothing works for me.
Thanks for the help in Advance.</p>

答:
Use below code if someone could not able to find a solution for this issue.</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
         <security>
             <authorization><add accessType="Deny" users="?"/></authorization>
         </security>
    </system.webServer>
</configuration>'
</code>```

Body:
Use below code if someone could not able to find a solution for this issue.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
         <security>
             <authorization><add accessType="Deny" users="?"/></authorization>
         </security>
    </system.webServer>
</configuration>'


问:
Are there any better ways to check this condition in Java 8?
I need to simplify following code in java.  Are there any way to using set and do this ?</p>

```<code>      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))
</code>```

答:
Provided the get methods have no side effects and return always the same value (within the scope of your sample),
you can use refactoring
Extract variable

s =dispensingOccasionModel.getOccasionDTO().getAdminState());

Also, you can statically import AdministrativeState.*.

You then get:

```<code> AdministrativeState s =dispensingOccasionModel.getOccasionDTO().getAdminState();

 if (!(((PLANNED == s) || (MISSED == s ) || (SKIPPED == s) ||
(SELF_ADMINISTERED == s) ||
(SELF_ADMINISTERED_BY_RANGE == s))
 && isSpecialDoseType(doseDetail))
</code>```

Then taking into account that the double pipe (Boolean OR) operator has quite a lot priority you can remove the parentheses around single comparisons:

```<code> (a==b)||(c==d) ===> a==b||c==d.
</code>```

You get:

```<code>if (!((PLANNED == s ||
MISSED == s  ||
SKIPPED == s ||
SELF_ADMINISTERED == s ||
SELF_ADMINISTERED_BY_RANGE == s))
&& isSpecialDoseType(doseDetail))
</code>```

There are double parentheses after ! And before &&. They can be reduced to a single one.

```<code>  if (!(PLANNED == s ||
 MISSED == s
 || SKIPPED == s ||
 SELF_ADMINISTERED == s ||
 SELF_ADMINISTERED_BY_RANGE == s)
  && isSpecialDoseType(doseDetail))
</code>```

Now you can use the rule of inverting logical expressions:

```<code>  !(a==b|| c==d) ===> a!=b&&c!=d,
</code>```

Which basically inverts all the operations due to the NOT (!) Operator. Since you will have only && operators left to combine Boolean sub expressions, then you can drop the parentheses.

```<code>if (PLANNED != s
&& MISSED != s
&& SKIPPED != s
&& SELF_ADMINISTERED != s
&& SELF_ADMINISTERED_BY_RANGE != s
&& isSpecialDoseType(doseDetail)
)
</code>```

Now if you have good domain knowledge you could know if you can combine self
Administered into one variable and shipped/missed into another to have something like: neither ( planned nor stoppedOrMissed nor selfAdministered)&& isSpecial. But without such knowledge I would live the expression at this level.

Body:
I need to simplify following code in java.  Are there any way to using set and do this ?

      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))

Body:
Provided the get methods have no side effects and return always the same value (within the scope of your sample),
you can use refactoring
Extract variable

s =dispensingOccasionModel.getOccasionDTO().getAdminState());

Also, you can statically import AdministrativeState.*.

You then get:

 AdministrativeState s =dispensingOccasionModel.getOccasionDTO().getAdminState();

 if (!(((PLANNED == s) || (MISSED == s ) || (SKIPPED == s) ||
(SELF_ADMINISTERED == s) ||
(SELF_ADMINISTERED_BY_RANGE == s))
 && isSpecialDoseType(doseDetail))

Then taking into account that the double pipe (Boolean OR) operator has quite a lot priority you can remove the parentheses around single comparisons:

 (a==b)||(c==d) ===> a==b||c==d.

You get:

if (!((PLANNED == s ||
MISSED == s  ||
SKIPPED == s ||
SELF_ADMINISTERED == s ||
SELF_ADMINISTERED_BY_RANGE == s))
&& isSpecialDoseType(doseDetail))

There are double parentheses after ! And before &&. They can be reduced to a single one.

  if (!(PLANNED == s ||
 MISSED == s
 || SKIPPED == s ||
 SELF_ADMINISTERED == s ||
 SELF_ADMINISTERED_BY_RANGE == s)
  && isSpecialDoseType(doseDetail))

Now you can use the rule of inverting logical expressions:

  !(a==b|| c==d) ===> a!=b&&c!=d,

Which basically inverts all the operations due to the NOT (!) Operator. Since you will have only && operators left to combine Boolean sub expressions, then you can drop the parentheses.

if (PLANNED != s
&& MISSED != s
&& SKIPPED != s
&& SELF_ADMINISTERED != s
&& SELF_ADMINISTERED_BY_RANGE != s
&& isSpecialDoseType(doseDetail)
)

Now if you have good domain knowledge you could know if you can combine self
Administered into one variable and shipped/missed into another to have something like: neither ( planned nor stoppedOrMissed nor selfAdministered)&& isSpecial. But without such knowledge I would live the expression at this level.


问:
Copy files from windows server from Linux server using python script
1) Can anyone please suggest me a way to copy files from windows server to linux server?

2) Initially I couldn't connect my windows server in linux server by using below command.

In Linux terminal,
ssh

I'm getting connection refused error.

Kindly anyone suggest me solution for above 2 questions.

答:
Normally windows does not run an ssh daemon (server). Therefore you normally cannot connect from linux to windows unless you set one up on windows.

The reverse is different. Linux normally runs an ssh daemon, so you can connect to it from windows provided you install a suitable client (e.g. putty).

However, in both cases, port 22 (the ssh port) will likely be blocked for incoming connections. You will need to open this port on the "server side". For details as to how this, you would need to search for your particular operating system. B.T.W. You will alost certainly need administrator priviliges to open network ports. For example, if you use putty (or similar) on windows, you will need to ensure that port 22 is open on the Linux system.

Once you have openned port 22, you can use scp (or pscp if you download putty tools to windows) to copy files over the network. Another popular tool is WinSCP which allows you to copy files from windows to linux using a file explorer type of interface (e.g. you can drag and drop them).

Having said all of that, it might be easier to just copy everything to a USB drive, then plug the USB drive into the other system and copy the files off of it. This of course assumes you have physical access to both systems.


问:
Get YAML for deployed Kubernetes services?
I am trying to deploy my app to Kubernetes running in Google Container
Engine.

The app can be found at: https://github.com/Industrial/docker-znc.

The Dockerfile is built into an image on Google Container Registry.

I have deployed the app in Kubernetes via the + button. I don't have the YAML
for this.

I have inserted a Secret in Kubernetes for the PEM file required by the app.

How do I get the YAML for the Deployment, Service and Pod created by
 Kubernetes by filling in the form?

How do I get the Secret into my Pod for usage?

答:
Like mentioned above "--export" is one option to get the manifest corresponding to the kubeernetes objects

But "--export" is considered to be buggy and there is a proposal to deprecate it

Currently the better option is to do "-o yaml" or "-o json" and remove the unnecessary fields

The main difference is "--export" is expected to remove the cluster specific settings (e.g. cluster service IP of a k8s service). But it is found to be inconsistent in this regard


问:
Should data be formatted in the backend or front-end?
I have a web application, and I'm wondering if its better to format the data in the front-end or the backend? They both get the job done, but can someone help me brainstorm which is the better option between the two.

As an example, say I have a backend that returns the a family tree of names in a certain format, but in the front-end I need to adjust the format to match the format a widget expects, should this adjustment be done in the backend or the front-end?

If its done in the backend, I can straighforwardly push the data into the widget in the front-end else, I would have to parse in the front-end beforehand. Can anyone think of pros/cons for this situation? Thanks.

答:
Another aspect to be considered is locale-awareness (thousands separator, comma separator, date format, etc).

If the consuming application is meant to be accessed from clients that are locale-aware (e.g. web browsers), I prefer to push the formatting to the front-end as much as possible. Technically it is possible to send the locale as parameter to the backend API, but modern front-end libraries are typically quite good in handling locale by default that it makes it far easier to do it in the front-end.

Exception to this is when you know for sure that your audience is limited to only one locale.


问:
Can we have two canvases in an activity ? (OR) Having a canvas outside the onDraw() is not working
```<code>@Override
        protected void onDraw(Canvas canvas) {
        // Draw graphic objects
         .....
             }

         public void displayCalc(){

           //Do some calculation & display results near these graphic objects
            String result = String.valueOf(value);

             //Do some calculation

              //Display Calculated values
             Canvas c =new Canvas();
             Paint paint = new Paint();
             paint.setStyle(Paint.Style.FILL);
             paint.setAntiAlias(true);
             paint.setColor(Color.WHITE);
             c.drawText(result,200,300,paint);
                     }
</code>```

But if i have the same thing in the function onDraw it works fine. I would like to know why or what changes i have to make to get it working

```<code>   @Override
    protected void onDraw(Canvas canvas) {

    // Draw graphic objects
    //Do some calculation & display results near these graphic objects
     .....
     String result = String.valueOf(value);

        //Display Calculated values
         Paint paint = new Paint();
         paint.setStyle(Paint.Style.FILL);
         paint.setAntiAlias(true);
         paint.setColor(Color.WHITE);
         canvas.drawText(result,200,300,paint);
}
</code>```

答:
If you're trying to implement some kind of double buffering, you might want to take a look at this

I think your problem is that you need to create a bitmap, then attach the canvas to it, something like:

```<code>Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas c = new Canvas(bitmap);

// then draw to the canvas..
// and when you're happy, draw the bitmap onto the canvas supplied to onDraw.
</code>```

Just creating a canvas, doesn't make it appear on the screen.

You may also want to take a look at: this tutorial

If you have a surfaceView, then you can do something like this (don't have a compiler, but hopefully you get the gist):

```<code>SurfaceView view = (SurfaceView)findViewById(R.id.view);

SurfaceHolder holder = view.getHolder(); // save this where it can be accessed by your function

Canvas c
try  {
    c = holder.lockCanvas();
    // draw stuff
}
finally {
    if(null != c) {
        holder.unlockCanvasAndPost(c);
    }
}
</code>```

Body:
@Override
        protected void onDraw(Canvas canvas) {
        // Draw graphic objects
         .....
             }

         public void displayCalc(){

           //Do some calculation & display results near these graphic objects
            String result = String.valueOf(value);

             //Do some calculation

              //Display Calculated values
             Canvas c =new Canvas();
             Paint paint = new Paint();
             paint.setStyle(Paint.Style.FILL);
             paint.setAntiAlias(true);
             paint.setColor(Color.WHITE);
             c.drawText(result,200,300,paint);
                     }

But if i have the same thing in the function onDraw it works fine. I would like to know why or what changes i have to make to get it working

   @Override
    protected void onDraw(Canvas canvas) {

    // Draw graphic objects
    //Do some calculation & display results near these graphic objects
     .....
     String result = String.valueOf(value);

        //Display Calculated values
         Paint paint = new Paint();
         paint.setStyle(Paint.Style.FILL);
         paint.setAntiAlias(true);
         paint.setColor(Color.WHITE);
         canvas.drawText(result,200,300,paint);
}

Body:
If you're trying to implement some kind of double buffering, you might want to take a look at this

I think your problem is that you need to create a bitmap, then attach the canvas to it, something like:

Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas c = new Canvas(bitmap);

// then draw to the canvas..
// and when you're happy, draw the bitmap onto the canvas supplied to onDraw.

Just creating a canvas, doesn't make it appear on the screen.

You may also want to take a look at: this tutorial

If you have a surfaceView, then you can do something like this (don't have a compiler, but hopefully you get the gist):

SurfaceView view = (SurfaceView)findViewById(R.id.view);

SurfaceHolder holder = view.getHolder(); // save this where it can be accessed by your function

Canvas c
try  {
    c = holder.lockCanvas();
    // draw stuff
}
finally {
    if(null != c) {
        holder.unlockCanvasAndPost(c);
    }
}


问:
How to fix hot-reload problem on a Flask application inside Docker?
I want my flask application to run with hot reload inside docker container but if I change my app.py flask application to app.run(debug=True,host='0.0.0.0') instead of False, it raises the error:

FileNotFoundError: [Errno 2] No such file or directory: '/app/app.py': '/app/app.py'

If I change back to False:

app.run(debug=False,host='0.0.0.0')

it will run, but without hot reload.

My Dockerfile is:

```<code>    FROM ubuntu:latest
    RUN apt-get update -y
    RUN apt-get install -y python3-pip python3-dev build-essential locales
    RUN locale-gen en_US.UTF-8
    ENV LANG en_US.UTF-8
    ENV LANGUAGE pt_BR:pt:en
    ENV LC_ALL en_US.UTF-8
    ENV FLASK_ENV="development"
    WORKDIR /app
    COPY . /app
    VOLUME ["/app"]
    RUN pip3 install -r requirements.txt
    ENTRYPOINT ["python3"]
    CMD ["app.py"]
</code>```

and I run it using the command:

docker run -p 5000:5000 -v /Users/rodrigodmpa/Documents/IA/web:/app flask-app

答:
I see a few things wrong with the Dockerfile. I think your immediate problem is the VOLUME ["/app"] line. You have copied the code statically into your image, and declared that containers running that image are exporting a volume at the /app location, then are launching the container with a bind-mount volume to the same location. There's likely some permissions issues where this ends up making the container no longer see the contents of /app. You don't need the VOLUME declaration, so ditch it.

Also: always put apt-get update and apt-get install in the same RUN declaration. If you don't, and then edit the packages installed, then by default Docker will cache layers from the previous command. That means you could be installing a package based on package definitions from a long time ago. It should look like RUN apt-get update -y && apt-get install -y python3-pip python3-dev build-essential locales

Body:
I want my flask application to run with hot reload inside docker container but if I change my app.py flask application to app.run(debug=True,host='0.0.0.0') instead of False, it raises the error:

FileNotFoundError: [Errno 2] No such file or directory: '/app/app.py': '/app/app.py'

If I change back to False:

app.run(debug=False,host='0.0.0.0')

it will run, but without hot reload.

My Dockerfile is:

    FROM ubuntu:latest
    RUN apt-get update -y
    RUN apt-get install -y python3-pip python3-dev build-essential locales
    RUN locale-gen en_US.UTF-8
    ENV LANG en_US.UTF-8
    ENV LANGUAGE pt_BR:pt:en
    ENV LC_ALL en_US.UTF-8
    ENV FLASK_ENV="development"
    WORKDIR /app
    COPY . /app
    VOLUME ["/app"]
    RUN pip3 install -r requirements.txt
    ENTRYPOINT ["python3"]
    CMD ["app.py"]

and I run it using the command:

docker run -p 5000:5000 -v /Users/rodrigodmpa/Documents/IA/web:/app flask-app


问:
How to speed up grep/awk command?
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

```<code># method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy
</code>```

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34
</code>```

Expected output file:

```<code>a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22
</code>```

答:
Use mawk, <s>avoid regex and do:

```<code>$ mawk -F, '$2!=""' file
a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
10,0,34,45
24,4a83944,3,22
</code>```

Let us know how long that took.</s>

I did some tests with 10M records of your data, based on the results: use mawk and regex:

GNU awk and regex:

```<code>$ time gawk -F, '$2~/a/' file > /dev/null

real    0m7.494s
user    0m7.440s
sys     0m0.052s
</code>```

GNU awk and no regex:

```<code>$ time gawk -F, '$2!=""' file >/dev/null

real    0m9.330s
user    0m9.276s
sys     0m0.052s
</code>```

mawk and no regex:

```<code>$ time mawk -F, '$2!=""' file >/dev/null

real    0m4.961s
user    0m4.904s
sys     0m0.060s
</code>```

mawk and regex:

```<code>$ time mawk -F, '$2~/a/' file > /dev/null

real    0m3.672s
user    0m3.600s
sys     0m0.068s
</code>```

Title: How to speed up grep/awk command?

Body:
I am going to process the text file (>300 GB) and split it into small text files (~1 GB). I want to speed up grep/awk commands.

I need to grep the line which has values on column b, here are my ways:

# method 1:
awk -F',' '$2 ~ /a/ { print }' input

# method 2:
grep -e ".a" < inpuy

Both of ways cost 1min for each file. So how can I speed up this operation?

Sample of input file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
9,,3,12
10,0,34,45
24,4a83944,3,22
45,,435,34

Expected output file:

a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
24,4a83944,3,22

Body:
Use mawk, <s>avoid regex and do:

$ mawk -F, '$2!=""' file
a,b,c,d
1,4a337485,2,54
4,2a4645647,4,56
6,5a3489556,3,22
10,0,34,45
24,4a83944,3,22

Let us know how long that took.</s>

I did some tests with 10M records of your data, based on the results: use mawk and regex:

GNU awk and regex:

$ time gawk -F, '$2~/a/' file > /dev/null

real    0m7.494s
user    0m7.440s
sys     0m0.052s

GNU awk and no regex:

$ time gawk -F, '$2!=""' file >/dev/null

real    0m9.330s
user    0m9.276s
sys     0m0.052s

mawk and no regex:

$ time mawk -F, '$2!=""' file >/dev/null

real    0m4.961s
user    0m4.904s
sys     0m0.060s

mawk and regex:

$ time mawk -F, '$2~/a/' file > /dev/null

real    0m3.672s
user    0m3.600s
sys     0m0.068s


问:
Trying to overwrite / append editor-style.css from parent theme in child theme
I am using the good old twenty eleven for a simple job and overwrite styles using a child.

The Problem is, that editor styles are not overwritten when i add an editor-child.css in the child theme folder.
Adding add_editor_style in the child themes functions.php (wrapped in after_setup_theme) doesn't seem to work. Can't I load multiple editor styles or what is the problem here? I can't figure out how I can overwrite this ugly twenty eleven editor css in gutenberg. It might even be better to disable it, but even that doesn't work using remove_editor_style. And I can't find anything on the subject using google or stackoverflow.

```<code><?php
// In the child theme functions.php. I simply want to use the style.css by the child theme as an extra editor style
function wysiwyg_styles() {
    add_editor_style( get_stylesheet_uri() );
}
add_action( 'after_setup_theme', 'wysiwyg_styles');
?>
</code>```

No css is loaded in the admin (after deleting chache AND cookies)

答:
What happen is that you're using the wrong action hook... you should be using the admin_enqueue_scripts hook.

Try doing it like this.. and check if it works for you:

```<code>add_action('admin_enqueue_scripts', function () {
  wp_enqueue_style('admin-styles', get_stylesheet_directory_uri().'/pathToYour.css');
});

// If the above does not work change get_stylesheet_directory_uri() for get_template_directory_uri()
</code>```

Hope this can help, good luck.

Body:
I am using the good old twenty eleven for a simple job and overwrite styles using a child.

The Problem is, that editor styles are not overwritten when i add an editor-child.css in the child theme folder.
Adding add_editor_style in the child themes functions.php (wrapped in after_setup_theme) doesn't seem to work. Can't I load multiple editor styles or what is the problem here? I can't figure out how I can overwrite this ugly twenty eleven editor css in gutenberg. It might even be better to disable it, but even that doesn't work using remove_editor_style. And I can't find anything on the subject using google or stackoverflow.

<?php
// In the child theme functions.php. I simply want to use the style.css by the child theme as an extra editor style
function wysiwyg_styles() {
    add_editor_style( get_stylesheet_uri() );
}
add_action( 'after_setup_theme', 'wysiwyg_styles');
?>

No css is loaded in the admin (after deleting chache AND cookies)

Body:
What happen is that you're using the wrong action hook... you should be using the admin_enqueue_scripts hook.

Try doing it like this.. and check if it works for you:

add_action('admin_enqueue_scripts', function () {
  wp_enqueue_style('admin-styles', get_stylesheet_directory_uri().'/pathToYour.css');
});

// If the above does not work change get_stylesheet_directory_uri() for get_template_directory_uri()

Hope this can help, good luck.


问:
Drop unordered duplicates across separate columns
I am trying to return a df where duplicate values have been removed. I have tried to use drop.duplicates() but the values in the columns which have been subset aren't ordered. As in, the values are duplicates but they aren't in the same order.

For instance, using the df below, if I try to remove duplicate values from Item_X and Item_Y it will return the same df. Where the intended output will remove the second row.

```<code>import pandas as pd

d = ({
    'Item_X' : ['Foo','Bar','Bot','Bot','Bar','Foo'],
    'Item_Y' : ['Bar','Foo','Foo','Bot','Bar','Foo'],
    'Value' : [1,2,3,4,5,6],
     })

df = pd.DataFrame(data = d)

df.drop_duplicates(subset=['Item_X','Item_Y'])
</code>```

Expected Result:

```<code>  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6
</code>```

Actual Output (Incorrect):

```<code>  Item_X Item_Y  Value
0    Foo    Bar      1
1    Bar    Foo      2
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6
</code>```

What would be the most efficient way to tackle this problem?

答:
You'll need to sort the columns along the horizontal axis, then get a mask to subset the original frame. Here's how you can use np.sort and df.duplicated to do that:

```<code>df[~pd.DataFrame(np.sort(df2[['Item_X', 'Item_Y']], axis=1)).duplicated()]

  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6
</code>```

Body:
I am trying to return a df where duplicate values have been removed. I have tried to use drop.duplicates() but the values in the columns which have been subset aren't ordered. As in, the values are duplicates but they aren't in the same order.

For instance, using the df below, if I try to remove duplicate values from Item_X and Item_Y it will return the same df. Where the intended output will remove the second row.

import pandas as pd

d = ({
    'Item_X' : ['Foo','Bar','Bot','Bot','Bar','Foo'],
    'Item_Y' : ['Bar','Foo','Foo','Bot','Bar','Foo'],
    'Value' : [1,2,3,4,5,6],
     })

df = pd.DataFrame(data = d)

df.drop_duplicates(subset=['Item_X','Item_Y'])

Expected Result:

  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6

Actual Output (Incorrect):

  Item_X Item_Y  Value
0    Foo    Bar      1
1    Bar    Foo      2
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6

What would be the most efficient way to tackle this problem?

Body:
You'll need to sort the columns along the horizontal axis, then get a mask to subset the original frame. Here's how you can use np.sort and df.duplicated to do that:

df[~pd.DataFrame(np.sort(df2[['Item_X', 'Item_Y']], axis=1)).duplicated()]

  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6


问:
Converting Bash command line options to variable name
I am trying to write a bash script that takes in an option.
Lets call these options A and B.

In the script A and B may or may not be defined as variables.

I want to be able to check if the variable is defined or not.

I have tried the following but it doesn't work.

```<code>if [ ! -n $1 ]; then
   echo "Error"
fi
</code>```

Thanks

答:
The trick is "$1", i.e.</p>

```<code>root@root:~# cat auto.sh
Usage () {

        echo "error"
}
if [ ! -n $1 ];then
        Usage
        exit 1
fi
root@root:~# bash auto.sh
root@root:~# cat auto2.sh
Usage () {

        echo "error"
}
if [ ! -n "$1" ];then
        Usage
        exit 1
fi
root@root:~# bash auto2.sh
error
</code>```

Body:
I am trying to write a bash script that takes in an option.
Lets call these options A and B.

In the script A and B may or may not be defined as variables.

I want to be able to check if the variable is defined or not.

I have tried the following but it doesn't work.

if [ ! -n $1 ]; then
   echo "Error"
fi

Thanks

Body:
The trick is "$1", i.e.

root@root:~# cat auto.sh
Usage () {

        echo "error"
}
if [ ! -n $1 ];then
        Usage
        exit 1
fi
root@root:~# bash auto.sh
root@root:~# cat auto2.sh
Usage () {

        echo "error"
}
if [ ! -n "$1" ];then
        Usage
        exit 1
fi
root@root:~# bash auto2.sh
error


问:
How do you capture the text on the first page of a Microsoft Word document?
Using VB.NET how do you capture the text on the first page of a Microsoft Word document?  I've imported the Word 12 interop library (for Word 2007), and I know how to use the document.range function, but how do you know which page you're on when you're selecting text?</p>

答:
Roughly speaking, you don't. Word doesn't have a solid concept of pages... See http://daiya.mvps.org/wordpages.htm for example.

You could try something like:

```<code>docMyDocument.Bookmarks("\Page").Range
</code>```

Which mostly works, but isn't guaranteed to. (It fails if there are tables stradding the end of the page, for example...)

see also http://support.microsoft.com/kb/212555

OwnerDisplayName: david

LastEditorDisplayName: Juan Manuel

Body:
Roughly speaking, you don't. Word doesn't have a solid concept of pages... See http://daiya.mvps.org/wordpages.htm for example.

You could try something like:

docMyDocument.Bookmarks("\Page").Range

Which mostly works, but isn't guaranteed to. (It fails if there are tables stradding the end of the page, for example...)

see also http://support.microsoft.com/kb/212555

OwnerDisplayName: Stobor


问:
Angular 6 : Different background color for events in Kendo-Schduler
Is there a way to style the background color of events depending on the type of event in kendo-scheduler in Angular 6?
I know that I can globally set the event background colors using CSS:

.k-event{background-color: #000;}

but this doesn't help me when I have different types of events with different colors. Is there any workaround for this?

As an example like this photo :

my data structure of events is like the following code:

```<code>{
        start:        startDate,
        end:          endDate,
        title:        holidayTitle,
        isAllDay:     true,
        description:  '',
        color :       holidayColor
}
</code>```

答:
You should define your resources in your class component .ts file and put your preferred colors like below

```<code>public resources: any[] = [
            {
                field: "Events",
                dataSource: [
                    { text: "Value1", value: 1, color: "#f8a398" },
                    { text: "Value2", value: 2, color: "#51a0ed" }
                ],
                multiple: true,
                title: "Events"
            }
        ]
</code>```

Please refer to this updated Demo link and Docs for more clarifications

Body:
Is there a way to style the background color of events depending on the type of event in kendo-scheduler in Angular 6?
I know that I can globally set the event background colors using CSS:

.k-event{background-color: #000;}

but this doesn't help me when I have different types of events with different colors. Is there any workaround for this?

As an example like this photo :

my data structure of events is like the following code:

{
        start:        startDate,
        end:          endDate,
        title:        holidayTitle,
        isAllDay:     true,
        description:  '',
        color :       holidayColor
}

Body:
You should define your resources in your class component .ts file and put your preferred colors like below

public resources: any[] = [
            {
                field: "Events",
                dataSource: [
                    { text: "Value1", value: 1, color: "#f8a398" },
                    { text: "Value2", value: 2, color: "#51a0ed" }
                ],
                multiple: true,
                title: "Events"
            }
        ]

Please refer to this updated Demo link and Docs for more clarifications


问:
Does getting a synchronized collection from collections class synchronize a class?
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

```<code>HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);
</code>```

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.

答:
As far as I understand it Collections.synchronizedMap does not guarantee that fields values inside stored objects will be synchronized but that each entry inside the map will be synchronized when modified within a synchronized method. It does not guarantee anything else. Whenever a synchronized map is modified in another thread other references of the same map in other threads will fall in sync.

This is my superficial understanding of it according to this source as well as Java documentation.

Body:
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.


问:
web.config authorization deny unauthorised
I am developing a .NET for ASP.NET Web Application and am trying to deny all users who are unauthorised from accessing my application but allowing them only to the login page.

Below is a snippet of the code which is inside my system.web section:

```<code><authentication mode="Forms">
   <forms loginUrl="Login.aspx" timeout="60" name="APPNAME" slidingExpiration="true" />
</authentication>
<authorization>
   <deny users="?" />
</authorization>
</code>```

I also have this outside to allow access to the login page:

```<code>  <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
</code>```

However I am still able to access pages when I am not logged in, how could I stop this from happening?

I have even added a Web.Config file to the Main folder which stores most of the website files which the contents of is:

```<code><?xml version="1.0"?>
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>
</code>```

But this is still not having any effect.

Solution

I had followed some optimisation tips for asp.net (http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx) and removed the AnonymousIdentification httpModule which I actually needed.

答:
You can put a new Web.config in the folder that needs the permissions applied. Inside it do something like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>
</code>```

Or you might need to wrap the <authorization> tag with a <security> tag.

Body:
I am developing a .NET for ASP.NET Web Application and am trying to deny all users who are unauthorised from accessing my application but allowing them only to the login page.

Below is a snippet of the code which is inside my system.web section:

<authentication mode="Forms">
   <forms loginUrl="Login.aspx" timeout="60" name="APPNAME" slidingExpiration="true" />
</authentication>
<authorization>
   <deny users="?" />
</authorization>

I also have this outside to allow access to the login page:

  <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

However I am still able to access pages when I am not logged in, how could I stop this from happening?

I have even added a Web.Config file to the Main folder which stores most of the website files which the contents of is:

<?xml version="1.0"?>
<configuration>
    <appSettings/>
    <connectionStrings/>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

But this is still not having any effect.

Solution

I had followed some optimisation tips for asp.net (http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx) and removed the AnonymousIdentification httpModule which I actually needed.

Body:
You can put a new Web.config in the folder that needs the permissions applied. Inside it do something like this

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.web>
        <authorization>
            <deny users="?" />
        </authorization>
    </system.web>
</configuration>

Or you might need to wrap the <authorization> tag with a <security> tag.


问:
How to fix AES encrypt function adding \0\0\0 to the end of encrypted text?
When I decrypt an encrypted username using AES encryption it shows a bunch of "\0\0\0" at the end of the decrypted username. Is there a way to not add these when encrypting?

The example code of the encryption and decryption:

```<code>  string ky = xx_Convert.Base64ToString("RllhSzNjM09PZFAwT2RYMkdxOFI2cG9HYjVmWVIybnQ=");
  string iv = xx_Convert.Base64ToString("Y2pZQmJsdVlqdlBYM0RtcXVleDJkNGNTa0FIYjhYQ2Y=");

  string username = "test@mail.com";

  string encriptedUsername = xx_Crypto.EncryptAES(ky, iv, username);
  string encriptedPassword = xx_Crypto.EncryptAES(ky, iv, "password");

  string decryptedUsername = xx_Crypto.DecryptAES(ky, iv, encriptedUsername);
  string decryptedPassword = xx_Crypto.DecryptAES(ky, iv, encriptedPassword);
</code>```

This gives the following result for decryptedUsername when inspecting the variable: "test@mail.com\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"

This is likely a result of the Padding property of the encryption function.
In the Encryption function the Padding is set to Padding = PaddingMode.Zeros but when I remove this line it still pads the result but with other invisible characters.

Encryption function:

```<code>public static string EncryptAES(string keyString, string ivString, string
text)
{
  RijndaelManaged myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

  byte[] encrypted = null;
  using (MemoryStream msEncrypt = new MemoryStream())
  {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
          CryptoStreamMode.Write))
    {
      using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
      {
        //Write all data to the stream.
        swEncrypt.Write(text);
      }
      encrypted = msEncrypt.ToArray();
    }
  }

  return (Convert.ToBase64String(encrypted));
}
</code>```

Edit: As requested here is the Decryption function:

```<code>public static string DecryptAES(string keyString, string ivString, string text)
{
  var myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

  byte[] sEncrypted = Convert.FromBase64String(text);

  byte[] fromEncrypt = new byte[sEncrypted.Length];

  MemoryStream msDecrypt = new MemoryStream(sEncrypted);
  CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

  csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

  return (Encoding.UTF8.GetString(fromEncrypt));
}
</code>```

So is it possible to prevent this in the encryption function?

P.S: I did not use the same keys as in the original code

答:
So is it possible to prevent this in the encryption function?

Yes, just use:

```<code>read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return (Encoding.UTF8.GetString(fromEncrypt, 0, read));
</code>```

You are currently encoding the entire buffer. The padding bytes are removed but the bytes in the buffer are preset to zero during initialization when you created the buffer.

Note that zero padding isn't used much because if your plaintext ends with one or more zero bytes, those bytes may be removed. So some messages cannot be decrypted successfully this way (and cryptographers want to encrypt arbitrary messages, not just strings).

Body:
When I decrypt an encrypted username using AES encryption it shows a bunch of "\0\0\0" at the end of the decrypted username. Is there a way to not add these when encrypting?

The example code of the encryption and decryption:

  string ky = xx_Convert.Base64ToString("RllhSzNjM09PZFAwT2RYMkdxOFI2cG9HYjVmWVIybnQ=");
  string iv = xx_Convert.Base64ToString("Y2pZQmJsdVlqdlBYM0RtcXVleDJkNGNTa0FIYjhYQ2Y=");

  string username = "test@mail.com";

  string encriptedUsername = xx_Crypto.EncryptAES(ky, iv, username);
  string encriptedPassword = xx_Crypto.EncryptAES(ky, iv, "password");

  string decryptedUsername = xx_Crypto.DecryptAES(ky, iv, encriptedUsername);
  string decryptedPassword = xx_Crypto.DecryptAES(ky, iv, encriptedPassword);

This gives the following result for decryptedUsername when inspecting the variable: "test@mail.com\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"

This is likely a result of the Padding property of the encryption function.
In the Encryption function the Padding is set to Padding = PaddingMode.Zeros but when I remove this line it still pads the result but with other invisible characters.

Encryption function:

public static string EncryptAES(string keyString, string ivString, string
text)
{
  RijndaelManaged myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

  byte[] encrypted = null;
  using (MemoryStream msEncrypt = new MemoryStream())
  {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,
          CryptoStreamMode.Write))
    {
      using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
      {
        //Write all data to the stream.
        swEncrypt.Write(text);
      }
      encrypted = msEncrypt.ToArray();
    }
  }

  return (Convert.ToBase64String(encrypted));
}

Edit: As requested here is the Decryption function:

public static string DecryptAES(string keyString, string ivString, string text)
{
  var myRijndael = new RijndaelManaged()
  {
    Padding = PaddingMode.Zeros,
    Mode = CipherMode.CBC,
    KeySize = 256,
    BlockSize = 256
  };

  byte[] key = Encoding.UTF8.GetBytes(keyString);
  byte[] IV = Encoding.UTF8.GetBytes(ivString);

  ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

  byte[] sEncrypted = Convert.FromBase64String(text);

  byte[] fromEncrypt = new byte[sEncrypted.Length];

  MemoryStream msDecrypt = new MemoryStream(sEncrypted);
  CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

  csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

  return (Encoding.UTF8.GetString(fromEncrypt));
}

So is it possible to prevent this in the encryption function?

P.S: I did not use the same keys as in the original code

Body:
So is it possible to prevent this in the encryption function?

Yes, just use:

read = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return (Encoding.UTF8.GetString(fromEncrypt, 0, read));

You are currently encoding the entire buffer. The padding bytes are removed but the bytes in the buffer are preset to zero during initialization when you created the buffer.

Note that zero padding isn't used much because if your plaintext ends with one or more zero bytes, those bytes may be removed. So some messages cannot be decrypted successfully this way (and cryptographers want to encrypt arbitrary messages, not just strings).


答:
IIUC, use:

```<code>m=pd.DataFrame(np.sort(df[['Item_X','Item_Y']])).duplicated()
df[~m]
</code>```

```<code>  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6
</code>```

Title: Drop unordered duplicates across separate columns

Body:
IIUC, use:

m=pd.DataFrame(np.sort(df[['Item_X','Item_Y']])).duplicated()
df[~m]

  Item_X Item_Y  Value
0    Foo    Bar      1
2    Bot    Foo      3
3    Bot    Bot      4
4    Bar    Bar      5
5    Foo    Foo      6


问:
reversing a linked list in ruby using a stack
I am implementing a reversed linked list using a stack.
Class Stack has methods push and pop, which turn a linked list into a stack from which the last element can be extracted in order to reverse the order.

I've encountered a similar situation here, and I'm trying to add a method to that base case. I'm trying to implement a reverse_list method that makes use of the Stack class's push and pop in order to change the pointer and reverse the linked list.

This is what I tried:

```<code>class LinkedListNode
  attr_accessor :value, :next_node

  def initialize(value, next_node=nil)
    @value = value
    @next_node = next_node
  end
end

def print_values(list_node)
  if list_node
    print "#{list_node.value} --> "
    print_values(list_node.next_node)
  else
    print "nil\n"
    return
  end
end

class Stack
    attr_reader :data

    def initialize
        @data = nil
    end

    def push(value)
      @data = LinkedListNode.new(value, @data)
    end

    def pop
      return nil if @data.nil?
      returning_value = @data.value
      @data = @data.next_element
      returning_value
    end
end

def reverse_list(list)
    stack = Stack.new.push(list.value)
    list = list.next_node

    while list
      stack.push(list.value)
      list = list.next_node
    end

    stack.pop
end

node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)

revlist = reverse_list(node3)
print_values(revlist)
# should return 37 --> 99 --> 12 --> nil
</code>```

I get errors when calling the Stack class in the reverse_list method (undefined method push for <Context::LinkedListNode:0x00000001c5e0a8>).

I'm at a loss as to why I cannot use Stack, push, and pop inside reverse_list. Any tips as to how I could go about implementing reverse_list will be well received.

答:
Your pop Method within your Stack class is calling for "next_element", but I think you should be referring to the "next_node" variable from the LinkedListNode class. I would re-write your "pop" method this way:

```<code>def pop
 if @data.nil?
   nil
 else
   returning_value = @data.value
   @data = @data.next_node
   returning_value
 end
end
</code>```

I would also rewrite the method to reverse the linked list like this:

```<code>def reversed_linked_list(list)
   stack = Stack.new
  while list
   stack.push(list.value)
   list = list.next_node
  end
  LinkedListNode.new(stack.pop, stack.data)
end
</code>```

Body:
I am implementing a reversed linked list using a stack.
Class Stack has methods push and pop, which turn a linked list into a stack from which the last element can be extracted in order to reverse the order.

I've encountered a similar situation here, and I'm trying to add a method to that base case. I'm trying to implement a reverse_list method that makes use of the Stack class's push and pop in order to change the pointer and reverse the linked list.

This is what I tried:

class LinkedListNode
  attr_accessor :value, :next_node

  def initialize(value, next_node=nil)
    @value = value
    @next_node = next_node
  end
end

def print_values(list_node)
  if list_node
    print "#{list_node.value} --> "
    print_values(list_node.next_node)
  else
    print "nil\n"
    return
  end
end

class Stack
    attr_reader :data

    def initialize
        @data = nil
    end

    def push(value)
      @data = LinkedListNode.new(value, @data)
    end

    def pop
      return nil if @data.nil?
      returning_value = @data.value
      @data = @data.next_element
      returning_value
    end
end

def reverse_list(list)
    stack = Stack.new.push(list.value)
    list = list.next_node

    while list
      stack.push(list.value)
      list = list.next_node
    end

    stack.pop
end

node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)

revlist = reverse_list(node3)
print_values(revlist)
# should return 37 --> 99 --> 12 --> nil

I get errors when calling the Stack class in the reverse_list method (undefined method push for <Context::LinkedListNode:0x00000001c5e0a8>).

I'm at a loss as to why I cannot use Stack, push, and pop inside reverse_list. Any tips as to how I could go about implementing reverse_list will be well received.

Body:
Your pop Method within your Stack class is calling for "next_element", but I think you should be referring to the "next_node" variable from the LinkedListNode class. I would re-write your "pop" method this way:

def pop
 if @data.nil?
   nil
 else
   returning_value = @data.value
   @data = @data.next_node
   returning_value
 end
end

I would also rewrite the method to reverse the linked list like this:

def reversed_linked_list(list)
   stack = Stack.new
  while list
   stack.push(list.value)
   list = list.next_node
  end
  LinkedListNode.new(stack.pop, stack.data)
end