问:
How to use purrr functions inside dplyr's select_if
I'm trying to find the shortest possible dplyr-purr combination.

Can I reduce the following statement which combines select_if() and map_df() ?

```<code>training.set.imputed %>%
  select_if(~sum(is.na(.))>0) %>% map_df(~sum(is.na(.)))
</code>```

I tried this:

```<code>training.set.imputed %>%
  select_if(~sum(is.na(.))>0, .funs = ~sum(is.na(.)))
</code>```

which throws this error:

Error: nm must be NULL or a character vector the same length as x

What does this mean?
Any ideas how to form the .funs term?

答:
The .funs argument in select_if requires a renaming function, and not a mutating function, so you can do something like this with it, but you can't mutate the variable values:

tibble(blah = 1:2, bleh = 3:4, bluh = c(NA, NA)) %>%
    select_if(~ sum(is.na(.x)) > 0, .funs = toupper)

#### OUTPUT ####

# A tibble: 2 x 1
  BLUH
  <lgl>
1 NA
2 NA
```

<p>If you insist on using a combination of purrr and dplyr, then this is probably your best bet <em>(Edit: I just noticed that G. Grothendieck gave this answer, but I'll include it anyway for the sake of completeness.)</em>:</p>

<pre class="lang-r prettyprint-override"><code>df %>%
    map_df(~ sum(is.na(.))) %>%
    select_if(~ . > 0)

#### OUTPUT ####

# A tibble: 1 x 2
      b     d
  <int> <int>
1     4     1
</code>```

However, you can simplify it a little by just using dplyr's summarize_if:

df %>%
    summarise_if(anyNA, ~ sum(is.na(.)))

#### OUTPUT ####

# A tibble: 1 x 2
      b     d
  <int> <int>
1     4     1
```

<p>Since you're really just after column sums, base R might offer the most concise option:</p>

<pre class="lang-r prettyprint-override"><code>colSums(is.na(df)) %>%
    .[. > 0]

#### OUTPUT ####

b d
4 1
</code>```

Data

