问:
Add toomanyattempts in my login controller in laravel
I need to add the functionality that toomanyloginattempts with my login . now its not working. Iam using Laravel Framework 5.1.45 (LTS).
The code that i used is mentioned below.
My controller function is

```<code>    <?php
    use App\Libraries\SessionHelper;
    use App\Libraries\ConfigUtils;
    use App\Libraries\GeneralLib;
    use App\Models\OrgSettings;
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\ThrottlesLogins;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

    class LoginController extends Controller {
     use AuthenticatesAndRegistersUsers, ThrottlesLogins;

      public function doLogin() {
        $email = Input::get('email');
        $pass = Input::get('password');
        $candidate_login_user = User::getUserByEmail($email);
        $data = User::authenticate($email, $pass);
        if (empty($data)) {
          User::logFailedAuthentication($email, $candidate_login_user->organization);
          Session::flash('error', "Incorrect email or password.");
          return Redirect::to('/login');
        }

    }
</code>```

my  view page is as follows

```<code>    <form action="login" method="post">
                    <div class="body bg-gray">
                       <div class="alert alert-danger">
        <strong >Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

                        <?php
                            Session::forget('error');
                            Session::forget('success');
                        ?>
                        <div class="form-group">
                            <input type="email" name="email" class="form-control"
                                placeholder="email"/>
                        </div>
                        <div class="form-group">
                            <input type="password" name="password"
                                class="form-control" placeholder="password"/>
                        </div>
</code>```

答:
Since you're implementing your own login action it is not enough to just add the traits to your LoginController to implement throttling.

You need to be checking the hasTooManyLoginAttempts method from your doLogin action, and firing the lockout event yourself, if necessary.

public function doLogin(\Illuminate\Http\Request $request) {
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    $email = Input::get('email');
    $pass = Input::get('password');
    $candidate_login_user = User::getUserByEmail($email);
    $data = User::authenticate($email, $pass);

    if (empty($data)) {
        User::logFailedAuthentication($email, $candidate_login_user->organization);
        Session::flash('error', "Incorrect email or password.");
        $this->incrementLoginAttempts($request);
        return Redirect::to('/login');
    }
}
```

Altogether, I think you'd be better off simply using the built-in Auth controllers to handle your login (or at least using them as a starting point) rather than reimplement your own.

Body:
I need to add the functionality that toomanyloginattempts with my login . now its not working. Iam using Laravel Framework 5.1.45 (LTS).
The code that i used is mentioned below.
My controller function is

    <?php
    use App\Libraries\SessionHelper;
    use App\Libraries\ConfigUtils;
    use App\Libraries\GeneralLib;
    use App\Models\OrgSettings;
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\ThrottlesLogins;
    use Illuminate\Foundation\Auth\AuthenticatesUsers;
    use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

    class LoginController extends Controller {
     use AuthenticatesAndRegistersUsers, ThrottlesLogins;

      public function doLogin() {
        $email = Input::get('email');
        $pass = Input::get('password');
        $candidate_login_user = User::getUserByEmail($email);
        $data = User::authenticate($email, $pass);
        if (empty($data)) {
          User::logFailedAuthentication($email, $candidate_login_user->organization);
          Session::flash('error', "Incorrect email or password.");
          return Redirect::to('/login');
        }

    }

my  view page is as follows

    <form action="login" method="post">

        Whoops! There were some problems with your input.

            @foreach ($errors->all() as $error)

{{ $error }}

            @endforeach

@endif

                        <?php
                            Session::forget('error');
                            Session::forget('success');
                        ?>

                            <input type="email" name="email" class="form-control"
                                placeholder="email"/>

                            <input type="password" name="password"
                                class="form-control" placeholder="password"/>

Body:
Since you're implementing your own login action it is not enough to just add the traits to your LoginController to implement throttling.

You need to be checking the hasTooManyLoginAttempts method from your doLogin action, and firing the lockout event yourself, if necessary.

public function doLogin(\Illuminate\Http\Request $request) {
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    $email = Input::get('email');
    $pass = Input::get('password');
    $candidate_login_user = User::getUserByEmail($email);
    $data = User::authenticate($email, $pass);

    if (empty($data)) {
        User::logFailedAuthentication($email, $candidate_login_user->organization);
        Session::flash('error', "Incorrect email or password.");
        $this->incrementLoginAttempts($request);
        return Redirect::to('/login');
    }
}

Altogether, I think you'd be better off simply using the built-in Auth controllers to handle your login (or at least using them as a starting point) rather than reimplement your own.


来源: stackexchange

问:
Create route from list item
I create a list of fruits and I want to be able to click on a fruit in the list and open a new route with the fruits description. I am not sure how to set up the route to this 'productDescription.ejs' file.

app.js:

```<code>const express = require('express'),
    mongoose = require('mongoose'),
    logger = require('morgan'),
    bodyParser = require('body-parser');

let app = express();

app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true}));

var products = [
    {
        name: 'Apple',
        description: 'Apple, (Malus domestica), fruit of the domesticated tree Malus domestica (family Rosaceae), one of the most widely cultivated tree fruits. The apple is a pome (fleshy) fruit, in which the ripened ovary and surrounding tissue both become fleshy and edible.'
    },
    {
        name: 'Apricots',
        description: 'An apricot is a fruit, or the tree that bears the fruit, of several species in the genus Prunus (stone fruits).'
    },
    {
        name: 'Avocado',
        description: 'Avocado, Persea americana, is an evergreen tree in the family Lauraceae which grown for its nutritious fruit.'
    },
    {
        name: 'Banana',
        description: 'A banana is a curved, yellow fruit with a thick skin and soft sweet flesh.'
    }
]

///////////ROUTES
//Home Page with list of products
app.get('/', function (req, res) {
    res.render('productList', {products:products});
});

//Page with the item description
app.get('/:products', function (req, res) {
    //THIS IS WHERE I NEED HELP
});

//LocalHost:3000 Port
app.listen(3000);
</code>```

productList.ejs:

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Fruits</title>
</head>
<body>
  <ul class="list-group list-group-flush">
    <% products.forEach((prod) => { %>
      <li class="list-group-item"><a href=<%= products.name%>> <%= prod.name %> </a></li>
    <% }) %>
  </ul>
</body>
</html>
</code>```

productDescription.ejs(What I want to show when a item is clicked on):

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Fruits</title>
</head>
<body>
    <h1><%= products.name %></h1>
    <p><%= products.description %></p>
</body>
</html>
</code>```

What the first page looks like with list items:
enter image description here

答:
You can place this in your code, and it should work

```<code>const productsParam = req.params.products;

const product = products.find(pro => pro.name === productsParam)

res.render('productDescription', {products:product});
</code>```

Another way to do it, and which is more in standard is to use the index of the array as an id. and use that to get the value from the array

Note: to make it more conventional you could remove the s from the second routers products(change all occurrences). make it product instead.

ContentLicense: CC BY-SA 4.0

Title: Create route from list item

Body:
I create a list of fruits and I want to be able to click on a fruit in the list and open a new route with the fruits description. I am not sure how to set up the route to this 'productDescription.ejs' file.

app.js:

const express = require('express'),
    mongoose = require('mongoose'),
    logger = require('morgan'),
    bodyParser = require('body-parser');

let app = express();

app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true}));

var products = [
    {
        name: 'Apple',
        description: 'Apple, (Malus domestica), fruit of the domesticated tree Malus domestica (family Rosaceae), one of the most widely cultivated tree fruits. The apple is a pome (fleshy) fruit, in which the ripened ovary and surrounding tissue both become fleshy and edible.'
    },
    {
        name: 'Apricots',
        description: 'An apricot is a fruit, or the tree that bears the fruit, of several species in the genus Prunus (stone fruits).'
    },
    {
        name: 'Avocado',
        description: 'Avocado, Persea americana, is an evergreen tree in the family Lauraceae which grown for its nutritious fruit.'
    },
    {
        name: 'Banana',
        description: 'A banana is a curved, yellow fruit with a thick skin and soft sweet flesh.'
    }
]

///////////ROUTES
//Home Page with list of products
app.get('/', function (req, res) {
    res.render('productList', {products:products});
});

//Page with the item description
app.get('/:products', function (req, res) {
    //THIS IS WHERE I NEED HELP
});

//LocalHost:3000 Port
app.listen(3000);

productList.ejs:

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Fruits</title>

    <% products.forEach((prod) => { %>

<a href=<%= products.name%>> <%= prod.name %>

    <% }) %>

productDescription.ejs(What I want to show when a item is clicked on):

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Fruits</title>

<%= products.name %>

<%= products.description %>

What the first page looks like with list items:
enter image description here

Body:
You can place this in your code, and it should work

const productsParam = req.params.products;

const product = products.find(pro => pro.name === productsParam)

res.render('productDescription', {products:product});

Another way to do it, and which is more in standard is to use the index of the array as an id. and use that to get the value from the array

Note: to make it more conventional you could remove the s from the second routers products(change all occurrences). make it product instead.


问:
padding leading zeros (0 characters) in some string
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

```<code>char str[11] = "12345";
</code>```

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

```<code>sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters
</code>```

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);
</code>```

2nd Method

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);
</code>```

If I try using sprintf with string as argument I get leading blanks:

```<code>char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);
</code>```

OUTPUT:

```<code>     12345   //leading spaces
</code>```

Is there any simple method to accomplish this?

答:
Or another method would be to simply loop over temp_string after your sprintf and replace spaces with zeros, e.g.

```<code>char *p = temp_string;