structure(list(a = c(2L, 2L, 5L, 10L, 10L, 18L, 18L, 19L, 11L,
14L, 12L, 10L, 4L, 16L, 5L, 5L, 11L, 2L, 14L, 7L), b = c(10L,
20L, 16L, NA, 6L, 1L, 11L, 12L, 12L, 12L, 8L, NA, NA, 8L, 11L,
19L, 8L, 9L, NA, 19L), c = c(11L, 11L, 20L, 8L, 15L, 4L, 17L,
4L, 4L, 11L, 20L, 11L, 6L, 12L, 17L, 7L, 14L, 18L, 15L, 19L),
    d = c(19L, 16L, 17L, 14L, 8L, 19L, 7L, 6L, 6L, 13L, 7L, 19L,
    11L, 17L, NA, 10L, 3L, 3L, 3L, 2L), e = c(12L, 17L, 14L,
    5L, 8L, 19L, 8L, 3L, 17L, 1L, 2L, 6L, 5L, 17L, 14L, 5L, 8L,
    2L, 8L, 2L)), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
```

Body:
I'm trying to find the shortest possible dplyr-purr combination.

Can I reduce the following statement which combines select_if() and map_df() ?

training.set.imputed %>%
  select_if(~sum(is.na(.))>0) %>% map_df(~sum(is.na(.)))

I tried this:

training.set.imputed %>%
  select_if(~sum(is.na(.))>0, .funs = ~sum(is.na(.)))

which throws this error:

Error: nm must be NULL or a character vector the same length as x

What does this mean?
Any ideas how to form the .funs term?

Body:
The .funs argument in select_if requires a renaming function, and not a mutating function, so you can do something like this with it, but you can't mutate the variable values:

tibble(blah = 1:2, bleh = 3:4, bluh = c(NA, NA)) %>%
    select_if(~ sum(is.na(.x)) > 0, .funs = toupper)

#### OUTPUT ####

# A tibble: 2 x 1
  BLUH
  <lgl>
1 NA
2 NA

If you insist on using a combination of purrr and dplyr, then this is probably your best bet (Edit: I just noticed that G. Grothendieck gave this answer, but I'll include it anyway for the sake of completeness.):

df %>%
    map_df(~ sum(is.na(.))) %>%
    select_if(~ . > 0)

#### OUTPUT ####

# A tibble: 1 x 2
      b     d
  <int> <int>
1     4     1

However, you can simplify it a little by just using dplyr's summarize_if:

df %>%
    summarise_if(anyNA, ~ sum(is.na(.)))

#### OUTPUT ####

# A tibble: 1 x 2
      b     d
  <int> <int>
1     4     1

Since you're really just after column sums, base R might offer the most concise option:

colSums(is.na(df)) %>%
    .[. > 0]

#### OUTPUT ####

b d
4 1

Data

structure(list(a = c(2L, 2L, 5L, 10L, 10L, 18L, 18L, 19L, 11L,
14L, 12L, 10L, 4L, 16L, 5L, 5L, 11L, 2L, 14L, 7L), b = c(10L,
20L, 16L, NA, 6L, 1L, 11L, 12L, 12L, 12L, 8L, NA, NA, 8L, 11L,
19L, 8L, 9L, NA, 19L), c = c(11L, 11L, 20L, 8L, 15L, 4L, 17L,
4L, 4L, 11L, 20L, 11L, 6L, 12L, 17L, 7L, 14L, 18L, 15L, 19L),
    d = c(19L, 16L, 17L, 14L, 8L, 19L, 7L, 6L, 6L, 13L, 7L, 19L,
    11L, 17L, NA, 10L, 3L, 3L, 3L, 2L), e = c(12L, 17L, 14L,
    5L, 8L, 19L, 8L, 3L, 17L, 1L, 2L, 6L, 5L, 17L, 14L, 5L, 8L,
    2L, 8L, 2L)), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))


来源: stackexchange

问:
HTML form with php adding "?" in the url instead of do the php script
I'm working in a contact section in a website and I need to send all the contact form's to a mail.

The problem is, I have a php script who make all the job, but; when I click "send", the site refresh and the url changes from "www.site.com/contact.html" to "www.site.com/contact.html?".

By the way, I'm working with Bootstrap and PHP 5.

I think the problem is the form is don't recognize the script or I don't linked the script with the form correctly. I tried to use the action="form_contact.php property in the html form tag.

HTML

                <form id="form_46788" data-form-type="blocs-form" novalidate data-success-msg="Your message was sent succsessfuly" data-fail-msg="Ups! something go wrong, try again.">

                            Name

                        <input id="name_46788" class="form-control" required data-validation-required-message="Send your name" />

                            Email

                        <input id="email_46788" class="form-control" type="email" required data-validation-required-message="Invalid Email" />

                            Tell us about you

                        <textarea id="message_46788" class="form-control" rows="4" cols="50" required data-validation-required-message="Invalid Message"></textarea>

                    <button class="btn btn-primary" type="submit">
                        Send
                    </button>
                </form>

```

<p><strong>PHP (file name: form_contact.php)</strong></p>

```<?php
    if(empty($_POST['name_contact']) && strlen($_POST['name_contact']) == 0 || empty($_POST['email_contact']) && strlen($_POST['email_contact']) == 0 || empty($_POST['message_contact']) && strlen($_POST['message_contact']) == 0)
    {
        return false;
    }

    $name_contact = $_POST['name_contact'];
    $email_contact = $_POST['email_contact'];
    $message_contact = $_POST['message_contact'];

    $to = 'irivero@ngine.digital'; // Email submissions are sent to this email

    // Create email
    $email_subject = "Mensaje desde el website";
    $email_body = "Haz recibido un mensaje desde la página web \n\n".
                  "Name_contact: $name_contact \nEmail_contact: $email_contact \nMessage_contact: $message_contact \n";
    $headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
    $headers .= "From: web@site.com\n";
    $headers .= "Reply-To: $email_contact";

    mail($to,$email_subject,$email_body,$headers); // Post message
    return true;
?>
```

The actual result I need to get is:

If some field don't have any information, the data-validation in the form inputs need to show the data-validation-required-message="error" message.

If all the fields are correct, the script will work and I will recieve the contact form in my mail.

答:
Ok, your code presents some errors, I edited your code to get it working, I added some extra validations through php (better than html5), now should works fine, I have not tested all code, let me know if it's enough for you...

form.php

```<code><?php @ini_set('default_charset', 'UTF-8'); ?>
<!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="pragma" content="no-cache">
  <meta name="robots" content="noindex, nofollow">
  <title>Contact Form</title>
  <link rel="stylesheet" type="text/css" media="all" href="form.css">
  <link rel="shortcut icon" href="/favicon.ico">
</head>

<body>

<div class="row justify-content-center" style="width: 100%">
  <div class="col-10 col-md-6 justify-content-center align-self-center">
    <p class="error"><?php if (isset($error)) { echo $error; } ?></p>
    <form name="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], NULL, 'UTF-8'); ?>" method="post">
      <div class="form-group">
        <label>Name</label>
        <input name="name_contact" id="name_contact" placeholder="Your Name..." value="<?php if (isset($_POST['name_contact'])) { echo htmlentities($_POST['name_contact'], ENT_QUOTES, 'UTF-8'); } ?>">
      </div>
      <div class="form-group">
        <label>Email</label>
        <input name="email_contact" id="email_contact" placeholder="Your Email Address..." value="<?php if (isset($_POST['email_contact'])) { echo htmlentities($_POST['email_contact'], ENT_QUOTES, 'UTF-8'); } ?>">
      </div>
      <div class="form-group">
        <label>Tell us about you</label><br />
        <textarea name="message_contact" id="message_contact" class="form-control" rows="4" cols="50" placeholder="Your Message..."><?php if (isset($_POST['message_contact'])) { echo htmlentities($_POST['message_contact'], ENT_QUOTES, 'UTF-8'); } ?></textarea>
      </div>
      <button class="btn btn-primary" name="submit" type="submit">Send</button>
    </form>
  </div>
</div>

</body>

</html>
</code>```

contact.php

```<code><?php
@ini_set('default_charset', 'UTF-8');
if (!isset($_POST['name_contact']) || !isset($_POST['email_contact']) || !isset($_POST['message_contact'])) {
  $error = "Please, fill all required fields!";
  include("./form.php");
  exit();
}
if (!isset($_POST['name_contact']) || empty($_POST['name_contact']) || strlen($_POST['name_contact']) == 0) {
  $error = "Please, provide a valid email name!";
  include("./form.php");
  exit();
} else {
  $name_contact = htmlentities($_POST['name_contact'], ENT_QUOTES, 'UTF-8');
}
if (!isset($_POST['email_contact']) || empty($_POST['email_contact']) || strlen($_POST['email_contact']) == 0 || !preg_match("/^[a-zA-Z0-9]+([_\\.-][a-zA-Z0-9]+)*". "@([a-zA-Z0-9]+([\.-][a-zA-Z0-9]+))+$/", $_POST['email_contact'])) {
  $error = "Please, provide a valid email address!";
  include("./form.php");
  exit();
} else {
  $email_contact = $_POST['email_contact'];
}
if (!isset($_POST['message_contact']) || empty($_POST['message_contact']) || strlen($_POST['message_contact']) == 0) {
  $error = "Please, provide a valid email message!";
  include("./form.php");
  exit();
} else {
  $message_contact = htmlentities($_POST['message_contact'], ENT_QUOTES, 'UTF-8');
}
if (isset($_POST['submit'])) {
  $to = 'irivero@ngine.digital'; // Email submissions are sent to this email
  // Create email
  $email_subject = "Mensaje desde el website";
  $email_body = "Haz recibido un mensaje desde la página web\n\n" . "Name_contact: $name_contact\nEmail_contact: $email_contact\nMessage_contact: $message_contact\n";
  $headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
  $headers .= "From: web@site.com\n";
  $headers .= "Reply-To: $email_contact";
  if (mail($to,$email_subject,$email_body,$headers)) { // Post message
    $error = "SUCCESS: Your Message is Sent!";
    include("./form.php");
    exit();
  } else {
    $error = "WARNING: Your Message cannot be Sent!";
    include("./form.php");
    exit();
  }
}
?>
</code>```

Just load contact.php to get the html form working... I hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I'm working in a contact section in a website and I need to send all the contact form's to a mail.

The problem is, I have a php script who make all the job, but; when I click "send", the site refresh and the url changes from "www.site.com/contact.html" to "www.site.com/contact.html?".

By the way, I'm working with Bootstrap and PHP 5.

I think the problem is the form is don't recognize the script or I don't linked the script with the form correctly. I tried to use the action="form_contact.php property in the html form tag.

HTML

                <form id="form_46788" data-form-type="blocs-form" novalidate data-success-msg="Your message was sent succsessfuly" data-fail-msg="Ups! something go wrong, try again.">

                            Name

                        <input id="name_46788" class="form-control" required data-validation-required-message="Send your name" />

                            Email

                        <input id="email_46788" class="form-control" type="email" required data-validation-required-message="Invalid Email" />

                            Tell us about you

                        <textarea id="message_46788" class="form-control" rows="4" cols="50" required data-validation-required-message="Invalid Message"></textarea>

                    <button class="btn btn-primary" type="submit">
                        Send
                    </button>
                </form>

PHP (file name: form_contact.php)

<?php
    if(empty($_POST['name_contact']) && strlen($_POST['name_contact']) == 0 || empty($_POST['email_contact']) && strlen($_POST['email_contact']) == 0 || empty($_POST['message_contact']) && strlen($_POST['message_contact']) == 0)
    {
        return false;
    }

    $name_contact = $_POST['name_contact'];
    $email_contact = $_POST['email_contact'];
    $message_contact = $_POST['message_contact'];

    $to = 'irivero@ngine.digital'; // Email submissions are sent to this email

    // Create email
    $email_subject = "Mensaje desde el website";
    $email_body = "Haz recibido un mensaje desde la página web \n\n".
                  "Name_contact: $name_contact \nEmail_contact: $email_contact \nMessage_contact: $message_contact \n";
    $headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
    $headers .= "From: web@site.com\n";
    $headers .= "Reply-To: $email_contact";

    mail($to,$email_subject,$email_body,$headers); // Post message
    return true;
?>

The actual result I need to get is:

If some field don't have any information, the data-validation in the form inputs need to show the data-validation-required-message="error" message.

If all the fields are correct, the script will work and I will recieve the contact form in my mail.

Body:
Ok, your code presents some errors, I edited your code to get it working, I added some extra validations through php (better than html5), now should works fine, I have not tested all code, let me know if it's enough for you...

form.php

<?php @ini_set('default_charset', 'UTF-8'); ?>
<!DOCTYPE html>

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="pragma" content="no-cache">
  <meta name="robots" content="noindex, nofollow">
  <title>Contact Form</title>
  <link rel="stylesheet" type="text/css" media="all" href="form.css">
  <link rel="shortcut icon" href="/favicon.ico">
</head>

<body>

<div class="row justify-content-center" style="width: 100%">
  <div class="col-10 col-md-6 justify-content-center align-self-center">
    <p class="error"><?php if (isset($error)) { echo $error; } ?></p>
    <form name="form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], NULL, 'UTF-8'); ?>" method="post">
      <div class="form-group">
        <label>Name</label>
        <input name="name_contact" id="name_contact" placeholder="Your Name..." value="<?php if (isset($_POST['name_contact'])) { echo htmlentities($_POST['name_contact'], ENT_QUOTES, 'UTF-8'); } ?>">
      </div>
      <div class="form-group">
        <label>Email</label>
        <input name="email_contact" id="email_contact" placeholder="Your Email Address..." value="<?php if (isset($_POST['email_contact'])) { echo htmlentities($_POST['email_contact'], ENT_QUOTES, 'UTF-8'); } ?>">
      </div>
      <div class="form-group">
        <label>Tell us about you</label><br />
        <textarea name="message_contact" id="message_contact" class="form-control" rows="4" cols="50" placeholder="Your Message..."><?php if (isset($_POST['message_contact'])) { echo htmlentities($_POST['message_contact'], ENT_QUOTES, 'UTF-8'); } ?></textarea>
      </div>
      <button class="btn btn-primary" name="submit" type="submit">Send</button>
    </form>
  </div>
</div>

</body>

</html>

contact.php

<?php
@ini_set('default_charset', 'UTF-8');
if (!isset($_POST['name_contact']) || !isset($_POST['email_contact']) || !isset($_POST['message_contact'])) {
  $error = "Please, fill all required fields!";
  include("./form.php");
  exit();
}
if (!isset($_POST['name_contact']) || empty($_POST['name_contact']) || strlen($_POST['name_contact']) == 0) {
  $error = "Please, provide a valid email name!";
  include("./form.php");
  exit();
} else {
  $name_contact = htmlentities($_POST['name_contact'], ENT_QUOTES, 'UTF-8');
}
if (!isset($_POST['email_contact']) || empty($_POST['email_contact']) || strlen($_POST['email_contact']) == 0 || !preg_match("/^[a-zA-Z0-9]+([_\\.-][a-zA-Z0-9]+)*". "@([a-zA-Z0-9]+([\.-][a-zA-Z0-9]+))+$/", $_POST['email_contact'])) {
  $error = "Please, provide a valid email address!";
  include("./form.php");
  exit();
} else {
  $email_contact = $_POST['email_contact'];
}
if (!isset($_POST['message_contact']) || empty($_POST['message_contact']) || strlen($_POST['message_contact']) == 0) {
  $error = "Please, provide a valid email message!";
  include("./form.php");
  exit();
} else {
  $message_contact = htmlentities($_POST['message_contact'], ENT_QUOTES, 'UTF-8');
}
if (isset($_POST['submit'])) {
  $to = 'irivero@ngine.digital'; // Email submissions are sent to this email
  // Create email
  $email_subject = "Mensaje desde el website";
  $email_body = "Haz recibido un mensaje desde la página web\n\n" . "Name_contact: $name_contact\nEmail_contact: $email_contact\nMessage_contact: $message_contact\n";
  $headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
  $headers .= "From: web@site.com\n";
  $headers .= "Reply-To: $email_contact";
  if (mail($to,$email_subject,$email_body,$headers)) { // Post message
    $error = "SUCCESS: Your Message is Sent!";
    include("./form.php");
    exit();
  } else {
    $error = "WARNING: Your Message cannot be Sent!";
    include("./form.php");
    exit();
  }
}
?>

Just load contact.php to get the html form working... I hope this helps.


问:
Getting html from site c#
I need to parse some data from this page https://warcraft3.info/replays/18723

Only WebBrowser helps me to get more html part, but I can't get all html text still. But WebBrowser control shows page correctly.

When I save page using browser I get what I need.

Can anybody help me with some advice?

```<code> var d = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.Body.OuterHtml;
</code>```

答:
HTML Agility Pack

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

I've personally used this for different projects. It's easy and friendly to use.

Title: Getting html from site c#

Body:
I need to parse some data from this page https://warcraft3.info/replays/18723

Only WebBrowser helps me to get more html part, but I can't get all html text still. But WebBrowser control shows page correctly.

When I save page using browser I get what I need.

Can anybody help me with some advice?

 var d = (wfhSample.Child as System.Windows.Forms.WebBrowser).Document.Body.OuterHtml;


问:
SELECT subCategory which equals parentCategory = value from outer table
I have a products table and I need to put discount on some products from a given sub category, which has parent category in another table.

```<code>TABLE products:

category_id      sku      discount
-----------------------------------
8             3141          NULL
7             4333          NULL
7             601           NULL
3             405           NULL

TABLE product_category:

id      parent_id           slug
-----------------------------------
8             18          somename
7             3           somename
</code>```

It's a pretty simple question but I can't figure out how to use the parent_id column to update my products table simply, instead of writing down every subcategory id like this:

```<code>UPDATE products
SET discount = 25
WHERE category_id IN (1,4,5,6 etc..);
</code>```

I want to update the products table by selecting the subcategory's parent id from the product_category table.

答:
Are you looking for something like this-</p>

```<code>UPDATE products
SET discount = 25
WHERE category_id IN (SELECT Parent_id FROM Product_Category);
</code>```

Body:
I have a products table and I need to put discount on some products from a given sub category, which has parent category in another table.

TABLE products:

category_id      sku      discount
-----------------------------------
8             3141          NULL
7             4333          NULL
7             601           NULL
3             405           NULL

TABLE product_category:

id      parent_id           slug
-----------------------------------
8             18          somename
7             3           somename

It's a pretty simple question but I can't figure out how to use the parent_id column to update my products table simply, instead of writing down every subcategory id like this:

UPDATE products
SET discount = 25
WHERE category_id IN (1,4,5,6 etc..);

I want to update the products table by selecting the subcategory's parent id from the product_category table.

Body:
Are you looking for something like this-

UPDATE products
SET discount = 25
WHERE category_id IN (SELECT Parent_id FROM Product_Category);


问:
Python: Getting all pairs and frequency of pairs in multi-dimensional list
my multi-dimensional list looks as follows:

```<code>    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]
</code>```

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

```<code>    fr_list = [[12,13],[12,13],[28,29],[34,35]]
</code>```

I wrote the following code to find the pairs

```<code>    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]
</code>```

Then, I tried this:

```<code>    fr_list = [find_pairs(mylist,1) for x in mylist]
</code>```

However, I get the following error message:

```<code>    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'
</code>```

Can anybody help me out? Thanks.

答: Your code is functionally correct, but your final list comprehension is incorrect. It should be fr_list = [find_pairs(x,1) for x in mylist]. In your case, you attempt to put a list of lists into your find_pairs function. However, changing mylist to x means you are iterating through each nested list, not the entire list of lists for every nested list.

Body:
my multi-dimensional list looks as follows:

    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

    fr_list = [[12,13],[12,13],[28,29],[34,35]]

I wrote the following code to find the pairs

    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]

Then, I tried this:

    fr_list = [find_pairs(mylist,1) for x in mylist]

However, I get the following error message:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'

Can anybody help me out? Thanks.


问:
Calculate Points from Letters in a Switch Case
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

```<code>/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }
</code>```

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

答:
Thanks everyone, I ended up with the following code which gives the output  I am after;</p>

```<code>  System.out.println("Points problem");

             File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + file);
        System.exit(0);
    } else {
        System.out.println("Successfully opened file: " + file + ".");
    }
    //read all the lines in the file//

    while (input.hasNext()) {
        String word = input.nextLine();
        //System.out.println(word);
        int l = word.length();
        int point = 0;
        for (int x = 0; x < l; x++) {
            char c = word.charAt(x);
            switch (c) {

                case 'a':
                case 'e':
                case 'i':
                case 'l':
                case 'n':
                case 'o':
                case 'r':
                case 's':
                case 't':
                case 'u':
                    point += 1;
                    break;

                case 'd':
                case 'g':
                    point += 2;
                    break;

                case 'b':
                case 'c':
                case 'm':
                case 'p':
                    point += 3;
                    break;

                case 'f':
                case 'h':
                case 'v':
                case 'w':
                case 'y':
                    point += 4;
                    break;

                case 'k':
                    point += 5;
                    break;

                case 'j':
                case 'x':
                    point += 8;
                    break;

                case 'q':
                case 'z':
                    point += 10;
                    break;
            }//end switch*/
        }//end point calculation loop
        System.out.println(word + "is worth " + point + " points." );
    }
</code>```

Body:
I am trying to create a scrabble-like program that calculates the points of letters contained in a word. These word are contained in a .txt file. I can get it to read from the file, but unsure how to get it to calculate the value of each word. I have attached what I have done so far, and am wondering if a switch case is the best way to go, and if so, how do I assign a value to a letter with a switch case. Any help is appreciated.

/*
 * To change this license header, choose License Headers in Project      Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
 package pointsproblem;

/**
 *
 */

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

 public class PointsProblem {

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 */
 public static void main(String[] args) throws FileNotFoundException {
    // TODO code application logic here

    //create new object//
    PointsProblem task1 = new PointsProblem();

    File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + input);
        System.exit(0);
    }
    else {
        System.out.println("Successfully opened file: " + input + ".");
    }
    //read all the lines in the file//
   {
        while (input.hasNext()) {
            String word = input.nextLine();
            System.out.println(word);
            System.out.println("'" + input + "' is worth " + point + " points");

    int point = "";
    switch(point)  {

    case 'a': = "1":
    case 'e': = "1";
    case 'i': = "1";
    case 'l': = "1";
    case 'n': = "1";
    case 'o': = "1";
    case 'r': = "1";
    case 's': = "1";
    case 't': = "1";
    case 'u': = "1";
    case 'g': = "2";
    case 'g': = "2";
    case 'b': = "3";
    case 'm': = "3";
    case 'c': = "3";
    case 'p': = "3";
    case 'f': = "4";
    case 'h': = "4";
    case 'v': = "4";
    case 'w': = "4";
    case 'y': = "4";
    case 'k': = "5";
    case 'j': = "8";
    case 'x': = "8";
    case 'q': = "10";
    case 'z': = "10";

    return score  =  point + "";
        }//end switch

     }//end point calculation loop

    public int getScore() {
        return score;
    }
    //public boolean containsLetter(Character letter) {
        //return points.contains(letter);//

    }

I have tried assigning an int of X to the value as well. I would like it to read the word contained in the file and give a total score.

Body:
Thanks everyone, I ended up with the following code which gives the output  I am after;

  System.out.println("Points problem");

             File file = new File("dictionary.txt");
    // read the file//
    Scanner input = new Scanner(file);

    //check if file can be found//
    if (!file.isFile()) {
        System.err.println("Cannot open file: " + file);
        System.exit(0);
    } else {
        System.out.println("Successfully opened file: " + file + ".");
    }
    //read all the lines in the file//

    while (input.hasNext()) {
        String word = input.nextLine();
        //System.out.println(word);
        int l = word.length();
        int point = 0;
        for (int x = 0; x < l; x++) {
            char c = word.charAt(x);
            switch (c) {

                case 'a':
                case 'e':
                case 'i':
                case 'l':
                case 'n':
                case 'o':
                case 'r':
                case 's':
                case 't':
                case 'u':
                    point += 1;
                    break;

                case 'd':
                case 'g':
                    point += 2;
                    break;

                case 'b':
                case 'c':
                case 'm':
                case 'p':
                    point += 3;
                    break;

                case 'f':
                case 'h':
                case 'v':
                case 'w':
                case 'y':
                    point += 4;
                    break;

                case 'k':
                    point += 5;
                    break;

                case 'j':
                case 'x':
                    point += 8;
                    break;

                case 'q':
                case 'z':
                    point += 10;
                    break;
            }//end switch*/
        }//end point calculation loop
        System.out.println(word + "is worth " + point + " points." );
    }


问:
Golang: Unmarshal Self Closing Tags
So I'm trying to Unmarshal an XML file generated as a save file by another program in Google Go. It seems to be going great as the documentation on this is quite extensive: http://golang.org/pkg/encoding/xml/#Unmarshal

Still I'm running into a problem. The output in the save file is like this:

```<code><location id="id4" x="-736" y="-544">
    <committed />
</location>
</code>```

Instead of committed, a location can also be urgent or neither. The locations can also have a name and different labels, but these seem to be parsing just fine.
In my Go code I'm using the following struct:

```<code>type Location struct {
    Id string `xml:"id,attr"`
    Committed bool `xml:"commited"`
    Urgent bool `xml:"urgent"`
    Labels []Label `xml:"label"`
}
</code>```

And although the Unmarshal function of the encoding/xml package runs without errors and the shown example is present in the data, all the values of both committed and urgent are "false".

What should I change to get the right values for these two fields?

(Unmarshalling is done using the following piece of code)

```<code>xmlFile, err := os.Open("model.xml")
if err != nil {
    fmt.Println("Error opening file:", err)
    return
}
defer xmlFile.Close()

b, _ := ioutil.ReadAll(xmlFile)

var xmlScheme uppaal.UppaalXML
err = xml.Unmarshal(b, &xmlScheme)
fmt.Println(err)
</code>```

答:
My case is different: I create app in golang as a forwarder to submit from api-a to api-b.
While api-a may generating a tag without closing and golang will not able to read it, which will not be read by api-b. Therefore I create two classes which one is reader and other is poster(sender).

maybe this will give some insight to others.

```<code>package main

import (
    "encoding/xml"
    "fmt"
)

type MyDataReader struct {
    Name string `xml:"name"`
    Lulus *struct{} `xml:"lulus"`
}

type MyDataPoster struct {
    Name string `xml:"name"`
    Lulus string `xml:"lulus"`
}

func ToPoster(m MyDataReader) MyDataPoster {
    res := MyDataPoster{}
    res.Name = m.Name
    if m.Lulus != nil {
        res.Lulus = "1"
    }
    return res
}

func main() {
    xmlString := `<data>
        <name>richard</name>
        <lulus />
    </data>`

    m := MyDataReader{}
    err := xml.Unmarshal([]byte(xmlString), &m)
    fmt.Println(err, m)

    mpost := ToPoster(m)
    output, errenc := xml.MarshalIndent(mpost, "", "    ")
    fmt.Println(errenc, string(output))
}
</code>```

I create two class. One for retrieving and parsing and one for submit the xml.

ContentLicense: CC BY-SA 3.0

Title: Golang: Unmarshal Self Closing Tags

Body:
So I'm trying to Unmarshal an XML file generated as a save file by another program in Google Go. It seems to be going great as the documentation on this is quite extensive: http://golang.org/pkg/encoding/xml/#Unmarshal