sprintf (temp_string, "%10s", main_string);

while (*p && *p == ' ')
    *p++ = '0';

puts (temp_string);
</code>```

Body:
I have to fill a string (containing numerals) with leading zeros if the content of that string was less than string's size.

example:

char str[11] = "12345";

The expected output should be: 0000012345

I have padded string with leading 0 by using sprintf but with an integer as argument:

sprintf(out_str,"%010d",some_integer);  //out_str is a string of 11 characters

but now I have only two methods left for padding a string (containing numerals) with leading zeros:

1st Method

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf("temp_string,"%010d", atoi(main_string));

strcpy(main_string,temp_string);

2nd Method

char main_string[11] = "12345";
char temp_string[11] = "";

memset(temp_string,'0',sizeof(temp_string));

strcpy(temp_string + sizeof(temp_string) - 1 - strlen(main_string), main_string);

strcpy(main_string, temp_string);

If I try using sprintf with string as argument I get leading blanks:

char main_string[11] = "12345";
char temp_string[11] = "";

sprintf(temp_string,"%010s",main_string);
printf("%s",temp_string);

OUTPUT:

     12345   //leading spaces

Is there any simple method to accomplish this?

Body:
Or another method would be to simply loop over temp_string after your sprintf and replace spaces with zeros, e.g.

char *p = temp_string;

sprintf (temp_string, "%10s", main_string);

while (*p && *p == ' ')
    *p++ = '0';

puts (temp_string);


问:
Counting the number of repeated entries in a file
When I read a file, it gives me an output like this:

```<code>CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749
</code>```

I want to count the total number of CW and CS in the file. The output should look like this:

```<code>3 #For CW
3 #For CS
</code>```

I tried using the following code:

```<code>with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)
</code>```

But it gives me this output

```<code>2
2
2
2
2
2
</code>```

I even tried importing counter, but it gives me output like this:

```<code>C 1
W 1
C 1
W 1
C 1
S 1
</code>```

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

答:
want to count the total number of CW and CS in the file.

Try this:

```<code>di = { }
with open("file", "r") as f:
    for l in f:
        l = l.strip()
        di[l] = di[l] + 1 if l in di else 1

for k, v in di.items():
    print("Line: %s and Count: %d" % (k, v))
</code>```

Output:

```<code>Line: CW and Count: 3
Line: CS and Count: 3
</code>```

Body:
When I read a file, it gives me an output like this:

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749

I want to count the total number of CW and CS in the file. The output should look like this:

3 #For CW
3 #For CS

I tried using the following code:

with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)

But it gives me this output

2
2
2
2
2
2

I even tried importing counter, but it gives me output like this:

C 1
W 1
C 1
W 1
C 1
S 1

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
want to count the total number of CW and CS in the file.

Try this:

di = { }
with open("file", "r") as f:
    for l in f:
        l = l.strip()
        di[l] = di[l] + 1 if l in di else 1

for k, v in di.items():
    print("Line: %s and Count: %d" % (k, v))

Output:

Line: CW and Count: 3
Line: CS and Count: 3


问:
The sandbox is not in sync with the Podfile.lock-ios
I have got the following errors after trying multiple answers from the google.

```<code>PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.
</code>```

I have updated and installed many times, but they are of no use.

答:
I think you are trying to use your old project pod folder in your current project, you have to copy Manifest.lock file of your current project and replace that file in your old project's pod folder which you added. Manifest.lock file location YourProject->Pods->Manifest.lock
Hope This was helpful. worked for me!

ContentLicense: CC BY-SA 3.0

Body:
I have got the following errors after trying multiple answers from the google.

PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-
    iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh
        cd "/Users/apple/Downloads/FoodSpot 2"
        /bin/sh -c /Users/apple/Library/Developer/Xcode/DerivedData/Build/Intermediates/FoodSpot.build/Debug-iphonesimulator/FoodSpotTests.build/Script-36819C3C1B6A30F50091382D.sh

    diff: /../Podfile.lock: No such file or directory
    diff: /Manifest.lock: No such file or directory
    error: The sandbox is not in sync with the Podfile.lock.
    Run 'pod   install' or update your CocoaPods installation.

I have updated and installed many times, but they are of no use.


问:
NA Remove to calculation
I have some problems with NA value cause my dataset from excel is not same column number so It showed NA. It deleted all row containing NA value when make calculation Similarity Index function Psicalc in RInSp package.

```<code>B   F
4   7
5   6
6   8
7   5
NA  4
NA  3
NA  2
</code>```

Do you know how to handle with NA or remove it but not delete all row or not affect to package?. Beside when I import.RinSP it has message
In if (class(filename) == "character") { :
  the condition has length > 1 and only the first element will be used
Thank you so much

答:
Many R functions ( specifically base R ) have an na.rm argument, which is FALSE by default. That means if you omit this argument, and your data has NA, your "calculation" will result in NA. To remove these in the calculations,  include an na.rm argument and assign it to TRUE.

Example:

```<code>x <- c(4,5,6,7,NA,NA)
mean(x)  # Oops!
[1] NA

mean(x, na.rm=TRUE)
[1] 5.5
</code>```

Title: NA Remove to calculation

Body:
I have some problems with NA value cause my dataset from excel is not same column number so It showed NA. It deleted all row containing NA value when make calculation Similarity Index function Psicalc in RInSp package.

B   F
4   7
5   6
6   8
7   5
NA  4
NA  3
NA  2

Do you know how to handle with NA or remove it but not delete all row or not affect to package?. Beside when I import.RinSP it has message
In if (class(filename) == "character") { :
  the condition has length > 1 and only the first element will be used
Thank you so much

Body:
Many R functions ( specifically base R ) have an na.rm argument, which is FALSE by default. That means if you omit this argument, and your data has NA, your "calculation" will result in NA. To remove these in the calculations,  include an na.rm argument and assign it to TRUE.

Example:

x <- c(4,5,6,7,NA,NA)
mean(x)  # Oops!
[1] NA

mean(x, na.rm=TRUE)
[1] 5.5


问:
combine a set of row statuses into a single summary status
I have a view that looks like this:

```<code>package_id  package_line  status_a        status_b
1           1             NOT_STARTED     FAILED
1           2             STARTED         STARTED
1           3             FAILED          NOT_STARTED
2           1             COMPLETE        STARTED
2           2             COMPLETE        NOT_STARTED
</code>```

and so on, for several thousand rows.  Status_a and status_b are separate unrelated statuses (in fact they are whether a package executed on system a and on system b).

I need a summary by package_id, to roll up to

```<code>   package_id status_a  status_b
   1          FAILED    FAILED
   2          COMPLETE  NOT_STARTED
</code>```

The rules for combining package lines are

```<code> 1. If any package line has failed, the package has failed.
 2. If all package lines are complete, the package is complete.
 3. If all package lines are NOT_STARTED, the package has not started.
 4. Otherwise, the package is started (i.e. a combination of started, not_started, and complete would summarize as STARTED).
</code>```

So I'm trying to come up with a query to create this summary.  I'd love to post a code sample, but I'm really at loss.  Presumably I want to GROUP_BY the package_id, but what can I use as an aggregate function that would allow me to apply the rules listed?

If it helps, I do have control over how the statuses are reported at the package line level, so I could report a numeric status (though I like having it human readable just for sanity).

答:
Try this (same for status_b):

```<code>SELECT package_id,
       CASE WHEN FAILED_COUNT > 0 THEN 'FAILED'
            WHEN COMPLETE_COUNT = ALL_COUNT THEN 'COMPLETE'
            WHEN NOT_STARTED_COUNT = ALL_COUNT THEN 'NOT_STARTED'
            ELSE 'STARTED'
       END status_a
FROM (
SELECT package_id,
     COUNT(status_a) ALL_COUNT,
     SUM(CASE WHEN status_a = 'FAILED' THEN 1 ELSE 0 END) FAILED_COUNT,
     SUM(CASE WHEN status_a = 'COMPLETE' THEN 1 ELSE 0 END) COMPLETE_COUNT,
     SUM(CASE WHEN status_a = 'NOT_STARTED' THEN 1 ELSE 0 END) NOT_STARTED_COUNT,
     SUM(CASE WHEN status_a = 'STARTED' THEN 1 ELSE 0 END) STARTED_COUNT
 FROM table
GROUP BY package_id
)
</code>```

Body:
I have a view that looks like this:

package_id  package_line  status_a        status_b
1           1             NOT_STARTED     FAILED
1           2             STARTED         STARTED
1           3             FAILED          NOT_STARTED
2           1             COMPLETE        STARTED
2           2             COMPLETE        NOT_STARTED

and so on, for several thousand rows.  Status_a and status_b are separate unrelated statuses (in fact they are whether a package executed on system a and on system b).

I need a summary by package_id, to roll up to

   package_id status_a  status_b
   1          FAILED    FAILED
   2          COMPLETE  NOT_STARTED

The rules for combining package lines are

 1. If any package line has failed, the package has failed.
 2. If all package lines are complete, the package is complete.
 3. If all package lines are NOT_STARTED, the package has not started.
 4. Otherwise, the package is started (i.e. a combination of started, not_started, and complete would summarize as STARTED).

So I'm trying to come up with a query to create this summary.  I'd love to post a code sample, but I'm really at loss.  Presumably I want to GROUP_BY the package_id, but what can I use as an aggregate function that would allow me to apply the rules listed?

If it helps, I do have control over how the statuses are reported at the package line level, so I could report a numeric status (though I like having it human readable just for sanity).

Body:
Try this (same for status_b):

SELECT package_id,
       CASE WHEN FAILED_COUNT > 0 THEN 'FAILED'
            WHEN COMPLETE_COUNT = ALL_COUNT THEN 'COMPLETE'
            WHEN NOT_STARTED_COUNT = ALL_COUNT THEN 'NOT_STARTED'
            ELSE 'STARTED'
       END status_a
FROM (
SELECT package_id,
     COUNT(status_a) ALL_COUNT,
     SUM(CASE WHEN status_a = 'FAILED' THEN 1 ELSE 0 END) FAILED_COUNT,
     SUM(CASE WHEN status_a = 'COMPLETE' THEN 1 ELSE 0 END) COMPLETE_COUNT,
     SUM(CASE WHEN status_a = 'NOT_STARTED' THEN 1 ELSE 0 END) NOT_STARTED_COUNT,
     SUM(CASE WHEN status_a = 'STARTED' THEN 1 ELSE 0 END) STARTED_COUNT
 FROM table
GROUP BY package_id
)


问:
`overflow:auto` doesn't hide scrollbar in mobile view
I have following CSS:

```<code>  .show_dropdown {
    max-height: 350px;
    overflow-y: auto;
  }