Still I'm running into a problem. The output in the save file is like this:

<location id="id4" x="-736" y="-544">
    <committed />
</location>

Instead of committed, a location can also be urgent or neither. The locations can also have a name and different labels, but these seem to be parsing just fine.
In my Go code I'm using the following struct:

type Location struct {
    Id string `xml:"id,attr"`
    Committed bool `xml:"commited"`
    Urgent bool `xml:"urgent"`
    Labels []Label `xml:"label"`
}

And although the Unmarshal function of the encoding/xml package runs without errors and the shown example is present in the data, all the values of both committed and urgent are "false".

What should I change to get the right values for these two fields?

(Unmarshalling is done using the following piece of code)

xmlFile, err := os.Open("model.xml")
if err != nil {
    fmt.Println("Error opening file:", err)
    return
}
defer xmlFile.Close()

b, _ := ioutil.ReadAll(xmlFile)

var xmlScheme uppaal.UppaalXML
err = xml.Unmarshal(b, &xmlScheme)
fmt.Println(err)

Body:
My case is different: I create app in golang as a forwarder to submit from api-a to api-b.
While api-a may generating a tag without closing and golang will not able to read it, which will not be read by api-b. Therefore I create two classes which one is reader and other is poster(sender).

maybe this will give some insight to others.

package main

import (
    "encoding/xml"
    "fmt"
)

type MyDataReader struct {
    Name string `xml:"name"`
    Lulus *struct{} `xml:"lulus"`
}

type MyDataPoster struct {
    Name string `xml:"name"`
    Lulus string `xml:"lulus"`
}

func ToPoster(m MyDataReader) MyDataPoster {
    res := MyDataPoster{}
    res.Name = m.Name
    if m.Lulus != nil {
        res.Lulus = "1"
    }
    return res
}

func main() {
    xmlString := `<data>
        <name>richard</name>
        <lulus />
    </data>`

    m := MyDataReader{}
    err := xml.Unmarshal([]byte(xmlString), &m)
    fmt.Println(err, m)

    mpost := ToPoster(m)
    output, errenc := xml.MarshalIndent(mpost, "", "    ")
    fmt.Println(errenc, string(output))
}

I create two class. One for retrieving and parsing and one for submit the xml.


问:
Concourse CI/CD - passing concourse credentials as shell script parameters
I am pretty much new and learning the ropes of setting up and running a concourse CI/CD pipeline.
One of my build tasks requires credentials stored in the concourse credential manager. They need to be passed as parameters to my shell script.
How do I pass them as arguments?

My shell script runs as : ci/scripts/build.sh -u username -p password

username and password are to be picked up from the credentials manager

my concourse pipeline task is set up as

```<code>    - task: build
    config:
      platform: linux
      image_resource:
        source:
          repository: java
          tag: "8"
        type: docker-image
      inputs:
        - name: resource-repo
      outputs:
        - name: artifacts
      run:
        path: ci/scripts/build.sh
      params:
        u: ((artifactory_user))
        p: ((artifactory_password))
</code>```

This doesn't seem to work. I guess there must be a better way to do it.

答:
You are almost there. From the task params documentation:

params: {string: string} Optional. A key-value mapping of values
  that are exposed to the task via environment variables.

Use this to provide things like credentials to a task.

So your shell script becomes

```<code>ci/scripts/build.sh -u ${u} -p ${p}
</code>```

Body:
I am pretty much new and learning the ropes of setting up and running a concourse CI/CD pipeline.
One of my build tasks requires credentials stored in the concourse credential manager. They need to be passed as parameters to my shell script.
How do I pass them as arguments?

My shell script runs as : ci/scripts/build.sh -u username -p password

username and password are to be picked up from the credentials manager

my concourse pipeline task is set up as

    - task: build
    config:
      platform: linux
      image_resource:
        source:
          repository: java
          tag: "8"
        type: docker-image
      inputs:
        - name: resource-repo
      outputs:
        - name: artifacts
      run:
        path: ci/scripts/build.sh
      params:
        u: ((artifactory_user))
        p: ((artifactory_password))

This doesn't seem to work. I guess there must be a better way to do it.

Body:
You are almost there. From the task params documentation:

params: {string: string} Optional. A key-value mapping of values
  that are exposed to the task via environment variables.

Use this to provide things like credentials to a task.

So your shell script becomes

ci/scripts/build.sh -u ${u} -p ${p}


问:
JavaScript load event execution sequence
I have the following code:

```
//create a tab and active it
var tab = gBrowser.addTab("chrome://xxx/content/html/xxx.html");
gBrowser.selectedTab = tab
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("load", function () {
    //event 1.
    }, true);
```

where xxx.html has:

```<code><script>
$(document).ready(function(){
        //event 2
});
$(window).load(function(){
    //event 3
});
</script>
</code>```

I understand that event 2 is fired before event 3.
And event 1 is fired before event 3 by place a alert(), can anyone explain me the reason of this. Or the sequence of 1 and 3 are unpredicted.

答:
Not quite sure about exactly what event 1 is - I'm guessing this is a Firefox plugin so it's actually triggering as soon as the tab itself loads rather than the document inside it.

Event 2 will fire as soon as the complete HTML DOM is ready, but before all external resources load (such as images and stylesheets).  Event 3 will only fire when all external resources have completed loading.

Body:
I have the following code:

//create a tab and active it
var tab = gBrowser.addTab("chrome://xxx/content/html/xxx.html");
gBrowser.selectedTab = tab
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("load", function () {
    //event 1.
    }, true);

where xxx.html has:

I understand that event 2 is fired before event 3.
And event 1 is fired before event 3 by place a alert(), can anyone explain me the reason of this. Or the sequence of 1 and 3 are unpredicted.


问:
Is there a way to change version code in flutter
I'm setting up the app to upload on play store but the play console gives error-You need to use a different version code for your APK or Android App Bundle because you already have one with version code 1.
   I tried changing the version code in android>app>build.gradle and even in local.properties but after hot reload or run command the local.properties automatically changes back to flutter.versionName=1.0.0 and flutter.versionCode=1.
   It may be because of error in my build.gradle file as it shows red mark and give can't resolve symbol for properties,rootProperties,getProperty etc. and the same error with flutter.buildMode=release in local.properties
   How can I solve this issue?</p>

答:
Instead of changing Gradle files, you need to make the changes in pubspec.yaml file.

It is located in the root directory of your project.

version: 1.0.0+1
```

A version number is three numbers separated by dots, like 1.2.43

followed by an optional build number separated by a +.

Google Play should accept your APK generated with increased build number.

Body:
Instead of changing Gradle files, you need to make the changes in pubspec.yaml file.

It is located in the root directory of your project.

version: 1.0.0+1

A version number is three numbers separated by dots, like 1.2.43

followed by an optional build number separated by a +.

Google Play should accept your APK generated with increased build number.


问:
pushed code to gerrit after cherry-pick by mistake
My code is based on a cherry-pick I have done to another patch.
I pushed it by mistake as the other patch is not ready yet. So in gerrit I see the other patch files as well.
How do I make now my pushed patch re-based without the other files that came in from the other patch?</p>

答:
To restore the branch to where it was before the cherry-pick, do this (where n is the number of cherry-picked commits):

```<code>git reset --hard HEAD~n
git push -f
</code>```

Note that a force-push might mess up the commit history for anyone who has pulled your branch after your cherry-pick.

If you want to cherry-pick parts of a commit (just the one file), it can for instance be done this way:

```<code>git cherry-pick <hash>
git reset --soft HEAD~1
//revert unwanted changes and commit
git push
</code>```

Body:
To restore the branch to where it was before the cherry-pick, do this (where n is the number of cherry-picked commits):

git reset --hard HEAD~n
git push -f

Note that a force-push might mess up the commit history for anyone who has pulled your branch after your cherry-pick.

If you want to cherry-pick parts of a commit (just the one file), it can for instance be done this way:

git cherry-pick <hash>
git reset --soft HEAD~1
//revert unwanted changes and commit
git push


问:
State stays the same when using event listeners
https://codesandbox.io/s/state-shenanigans-mifyg

This code example is a bit un-orthodox, but it still puzzles me so I decided to form it into a question.

Please open the link above and play with the example. Keep the console open as well.

When the form changes I'm calling console.log, passing it the state. As you can see when changing the question it logs the right value (the new question with the existing answer).

But if you then change the answer you find that the old question is logged out with the new answer.

I guess it has something to do with closures, but I couldn't figure it out.

```<code>import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
      });
    }
  }, []);

  return (
    <div>
      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />
    </div>
  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);
</code>```

答:
I'm not sure what you mean by "old" and "new" question, since there's only one question. In any case, you don't have to use DOM references and manual EvenListeners in React. React was invented to handle that kind of stuff for you!</p>

```<code>function Faq({ onChange, data }) {

  const handleChange = (e) => {
    console.log("the new value is")
    console.log(e.currentTarget.value)
  }

  return (
    <div>
      <input onChange={handleChange} type="text" defaultValue={data.question} />
      <input onChange={handleChange} type="text" defaultValue={data.answer} />
    </div>
  );
}
</code>```

Body:
https://codesandbox.io/s/state-shenanigans-mifyg

This code example is a bit un-orthodox, but it still puzzles me so I decided to form it into a question.

Please open the link above and play with the example. Keep the console open as well.

When the form changes I'm calling console.log, passing it the state. As you can see when changing the question it logs the right value (the new question with the existing answer).

But if you then change the answer you find that the old question is logged out with the new answer.

I guess it has something to do with closures, but I couldn't figure it out.

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

function Faq({ onChange, data }) {
  const questionRef = React.createRef<HTMLInputElement>();
  const answerRef = React.createRef<HTMLInputElement>();

  React.useEffect(() => {
    if (questionRef.current) {
      questionRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, question: e.target.value });
      });
    }

    if (answerRef.current) {
      answerRef.current.addEventListener("keydown", (e: any) => {
        onChange({ ...data, answer: e.target.value });
      });
    }
  }, []);

  return (

      <input ref={questionRef} type="text" defaultValue={data.question} />
      <input ref={answerRef} type="text" defaultValue={data.answer} />

  );
}

const App = () => {
  const [faq, setFaq] = React.useState({
    id: "1",
    question: "I am a question?",
    answer: "I am the answer!"
  });
  React.useEffect(() => {
    console.log(faq);
  }, [faq]);
  return <Faq data={faq} onChange={setFaq} />;
};

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Body:
I'm not sure what you mean by "old" and "new" question, since there's only one question. In any case, you don't have to use DOM references and manual EvenListeners in React. React was invented to handle that kind of stuff for you!

function Faq({ onChange, data }) {

  const handleChange = (e) => {
    console.log("the new value is")
    console.log(e.currentTarget.value)
  }

  return (
    <div>
      <input onChange={handleChange} type="text" defaultValue={data.question} />
      <input onChange={handleChange} type="text" defaultValue={data.answer} />
    </div>
  );
}


问:
How to read text file in classic asp
I am uploading image.While uploading images i am saving image name and the link for that iage in one textfile.
like this,
abc.jpeg,http://google.com

Now i want to display all that images with corresponding links using classic asp.

How should I do this?

Please help.

I used this asp code:

<%
For Each FileName in fold.Files
Dim Fname
Dim strFileName
Dim objFSO
Dim objTextFile
Dim URLString
Dim strReadLineText

Fname= mid(FileName.Path,instrrev(FileName.Path,"\\")+1)
strFileName = "../admin/Links.txt"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName))

URLString=""

Do While Not objTextFile.AtEndOfStream
    strReadLineText = objTextFile.ReadLine
    'response.Write(strReadLineText & "
")

    If strReadLineText<>"" then
        If Instr(strReadLineText,",")>0 then
            strReadLineTextArr=split(strReadLineText,",")
            response.Write(strReadLineTextArr(0))
            URLString=strReadLineTextArr(1)
        end if
    end if
Loop

' Close and release file references

objTextFile.Close

Set objTextFile = Nothing

Set objFSO = Nothing
```

its displaying all images but for all images link is same.its reading directly the last link from textfile....What is the problem with my code?

答:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
// Fajlovi
using System.IO;

namespace A7
{
    public partial class redvoznje : System.Web.UI.Page
    {
        class Red {
            public int Rbr { get; set; }
            public string Vreme { get; set; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack) {

                string[] fajlovi = Directory.GetFiles(Server.MapPath("linije"));

                for (int i = 0; i < fajlovi.Length; i++) {

                    string ime = Path.GetFileNameWithoutExtension(fajlovi[i]);

                    LinijaLista.Items.Add(ime);
                }

                string trenutnaLinija = LinijaLista.Text;

                using (StreamReader sr =
                    new StreamReader(Server.MapPath("linije" + "/" + trenutnaLinija + ".txt"))) {
                        string linija;

                        while ((linija = sr.ReadLine()) != null) {

                            if (linija.StartsWith("SMER")) {
                                string smer = linija.Substring(5);
                                SmerLista.Items.Add(smer);
                            }
                        }
                }

            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            Table1.Rows.Clear();

            string trenutnaLinija = LinijaLista.Text;
            string smer = SmerLista.Text;

            List<Red> redovi = new List<Red>();

            using (StreamReader sr =
                    new StreamReader(Server.MapPath("linije" + "/" + trenutnaLinija + ".txt")))
            {
                string linija;
                bool stani = false;
                bool pronadjenaLinija = false;
                int rbr = -1;

                while ((linija = sr.ReadLine()) != null)
                {
                    if (linija.StartsWith("SMER:" + smer))
                    {
                        pronadjenaLinija = true;
                    }

                    if (pronadjenaLinija)
                    {
                        if (linija.StartsWith("SMER") && !linija.StartsWith("SMER:" + smer))
                        {
                            stani = true;
                        }

                        if (!stani)
                        {
                            rbr++;
                            redovi.Add(new Red() { Rbr = rbr, Vreme = linija });
                        }
                    }
                }
            }

            redovi.RemoveAt(0);

            TableRow zaglavlje = new TableRow();

            TableCell kol1 = new TableCell();
            TableCell kol2 = new TableCell();

            kol1.Text = "Redni broj polaska";
            kol2.Text = "Vreme polaska";

            zaglavlje.Controls.Add(kol1);
            zaglavlje.Controls.Add(kol2);

            Table1.Rows.Add(zaglavlje);

            for (int i = 0; i < redovi.Count; i++)
            {
                TableRow red = new TableRow();

                TableCell rbrKol = new TableCell();
                TableCell vremeKol = new TableCell();

                rbrKol.Text = redovi[i].Rbr.ToString();
                vremeKol.Text = redovi[i].Vreme;

                red.Controls.Add(rbrKol);
                red.Controls.Add(vremeKol);

                Table1.Rows.Add(red);
            }

            Table1.Visible = true;

        }

        protected void LinijaLista_SelectedIndexChanged(object sender, EventArgs e)
        {
                SmerLista.Items.Clear();

                string trenutnaLinija = LinijaLista.Text;

                using (StreamReader sr =
                    new StreamReader(Server.MapPath("linije" + "/" + trenutnaLinija + ".txt")))
                {
                    string linija;

                    while ((linija = sr.ReadLine()) != null)
                    {

                        if (linija.StartsWith("SMER"))
                        {

                            string smer = linija.Substring(5);

                            SmerLista.Items.Add(smer);
                        }
                    }
                }

        }
    }
}```

Title: How to read text file in classic asp

Body:
I am uploading image.While uploading images i am saving image name and the link for that iage in one textfile.
like this,
abc.jpeg,http://google.com

Now i want to display all that images with corresponding links using classic asp.

How should I do this?

Please help.

I used this asp code:

<%
For Each FileName in fold.Files
Dim Fname
Dim strFileName
Dim objFSO
Dim objTextFile
Dim URLString
Dim strReadLineText

Fname= mid(FileName.Path,instrrev(FileName.Path,"\\")+1)
strFileName = "../admin/Links.txt"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Set objTextFile = objFSO.OpenTextFile(Server.MapPath(strFileName))

URLString=""

Do While Not objTextFile.AtEndOfStream
    strReadLineText = objTextFile.ReadLine
    'response.Write(strReadLineText & "
")

    If strReadLineText<>"" then
        If Instr(strReadLineText,",")>0 then
            strReadLineTextArr=split(strReadLineText,",")
            response.Write(strReadLineTextArr(0))
            URLString=strReadLineTextArr(1)
        end if
    end if
Loop

' Close and release file references

objTextFile.Close

Set objTextFile = Nothing

Set objFSO = Nothing

its displaying all images but for all images link is same.its reading directly the last link from textfile....What is the problem with my code?


问:
Getting an error when clicking a link element on a web page by a Selenium script
When my Selenium script clicks a link element presented on a web page by  click() method, I am getting the below error:

```<code>org.openqa.selenium.WebDriverException: Element is not clickable at point (36, 72).
</code>```

This is my HTML code

```<code><div id="targettab">
<a href="Default.aspx" id="highlight-book">Book</a>
</div>
</code>```

This is my Selenium code:

```<code>driver.findElement(By.id("highlight-book")).click();
</code>```

What am I doing wrong here? Could you please advise me about possible solutions? Thanks.

答:
If element is present in lot of nested divs, rarely selenium driver will fails to click element. You can try clicking using Enter button.</p>

```<code>driver.findElement(By.id("highlight-book")).sendKeys(Keys.Return);
</code>```

Body:
When my Selenium script clicks a link element presented on a web page by  click() method, I am getting the below error:

org.openqa.selenium.WebDriverException: Element is not clickable at point (36, 72).

This is my HTML code

Book

This is my Selenium code:

driver.findElement(By.id("highlight-book")).click();

What am I doing wrong here? Could you please advise me about possible solutions? Thanks.

Body:
If element is present in lot of nested divs, rarely selenium driver will fails to click element. You can try clicking using Enter button.

driver.findElement(By.id("highlight-book")).sendKeys(Keys.Return);


问:
php - Insert data from checkbox array into MySQL
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

```<code><div class="pscdiv"><input type="checkbox" class="psc" name="camps[]" value="psc_1"/><label for="psc_1">AM - Week 1: Camp Description</label></div>
</code>```

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

```<code>
    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}</p>

<p>// The above to create a comma separated string</p>

<p>$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma</p>