</code>```

in a mobile view the dropdown list is less than 350px and this should hide scrollbar because it is not necessary. However, in bigger screen it works fine and hide scroll when it is not needed.

Thanks for reading and helping

Full code can be find here

答:
You can use vendor prefixes for this, and it's the approach I'd recommend.

```<code>.dropdown_list {
    -ms-overflow-style: none;  /* Internet Explorer 10+ */
    scrollbar-width: none;  /* Firefox */
}
.dropdown_list::-webkit-scrollbar {
    display: none;  /* Safari and Chrome */
}
</code>```

Codepen: https://codepen.io/CewisLewis/pen/poJyzJV

Body:
I have following CSS:

  .show_dropdown {
    max-height: 350px;
    overflow-y: auto;
  }

in a mobile view the dropdown list is less than 350px and this should hide scrollbar because it is not necessary. However, in bigger screen it works fine and hide scroll when it is not needed.

Thanks for reading and helping

Full code can be find here

Body:
You can use vendor prefixes for this, and it's the approach I'd recommend.

.dropdown_list {
    -ms-overflow-style: none;  /* Internet Explorer 10+ */
    scrollbar-width: none;  /* Firefox */
}
.dropdown_list::-webkit-scrollbar {
    display: none;  /* Safari and Chrome */
}

Codepen: https://codepen.io/CewisLewis/pen/poJyzJV


问:
URLSessionDataTask has no member 'map' Swift 5
Hello this is an error I do not know how to fix. from this tutorial:

Reusable Image Cache in Swift

Code:

```<code>final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
    if let image = cache[url] {
        return Just(image).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTask(with: url)
        .map { (data, response) -> UIImage? in return UIImage(data: data) }
        .catch { error in return Just(nil) }
        .handleEvents(receiveOutput: {[unowned self] image in
            guard let image = image else { return }
            self.cache[url] = image
        })
        .subscribe(on: .background)
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}
}
</code>```

Update:

If You Use dataTaskPublisher:

答:
You have to use dataTaskPublisher for that purpose not dataTask itself

```<code>final class ImageLoader {

    private let cache = ImageCache()

    func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
        if let image = cache[url] {
            return Just(image).eraseToAnyPublisher()
        }
        return URLSession.shared.dataTaskPublisher(for: url)
            .map { UIImage(data: $0.data) }
            .catch { error in return Just(nil) }
            .handleEvents(receiveOutput: {[unowned self] image in
                guard let image = image else { return }
                self.cache[url] = image
            })
            .subscribe(on: DispatchQueue.global(qos: .background))
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }
}
</code>```

Body:
Hello this is an error I do not know how to fix. from this tutorial:

Reusable Image Cache in Swift

Code:

final class ImageLoader {

private let cache = ImageCache()

func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
    if let image = cache[url] {
        return Just(image).eraseToAnyPublisher()
    }
    return URLSession.shared.dataTask(with: url)
        .map { (data, response) -> UIImage? in return UIImage(data: data) }
        .catch { error in return Just(nil) }
        .handleEvents(receiveOutput: {[unowned self] image in
            guard let image = image else { return }
            self.cache[url] = image
        })
        .subscribe(on: .background)
        .receive(on: RunLoop.main)
        .eraseToAnyPublisher()
}
}

Update:

If You Use dataTaskPublisher:

Body:
You have to use dataTaskPublisher for that purpose not dataTask itself

final class ImageLoader {

    private let cache = ImageCache()

    func loadImage(from url: URL) -> AnyPublisher<UIImage?, Never> {
        if let image = cache[url] {
            return Just(image).eraseToAnyPublisher()
        }
        return URLSession.shared.dataTaskPublisher(for: url)
            .map { UIImage(data: $0.data) }
            .catch { error in return Just(nil) }
            .handleEvents(receiveOutput: {[unowned self] image in
                guard let image = image else { return }
                self.cache[url] = image
            })
            .subscribe(on: DispatchQueue.global(qos: .background))
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }
}


问:
How to convert Decimal to Hexadecimal in JavaScript?
I am trying to solve this problem but i can't. Would need some help. Thank you.

Write a JavaScript code in a Web page dec2hex.html that enters a positive integer number num and converts and converts it to a hexadecimal form. The input should be entered as JavaScript prompt window. The output should be shown as browser popup window (alert).

My code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Decimal</title>
</head>
<body>
    <script type="text/javascript">
         var decimal = prompt("Write your decimal number");
         var hex = decimal.toString(16);
         alert(hex);
    </script>

</body>
</html>
</code>```

Examples:

Input: 254

Output: FE

Input: 6779

Output: 1A7B

答:
Replace hex = decimal.toString(16) to hex = parseInt(decimal, 16)

To test this in console, use the below:

```<code>dec = prompt("Decimal Number");
hex = parseInt(dec, 16);

console.log("DEC: " + dec);
console.log("HEX: " + hex);
</code>```

Body:
I am trying to solve this problem but i can't. Would need some help. Thank you.

Write a JavaScript code in a Web page dec2hex.html that enters a positive integer number num and converts and converts it to a hexadecimal form. The input should be entered as JavaScript prompt window. The output should be shown as browser popup window (alert).

My code:

<!DOCTYPE html>

    <title>Decimal</title>

Examples:

Input: 254

Output: FE

Input: 6779

Output: 1A7B

Body:
Replace hex = decimal.toString(16) to hex = parseInt(decimal, 16)

To test this in console, use the below:

dec = prompt("Decimal Number");
hex = parseInt(dec, 16);

console.log("DEC: " + dec);
console.log("HEX: " + hex);


问:
Combine two (or more) value from an existing fields in DataStudio
I cannot find a way to combine two value of an existing field in Google data studio.

My existing field is sub-status. Inside this field, I have many different sub-status (A,B,C,D and so on) that of course do not appear in my fields as they are sub-value of the field.

So I would like to combine two value of fields in my charts

```<code>sub-status = A , B , C, D ,E , f

value A = A + B
</code>```

答:
For future reference, to answer the initial question, consolidating A and B to a single value, A, can be achieved using a CASE Statement:

```<code>CASE
  WHEN REGEXP_MATCH(sub-status, "A|B") THEN "A"
  ELSE sub-status
END
</code>```

Created a Google Data Studio Report (Google Sheets Embedded) to elaborate.

Body:
I cannot find a way to combine two value of an existing field in Google data studio.

My existing field is sub-status. Inside this field, I have many different sub-status (A,B,C,D and so on) that of course do not appear in my fields as they are sub-value of the field.

So I would like to combine two value of fields in my charts

sub-status = A , B , C, D ,E , f

value A = A + B

Body:
For future reference, to answer the initial question, consolidating A and B to a single value, A, can be achieved using a CASE Statement:

CASE
  WHEN REGEXP_MATCH(sub-status, "A|B") THEN "A"
  ELSE sub-status
END

Created a Google Data Studio Report (Google Sheets Embedded) to elaborate.


问:
SQL Server insert problem. Data insert operation is successful but after closing the application and re open it that data can not be found
I am trying to write a C# application which will have an attached database.

So I did an insert operation which is working perfectly and after insert operation I can see my data in my data grid view. But after closing the application, I saw that my data table is empty. So I reopened my application and the data grid view is also empty.

Here is my sample code :

Insert

```<code>    private void button_create_Click(object sender, EventArgs e)
    {
        int id = 7;

        string ConStr = ConfigurationManager.ConnectionStrings["Doctor_s_Assistant.Properties.Settings.DocAssistDBConnectionString"].ConnectionString;
        SqlConnection offDBconnection = new SqlConnection(ConStr);

        offDBconnection.Open();

        string sqlCommand = "INSERT INTO Treatment_Template VALUES (@id, @t_name, @t_body, @t_advice)";

        SqlCommand sql = new SqlCommand(sqlCommand, offDBconnection);

        sql.Parameters.AddWithValue("@id",id);
        sql.Parameters.AddWithValue("@t_name", textBox_temp_name.Text);
        sql.Parameters.AddWithValue("@t_body", richTextBox_temp_body.Text);
        sql.Parameters.AddWithValue("@t_advice", richTextBox_temp_advice.Text);

        sql.ExecuteNonQuery();
        offDBconnection.Close();

        MessageBox.Show("New Template Created");
    }
</code>```