<p>$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");
```

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

```<code>
if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]<br />";
}
}
```

答:
A nice trick to remove the trailing comma would be.

```<code>$camp_string = rtrim($camp_string,',');
</code>```

Anyway your query is not formated correctly.

```<code>INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')
</code>```

You cannot have single quotes in the first bracket

Body:
I have a form for registering for weekly summer camps. There are checkboxes to select which camp the person is signing up for that look like this:

<input type="checkbox" class="psc" name="camps[]" value="psc_1"/>AM - Week 1: Camp Description

There are about 30 of them total. What I'm trying to do is take the $_POST['camps'] variable on the next page and break it into something I can insert into a MySQL table that has a structure like this:

regid | psc_1 | psc_2 | psc_3 | ...

My code:

    if(!empty($_POST['camps'])) {
$boxes=$_POST['camps'];
while (list ($k,$camp) = @each ($boxes)) {
    $camp_string .= "'$camp',";
}
}

// The above to create a comma separated string

$camp_string = (substr($camp_string,-1) == ',') ? substr($camp_string, 0, -1) : $camp_string;
// To remove the trailing comma

$newreg_camps = mysql_query("INSERT INTO camps_registered (regid,$camp_string) VALUES ($regid,$camp_string)");

The column names (other than regid which I specify earlier in the script) are the same as the data being put into them. It was the easiest thing I could think of at the time.

I'm not sure what I'm missing.

--
Update#1 (in reference to a comment below)

if(!empty($_POST['camps'])) {
    $box=$_POST['camps'];
    while (list ($key,$val) = @each ($box)) {
    $camp_totals += $campcost[$val];
    echo "$campdesc[$val] - $$campcost[$val]
";
}
}

Body:
A nice trick to remove the trailing comma would be.

$camp_string = rtrim($camp_string,',');

Anyway your query is not formated correctly.

INSERT INTO camps_registered (regid,'psc_1', 'psc_2', 'psc_3') VALUES ($regid,psc_1', 'psc_2', 'psc_3')

You cannot have single quotes in the first bracket


问:
Firebase storage security rules 400 error issue "Permission denied. Could not access bucket xxxxx-****.appspot.com"
I keeps getting message error from firebase link saying 400 error with my firebase storage upload in my react project when trying to upload photo... everything were working fine before and uploads images successfully, but now it stop uploading of photo giving the following error, i don't know where the problem is...

The link that prompt out in inspect

```<code>POST https://firebasestorage.googleapis.com/v0/b/xxxxx-****.appspot.com/o?name=usertemp%2F0rdrGK4MRDRptAMCc3mHDveytJv1%2F0rdrGK4MRDRptAMCc3mHDveytJv1.jpg 400 ()
</code>```

Here is the error from the link response

```<code>{
  "error": {
    "code": 400,
    "message": "Permission denied. Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources."
  }
</code>```

Here is my security

```<code>service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}
</code>```

I still tried changing the match to /b/xxxxx-****.appspot.com/o with still no success

答:
This error happend when you are trying to upload image before creating Firebase Storage which is specific for file uploading.

Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources

Thats why you are facing the error with message Please Enable Firebase Storage for your bucket because Firebase Storage act as default location for bucket media upload.

```<code>{
  "error": {
    "code": 400,
    "message": "Permission denied. Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources."
  }
</code>```

What to do?

Just Go to your project Firebase console  >> Storage >> and Just Click GET STARTED

Body:
I keeps getting message error from firebase link saying 400 error with my firebase storage upload in my react project when trying to upload photo... everything were working fine before and uploads images successfully, but now it stop uploading of photo giving the following error, i don't know where the problem is...

The link that prompt out in inspect

POST https://firebasestorage.googleapis.com/v0/b/xxxxx-****.appspot.com/o?name=usertemp%2F0rdrGK4MRDRptAMCc3mHDveytJv1%2F0rdrGK4MRDRptAMCc3mHDveytJv1.jpg 400 ()

Here is the error from the link response

{
  "error": {
    "code": 400,
    "message": "Permission denied. Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources."
  }

Here is my security

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth!=null;
    }
  }
}

I still tried changing the match to /b/xxxxx-****.appspot.com/o with still no success

Body:
This error happend when you are trying to upload image before creating Firebase Storage which is specific for file uploading.

Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources

Thats why you are facing the error with message Please Enable Firebase Storage for your bucket because Firebase Storage act as default location for bucket media upload.

{
  "error": {
    "code": 400,
    "message": "Permission denied. Could not access bucket xxxxx-****.appspot.com. Please enable Firebase Storage for your bucket by visiting the Storage tab in the Firebase Console and ensure that you have sufficient permission to properly provision resources."
  }

What to do?

Just Go to your project Firebase console  >> Storage >> and Just Click GET STARTED


问:
Statistics: combinations in Python
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat  libraries. Something like a function of the type:

```<code>comb = calculate_combinations(n, r)
</code>```

I need the number of possible combinations, not the actual combinations, so itertools.combinations does not interest me.

Finally, I want to avoid using factorials, as the numbers I'll be calculating the combinations for can get too big and the factorials are going to be monstrous.

This seems like a REALLY easy to answer question, however I am being drowned in questions about generating all the actual combinations, which is not what I want.

答:
Starting Python 3.8, the standard library now includes the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

```<code>import math
math.comb(10, 5) # 252
</code>```

Title: Statistics: combinations in Python

Body:
I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat  libraries. Something like a function of the type:

comb = calculate_combinations(n, r)

I need the number of possible combinations, not the actual combinations, so itertools.combinations does not interest me.

Finally, I want to avoid using factorials, as the numbers I'll be calculating the combinations for can get too big and the factorials are going to be monstrous.

This seems like a REALLY easy to answer question, however I am being drowned in questions about generating all the actual combinations, which is not what I want.

Body:
Starting Python 3.8, the standard library now includes the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

import math
math.comb(10, 5) # 252


问:
Struct structure with method in linux source code
I am reading android kernel code and I'm facing this kind of data structures ,

```<code>static const struct file_operations tracing_fops = {
.open       = tracing_open,
.read       = seq_read,
.write      = tracing_write_stub,
.llseek     = tracing_seek,
.release    = tracing_release,
};
</code>```

can someone explain this syntax generally ? right side of equations are functions names and  &tracing_fops later is passed as an argument to another function that inits debugfs file system.

答:
This is simply a struct initialization, using field names to assign values to specific fields only. You can take a look at struct initialization at cppreference which demonstrates these use cases (and even more advanced situations, such as omitting specific field names, etc.)

The Linux kernel sources often make use of structs consisting of sets of function pointers for related operations. These are used to provide distinct implementations of the same interface, akin to what would be accomplished using class inheritance in object-oriented languages. For instance, in C++ this same idea would be implemented using virtual methods and the function pointers would be stored in the class vtable (which means this would be implicit rather than explicit in C++.)

Using this struct in C is similar to how you'd use an object of a class using virtual methods in C++, since you can simply call one of the "methods" using:

```<code>int r = fops->open(inode, filp);
</code>```

The actual code typically tests whether the struct member is set, since the struct initialization will keep the pointers that are not explicitly mentioned set to NULL, making it possible to use this kind of struct to implement optional operations as well.

The main difference being that in C++ you'd have an implicit reference to the object itself (this), while in C you have to pass that as an additional argument in cases where it's needed.

OwnerDisplayName: fjahan

Body:
I am reading android kernel code and I'm facing this kind of data structures ,

static const struct file_operations tracing_fops = {
.open       = tracing_open,
.read       = seq_read,
.write      = tracing_write_stub,
.llseek     = tracing_seek,
.release    = tracing_release,
};

can someone explain this syntax generally ? right side of equations are functions names and  &tracing_fops later is passed as an argument to another function that inits debugfs file system.

Body:
This is simply a struct initialization, using field names to assign values to specific fields only. You can take a look at struct initialization at cppreference which demonstrates these use cases (and even more advanced situations, such as omitting specific field names, etc.)

The Linux kernel sources often make use of structs consisting of sets of function pointers for related operations. These are used to provide distinct implementations of the same interface, akin to what would be accomplished using class inheritance in object-oriented languages. For instance, in C++ this same idea would be implemented using virtual methods and the function pointers would be stored in the class vtable (which means this would be implicit rather than explicit in C++.)

Using this struct in C is similar to how you'd use an object of a class using virtual methods in C++, since you can simply call one of the "methods" using:

int r = fops->open(inode, filp);

The actual code typically tests whether the struct member is set, since the struct initialization will keep the pointers that are not explicitly mentioned set to NULL, making it possible to use this kind of struct to implement optional operations as well.

The main difference being that in C++ you'd have an implicit reference to the object itself (this), while in C you have to pass that as an additional argument in cases where it's needed.

OwnerDisplayName: filbranden


答:
The assignment is an example of using Compund Literals. According to C99 Section #6.5.2.5:

A postfix expression that consists of a parenthesized type name
followed by a brace- enclosed list of initializers is a compound
literal. It provides an unnamed object whose value is given by the
initializer list.

In simpler version, according to GCC docs: Compound literals:

A compound literal looks like a cast of a brace-enclosed aggregate
initializer list. Its value is an object of the type specified in the
cast, containing the elements specified in the initializer. Unlike the
result of a cast, a compound literal is an lvalue. ISO C99 and later
support compound literals. As an extension, GCC supports compound
literals also in C90 mode and in C++, although as explained below, the
C++ semantics are somewhat different.

An simple example:

struct foo { int x; int y; };

func() {
    struct foo var = { .x = 2, .y = 3 };
    ...
}
```

<p>In the question's example, the <code>struct file_operations</code> is defined in include/linux/fs.h and <code>tracing_fops</code> is in kernel/trace/trace.c file in Linux source tree.</p>
<pre class="lang-c prettyprint-override"><code>struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
...
};
</code>```

The open, read, write are Function Pointers which are pointers that points to a function. After dereferencing the function pointer, it can be used as normal function call. The tracing_fops structure is file_operations type. The values of function pointer members are assigned to the functions in the same trace.c file using compound literals.

With compound literals, we don't have to explicitly specify/assign all members in the structure type because other members are set to zero or null. Structure objects created using compound literals can be passed to functions without depending on member order. The function parameters should be same for both side. For example, the parameters of

```<code>int (*open) (struct inode *, struct file *);
</code>```

is same as

```<code>int tracing_open(struct inode *inode, struct file *file);
</code>```

In object oriented programming, this idea is somewhat similar as Virtual Function Table.

Title: Struct structure with method in linux source code

Body:
The assignment is an example of using Compund Literals. According to C99 Section #6.5.2.5:

A postfix expression that consists of a parenthesized type name
followed by a brace- enclosed list of initializers is a compound
literal. It provides an unnamed object whose value is given by the
initializer list.

In simpler version, according to GCC docs: Compound literals:

A compound literal looks like a cast of a brace-enclosed aggregate
initializer list. Its value is an object of the type specified in the
cast, containing the elements specified in the initializer. Unlike the
result of a cast, a compound literal is an lvalue. ISO C99 and later
support compound literals. As an extension, GCC supports compound
literals also in C90 mode and in C++, although as explained below, the
C++ semantics are somewhat different.

An simple example:

struct foo { int x; int y; };

func() {
    struct foo var = { .x = 2, .y = 3 };
    ...
}

In the question's example, the struct file_operations is defined in include/linux/fs.h and tracing_fops is in kernel/trace/trace.c file in Linux source tree.

struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
...
};

The open, read, write are Function Pointers which are pointers that points to a function. After dereferencing the function pointer, it can be used as normal function call. The tracing_fops structure is file_operations type. The values of function pointer members are assigned to the functions in the same trace.c file using compound literals.

With compound literals, we don't have to explicitly specify/assign all members in the structure type because other members are set to zero or null. Structure objects created using compound literals can be passed to functions without depending on member order. The function parameters should be same for both side. For example, the parameters of

int (*open) (struct inode *, struct file *);

is same as

int tracing_open(struct inode *inode, struct file *file);

In object oriented programming, this idea is somewhat similar as Virtual Function Table.

OwnerDisplayName: Biswapriyo


问:
How do I convert a json field of nested arrays into a Java entity?
I have a json from the Twitter Stream API. A field in this json consists of a nested array.

This json field looks like this:

```<code>{
"bounding_box": {
"coordinates": [
  [
    [
      -74.026675,
      40.683935
    ],
    [
      -74.026675,
      40.877483
    ],
    [
      -73.910408,
      40.877483
    ],
    [
      -73.910408,
      40.3935
    ]
  ]
],
"type": "Polygon"
}
}
</code>```

I create a java class called BoundingBox, and in it I define a variable of the type coordinates. What type should this variable have?

I need help with how to turn this space into a Java object. Can you please help me?

答:
Actually your coordinates property is three dimensional array so to parse it you would have to use for example List<List<List<Double>>>. Your BoundingBox class could look like this :

```<code>public class BoundingBox {
    private List<List<List<Double>>> coordinates;
    private String type;
    // constructors, getters, setter
}
</code>```

Personally I think that storing data in three nested lists is a bad approach and you should think how to logically arrange those data. Maybe the most nested list represent x, y coordinates of some location and you could create another POJO that would actually make your data model more readable.

Body:
I have a json from the Twitter Stream API. A field in this json consists of a nested array.

This json field looks like this:

{
"bounding_box": {
"coordinates": [
  [
    [
      -74.026675,
      40.683935
    ],
    [
      -74.026675,
      40.877483
    ],
    [
      -73.910408,
      40.877483
    ],
    [
      -73.910408,
      40.3935
    ]
  ]
],
"type": "Polygon"
}
}

I create a java class called BoundingBox, and in it I define a variable of the type coordinates. What type should this variable have?

I need help with how to turn this space into a Java object. Can you please help me?

Body:
Actually your coordinates property is three dimensional array so to parse it you would have to use for example List<List<List<Double>>>. Your BoundingBox class could look like this :

public class BoundingBox {
    private List<List<List<Double>>> coordinates;
    private String type;
    // constructors, getters, setter
}

Personally I think that storing data in three nested lists is a bad approach and you should think how to logically arrange those data. Maybe the most nested list represent x, y coordinates of some location and you could create another POJO that would actually make your data model more readable.


问:
How to quietly remove a directory with content in PowerShell
Using PowerShell, is it possible to remove some directory that contains files without prompting to confirm action?</p>

答:
Since my directory was in C:\users I had to run my powershell as administrator,

```<code>del ./[your Folder name] -Force -Recurse
</code>```

this command worked for me.

Body:
Since my directory was in C:\users I had to run my powershell as administrator,

del ./[your Folder name] -Force -Recurse

this command worked for me.


答:
You made a mistake here:

```<code>[find_pairs(mylist, 1) for x in mylist]
</code>```

You passed the same original list everytime to the function and not the sublists. Hence, inside function when you do if a-b==key, a and b are lists.

Correcting this, you can use following code to obtain your desired output:

```<code>from itertools import permutations, chain

def find_pairs(lst, key):
    return [(a, b) for a, b in permutations(lst, 2) if a - b == key]

mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
          [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
          [31, 44, 6, 49, 5, 39]]

temp_list = list(chain.from_iterable([find_pairs(x, 1) for x in mylist]))
fr_list = sorted(temp_list, key=lambda x: temp_list.count(x), reverse=True)

print(fr_list)
</code>```

Title: Python: Getting all pairs and frequency of pairs in multi-dimensional list

Body:
my multi-dimensional list looks as follows:

    mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
              [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
              [31, 44, 6, 49, 5, 39]]

There are pairs (numbers with difference 1) in some of the lists. not in every list: (12,13) in the first list, (34,35) in the third list, (28,29) and (12,13) in the fourth.

What I want to have is to get all the found pairs which should be saved in a (sorted) list based on the frequency (ascending). In my case above, it would look like follows:

    fr_list = [[12,13],[12,13],[28,29],[34,35]]

I wrote the following code to find the pairs

    def find_pairs(lst, key):
            return [(a,b) for a,b in permutations(lst, 2) if a-b==key]

Then, I tried this:

    fr_list = [find_pairs(mylist,1) for x in mylist]

However, I get the following error message:

    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <listcomp>
      File "<stdin>", line 2, in find_pairs
      File "<stdin>", line 2, in <listcomp>
    TypeError: unsupported operand type(s) for -: 'list' and 'list'

Can anybody help me out? Thanks.

Body:
You made a mistake here:

[find_pairs(mylist, 1) for x in mylist]

You passed the same original list everytime to the function and not the sublists. Hence, inside function when you do if a-b==key, a and b are lists.

Correcting this, you can use following code to obtain your desired output:

from itertools import permutations, chain

def find_pairs(lst, key):
    return [(a, b) for a, b in permutations(lst, 2) if a - b == key]

mylist = [[13, 41, 3, 23, 12, 16], [12, 32, 30, 49, 3, 18],
          [34, 12, 14, 24, 35, 20], [29, 28, 12, 44, 13, 4],
          [31, 44, 6, 49, 5, 39]]

temp_list = list(chain.from_iterable([find_pairs(x, 1) for x in mylist]))
fr_list = sorted(temp_list, key=lambda x: temp_list.count(x), reverse=True)

print(fr_list)


问:
view in base.html django
I have notification scrollbar like on fb or twitter. Top menu.html is directly included by base.html Unfortunatelly, I can use only User method there. Is it possible to not write in every view that I need notifications? I want to once paste in one view and have it always in top menu.html which is in base!

from intarface import
menu_nots

nots = menu_nots(request)

答: add to setting.py part of TEMPLATE append to context_processors list -> app_name.view.base,

Title: view in base.html django


问:
@keyframes doesn't support Arabic
I try to write a sentence in Arabic with @keyframes but @keyframes doesn't support the Arabic language and comes out with unintelligible characters

.caption { background-color: black; }

.caption h1::after {
  animation: move 3s infinite;
  content: "";
  border-left: 1px solid #fff;
  color: #fff !important;
}

@keyframes move {
  0% {
    content: "م"
  }
  10% {
    content: "مر"
  }
  20% {
    content: "مرح"
  }
  30% {
    content: "مرحب"
  }
  100% {
    content: "مرحباً"
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="caption">
  <h1></h1>
</div></code>```

Letters and symbols similar to =-&++#@

答:
For Arabic include the attributes dir="rtl" and lang="ar" on tag elements with Arabic characters:

```<code>h1::after {
  content: "مرح";
}
</code>```

Example 1:

```<code><h1>Testing Arabic</h1>
</code>```