Preview data:

```<code>    private void button_Load_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DocAssistDB.mdf;Integrated Security=True");
        con.Open();

        SqlCommand cmd = new SqlCommand("select * from Treatment_Template", con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dataGridView1.DataSource = dt;

        con.Close();
    }
</code>```

Thanks in advance

答:
You're either looking in the wrong DB (you're looking in the MDF file in the project main folder alongside your csproj but the MDF your app altered is found in the BIN\DEBUG or BIN\RELEASE subfolder - the MDF was copied there during build)

Or

For your MDF file you have "copy to output folder" set to Copy Always so your build prices is always overwriting the MDF that your exe is editing (in the BIN\xxx subfolders) with a fresh blank database from the project folder

Click the MDF in Solution Explorer and set the copy option to Copy If Newer in the Properties window. Always make schema changes to the MDF in the project folder, not the bin folder. Be aware that when you make schema changes etc the file will become newer and overwrite your test data - if you want to keep the test data and other timings your program has written, copy the file back from bin folders first, then change the schema, then it will be copied out again during builds

Oh, by the way; check out http://dapper-tutorial.net - it will save you wasting your life writing tedious data access code; all that code you wrote in your post can be reduced to about 4 lines

Body:
I am trying to write a C# application which will have an attached database.

So I did an insert operation which is working perfectly and after insert operation I can see my data in my data grid view. But after closing the application, I saw that my data table is empty. So I reopened my application and the data grid view is also empty.

Here is my sample code :

Insert

    private void button_create_Click(object sender, EventArgs e)
    {
        int id = 7;

        string ConStr = ConfigurationManager.ConnectionStrings["Doctor_s_Assistant.Properties.Settings.DocAssistDBConnectionString"].ConnectionString;
        SqlConnection offDBconnection = new SqlConnection(ConStr);

        offDBconnection.Open();

        string sqlCommand = "INSERT INTO Treatment_Template VALUES (@id, @t_name, @t_body, @t_advice)";

        SqlCommand sql = new SqlCommand(sqlCommand, offDBconnection);

        sql.Parameters.AddWithValue("@id",id);
        sql.Parameters.AddWithValue("@t_name", textBox_temp_name.Text);
        sql.Parameters.AddWithValue("@t_body", richTextBox_temp_body.Text);
        sql.Parameters.AddWithValue("@t_advice", richTextBox_temp_advice.Text);

        sql.ExecuteNonQuery();
        offDBconnection.Close();

        MessageBox.Show("New Template Created");
    }

Preview data:

    private void button_Load_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DocAssistDB.mdf;Integrated Security=True");
        con.Open();

        SqlCommand cmd = new SqlCommand("select * from Treatment_Template", con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dataGridView1.DataSource = dt;

        con.Close();
    }

Thanks in advance


问:
Complementing of boolean not working, with ngIf in ngx-datatable
onSelect() is called whenever a row in ngx-datatable is selected. isNodeSelected for some reason is not getting complemented when the same row is selected, even though it enters that if statement. isNodeSelected is used with ngIf to display buttons. Webstorm highlights the complement  statement and says 'narrowed to true'

```<code>onSelect({ selected }) {
    this.isNodeSelected = true;
    if (Array.isArray(this.selected) && this.selected.length === 1) {
      if (this.selected[0].hasOwnProperty('id') && this.selected[0].id === selected[0].id) {
        this.isNodeSelected = !this.isNodeSelected;
      } else if (this.selected[0].hasOwnProperty('id') && this.selected[0].id !== selected[0].id) {
        this.selected = selected;
        this.isNodeSelected = true;
      }
    } else {
      this.selected = selected;
      this.isNodeSelected = true;
    }
  }
</code>```

答:
If this function is in your component.ts file then at least you need to replace:

```<code>onSelect({ selected }) {
</code>```

with

```<code>onSelect(selected) {
</code>```

as the curly brace is used to insert variables values in the template, not in the code behind.

Other than that, step through each bit with your debugger to check the values at each point.

E.g. does it enter the second if statement, if so, what is the value of selected[0].id etc.

Body:
onSelect() is called whenever a row in ngx-datatable is selected. isNodeSelected for some reason is not getting complemented when the same row is selected, even though it enters that if statement. isNodeSelected is used with ngIf to display buttons. Webstorm highlights the complement  statement and says 'narrowed to true'

onSelect({ selected }) {
    this.isNodeSelected = true;
    if (Array.isArray(this.selected) && this.selected.length === 1) {
      if (this.selected[0].hasOwnProperty('id') && this.selected[0].id === selected[0].id) {
        this.isNodeSelected = !this.isNodeSelected;
      } else if (this.selected[0].hasOwnProperty('id') && this.selected[0].id !== selected[0].id) {
        this.selected = selected;
        this.isNodeSelected = true;
      }
    } else {
      this.selected = selected;
      this.isNodeSelected = true;
    }
  }

Body:
If this function is in your component.ts file then at least you need to replace:

onSelect({ selected }) {

with

onSelect(selected) {

as the curly brace is used to insert variables values in the template, not in the code behind.

Other than that, step through each bit with your debugger to check the values at each point.

E.g. does it enter the second if statement, if so, what is the value of selected[0].id etc.


问:
I cannot get label tag
Hello guys when I click one of these words on Button, I take an error about NullReferenceException was unhandled.   look: error image

error image

namespace HangMan
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

```<code>    string[] words = { "PENCIL", "UMBRELLA", "RUBBER", "RING", "NECKLACE", "SPEED", "PROGRAMMER" };
    private void Form1_Load(object sender, EventArgs e)
    {
        setWords();
        getWords();
    }

    private void getWords()
    {
        Random rnd = new Random();

        string selectedWord = words[rnd.Next(0, words.Length)];

        foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            flowLayoutPanel2.Controls.Add(lbl);
        }

    }
    private void setWords()
    {
        for (char i = 'A'; i <= 'Z'; i++)
        {
            Button btn = new Button();
            btn.Text = i.ToString();
            btn.Width = 25;
            btn.Height = 25;
            btn.Click += Btn_Click;

            flowLayoutPanel1.Controls.Add(btn);
        }
    }

    int Score = 0;

    private void Btn_Click(object sender, EventArgs e)
    {

        Button clicked = sender as Button;

        bool IsCharOpened = false;
        foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item;

                if (lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }

        if (IsCharOpened == false)
        {
            lblRemaining.Text = (int.Parse(lblRemaining.Text) - 1).ToString();
            if (int.Parse(lblRemaining.Text) == 0)
            {
                MessageBox.Show("YOU HAVE FAILED..!");
                Application.Exit();
            }
        }

        lblScore.Text = Score.ToString();
        clicked.Enabled = false;
    }
}
</code>```

}

I cannot find any solution, and I am new on c#. I need your help guys, thanks.

答:
Just try this and it should work.
TO this:    </p>

```<code>           if (lbl.Tag.ToString() == clicked.Text.ToString)
            {
                lbl.Text = clicked.Text.ToString();

            }
</code>```

Title: I cannot get label tag

Body:
Hello guys when I click one of these words on Button, I take an error about NullReferenceException was unhandled.   look: error image

error image

namespace HangMan
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    string[] words = { "PENCIL", "UMBRELLA", "RUBBER", "RING", "NECKLACE", "SPEED", "PROGRAMMER" };
    private void Form1_Load(object sender, EventArgs e)
    {
        setWords();
        getWords();
    }

    private void getWords()
    {
        Random rnd = new Random();

        string selectedWord = words[rnd.Next(0, words.Length)];

        foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            flowLayoutPanel2.Controls.Add(lbl);
        }

    }
    private void setWords()
    {
        for (char i = 'A'; i <= 'Z'; i++)
        {
            Button btn = new Button();
            btn.Text = i.ToString();
            btn.Width = 25;
            btn.Height = 25;
            btn.Click += Btn_Click;

            flowLayoutPanel1.Controls.Add(btn);
        }
    }

    int Score = 0;

    private void Btn_Click(object sender, EventArgs e)
    {

        Button clicked = sender as Button;

        bool IsCharOpened = false;
        foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item;

                if (lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }

        if (IsCharOpened == false)
        {
            lblRemaining.Text = (int.Parse(lblRemaining.Text) - 1).ToString();
            if (int.Parse(lblRemaining.Text) == 0)
            {
                MessageBox.Show("YOU HAVE FAILED..!");
                Application.Exit();
            }
        }

        lblScore.Text = Score.ToString();
        clicked.Enabled = false;
    }
}

}

I cannot find any solution, and I am new on c#. I need your help guys, thanks.

Body:
Just try this and it should work.
TO this:

           if (lbl.Tag.ToString() == clicked.Text.ToString)
            {
                lbl.Text = clicked.Text.ToString();

            }


答:
Here....... (lbl.Tag.ToString() == clicked.Text)
you have'nt set any tag data lbl.Tag null
that's why you are getting null reference exception

Replace your code with

```<code>foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            lbl.Tag = item;
            flowLayoutPanel2.Controls.Add(lbl);
        }
</code>```

And in Second Place Replace Code With

```<code>foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item; //C# özgü
                                         //Label lbl = item as Label; Label lbl = item as Label; // V.B özgü ama ikiside olur.
                if (lbl.Tag!=null && lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }
</code>```

Title: I cannot get label tag

Body:
Here....... (lbl.Tag.ToString() == clicked.Text)
you have'nt set any tag data lbl.Tag null
that's why you are getting null reference exception

Replace your code with

foreach (char item in selectedWord)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Width = 25;
            lbl.Height = 25;
            lbl.Text = "_";
            lbl.Tag = item;
            flowLayoutPanel2.Controls.Add(lbl);
        }

And in Second Place Replace Code With

foreach (Control item in flowLayoutPanel2.Controls)
        {
            if (item is Label)
            {
                Label lbl = (Label)item; //C# özgü
                                         //Label lbl = item as Label; Label lbl = item as Label; // V.B özgü ama ikiside olur.
                if (lbl.Tag!=null && lbl.Tag.ToString() == clicked.Text)
                {
                    lbl.Text = clicked.Text;
                    Score += 100;
                    IsCharOpened = true;
                }
            }
        }


问:
How to update multiple elements for each data
There are a lot of articles about how to update dom for each data. But what if I want to update multiple dom nodes for each data.

For example, for each data, generate div and span according to the number in the data.

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

I want to yield like

```<code><div class="data">
  <div>1</div><span>2</span><span>2</span>
</div>
<div class="data">
  <div>2</div><div>2</div><span>1</span>
</div>
</code>```

Should start with

```<code>const selection = d3.selectAll("div.data");
selection.exit().remove();
selection.enter().append("div").attr("class", "data").merge(selection);
// Then I don't know how to add multiple dom according to the data value.
</code>```

答:
d3 supports nesting of selections.  The critical bit here is after binding data to the parent elements, call parent.selectAll() and then bind the data using a function instead of a variable, e.g., parent.selectAll(child).data(d => d). d3 will automatically bind the nested arrays to each child element.  This is described in the link, which defines a table with nested tr and td elements:

The data operator defines the array of data for each group. Here the data function is invoked once per row and successively passed each parent datum. Since the parent data is an array of arrays, the data function simply returns the inner array for each row of cells.

 let data = [
   [1, 2],
   [2, 1],
 ]

 let selection =  d3.selectAll('div.data')
 .data(data)
 .enter()
 .append("div")
 .attr("class", "data")

 selection
 .selectAll('span')
 .data(function(d) {
  return  d;
 })
.enter()
.append('span')
.text(d => d)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.data span {
 background: white;
 border: 1px solid black;
 padding: 5px;
 margin: 5px;
}

.data {
 background: yellow;
 margin: 10px;
 border: 1px solid red;
 padding: 8px;
}</code>```

```

Body:
There are a lot of articles about how to update dom for each data. But what if I want to update multiple dom nodes for each data.

For example, for each data, generate div and span according to the number in the data.

[
  [1, 2],
  [2, 1],
]

I want to yield like

1
22

2

2
1

Should start with

const selection = d3.selectAll("div.data");
selection.exit().remove();
selection.enter().append("div").attr("class", "data").merge(selection);
// Then I don't know how to add multiple dom according to the data value.

Body:
d3 supports nesting of selections.  The critical bit here is after binding data to the parent elements, call parent.selectAll() and then bind the data using a function instead of a variable, e.g., parent.selectAll(child).data(d => d). d3 will automatically bind the nested arrays to each child element.  This is described in the link, which defines a table with nested tr and td elements:

The data operator defines the array of data for each group. Here the data function is invoked once per row and successively passed each parent datum. Since the parent data is an array of arrays, the data function simply returns the inner array for each row of cells.

 let data = [
   [1, 2],
   [2, 1],
 ]

 let selection =  d3.selectAll('div.data')
 .data(data)
 .enter()
 .append("div")
 .attr("class", "data")

 selection
 .selectAll('span')
 .data(function(d) {
  return  d;
 })
.enter()
.append('span')
.text(d => d)

.data span {
 background: white;
 border: 1px solid black;
 padding: 5px;
 margin: 5px;
}

.data {
 background: yellow;
 margin: 10px;
 border: 1px solid red;
 padding: 8px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>


问:
Does BS4 offer a means to size `.input-group` down on various devices
I'm looking to size a BS4 input-group down as and when it is loaded on various devices. Kinda like how you can tell a col what it should be displaying on various screens. I.e.

I want to do something similar on mobile devices, I.e. on a desktop
  use .input-group-lg on a mobile use .input-group-sm etc.

Is this something BS4 can do? (I can't see any mention of it in the
  docs?)

Here's a jsfiddle with an example, if it helps.

答:
```<code><div class="row">
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
        <div class="form-group">
            <label>Title</label>
            <input type="text" class="form-control" required>
        </div>
    </div>
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
        <div class="form-group">
            <label>Price</label>
            <input type="text" class="form-control">
        </div>
    </div>
</div>
</code>```


问:
Vue: How do I call multiple functions with @click?
How can I call multiple functions in a single @click? (aka v-on:click)?

So far I tried

Splitting the functions with a semicolon:

;

Using several @click:

;

and as a workaround, I can just create a handler:

```<code><div v-on:click="fn3('foo', 'bar')"> </div>

function fn3 (args) {
  fn1(args);
  fn2(args);
}
</code>```

But sometimes this isn't nice. What would be the proper method/syntax?

答:
I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon</p>

```<code>  @click="method1(); $emit('emit1'); $emit('emit2');"
</code>```

Body:
How can I call multiple functions in a single @click? (aka v-on:click)?

So far I tried

Splitting the functions with a semicolon:

;

Using several @click:

;

and as a workaround, I can just create a handler:

function fn3 (args) {
  fn1(args);
  fn2(args);
}

But sometimes this isn't nice. What would be the proper method/syntax?

Body:
I'd add, that you can also use this to call multiple emits or methods or both together by separating with ; semicolon

  @click="method1(); $emit('emit1'); $emit('emit2');"


问:
Looping Threads every 3 seconds in JavaFX
I'm currently working on a stock market application that changes the values of the prices of the stocks every so often (for this example, let's have the stocks change value every 3 seconds). I looked into doing tasks but I couldn't find a way to make the tasks run continuously. Is there a way to make a task loop every 3 seconds within the main class? (To clarify, I would like this looped task to be added into the body of my main method, without using external classes besides the main method)

Here's what I have so far:

```<code>Task<Void> change = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                try {
                    Thread.sleep(3000);
                }
                catch (InterruptedException e) {}
                return null;
            }
        };
        change.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {

            }
        });
        new Thread(change).start();
</code>```

NOTE: This code was referenced from here

答:
Do not think in terms of “continuously” or “looping”. Instead think of the job to be done (look up fresh stock prices), and how often do you want that task to be performed.

For the first part, your task, define a Runnable (or Callable). That means simply having a run method to comply with the contract of the interface.

In lambda syntax:

```<code>Runnable runnable =
    () -> {
        System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() ) ;
    }
;
</code>```

Next, study up on the Executors framework built into modern Java. See Oracle Tutorial. This framework greatly simplifies the tricky work of scheduling work on threads.

Specifically, you want to use ScheduledExecutorService. This interface is for scheduling a task to run once at a specific time (actually, run once after a specific delay expires), or run a task repeatedly. You, of course, want the latter.

Get an implementation from the Executors class. For your needs, we need only a single-thread. In other cases, you may want to use a thread pool.

```<code>ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;
</code>```

You have a choice two variations for scheduling: scheduleAtFixedRate and scheduleWithFixedDelay. Study them both to decide which is best for your case. In either case, know that you cannot rely on the scheduling perfectly. Your host OS controls granting access to the CPU cores to the JVM, and the JVM may be juggling a multitude of threads. So the timing may be delayed sporadically, though for most business apps the delays should be insignificant.

```<code>ses.scheduleWithFixedDelay( runnable , 0L , 3L , TimeUnit.SECONDS ) ;
</code>```

You may want to capture the returned ScheduledFuture object to monitor progress or completion. Our line of code above ignores it.

IMPORTANT Be sure to gracefully shutdown your executor service when no longer needed, or when your app is being shut down. Otherwise your threads may continue running in the background, surviving your app's exit.

IMPORTANT Wrap the task inside your Runnable task with a try-catch. Any exception or error thrown that bubbles up to the level of the Runnable object will result in your executor service silently terminating. No further calls will be scheduled. Search Stack Overflow to learn more.

```<code>Runnable runnable =
        ( ) -> {
            try
            {
                System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() );
            }
            catch ( Exception e )
            {
                // … try to recover, if you want the scheduled executor service to continue scheduling this task.
                // Or, at least, do logging/notifications to know when and why the scheduling of this task halted.
                e.printStackTrace();
            }
        };
</code>```

IMPORTANT Never access/modify any user-interface widget from a background thread when using UI frameworks like JavaFX, Swing, or Vaadin. Each UI framework will provide its own mechanism by which you can schedule widget-updating work to be performed on the UI’s thread. I am not familiar with JavaFX, so I cannot be more specific.

Put all that together in this example code. And, for those not comfortable with lambda syntax, use an anonymous class for our Runnable.