This render incorrectly characters (on Chrome it seems to work, but in Safari and Firefox don't).

Example 2:

```<code><h1 dir="rtl" lang="ar">Testing Arabic</h1>
</code>```

This render correctly!

Also, you can read more about problems animating the "content" property here: https://css-tricks.com/animating-the-content-property/

Also you can include inside yours  tags <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Title: @keyframes doesn't support Arabic

Body:
I try to write a sentence in Arabic with @keyframes but @keyframes doesn't support the Arabic language and comes out with unintelligible characters

.caption { background-color: black; }

.caption h1::after {
  animation: move 3s infinite;
  content: "";
  border-left: 1px solid #fff;
  color: #fff !important;
}

@keyframes move {
  0% {
    content: "م"
  }
  10% {
    content: "مر"
  }
  20% {
    content: "مرح"
  }
  30% {
    content: "مرحب"
  }
  100% {
    content: "مرحباً"
  }
}

Letters and symbols similar to =-&++#@

Body:
For Arabic include the attributes dir="rtl" and lang="ar" on tag elements with Arabic characters:

h1::after {
  content: "مرح";
}

Example 1:

<h1>Testing Arabic</h1>

This render incorrectly characters (on Chrome it seems to work, but in Safari and Firefox don't).

Example 2:

<h1 dir="rtl" lang="ar">Testing Arabic</h1>

This render correctly!

Also, you can read more about problems animating the "content" property here: https://css-tricks.com/animating-the-content-property/

Also you can include inside yours <head></head> tags <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">


问:
How to git ls-remote tags in a specific branch
Before cloning a repository, I want to list all the tags in the master branch to filter and finally retrieve a subset of required commits without transferring any additional data.

Is it possible to use git ls-remote to list all tags in a particular branch?

答: git ls-remote can list branches, tags or heads (branches+tags); it can list all or filter by name but it cannot filter by commit graph because it cannot access commits in the remote repository.


问:
React.js files syntax in sublime text 3
i am using sublime text 3 as my code editor,i have written a basic hello world example in React.but the coloring is improper on the code ,i have tried installing Babel plugin but even after that also the coloring doesn't seem to work ,as you can see the image below

答:
This might possibly help you out...follow below steps

press Ctrl + Shift + P

Doing so, Command Palette pops up and there type : Package control . And then
select the option Package Control: install package

Now typein and select 'Babel'

Now open 'View' menu and Navigate to Syntax, Open all with current extension
as…, Babel, Javascript (Babel).

Title: React.js files syntax in sublime text 3


问:
How to concat all ffmpeg inputs without mapping them in the filter using windows batch script?
I'm running multiple runs of the ffmpeg concat filter on multiple files using Windows batch file script. I don't always know how many files exactly need to be concatenated and the problem is that ffmpeg doesn't automatically concatenate the inputs unless you map them all. For example, if I have to join eight files, I use the following filter mapping scheme:

```<code> -filter_complex "[0][1][2][3][4][5][6][7]concat=n=8:v=1:a=0"
</code>```

If I have to join only 4 files later in the script, I have to change it to:

```<code> -filter_complex "[0][1][2][3]concat=n=4:v=1:a=0"
</code>```

I had hoped not entering any mapping would automatically take all the inputs in order. I'm disappointed to find that it only takes the first two and ignores the rest. I tried simply:

```<code> -filter_complex "concat"
</code>```

and it "guessed" the mapping according to warnings, but completely ignored all inputs after the second.

There is no way to do this with ffmpeg alone, so I'm seeking a way to do this with the Windows batch script.

An example of a complete and working command is:

```<code>set commands=-filter_complex "[0][1][2][3][4][5][6][7]concat=n=8:v=1:a=0","crop=1064:800" /
-crf 30 -an -movflags +faststart -loglevel quiet -stats

ffmpeg -ss 00:00:36.737 -t 00:13:33.630 -i 1201.avi /
-ss 00:00:00.000 -t 00:13:51.397 -i 1202.avi /
-ss 00:00:00.033 -t 00:13:06.052 -i 1203.avi /
-ss 00:00:00.000 -t 00:17:31.617 -i 1204.avi /
-ss 00:17:31.551 -t 00:00:00.067 -i 1204.avi /
-ss 00:00:00.000 -t 00:15:07.907 -i 1205.avi /
-ss 00:15:07.840 -t 00:00:00.067 -i 1205.avi /
-ss 00:00:00.000 -t 00:02:36.990 -i 1206.avi /
%commands% 12-concat.mp4
</code>```

My goal here is that I can set commands (and/or other variables) once in the script, instead of having to change it each time the command has more or less inputs.

答:
```<code>@echo off
setlocal enabledelayedexpansion

if not exist "inputs.txt" (
    >&2 echo File inputs.txt not found.
    exit /b 1
)

set /p "savefile=Save file: "

set "inputs="

for /f "tokens=1-3" %%A in (inputs.txt) do (
    set "inputs=!inputs!-ss %%~A -t %%~B -i %%~C "
)

call :buildcommands 8 1064:800 30

echo ffmpeg %inputs% %commands% %savefile%
exit /b 0

:buildcommands  maps  [width:height]  [crf]
setlocal enabledelayedexpansion
set /a "ubound=%~1-1"
set "crop=%~2"
set "crf=%~3"
set "maps="

rem Set defaults if not defined.
if not defined crop set "crop=1280:720"
if not defined crf set "crf=23"

rem Build maps string.
for /l %%A in (0 1 %ubound%) do set "maps=!maps![%%~A]"

rem Build entire string.
set commands=-filter_complex "%maps%concat=n=%~1:v=1:a=0","crop=%crop%"^
 -crf %crf% -an -movflags +faststart -loglevel quiet -stats

rem Set global commands.
endlocal & set commands=%commands%
exit /b 0
</code>```

This will build the inputs from file and commands from
call arguments.

You can use the preset defaults by:

```<code>call :buildcommands 8
</code>```

so that crop is 1280:720 and constant rate factor is 23.

input.txt would be like:

```<code>00:00:36.737 00:13:33.630 1201.avi
00:00:00.000 00:13:51.397 1202.avi
00:00:00.033 00:13:06.052 1203.avi
00:00:00.000 00:17:31.617 1204.avi
00:17:31.551 00:00:00.067 1204.avi
00:00:00.000 00:15:07.907 1205.avi
00:15:07.840 00:00:00.067 1205.avi
00:00:00.000 00:02:36.990 1206.avi
</code>```

It is mostly data so I do not know how you
could improve it's input into the script.

Remove the echo in front of ffmpeg to make it work instead of just echo.

Body:
I'm running multiple runs of the ffmpeg concat filter on multiple files using Windows batch file script. I don't always know how many files exactly need to be concatenated and the problem is that ffmpeg doesn't automatically concatenate the inputs unless you map them all. For example, if I have to join eight files, I use the following filter mapping scheme:

 -filter_complex "[0][1][2][3][4][5][6][7]concat=n=8:v=1:a=0"

If I have to join only 4 files later in the script, I have to change it to:

 -filter_complex "[0][1][2][3]concat=n=4:v=1:a=0"

I had hoped not entering any mapping would automatically take all the inputs in order. I'm disappointed to find that it only takes the first two and ignores the rest. I tried simply:

 -filter_complex "concat"

and it "guessed" the mapping according to warnings, but completely ignored all inputs after the second.

There is no way to do this with ffmpeg alone, so I'm seeking a way to do this with the Windows batch script.

An example of a complete and working command is:

set commands=-filter_complex "[0][1][2][3][4][5][6][7]concat=n=8:v=1:a=0","crop=1064:800" /
-crf 30 -an -movflags +faststart -loglevel quiet -stats

ffmpeg -ss 00:00:36.737 -t 00:13:33.630 -i 1201.avi /
-ss 00:00:00.000 -t 00:13:51.397 -i 1202.avi /
-ss 00:00:00.033 -t 00:13:06.052 -i 1203.avi /
-ss 00:00:00.000 -t 00:17:31.617 -i 1204.avi /
-ss 00:17:31.551 -t 00:00:00.067 -i 1204.avi /
-ss 00:00:00.000 -t 00:15:07.907 -i 1205.avi /
-ss 00:15:07.840 -t 00:00:00.067 -i 1205.avi /
-ss 00:00:00.000 -t 00:02:36.990 -i 1206.avi /
%commands% 12-concat.mp4

My goal here is that I can set commands (and/or other variables) once in the script, instead of having to change it each time the command has more or less inputs.

Body:
@echo off
setlocal enabledelayedexpansion

if not exist "inputs.txt" (
    >&2 echo File inputs.txt not found.
    exit /b 1
)

set /p "savefile=Save file: "

set "inputs="

for /f "tokens=1-3" %%A in (inputs.txt) do (
    set "inputs=!inputs!-ss %%~A -t %%~B -i %%~C "
)

call :buildcommands 8 1064:800 30

echo ffmpeg %inputs% %commands% %savefile%
exit /b 0

:buildcommands  maps  [width:height]  [crf]
setlocal enabledelayedexpansion
set /a "ubound=%~1-1"
set "crop=%~2"
set "crf=%~3"
set "maps="

rem Set defaults if not defined.
if not defined crop set "crop=1280:720"
if not defined crf set "crf=23"

rem Build maps string.
for /l %%A in (0 1 %ubound%) do set "maps=!maps![%%~A]"

rem Build entire string.
set commands=-filter_complex "%maps%concat=n=%~1:v=1:a=0","crop=%crop%"^
 -crf %crf% -an -movflags +faststart -loglevel quiet -stats

rem Set global commands.
endlocal & set commands=%commands%
exit /b 0

This will build the inputs from file and commands from
call arguments.

You can use the preset defaults by:

call :buildcommands 8

so that crop is 1280:720 and constant rate factor is 23.

input.txt would be like:

00:00:36.737 00:13:33.630 1201.avi
00:00:00.000 00:13:51.397 1202.avi
00:00:00.033 00:13:06.052 1203.avi
00:00:00.000 00:17:31.617 1204.avi
00:17:31.551 00:00:00.067 1204.avi
00:00:00.000 00:15:07.907 1205.avi
00:15:07.840 00:00:00.067 1205.avi
00:00:00.000 00:02:36.990 1206.avi

It is mostly data so I do not know how you
could improve it's input into the script.

Remove the echo in front of ffmpeg to make it work instead of just echo.


问:
Need to remove duplicate columns from a dataframe in pyspark
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

```<code>df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()
</code>```

The error is

```<code>An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........
</code>```

Can someone help me on this?

答:
The solution below should get rid of duplicates plus preserve the column order of input df.

Load some sample data

```<code>df_tickets = spark.createDataFrame([(1,2,3,4,5)],['a','b','c','d','e'])
duplicatecols = spark.createDataFrame([(1,3,5)],['a','c','e'])
</code>```

Check df schemas

```<code>df_tickets.printSchema()
root
 |-- a: long (nullable = true)
 |-- b: long (nullable = true)
 |-- c: long (nullable = true)
 |-- d: long (nullable = true)
 |-- e: long (nullable = true)
</code>```

Remove duplicated columns

```<code>duplicatecols.printSchema()

root
 |-- a: long (nullable = true)
 |-- c: long (nullable = true)
 |-- e: long (nullable = true)

outCols = [x for x in df_tickets.columns if x not in set(duplicatecols.columns)]

df_tickets[outCols].show()

+---+---+
|  b|  d|
+---+---+
|  2|  4|
+---+---+
</code>```

Body:
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()

The error is

An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........

Can someone help me on this?

Body:
The solution below should get rid of duplicates plus preserve the column order of input df.

Load some sample data

df_tickets = spark.createDataFrame([(1,2,3,4,5)],['a','b','c','d','e'])
duplicatecols = spark.createDataFrame([(1,3,5)],['a','c','e'])

Check df schemas

df_tickets.printSchema()
root
 |-- a: long (nullable = true)
 |-- b: long (nullable = true)
 |-- c: long (nullable = true)
 |-- d: long (nullable = true)
 |-- e: long (nullable = true)

Remove duplicated columns

duplicatecols.printSchema()

root
 |-- a: long (nullable = true)
 |-- c: long (nullable = true)
 |-- e: long (nullable = true)

outCols = [x for x in df_tickets.columns if x not in set(duplicatecols.columns)]

df_tickets[outCols].show()

+---+---+
|  b|  d|
+---+---+
|  2|  4|
+---+---+