```<code>package work.basil.example;

import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Bogus
{
    public static void main ( String[] args )
    {
        Runnable runnable =
                new Runnable()
                {
                    @Override
                    public void run ( )
                    {
                        try
                        {
                            System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() );
                        }
                        catch ( Exception e )
                        {
                            // … try to recover, if you want the scheduled executor service to continue scheduling this task.
                            // Or, at least, do logging/notifications to know when and why the scheduling of this task halted.
                            e.printStackTrace();
                        }
                    }
                };

        ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

        ses.scheduleWithFixedDelay( runnable , 0L , 3L , TimeUnit.SECONDS );

        try
        {
            Thread.sleep( TimeUnit.MINUTES.toMillis( 1 ) );
        }
        catch ( InterruptedException e )
        {
            e.printStackTrace();
        }
        finally
        {
            ses.shutdown();  // IMPORTANT Always shutdown gracefully your executor service so the thread pool does not outlive your app.
        }

        System.out.println( "INFO - Completed run at: " + Instant.now() );
    }
}
</code>```

When run.

Looking up fresh stock prices at 2020-02-15T06:35:35.987199Z

Looking up fresh stock prices at 2020-02-15T06:35:39.026132Z

Looking up fresh stock prices at 2020-02-15T06:35:42.030302Z

Looking up fresh stock prices at 2020-02-15T06:35:45.035176Z

…

Looking up fresh stock prices at 2020-02-15T06:36:30.097743Z

Looking up fresh stock prices at 2020-02-15T06:36:33.100713Z

INFO - Completed run at: 2020-02-15T06:36:35.988752Z

As mentioned above, notice how the tasks are not exactly three seconds apart, but are pretty close. This example was run on a Mac mini with 6 real cores and no hyper-threading, 32 gigs of memory, on macOS Mojave, with Java 13.

Body:
I'm currently working on a stock market application that changes the values of the prices of the stocks every so often (for this example, let's have the stocks change value every 3 seconds). I looked into doing tasks but I couldn't find a way to make the tasks run continuously. Is there a way to make a task loop every 3 seconds within the main class? (To clarify, I would like this looped task to be added into the body of my main method, without using external classes besides the main method)

Here's what I have so far:

Task<Void> change = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                try {
                    Thread.sleep(3000);
                }
                catch (InterruptedException e) {}
                return null;
            }
        };
        change.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent event) {

            }
        });
        new Thread(change).start();

NOTE: This code was referenced from here

Body:
Do not think in terms of “continuously” or “looping”. Instead think of the job to be done (look up fresh stock prices), and how often do you want that task to be performed.

For the first part, your task, define a Runnable (or Callable). That means simply having a run method to comply with the contract of the interface.

In lambda syntax:

Runnable runnable =
    () -> {
        System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() ) ;
    }
;

Next, study up on the Executors framework built into modern Java. See Oracle Tutorial. This framework greatly simplifies the tricky work of scheduling work on threads.

Specifically, you want to use ScheduledExecutorService. This interface is for scheduling a task to run once at a specific time (actually, run once after a specific delay expires), or run a task repeatedly. You, of course, want the latter.

Get an implementation from the Executors class. For your needs, we need only a single-thread. In other cases, you may want to use a thread pool.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

You have a choice two variations for scheduling: scheduleAtFixedRate and scheduleWithFixedDelay. Study them both to decide which is best for your case. In either case, know that you cannot rely on the scheduling perfectly. Your host OS controls granting access to the CPU cores to the JVM, and the JVM may be juggling a multitude of threads. So the timing may be delayed sporadically, though for most business apps the delays should be insignificant.

ses.scheduleWithFixedDelay( runnable , 0L , 3L , TimeUnit.SECONDS ) ;

You may want to capture the returned ScheduledFuture object to monitor progress or completion. Our line of code above ignores it.

IMPORTANT Be sure to gracefully shutdown your executor service when no longer needed, or when your app is being shut down. Otherwise your threads may continue running in the background, surviving your app's exit.

IMPORTANT Wrap the task inside your Runnable task with a try-catch. Any exception or error thrown that bubbles up to the level of the Runnable object will result in your executor service silently terminating. No further calls will be scheduled. Search Stack Overflow to learn more.

Runnable runnable =
        ( ) -> {
            try
            {
                System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() );
            }
            catch ( Exception e )
            {
                // … try to recover, if you want the scheduled executor service to continue scheduling this task.
                // Or, at least, do logging/notifications to know when and why the scheduling of this task halted.
                e.printStackTrace();
            }
        };

IMPORTANT Never access/modify any user-interface widget from a background thread when using UI frameworks like JavaFX, Swing, or Vaadin. Each UI framework will provide its own mechanism by which you can schedule widget-updating work to be performed on the UI’s thread. I am not familiar with JavaFX, so I cannot be more specific.

Put all that together in this example code. And, for those not comfortable with lambda syntax, use an anonymous class for our Runnable.

package work.basil.example;

import java.time.Instant;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Bogus
{
    public static void main ( String[] args )
    {
        Runnable runnable =
                new Runnable()
                {
                    @Override
                    public void run ( )
                    {
                        try
                        {
                            System.out.println( "Looking up fresh stock prices at " + Instant.now().toString() );
                        }
                        catch ( Exception e )
                        {
                            // … try to recover, if you want the scheduled executor service to continue scheduling this task.
                            // Or, at least, do logging/notifications to know when and why the scheduling of this task halted.
                            e.printStackTrace();
                        }
                    }
                };

        ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

        ses.scheduleWithFixedDelay( runnable , 0L , 3L , TimeUnit.SECONDS );

        try
        {
            Thread.sleep( TimeUnit.MINUTES.toMillis( 1 ) );
        }
        catch ( InterruptedException e )
        {
            e.printStackTrace();
        }
        finally
        {
            ses.shutdown();  // IMPORTANT Always shutdown gracefully your executor service so the thread pool does not outlive your app.
        }

        System.out.println( "INFO - Completed run at: " + Instant.now() );
    }
}

When run.

Looking up fresh stock prices at 2020-02-15T06:35:35.987199Z

Looking up fresh stock prices at 2020-02-15T06:35:39.026132Z

Looking up fresh stock prices at 2020-02-15T06:35:42.030302Z

Looking up fresh stock prices at 2020-02-15T06:35:45.035176Z

…

Looking up fresh stock prices at 2020-02-15T06:36:30.097743Z

Looking up fresh stock prices at 2020-02-15T06:36:33.100713Z

INFO - Completed run at: 2020-02-15T06:36:35.988752Z

As mentioned above, notice how the tasks are not exactly three seconds apart, but are pretty close. This example was run on a Mac mini with 6 real cores and no hyper-threading, 32 gigs of memory, on macOS Mojave, with Java 13.


问:
Is there a way to accept full payment from customers later on when their order is ready to deliver in woocommerce?
I am trying to develop a website using woocommerce wherein my customers would place an order to get some graphics designed by me as per their requirmens.

Now what I am trying to achieve is to fetch their requirement and if possible get a fraction of total amount from the customer as advance payment. I should then be able to design the graphic as per their requirement which will take some time suppose 2 to 3 days after which I should give them a link to the designed graphic but they should only be able to download it when they pay the rest of the amount i.e. the full amount.

Is there a plugin to achieve this functionality?

答:
Here's an alternative solution:
You can use a plugin to offer your customers to send you a quote for your service. Once you receive the quote you add your product and send them back the quote with real order for them to pay. You first them the % they need to pay for you to start the service, and after you finish and confirm the final work you MANUALLY send another order with a full price this time.

This is a free plugin to do so.
https://wordpress.org/plugins/yith-woocommerce-request-a-quote/

Another cool plugin to help you with manual work:
https://wordpress.org/plugins/wc-invoice-gateway/

TO put this solution simple you just need to send the first deposit payment separately from the final delivery payment. You can do with multiply ways and tools, so it's up to you.

Thanks


问:
PowerBI Web: Connect to Oracle Cloud database
I would like to know if it is possible in Power BI Web to retrieve data from an Oracle database hosted in Oracle Cloud. Or to any other database/cloud combo different that Azure SQL Server.

Thanks!

答:
Yes you can definitely achieve this.

There are connectors available for connecting powerbi desktop to oracle database.
Link
Link 2


问:
Counting the number of repeated entries in a file
When I read a file, it gives me an output like this:

```<code>CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749
</code>```

I want to count the total number of CW and CS in the file. The output should look like this:

```<code>3 #For CW
3 #For CS
</code>```

I tried using the following code:

```<code>with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)
</code>```

But it gives me this output

```<code>2
2
2
2
2
2
</code>```

I even tried importing counter, but it gives me output like this:

```<code>C 1
W 1
C 1
W 1
C 1
S 1
</code>```

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
When I read a file, it gives me an output like this:

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749

I want to count the total number of CW and CS in the file. The output should look like this:

3 #For CW
3 #For CS

I tried using the following code:

with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)

But it gives me this output

2
2
2
2
2
2

I even tried importing counter, but it gives me output like this:

C 1
W 1
C 1
W 1
C 1
S 1

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
indeed use Counter

from collections import Counter
with open("xyz.txt") as f:
    c = Counter(line.split()[0] for line in f)
    for k,n in c.items():
        print(k, n)

with an input file of

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042 1
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076 1
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236 1
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213 1
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166 1
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749 1

produces

CW 3
CS 3


问:
Android TextView not scrolling [C#]
Why my TextView field doesn't scroll with finger? Have I missed something?

```<code>    <TextView
    android:text="Hi! Type help for more info"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_width="match_parent"
    android:layout_height="186.0dp"
    android:id="@+id/chat_box"
    android:layout_marginBottom="5dp"
    android:maxLines="12"
    android:textSize="12sp"

    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"
    android:scrollbars="vertical" />
</code>```

I've tried solution from another post, but for some reason my TextView doesn't have setMovementMethod(new ScrollingMovementMethod()) method.

答:
It is an old thread but as a reference,

I tried all properties of TextView about 'scrolling' in Xamarin.Android but none of them worked.( Maybe I missed something...)
Anyway,
 I could achieve this in another way

```<code>TextView dynamicTextView = new TextView(this);
dynamicTextView.Text = "long text blablabla ";
dynamicTextView.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 500); //Limit the height so you can scroll

ScrollView dynamicScrollView = new ScrollView(this);
 dynamicScrollView.AddView(dynamicTextView);
</code>```

Title: Android TextView not scrolling [C#]

Body:
Why my TextView field doesn't scroll with finger? Have I missed something?

    <TextView
    android:text="Hi! Type help for more info"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_width="match_parent"
    android:layout_height="186.0dp"
    android:id="@+id/chat_box"
    android:layout_marginBottom="5dp"
    android:maxLines="12"
    android:textSize="12sp"

    android:overScrollMode="always"
    android:scrollbarStyle="insideInset"
    android:scrollbars="vertical" />

I've tried solution from another post, but for some reason my TextView doesn't have setMovementMethod(new ScrollingMovementMethod()) method.

Body:
It is an old thread but as a reference,

I tried all properties of TextView about 'scrolling' in Xamarin.Android but none of them worked.( Maybe I missed something...)
Anyway,
 I could achieve this in another way

TextView dynamicTextView = new TextView(this);
dynamicTextView.Text = "long text blablabla ";
dynamicTextView.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 500); //Limit the height so you can scroll

ScrollView dynamicScrollView = new ScrollView(this);
 dynamicScrollView.AddView(dynamicTextView);


问:
time and date validation in javascript
I have two inputs in boostrap and I require the user to select a date in the first input and validate it.

If the date selected is the current date then the second input (which is a clock in jquery) will show the current hour +1. But if the date selected is different front the current one then the clock will display the time normally.

I have had a lot of trouble trying to do is so if you can help me or give me some advice I'd appreciate it, thanks.

```<code><html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="bootstrap/bootstrap.min.js"></script>
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="timepicker/jquery.timepicker.min.css">
    <script src="timepicker/jquery.timepicker.min.js"></script>
    <script src="moment.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#hora').timepicker({});
        });
    </script>
</head>
<body>
    <div class="container">
        <form action="">
            <div class="row">
                <div class="col-sm">
                    <label class="bmd-label-floating">Date</label>
                    <input id="fecha" type="date" name="fecha" class="form-
                      control" required onchange="validacion()">
                    <script>
                        function validacion() {
                            var fechaActual = moment().format("YYYY MM DD");
                            var fechaSeleccionada =
                                document.getElementById('fecha').value;
                            var diferencia =
                                fechaActual.diff(fechaSeleccionada);
                            console.log(fechaActual);
                            console.log(fechaSeleccionada);
                            console.log(diferencia);
                        }
                    </script>
                </div>
                <div id="recargar" class="col-sm">
                    <label>Time</label>
                    <input class="form-control" type="text" id="hora"
                           required>
                </div>
            </div>
        </form>
    </div>
</body>
</html>
</code>```

答:
I have done a workaround for you to achieve what you have said

```<code><input type="text" value="Enter date!" id="dte" class="datepicker">
<br/>
<br/>
<input type="text" id="time" value=" time!" >
</code>```

```<code>$(".datepicker").datepicker({dateFormat: "yy-mm-dd"});
$("input.datepicker").on("keyup change", function(){
var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();

var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '-' +
    ((''+month).length<2 ? '0' : '') + month + '-' +
    ((''+day).length<2 ? '0' : '') + day;

var selected = $("#dte").val();
if(selected==output)
{
var today = new Date();
today.setHours(today.getHours()+1);
var dt = new Date();
var time = dt.getHours() +1;
var ee=time+":"+ dt.getMinutes() + ":" + dt.getSeconds();
$("#time").val(ee);
}
else
{
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("#time").val(time);
}
});

</code>```

Here is a working fiddle:https://jsfiddle.net/athulmathew/06y8w72x/35/

Note: This is just a workaround you should use it as per your needs!

Title: time and date validation in javascript

Body:
I have two inputs in boostrap and I require the user to select a date in the first input and validate it.

If the date selected is the current date then the second input (which is a clock in jquery) will show the current hour +1. But if the date selected is different front the current one then the clock will display the time normally.

I have had a lot of trouble trying to do is so if you can help me or give me some advice I'd appreciate it, thanks.

    <link rel="stylesheet" href="bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="timepicker/jquery.timepicker.min.css">

        <form action="">

                    Date
                    <input id="fecha" type="date" name="fecha" class="form-
                      control" required onchange="validacion()">

                    Time
                    <input class="form-control" type="text" id="hora"
                           required>

        </form>

Body:
I have done a workaround for you to achieve what you have said

<input type="text" value="Enter date!" id="dte" class="datepicker">
<br/>
<br/>
<input type="text" id="time" value=" time!" >

$(".datepicker").datepicker({dateFormat: "yy-mm-dd"});
$("input.datepicker").on("keyup change", function(){
var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();

var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '-' +
    ((''+month).length<2 ? '0' : '') + month + '-' +
    ((''+day).length<2 ? '0' : '') + day;

var selected = $("#dte").val();
if(selected==output)
{
var today = new Date();
today.setHours(today.getHours()+1);
var dt = new Date();
var time = dt.getHours() +1;
var ee=time+":"+ dt.getMinutes() + ":" + dt.getSeconds();
$("#time").val(ee);
}
else
{
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("#time").val(time);
}
});

Here is a working fiddle:https://jsfiddle.net/athulmathew/06y8w72x/35/

Note: This is just a workaround you should use it as per your needs!


问:
How does kube-proxy behave when it can't reach the master?
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

```<code>nc -zv ip-of-pod 80
</code>```

succeeds, but

```<code>nc -zv ip-of-service 80
</code>```

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.

答:
Once you remove taints, kubernetes scheduler don't need any tolerations to schedule pods on your master node. So it is as good as your worker node with control plane components running on it and you can also run your workload pods on this node (although its not a recommended practice).

Kube-proxy (https://kubernetes.io/docs/concepts/overview/components/#kube-proxy) is the component deployed on all the nodes of cluster and it handles the networking and routing connection to your pods. So, even if your master node is down kube-proxy still works fine on the worker node and it will route traffic to your pods running on worker node.

If all your pods are running in worker nodes (which are still up and running), then kube-proxy will continue to route traffic to your pods even via service.

Body:
From what I've read about Kubernetes, if the master(s) die, the workers should still be able to function as normal (https://stackoverflow.com/a/39173007/281469), although no new scheduling will occur.

However, I've found this to not be the case when the master can also schedule worker pods. Take a 2-node cluster, where one node is a master and the other a worker, and the master has the taints removed:

If I shut down the master and docker exec into one of the containers on the worker I can see that:

nc -zv ip-of-pod 80

succeeds, but

nc -zv ip-of-service 80

fails half of the time. The Kubernetes version is v1.15.10, using iptables mode for kube-proxy.

I'm guessing that since the kube-proxy on the worker node can't connect to the apiserver, it will not remove the master node from the iptables rules.

Questions:

Is it expected behaviour that kube-proxy won't stop routing to pods on master nodes, or is there something "broken"?

Are any workarounds available for this kind of setup to allow the worker nodes to still function correctly?

I realise the best thing to do is separate the CP nodes but that's not viable for what I'm working on at the moment.


问:
Export certificate in windows store to a p12 file using Java
I will need to export a certificate in windows store to a p12 file. Similar to what you can do from firefox/IE browser but in JAVA. The only way I am able to do it currently is doing a C# with double Cpp wrappers or MCPP with wrapper using JNI which is not really useful. I have tried using SUNMSCAPI but I was not able to.. Any inputs appreciated.. Thank you..

If the above is certainly not possible, can a keystore be created with these certs?

答:
You can use the Java standard keystore API, with Bouncy Castle. You can load the keystore called Windows-MY, that contains all the certificates stored in the Windows keystore.

```<code>KeyStore.getInstance("Windows-MY");
</code>```

The reference to the Windows keystore provides method to extract certificates, via the KeyStore.getCertificate(String alias) method.

Once you retrieved the certificate, export it to a PKCS12 file.

ContentLicense: CC BY-SA 2.5

Body:
You can use the Java standard keystore API, with Bouncy Castle. You can load the keystore called Windows-MY, that contains all the certificates stored in the Windows keystore.

KeyStore.getInstance("Windows-MY");

The reference to the Windows keystore provides method to extract certificates, via the KeyStore.getCertificate(String alias) method.

Once you retrieved the certificate, export it to a PKCS12 file.


问:
Multi-part identifier error when adding a function to table- SQL Server
Currently I have the following function

```<code>CREATE FUNCTION dbo.CurrentEmpCount()
RETURNS DECIMAL
AS
BEGIN
    DECLARE @RetCount DECIMAL, @Return DECIMAL;

    SELECT @RetCount = COUNT(*)
    FROM Employee
    GROUP BY DepartmentID

    SET @Return = @RetCount

    RETURN  @Return
END
</code>```

When I try to add it to the department table with alter, I get an error:

The multi-part identifier "dbo.CurrentEmpCount" could not be bound.

```<code>ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount
GO
</code>```

Could anyone suggest anything to try out? In examples I've seen, they were doing it similarly.

答:
you cannot directly add function value as a column in a table.

What's your actual requirement

If you want department wise an employee count in the department table.
 then you have to calculate  using below query

UPDATE  B
SET     B.dept_no_employee = A.no_count
FROM    Department B
OUTER APPLY
(
    SELECT  COUNT(A.id) AS no_count
    FROM    Employee A
    WHERE A.dept_id = B.dept_id
)A

Else ignore the answer.

Body:
Currently I have the following function

CREATE FUNCTION dbo.CurrentEmpCount()
RETURNS DECIMAL
AS
BEGIN
    DECLARE @RetCount DECIMAL, @Return DECIMAL;

    SELECT @RetCount = COUNT(*)
    FROM Employee
    GROUP BY DepartmentID

    SET @Return = @RetCount

    RETURN  @Return
END

When I try to add it to the department table with alter, I get an error:

The multi-part identifier "dbo.CurrentEmpCount" could not be bound.

ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount
GO

Could anyone suggest anything to try out? In examples I've seen, they were doing it similarly.


问:
.htaccess rule slight help needed
I have spent hours trying to get this rule right and I am really struggling. I have got so close but I can not get it right. Any help is more than welcome... Thank you #

Trying to remove unwanted segments in the URL. From this:

https://example.com/index.php/module/action/param1/static/PFBC/js/jquery/rss/static/css/js/jquery/smoothness/templates/themes/datelove/img/icon/xml/sitemap/user/help/rss/legal/rss/comment-picture

To this:

https://example.com/comment-picture

The segments are random in name and in quantity, this is the rules I have so far

RewriteEngine on

RewriteCond %{REQUEST_URI} (\^|~|`|<|>|,|%|\\|\{|\}|\[|\]|\|)/ [NC]

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

It almost works but I need the last segment to be left, this rule gives a new URL of

The new url is https://example.com/
Test are stopped, a redirect will be made with status code 301

What is needed to leave the final segment?

I am getting closer

RewriteCond %{REQUEST_URI} (^https:.*?com|\/[\w+-]+$) ~gm [NC]

RewriteRule ^https:.*?com|\/(.*)[\w+-]+$(.*) $2 [R=301,L]

Gives me

https://example.com/index.php

So selecting the wrong part of URL but getting closer!

答:
This is the correct answer and I wish I could take the credit for it but I can't

```<code>RewriteEngine On

RewriteRule ^index\.php/module/action/param1/.*/(.*+)$ /$1 [L,R=301]
</code>```

This Is the work of a genus, I asked him for advice after coming across a very nice tool he has created. RewriteRule_Generator

Title: .htaccess rule slight help needed

Body:
This is the correct answer and I wish I could take the credit for it but I can't

RewriteEngine On

RewriteRule ^index\.php/module/action/param1/.*/(.*+)$ /$1 [L,R=301]

This Is the work of a genus, I asked him for advice after coming across a very nice tool he has created. RewriteRule_Generator


问:
How to send emails from Gmail without turning on "allow less secure apps" setting?
Is there any way to send an email in a Django project without turning on the "allow less secure apps" feature? Is using OAuth2 a must or can I send it using Google's API?

So far, I just use:

```<code>EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_HOST_USER = 'myemailaddress'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
</code>```

But this gives me an SMTPAuthenticationError, which only works when I turn on "allow less secure apps" in Google.  Is there any way to circumvent this without using OAuth2 and allow multiple users to login to that account easily?

答:
Using the gmail app password through you can send the email not provide the actual password and no one can login in your account. Without enable less secure apps setting  here is give the link try and it's work let me know if it right google or gmail app password

after it change the actual password to your app password in

setting.py file EMAIL_HOST_PASSWORD = 'your app password'  give by google
not change in other constant

if you do not use 2 step email verification you need to use third party service here i give the link you see sendgrid

Body:
Is there any way to send an email in a Django project without turning on the "allow less secure apps" feature? Is using OAuth2 a must or can I send it using Google's API?

So far, I just use:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = '587'
EMAIL_HOST_USER = 'myemailaddress'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

But this gives me an SMTPAuthenticationError, which only works when I turn on "allow less secure apps" in Google.  Is there any way to circumvent this without using OAuth2 and allow multiple users to login to that account easily?


问:
Adonis.js, Ionic and Cors
I'm trying to get CORS working on my adonis.js backend and ionic front end but I can't get anything working for some reason.

I've added the cors provider to my app.js

```<code>const providers = [
    '@adonisjs/framework/providers/AppProvider',
    '@adonisjs/auth/providers/AuthProvider',
    '@adonisjs/bodyparser/providers/BodyParserProvider',
    '@adonisjs/lucid/providers/LucidProvider',
    '@adonisjs/cors/providers/CorsProvider',
];
</code>```

Loaded it in kernel.js

```<code>const serverMiddleware = [
    'Adonis/Middleware/Cors',
];

Server
    .registerGlobal(globalMiddleware)
    .registerNamed(namedMiddleware)
    .use(serverMiddleware);
</code>```

and I've set my origin: true and no matter what I do, nothing seems to be fixing it. I've even done the following function with origin to try get it to log out the origin, and nothing is being logged out, so it makes me wonder if it's even loading my cors.js config.

```<code>origin: function (currentOrigin) {
    Logger.info(currentOrigin);
    return currentOrigin === 'mywebsite.com'
},
</code>```

Does anyone have any idea as to how to get it working? Many thanks in advance

答: So, it wasn't even a cors issue. Once I did some more reading it's due to developing on a localhost/127.0.0.1 environment, which is considered to send back "secure" requests, and it was trying to reach the API on unsecure local ip (10.0.0.5). So due to this, Firefox simply blocks all cross origin requests and why it wasn't even making it to my API to log anything out

Title: Adonis.js, Ionic and Cors

Body:
I'm trying to get CORS working on my adonis.js backend and ionic front end but I can't get anything working for some reason.

I've added the cors provider to my app.js

const providers = [
    '@adonisjs/framework/providers/AppProvider',
    '@adonisjs/auth/providers/AuthProvider',
    '@adonisjs/bodyparser/providers/BodyParserProvider',
    '@adonisjs/lucid/providers/LucidProvider',
    '@adonisjs/cors/providers/CorsProvider',
];

Loaded it in kernel.js

const serverMiddleware = [
    'Adonis/Middleware/Cors',
];

Server
    .registerGlobal(globalMiddleware)
    .registerNamed(namedMiddleware)
    .use(serverMiddleware);

and I've set my origin: true and no matter what I do, nothing seems to be fixing it. I've even done the following function with origin to try get it to log out the origin, and nothing is being logged out, so it makes me wonder if it's even loading my cors.js config.

origin: function (currentOrigin) {
    Logger.info(currentOrigin);
    return currentOrigin === 'mywebsite.com'
},

Does anyone have any idea as to how to get it working? Many thanks in advance


问:
System.IO.FileLoadException: Could not load file or assembly 'testhost, when debugging tests
Everytime I try to debug unit tests from Rider IDE, test execution fails with an exception

System.IO.FileLoadException: Could not load file or assembly
  'testhost, Culture=neutral, PublicKeyToken=null'. Could not find or
  load a specific file. (Exception from HRESULT: 0x80131621) File name:
  'testhost, Culture=neutral, PublicKeyToken=null'

StackTrace:

```<code>at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Xunit.Runner.VisualStudio.VsTestRunner.GetAvailableRunnerReporters(IEnumerable`1 sources) in C:\Dev\xunit\xunit\src\xunit.runner.visualstudio\VsTestRunner.cs:line 711
</code>```

Error happens only in one complicated project, with simple projects debugger starts and works properly.

Debugging in Visual Studio works ok.
I would appreciate a hint of the direction to look for possible solution.

答:
I got solved this issue by "nuking" whole project :)

After removing whole repository from the disk

- Clone repository back

- Generate Visual Studio solution file again (we don't keep them in repository)

- Build solution

- Run tests

- Debug one of the test - Debugger works properly

I found from some JetBrains forums an advise to remove Micrososft.AspNet.Core folder from dotnet location, while advised approach didn't work, it gave me an idea that the problem can be with this particular solution dependencies.

Body:
Everytime I try to debug unit tests from Rider IDE, test execution fails with an exception

System.IO.FileLoadException: Could not load file or assembly
  'testhost, Culture=neutral, PublicKeyToken=null'. Could not find or
  load a specific file. (Exception from HRESULT: 0x80131621) File name:
  'testhost, Culture=neutral, PublicKeyToken=null'

StackTrace:

at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, IntPtr ptrLoadContextBinder)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at Xunit.Runner.VisualStudio.VsTestRunner.GetAvailableRunnerReporters(IEnumerable`1 sources) in C:\Dev\xunit\xunit\src\xunit.runner.visualstudio\VsTestRunner.cs:line 711

Error happens only in one complicated project, with simple projects debugger starts and works properly.

Debugging in Visual Studio works ok.
I would appreciate a hint of the direction to look for possible solution.