问:
SSRS - calculations from different datasets
I am new to SSRS and need help in completing this.
I have a SSRS report which has 2 different datasets Dataset 1 & Dataset 2. In Dataset 2 I have to use a calculation in one of the rows, which requires values from Dataset 2 and Dataset 1. Please see the image attached for the layout of the report and for other details. I would request your help in achieving the orange highlighted fields.

答:
It is generally better to perform these calculations in the query if possible, but it is not impossible to include items from datasets other than the specified dataset for a tablix.

Depending on exactly how your datasets are set up, you may be able to use the Lookup function. This assumes you have a one-to-one relationship between the datasets. You can also sort of trick the function into working for datasets that don't have an explicit one-to-one relationship.

It's a little hard to tell your dataset structure from the information provided, I have a feeling your screenshot doesn't accurately depict your structure. Assuming your datasets are structured something more like this:

```<code>+------------------------------------+
| Category      | Date       | Value |
+------------------------------------+
| Gross Revenue | 2017-08-01 | GR8   |
| Gross Revenue | 2017-09-01 | GR9   |
| Gross Revenue | 2017-10-01 | GR10  |
| Profit        | 2017-08-01 | P8    |
| Profit        | 2017-09-01 | P9    |
| Profit        | 2017-10-01 | P10   |
+------------------------------------+
</code>```

and similar for Dataset 2, you should be able to use something like this to access the value from the other dataset:

=Lookup(Fields!Date.Value & "Cash Flow Rate", Fields!Date.Value & Fields!Category.Value, Fields!Value.Value, "Dataset2")

Body:
It is generally better to perform these calculations in the query if possible, but it is not impossible to include items from datasets other than the specified dataset for a tablix.

Depending on exactly how your datasets are set up, you may be able to use the Lookup function. This assumes you have a one-to-one relationship between the datasets. You can also sort of trick the function into working for datasets that don't have an explicit one-to-one relationship.

It's a little hard to tell your dataset structure from the information provided, I have a feeling your screenshot doesn't accurately depict your structure. Assuming your datasets are structured something more like this:

+------------------------------------+
| Category      | Date       | Value |
+------------------------------------+
| Gross Revenue | 2017-08-01 | GR8   |
| Gross Revenue | 2017-09-01 | GR9   |
| Gross Revenue | 2017-10-01 | GR10  |
| Profit        | 2017-08-01 | P8    |
| Profit        | 2017-09-01 | P9    |
| Profit        | 2017-10-01 | P10   |
+------------------------------------+

and similar for Dataset 2, you should be able to use something like this to access the value from the other dataset:

=Lookup(Fields!Date.Value & "Cash Flow Rate", Fields!Date.Value & Fields!Category.Value, Fields!Value.Value, "Dataset2")


来源: stackexchange

问:
500 error on my website
I wanted to add to my website something like maintenance page, using PHP and MySQL. For example, if I'm adding some functions, I will set it in settings and it will display maintenace page instead of any page. But when I uploaded the whole code, it is showing me 500 error. Here is the code which will detect if maintenance page have to be shown or not:

```<code>if (isset($vsetko)) {
     header('include/maintenance_page.php');
     }
     if (!isset($vsetko)) { ?>
     <!DOCTYPE html>
     <html lang="sk_SK">
     <head>
...
Here is the website
...
    </body>
    </html>
    <?php   }?>
</code>```

Can you help me with it?

Here's the whole code:

```<code><?php
    ob_start();
    session_start();
    require_once 'include/connect.php';
    include 'include/maintenance.php';

    if ( isset($_SESSION['user']) ) {
        //údaje o prihlásenom
        $res=mysql_query("SELECT * FROM users WHERE userID=".$_SESSION['user']);
        $userRow=mysql_fetch_array($res);
    }

    //Chybové hlášky podľa URI
    $url = "$_SERVER[REQUEST_URI]";
    if (stripos($url, 'error=')) {
        $errTyp = "danger";
        $errMSG = "Kód chyby neexistuje.";
    }
    if (stripos($url, 'error=1')) {
        $errTyp = "danger";
        $errMSG = "Na tejto funkcii sa pracuje. Prístup povolený iba administrátorovi.";
    }
    if (isset($vsetko) && $vsetko = 'true') {
        header('include/maintenance_page.php');
    }else{ ?>
    <!DOCTYPE html>
    <html lang="sk_SK">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <title>DJ LiMix</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
        <script src="slidedown.js"></script>
        <link rel="shortcut icon" type="image/ico" href="/icon.ico"/>
    </head>
    <body>
<?php include('include/header.php') ?>
    <div id="wrapper" class="vrch page">
        <div class="container">
        <div class="page-header vrch">
                    <?php
   if ( isset($errMSG) ) {

    ?>
    <div class="form-group">
             <div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
    <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                <div id="zavriet" style="float: right;" title="Zavrieť upozornenie">×</div></div>
             </div>
                <?php
   }
   ?>
            <h3>Toto je úvodná stránka.</h3>
        </div>

            <div class="row">
                <div class="col-lg-12">
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error iste ut quidem libero, et ipsa distinctio mollitia tempore debitis impedit dolores, minus ullam illum quis dolor numquam. Quidem doloribus, atque.</p>
                </div>
            </div>
        </div>
<?php include 'include/sidebar.html'; ?>
<?php include 'include/footer.php'; ?>
</body>
</html>
<?php   }
ob_end_flush(); ?>
</code>```

This is in log:

```<code>[Wed Nov 15 20:48:43.722497 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] [id +UeBylJIYQE] [client 78.99.223.120:54183] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:43.722598 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] [id +UeBylJIYQE] [client 78.99.223.120:54183] AH01070: Error parsing script headers
[Wed Nov 15 20:48:43.722607 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] (22)Invalid argument: [id +UeBylJIYQE] [client 78.99.223.120:54183] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:44.551120 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:44.551209 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] AH01070: Error parsing script headers
[Wed Nov 15 20:48:44.551218 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] (22)Invalid argument: [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:45.137926 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] [id HvyWykJjMgI] [client 78.99.223.120:54185] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:45.138010 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] [id HvyWykJjMgI] [client 78.99.223.120:54185] AH01070: Error parsing script headers
[Wed Nov 15 20:48:45.138019 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] (22)Invalid argument: [id HvyWykJjMgI] [client 78.99.223.120:54185] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:45.649078 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] [id PMeeyhJHYQE] [client 78.99.223.120:54186] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:45.649224 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] [id PMeeyhJHYQE] [client 78.99.223.120:54186] AH01070: Error parsing script headers
[Wed Nov 15 20:48:45.649237 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] (22)Invalid argument: [id PMeeyhJHYQE] [client 78.99.223.120:54186] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.064124 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] [id PCClytJ3MgI] [client MY IP] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.064217 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] [id PCClytJ3MgI] [client MY IP] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.064225 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] (22)Invalid argument: [id PCClytJ3MgI] [client MY IP] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.415746 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] [id vIeqygLaBwI] [client 78.99.223.120:54188] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.417215 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] [id vIeqygLaBwI] [client 78.99.223.120:54188] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.417228 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] (22)Invalid argument: [id vIeqygLaBwI] [client 78.99.223.120:54188] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.699343 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] [id RNKuymJVYQE] [client 78.99.223.120:54189] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.699487 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] [id RNKuymJVYQE] [client 78.99.223.120:54189] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.699496 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] (22)Invalid argument: [id RNKuymJVYQE] [client 78.99.223.120:54189] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:47.039864 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] [id uOazyiJSYQE] [client 78.99.223.120:54192] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:47.040108 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] [id uOazyiJSYQE] [client 78.99.223.120:54192] AH01070: Error parsing script headers
[Wed Nov 15 20:48:47.040127 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] (22)Invalid argument: [id uOazyiJSYQE] [client 78.99.223.120:54192] AH01075: Error dispatching request to :
</code>```

答:
500 normally means something is wrong from your settings. But in this case its just bad syntax

Also I am no php expert but I have never seen header()

the correct syntax would be

```<code>     <?php
      $mMode = true;
       if (isset($mMode) && $mMode = true) {
         include('maintenance_page.php');
     }else {
    ?>

<!DOCTYPE html>
 <html lang="sk_SK">
 <head>
 </head>
 <body>

         ...
      Here is the website
    ...
   </body>
 </html>
 <?php   }?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: 500 error on my website

Body:
I wanted to add to my website something like maintenance page, using PHP and MySQL. For example, if I'm adding some functions, I will set it in settings and it will display maintenace page instead of any page. But when I uploaded the whole code, it is showing me 500 error. Here is the code which will detect if maintenance page have to be shown or not:

if (isset($vsetko)) {
     header('include/maintenance_page.php');
     }
     if (!isset($vsetko)) { ?>
     <!DOCTYPE html>

...
Here is the website
...

    <?php   }?>

Can you help me with it?

Here's the whole code:

<?php
    ob_start();
    session_start();
    require_once 'include/connect.php';
    include 'include/maintenance.php';

    if ( isset($_SESSION['user']) ) {
        //údaje o prihlásenom
        $res=mysql_query("SELECT * FROM users WHERE userID=".$_SESSION['user']);
        $userRow=mysql_fetch_array($res);
    }

    //Chybové hlášky podľa URI
    $url = "$_SERVER[REQUEST_URI]";
    if (stripos($url, 'error=')) {
        $errTyp = "danger";
        $errMSG = "Kód chyby neexistuje.";
    }
    if (stripos($url, 'error=1')) {
        $errTyp = "danger";
        $errMSG = "Na tejto funkcii sa pracuje. Prístup povolený iba administrátorovi.";
    }
    if (isset($vsetko) && $vsetko = 'true') {
        header('include/maintenance_page.php');
    }else{ ?>
    <!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>DJ LiMix</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

        <link rel="shortcut icon" type="image/ico" href="/icon.ico"/>

<?php include('include/header.php') ?>

                    <?php
   if ( isset($errMSG) ) {

    ?>

             <div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
     <?php echo $errMSG; ?>

×

                <?php
   }
   ?>

Toto je úvodná stránka.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Error iste ut quidem libero, et ipsa distinctio mollitia tempore debitis impedit dolores, minus ullam illum quis dolor numquam. Quidem doloribus, atque.

<?php include 'include/sidebar.html'; ?>
<?php include 'include/footer.php'; ?>

<?php   }
ob_end_flush(); ?>

This is in log:

[Wed Nov 15 20:48:43.722497 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] [id +UeBylJIYQE] [client 78.99.223.120:54183] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:43.722598 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] [id +UeBylJIYQE] [client 78.99.223.120:54183] AH01070: Error parsing script headers
[Wed Nov 15 20:48:43.722607 2017] [proxy_fcgi:error] [pid 22673:tid 140046944069376] (22)Invalid argument: [id +UeBylJIYQE] [client 78.99.223.120:54183] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:44.551120 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:44.551209 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] AH01070: Error parsing script headers
[Wed Nov 15 20:48:44.551218 2017] [proxy_fcgi:error] [pid 22663:tid 140047372134144] (22)Invalid argument: [id 5/SNyuJ0MgI] [client 78.99.223.120:54184] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:45.137926 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] [id HvyWykJjMgI] [client 78.99.223.120:54185] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:45.138010 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] [id HvyWykJjMgI] [client 78.99.223.120:54185] AH01070: Error parsing script headers
[Wed Nov 15 20:48:45.138019 2017] [proxy_fcgi:error] [pid 22663:tid 140046679803648] (22)Invalid argument: [id HvyWykJjMgI] [client 78.99.223.120:54185] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:45.649078 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] [id PMeeyhJHYQE] [client 78.99.223.120:54186] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:45.649224 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] [id PMeeyhJHYQE] [client 78.99.223.120:54186] AH01070: Error parsing script headers
[Wed Nov 15 20:48:45.649237 2017] [proxy_fcgi:error] [pid 22673:tid 140046902109952] (22)Invalid argument: [id PMeeyhJHYQE] [client 78.99.223.120:54186] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.064124 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] [id PCClytJ3MgI] [client MY IP] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.064217 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] [id PCClytJ3MgI] [client MY IP] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.064225 2017] [proxy_fcgi:error] [pid 22663:tid 140047319684864] (22)Invalid argument: [id PCClytJ3MgI] [client MY IP] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.415746 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] [id vIeqygLaBwI] [client 78.99.223.120:54188] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.417215 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] [id vIeqygLaBwI] [client 78.99.223.120:54188] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.417228 2017] [proxy_fcgi:error] [pid 22673:tid 140047867176704] (22)Invalid argument: [id vIeqygLaBwI] [client 78.99.223.120:54188] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:46.699343 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] [id RNKuymJVYQE] [client 78.99.223.120:54189] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:46.699487 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] [id RNKuymJVYQE] [client 78.99.223.120:54189] AH01070: Error parsing script headers
[Wed Nov 15 20:48:46.699496 2017] [proxy_fcgi:error] [pid 22667:tid 140047332194048] (22)Invalid argument: [id RNKuymJVYQE] [client 78.99.223.120:54189] AH01075: Error dispatching request to :
[Wed Nov 15 20:48:47.039864 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] [id uOazyiJSYQE] [client 78.99.223.120:54192] malformed header from script 'index.php': Bad header:
[Wed Nov 15 20:48:47.040108 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] [id uOazyiJSYQE] [client 78.99.223.120:54192] AH01070: Error parsing script headers
[Wed Nov 15 20:48:47.040127 2017] [proxy_fcgi:error] [pid 22664:tid 140047122396928] (22)Invalid argument: [id uOazyiJSYQE] [client 78.99.223.120:54192] AH01075: Error dispatching request to :

Body:
500 normally means something is wrong from your settings. But in this case its just bad syntax

Also I am no php expert but I have never seen header()

the correct syntax would be

     <?php
      $mMode = true;
       if (isset($mMode) && $mMode = true) {
         include('maintenance_page.php');
     }else {
    ?>

<!DOCTYPE html>
 <html lang="sk_SK">
 <head>
 </head>
 <body>

         ...
      Here is the website
    ...
   </body>
 </html>
 <?php   }?>


问:
Django counter in loop to index list
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

```<code>{% for i in list %}
</code>```

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

答: don't think you'll be able to do it like that.  You'll need either a template tag, or much better, to align the lists in your view logic, before passing an aligned data structure to you template.</p>

ContentLicense: CC BY-SA 2.5

Title: Django counter in loop to index list

Body:
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks


问:
How can I get the means of every pair of values in a numpy array?
What I'm trying to do is to reduce the "resolution" of 1D data by finding the mean of every distinct pair of elements and setting the values to that mean. For example:

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

should become:

```<code>[ 1.5, 1.5, 3.5, 3.5 ]
</code>```

If the number of elements is odd, then the last one stays as it is, or is removed/ignored. Is there an easy way to do this?

Perhaps it would be easier to first get [ 1.5, 3.5 ] and then duplicate each element — I'm not sure.

Eventually I would like to keep doing this recursively (or iteratively for every pair, then every four, then every eight, then every 2^i) such that the resolution becomes lower and lower until it's just a grand mean.

答:
You could use reshape like</p>

```<code>a = np.arange(1,15)
# groups of four in this example
k = 4
result = np.empty(a.shape)
# arrange the elements in as many full (4 item) rows as possible
rect = k * (len(a) // k)
resview = np.reshape(result[:rect], (-1, k))
# perform mean along rows without collapsing them
resview[...] = np.mean(np.reshape(a[:rect], (-1, k)), axis=-1, keepdims=True)
if len(a) > rect:
    # handle the last, incomplete (<4 items) row
    result[rect:] = a[rect:].mean()
print(result)
[  2.5   2.5   2.5   2.5   6.5   6.5   6.5   6.5  10.5  10.5  10.5  10.5  13.5  13.5]
</code>```

Body:
What I'm trying to do is to reduce the "resolution" of 1D data by finding the mean of every distinct pair of elements and setting the values to that mean. For example:

[ 1, 2, 3, 4 ]

should become:

[ 1.5, 1.5, 3.5, 3.5 ]

If the number of elements is odd, then the last one stays as it is, or is removed/ignored. Is there an easy way to do this?

Perhaps it would be easier to first get [ 1.5, 3.5 ] and then duplicate each element — I'm not sure.

Eventually I would like to keep doing this recursively (or iteratively for every pair, then every four, then every eight, then every 2^i) such that the resolution becomes lower and lower until it's just a grand mean.

Body:
You could use reshape like

a = np.arange(1,15)
# groups of four in this example
k = 4
result = np.empty(a.shape)
# arrange the elements in as many full (4 item) rows as possible
rect = k * (len(a) // k)
resview = np.reshape(result[:rect], (-1, k))
# perform mean along rows without collapsing them
resview[...] = np.mean(np.reshape(a[:rect], (-1, k)), axis=-1, keepdims=True)
if len(a) > rect:
    # handle the last, incomplete (<4 items) row
    result[rect:] = a[rect:].mean()
print(result)
[  2.5   2.5   2.5   2.5   6.5   6.5   6.5   6.5  10.5  10.5  10.5  10.5  13.5  13.5]


问:
Finding duplicate values only for 2 highest values in a dict
Code:

```<code>candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")
</code>```

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

答:
Just preserve a and b to take the rigth choice:

```<code>candidates_and_fp_votes =  {'a': 25, 'c': 25, 'b': 0, 'e': 23, 'd': 23}

print(candidates_and_fp_votes)
final_vals = [[a,b] for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)

fAndS=sorted(candidates_and_fp_votes.values())[len(candidates_and_fp_votes)-2:len(candidates_and_fp_votes)]
maxVals=[[a,b] for a, b in candidates_and_fp_votes.items() if b==max(candidates_and_fp_votes.values())]
if final_vals:
    print("There is a duplicate with")
    print(final_vals)

if len(maxVals)==2:
    print("2 highest scoring candidates are equal")
    print(maxVals)
    print("No tiebreaker sys required")
else:
    final_vals = [ a for a,b in final_vals if b in fAndS]
    if not final_vals:
        print("It is not a duplicate with the second and highest values")
        print(fAndS)
        print("No tiebreaker sys required")
    else:
        print("There is a duplicate with the second and highest values")
        print(fAndS)
        print("Tie-breaker required")
</code>```

Output 1:

```<code>{'a': 25, 'c': 17, 'b': 0, 'e': 0, 'd': 23}
Duplicates are:
['b', 0]
['e', 0]
There is a duplicate with
[['b', 0], ['e', 0]]
It is not a duplicate with the second and highest values
[23, 25]
No tiebreaker sys required
</code>```

Output 2:

```<code>{'a': 25, 'c': 23, 'b': 0, 'e': 0, 'd': 23}
Duplicates are:
['c', 23]
['b', 0]
['e', 0]
['d', 23]
There is a duplicate with
[['c', 23], ['b', 0], ['e', 0], ['d', 23]]
There is a duplicate with the second and highest values
[23, 25]
Tie-breaker required
</code>```

Output 3:

```<code>{'a': 25, 'c': 25, 'b': 0, 'e': 23, 'd': 23}
Duplicates are:
['a', 25]
['c', 25]
['e', 23]
['d', 23]
There is a duplicate with
[['a', 25], ['c', 25], ['e', 23], ['d', 23]]
2 highest scoring candidates are equal
[['a', 25], ['c', 25]]
No tiebreaker sys required
</code>```

[EDIT]
Here is a more simple answer, just thinking all conditions together:
(Based only the dict sorted)

```<code>candidates_and_fp_votes =  {'a': 25, 'c': 25, 'b': 0, 'e': 0, 'd': 23}
sorted_votes = sorted([[value,key] for key,value in candidates_and_fp_votes.items()])

resultList=[]
dictSize = len(candidates_and_fp_votes)
print sorted_votes
if(dictSize>=3):
  if sorted_votes[dictSize-2][0]==sorted_votes[dictSize-3][0]:
    print("Need tie break between")
    resultList = [ key for value,key in sorted_votes if value==sorted_votes[dictSize-2][0] ]
    print resultList
  else:
    print("Winers")
    resultList = [key for value,key in sorted_votes[dictSize-2:dictSize]]
    print resultList
</code>```

Output:

```<code>[[0, 'b'], [0, 'e'], [23, 'd'], [25, 'a'], [25, 'c']]
Winers
['a', 'c']
</code>```

Body:
Code:

candidates_and_fp_votes = {'a': 25, 'b': 0, 'c': 17, 'd': 23, 'e': 0}

print(candidates_and_fp_votes)
final_vals = [a for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)
print(final_vals)

if not final_vals:
    print("No tiebreaker sys required")
else:
    print("Tie-breaker required")

Currently, this outputs "Tie-breaker required" as 'b' and 'e' have a value of 0.
I would like this so it only finds duplicates that affect the highest or second highest value.
Eg:

Right now, it should print "No tiebreaker sys required because even if there is a duplicate with 'b' and 'e' it is not
a duplicate with the second and highest values '25' and '23'

if the dict to be = {'a': 25, 'b': 0, 'c': 23, 'd': 23, 'e': 0}
it would print out "Tie-breaker required as it is affecting the 2nd highest value - 23.

Also, I just had a little change in mind, if the highest score is duplicating with a number but this number does not duplicate with the second highest, it would just output "No tiebreaker sys required"

How can I do this?

Thanks in advance.

Body:
Just preserve a and b to take the rigth choice:

candidates_and_fp_votes =  {'a': 25, 'c': 25, 'b': 0, 'e': 23, 'd': 23}

print(candidates_and_fp_votes)
final_vals = [[a,b] for a, b in candidates_and_fp_votes.items() if
              list(candidates_and_fp_votes.values()).count(b) > 1]
print("Duplicates are: ")
for i in final_vals:
    print(i)

fAndS=sorted(candidates_and_fp_votes.values())[len(candidates_and_fp_votes)-2:len(candidates_and_fp_votes)]
maxVals=[[a,b] for a, b in candidates_and_fp_votes.items() if b==max(candidates_and_fp_votes.values())]
if final_vals:
    print("There is a duplicate with")
    print(final_vals)

if len(maxVals)==2:
    print("2 highest scoring candidates are equal")
    print(maxVals)
    print("No tiebreaker sys required")
else:
    final_vals = [ a for a,b in final_vals if b in fAndS]
    if not final_vals:
        print("It is not a duplicate with the second and highest values")
        print(fAndS)
        print("No tiebreaker sys required")
    else:
        print("There is a duplicate with the second and highest values")
        print(fAndS)
        print("Tie-breaker required")

Output 1:

{'a': 25, 'c': 17, 'b': 0, 'e': 0, 'd': 23}
Duplicates are:
['b', 0]
['e', 0]
There is a duplicate with
[['b', 0], ['e', 0]]
It is not a duplicate with the second and highest values
[23, 25]
No tiebreaker sys required

Output 2:

{'a': 25, 'c': 23, 'b': 0, 'e': 0, 'd': 23}
Duplicates are:
['c', 23]
['b', 0]
['e', 0]
['d', 23]
There is a duplicate with
[['c', 23], ['b', 0], ['e', 0], ['d', 23]]
There is a duplicate with the second and highest values
[23, 25]
Tie-breaker required

Output 3:

{'a': 25, 'c': 25, 'b': 0, 'e': 23, 'd': 23}
Duplicates are:
['a', 25]
['c', 25]
['e', 23]
['d', 23]
There is a duplicate with
[['a', 25], ['c', 25], ['e', 23], ['d', 23]]
2 highest scoring candidates are equal
[['a', 25], ['c', 25]]
No tiebreaker sys required

[EDIT]
Here is a more simple answer, just thinking all conditions together:
(Based only the dict sorted)

candidates_and_fp_votes =  {'a': 25, 'c': 25, 'b': 0, 'e': 0, 'd': 23}
sorted_votes = sorted([[value,key] for key,value in candidates_and_fp_votes.items()])

resultList=[]
dictSize = len(candidates_and_fp_votes)
print sorted_votes
if(dictSize>=3):
  if sorted_votes[dictSize-2][0]==sorted_votes[dictSize-3][0]:
    print("Need tie break between")
    resultList = [ key for value,key in sorted_votes if value==sorted_votes[dictSize-2][0] ]
    print resultList
  else:
    print("Winers")
    resultList = [key for value,key in sorted_votes[dictSize-2:dictSize]]
    print resultList

Output:

[[0, 'b'], [0, 'e'], [23, 'd'], [25, 'a'], [25, 'c']]
Winers
['a', 'c']


问:
Write to global ViewBag from partial view in ASP.Net Core
In an application written with ASP.Net Core 2.0, how can I in a partial view write to the global ViewBag? The partial get's its own local ViewBag so anything I write there won't be stored in the global ViewBag it seems.

For example, let's say that the "Home/Index" view renders a partial "_TitleBar", inside this partial we set ViewBag.PageName = "MyPage". Now, later in the same request, in "_Layout" I want to render whatever value is stored in ViewBag.PageName. This does not work in the above scenario. So how can I access the global ViewBag from my "_TitleBar" so that this value can be picked up elsewhere ?

For now, the workaround is to store data in TempData instead which is global.

答:
Razor renders the actual page then the layout then the partial views, and that's why partial views cannot have features such as sections. You can do this using JavaScript or JQuery without relying on Razor. All you have to do is to add a script in the partial view to update the PageName. For example:

```<code>_Layout.cshtml
------------------
<title>Site Name | Page Name </title>

_partial.cshtml
<script type="text/javascript">
    $(document).ready(function () {
         document.title = "new title";
    })
</script>
</code>```

Body:
Razor renders the actual page then the layout then the partial views, and that's why partial views cannot have features such as sections. You can do this using JavaScript or JQuery without relying on Razor. All you have to do is to add a script in the partial view to update the PageName. For example:

_Layout.cshtml
------------------
<title>Site Name | Page Name </title>

_partial.cshtml
<script type="text/javascript">
    $(document).ready(function () {
         document.title = "new title";
    })
</script>


问:
how to set the pyversions icon on my github readme?
I'm trying to set my pyversion icon to my github README, similar to this:

I've been trying to reverse engineer the setup from the coveralls-python project.

My .travis.yaml file looks like this:

```<code>language: python
python:
  - "2.7"
  - "3.3"
  - "3.4"
  - "3.5"
  - "3.6"
install:
  - pip install tox-travis
  - pip install python-coveralls

script:
  - tox
  - coverage run --source ibm_analytics_engine -m ibm_analytics_engine.iae
  - coverage report -m

after_success:
  - coveralls
</code>```

And my README has:

```<code>[![Pyversions](https://img.shields.io/pypi/pyversions/ibm-analytics-engine-python.svg?style=flat-square)](https://pypi.python.org/pypi/ibm-analytics-engine-python)
</code>```

However, my output looks like this:

Where does the pyversions information get taken from?  Is it from the pypi page?  If not, how do I get shields.io to reflect the versions of python my library supports?

答:
Ok, the python versions is read from PyPi.

I just needed to add this to my setup.py trove classifiers:

```<code>Programming Language :: Python
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to set my pyversion icon to my github README, similar to this:

I've been trying to reverse engineer the setup from the coveralls-python project.

My .travis.yaml file looks like this:

language: python
python:
  - "2.7"
  - "3.3"
  - "3.4"
  - "3.5"
  - "3.6"
install:
  - pip install tox-travis
  - pip install python-coveralls

script:
  - tox
  - coverage run --source ibm_analytics_engine -m ibm_analytics_engine.iae
  - coverage report -m

after_success:
  - coveralls

And my README has:

[![Pyversions](https://img.shields.io/pypi/pyversions/ibm-analytics-engine-python.svg?style=flat-square)](https://pypi.python.org/pypi/ibm-analytics-engine-python)

However, my output looks like this:

Where does the pyversions information get taken from?  Is it from the pypi page?  If not, how do I get shields.io to reflect the versions of python my library supports?

Body:
Ok, the python versions is read from PyPi.

I just needed to add this to my setup.py trove classifiers:

Programming Language :: Python
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5


问:
python tkinter package tk.call eval
I'm using python tkinter to run tcl in python
And there are two ways to run a tcl command:

```<code>import tkinter
root = tkinter.Tk()
root.eval("winfo exists .l0")
root.tk.call("winfo exists .l0")
</code>```

They have the same meaning

But what's different?
And if I haven't define a widget names .l0
and can I directly use

```<code>child = ".l0"
child.winfo_exists()
</code>```

?
Because python told me "str has no attribute winfo_exists"

答:
The difference is that call passes each argument to tcl as a separate word, where eval will evaluate a string by first parsing it and then executing it.

In other words, this:

```<code>root.eval("winfo exists .l0")
</code>```

... is functionally identical to this:

```<code>root.tk.call("winfo", "exists", ".l0")
</code>```

As for the error message 'str' object has no attribute 'winfo_exists', it means exactly that. "l0" is the name of an object in the embedded tcl interpreter, but in python "l0" is just a string and python strings don't have the attribute winfo_exists.

Title: python tkinter package tk.call eval

Body:
I'm using python tkinter to run tcl in python
And there are two ways to run a tcl command:

import tkinter
root = tkinter.Tk()
root.eval("winfo exists .l0")
root.tk.call("winfo exists .l0")

They have the same meaning

But what's different?
And if I haven't define a widget names .l0
and can I directly use

child = ".l0"
child.winfo_exists()

?
Because python told me "str has no attribute winfo_exists"

Body:
The difference is that call passes each argument to tcl as a separate word, where eval will evaluate a string by first parsing it and then executing it.

In other words, this:

root.eval("winfo exists .l0")

... is functionally identical to this:

root.tk.call("winfo", "exists", ".l0")

As for the error message 'str' object has no attribute 'winfo_exists', it means exactly that. "l0" is the name of an object in the embedded tcl interpreter, but in python "l0" is just a string and python strings don't have the attribute winfo_exists.


问:
SQL return the output of SELECT and not the output of another stored procedure
How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!

In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable @StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:

```<code>-- Main stored procedure
BEGIN
    DECLARE @StartDate DATETIME

    EXEC @StartDate = spCuExt_ExtractLog 'Customers'

    SELECT Id, [Name], LogoPath, IsDeleted
    FROM dbo.Customers
    WHERE RecordCreatedDateUTC>= @StartDate
END
</code>```

This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.

How do I do this?

答:
Put the results into a table variable instead:</p>

```<code>create procedure dbo.usp_Child
as
begin
    select N'Hello world!' as [message];
end;
go

create procedure dbo.usp_Main
as
begin;
    declare @results table ([message] nvarchar(max));

    insert into @results
    execute dbo.usp_Child;

    select N'success';
end;
go

execute dbo.usp_Main;
</code>```

Body:
How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!

In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable @StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:

-- Main stored procedure
BEGIN
    DECLARE @StartDate DATETIME

    EXEC @StartDate = spCuExt_ExtractLog 'Customers'

    SELECT Id, [Name], LogoPath, IsDeleted
    FROM dbo.Customers
    WHERE RecordCreatedDateUTC>= @StartDate
END

This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.

How do I do this?

Body:
Put the results into a table variable instead:

create procedure dbo.usp_Child
as
begin
    select N'Hello world!' as [message];
end;
go

create procedure dbo.usp_Main
as
begin;
    declare @results table ([message] nvarchar(max));

    insert into @results
    execute dbo.usp_Child;

    select N'success';
end;
go

execute dbo.usp_Main;


问:
Problems installing Docker for Windows CE

Unable to stop: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: The specified module 'Hyper-V' was not loaded because no valid module file was found in any module directory.
  at , : line 79
     at Docker.Backend.HyperV.RunScript(String action, Dictionary`2 parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Backend\HyperV.cs:line 177
     at Docker.Backend.ContainerEngine.Linux.DoStop() in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Backend\ContainerEngine\Linux.cs:line 279
     at Docker.Backend.ContainerEngine.Linux.Start(Settings settings, String daemonOptions) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Backend\ContainerEngine\Linux.cs:line 122
     at Docker.Core.Pipe.NamedPipeServer.<>c__DisplayClass9_0.b__0(Object[] parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Core\pipe\NamedPipeServer.cs:line 47
     at Docker.Core.Pipe.NamedPipeServer.RunAction(String action, Object[] parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Core\pipe\NamedPipeServer.cs:line 145

I have just download the stable version of Docker for Windows and after installing it I clicked on the icon and opened it, it gave the above error.

I have tried reinstalling it a couple of times, I have tried resetting to factory defaults, I have tried generating the following error code but cant find the solution anywhere, diagnostic-id:B5D6D78B-961A-48B2-AC08-2CEDD9BF5D2D/2017-10-13_18-45-00.

答:
The problem is that "Docker for Windows" isn't compatible with Windows 10 Home Edition. It requires Hyper-V which is only available in the Professional & Enterprise Editions. It doesn't clearly warn you about this though.

The solution according to Docker is to use Docker Toolbox for Windows instead.

Note: when I tried to install Docker Toolbox, I ran into several problems, and I had to uninstall VirtualBox and reinstall the official version from Oracle. It may be worth reading the Docker Toolbox setup instructions.


问:
loop through string to find substring
I have this string:

```<code>text = "book//title//page/section/para";
</code>```

I want to go through it to find all // and / and their index.

I tried doing this with:

```<code>if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}
</code>```

I was also thinking about using:

```<code>Foreach(char c in text)
</code>```

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

```<code>string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }
</code>```

Thank you in advance.

答:
You could replace // and / with your own words and then find the last index of

```<code>string s = "book//title//page/section/para";

        s = s.Replace("//", "DOUBLE");
        s = s.Replace("/", "SINGLE");

        IList<int> doubleIndex = new List<int>();

        while (s.Contains("DOUBLE"))
        {
            int index = s.IndexOf("DOUBLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "//");
            doubleIndex.Add(index);
        }

        IList<int> singleIndex = new List<int>();

        while (s.Contains("SINGLE"))
        {
            int index = s.IndexOf("SINGLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "/");
            singleIndex.Add(index);
        }
</code>```

Remember to first replace double, otherwise you'll get SINGLESINGLE for // instead of DOUBLE. Hope this helps.

Title: loop through string to find substring

Body:
I have this string:

text = "book//title//page/section/para";

I want to go through it to find all // and / and their index.

I tried doing this with:

if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));
}

I was also thinking about using:

Foreach(char c in text)

but it will not work since // is not a single char.

How can I achieve what I want?

I tried this one also but did not display result

string input = "book//title//page/section/para";
string pattern = @"\/\//";

Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }

Thank you in advance.

Body:
You could replace // and / with your own words and then find the last index of

string s = "book//title//page/section/para";

        s = s.Replace("//", "DOUBLE");
        s = s.Replace("/", "SINGLE");

        IList<int> doubleIndex = new List<int>();

        while (s.Contains("DOUBLE"))
        {
            int index = s.IndexOf("DOUBLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "//");
            doubleIndex.Add(index);
        }

        IList<int> singleIndex = new List<int>();

        while (s.Contains("SINGLE"))
        {
            int index = s.IndexOf("SINGLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "/");
            singleIndex.Add(index);
        }

Remember to first replace double, otherwise you'll get SINGLESINGLE for // instead of DOUBLE. Hope this helps.


问:
Name convention over a Rails Migration reference
i have a problem creating a db table through rails generators.

I named a table personal_data and works fine.

```<code>class CreatePersonalData < ActiveRecord::Migration
 def change
  create_table :personal_data do |t|
    t.string :name
    t.string :lastName
    t.string :dni
    t.string :contact
    t.references :user, index: true, foreign_key: true

    t.timestamps null: false
  end
 end
end
</code>```

But i created another table with a reference to Personal Data

```<code>class CreateMerchants < ActiveRecord::Migration
 def change
  create_table :merchants do |t|
    t.string :storeName
    t.references :personal_data, index: true, foreign_key: true
    t.references :category, index: true, foreign_key: true
    t.string :webPage
    t.string :city

    t.timestamps null: false
  end
 end
end
</code>```

And when a run the migration instead of seeking for personal_data_id the migrations looks for personal_datum_id and throws and exception.

PG::UndefinedColumn: ERROR:  no existe la columna «personal_datum_id» referida en la llave foránea
  : ALTER TABLE "merchants" ADD CONSTRAINT "fk_rails_e4239c30dc"
  FOREIGN KEY ("personal_datum_id")
    REFERENCES "personal_data" ("id")

I translate the error to English

column "personal_datum_id" referenced in foreign key constraint does not exist

答: add self.table_name = 'personal_data' in your personal_data.rb model and run the migration

Body:
i have a problem creating a db table through rails generators.

I named a table personal_data and works fine.

class CreatePersonalData < ActiveRecord::Migration
 def change
  create_table :personal_data do |t|
    t.string :name
    t.string :lastName
    t.string :dni
    t.string :contact
    t.references :user, index: true, foreign_key: true

    t.timestamps null: false
  end
 end
end

But i created another table with a reference to Personal Data

class CreateMerchants < ActiveRecord::Migration
 def change
  create_table :merchants do |t|
    t.string :storeName
    t.references :personal_data, index: true, foreign_key: true
    t.references :category, index: true, foreign_key: true
    t.string :webPage
    t.string :city

    t.timestamps null: false
  end
 end
end

And when a run the migration instead of seeking for personal_data_id the migrations looks for personal_datum_id and throws and exception.

PG::UndefinedColumn: ERROR:  no existe la columna «personal_datum_id» referida en la llave foránea
  : ALTER TABLE "merchants" ADD CONSTRAINT "fk_rails_e4239c30dc"
  FOREIGN KEY ("personal_datum_id")
    REFERENCES "personal_data" ("id")

I translate the error to English

column "personal_datum_id" referenced in foreign key constraint does not exist


问:
Polymer - How to remove an item from iron-list?
This live snippet builds a web-component which uses iron-list. Each item in the list has a delete button which, on click, removes the item from the list.
When an item is removed, all the next items shift up, but the last item displayed stays rather than disapear as it should be.

According to this stackoverflow, simply by firing the event resize on the iron-list should be enough. But in my snippet, this doesn't help. Nether the iron-resize or the notifyResize function from the official iron-list documentation.

<link rel="import"  href="https://polygit.org/components/polymer/polymer-element.html">
<link rel="import"  href="https://polygit.org/components/iron-list/iron-list.html">
<link rel="import"  href="https://polygit.org/components/paper-button/paper-button.html">

<dom-module id="my-list">
  <template>

    <iron-list id="list" items="{{items}}">

      <template>

            {{item}}

          <paper-button on-tap="_onDeleteClicked"
          style="background: red; color: white;">Remove</paper-button>

      </template>

    </iron-list>

  </template>

</dom-module>

<my-list></my-list>```

答:
You may find an "hidden" attribute on the last item. As items are reused by iron-list when scrolling the item does not get removed. This CSS rule should hide it away</p>

```<code>#list [hidden] { display: none; }
</code>```

Body:
You may find an "hidden" attribute on the last item. As items are reused by iron-list when scrolling the item does not get removed. This CSS rule should hide it away

#list [hidden] { display: none; }


问:
How to add content to ember component dynamically
I am writing a web application in ember.js for the first time. I'm using ember-leaflet in order to create a map, which is the main page of the application. The map is located in a component called main-map and looks like:

```<code>{{#leaflet-map lat=lat lng=lng zoom=zoom class="max-height" }}

  {{#each availableBasemaps as |basemap|}}
    {{#layer-group name=basemap.name default=basemap.default baselayer=true}}
      {{tile-layer url=basemap.url attribution=basemap.attrib}}
    {{/layer-group}}
  {{/each}}

  {{#each availableLayers as |lr|}}
    {{#layer-group name=lr.name default=lr.default}}
      {{wms-tile-layer url=lr.url version=lr.version layers=lr.layers format=lr.format styles=lr.styles transparent=lr.transparent}}
    {{/layer-group}}
  {{/each}}

  {{layer-control handler=(action "layerControlEvent")}}
{{/leaflet-map}}
</code>```

This main-map component is located in my application.hbs so it is present in all routes in my website. In one route that I have, called search-address, I need to add a marker to the map based on the user input. The marker will look something like:

```<code>{{#marker-layer location=Location}}
   {{#popup-layer}}
     <h4> My address </h4>
   {{/popup-layer}}
 {{/marker-layer}}
</code>```

I need a way to modify the main-map from within my search-address.js file in order to add these markers to my map. How can I accomplish this in Ember?

答:
Ember's application controller has currentRouteName property. Therefore you can reach current route's name in your application.hbs template or application.js controller anytime. In your case, in your application.js, you can define a computed property such as:

```<code>inSearchAddress: Ember.computed('currentRouteName', function(){
    return this.get('currentRouteName') === 'search-address';
})
</code>```

And in your application.hbs, you can pass this computed property to your main-map component such as {{main-map inSearchAddress=inSearchAddress}} and then use it in the component like:

```<code>{{#if inSearchAddress}}
    {{#marker-layer location=Location}}
        {{#popup-layer}}
           <h4> My address </h4>
        {{/popup-layer}}
     {{/marker-layer}}
{{/if}}
</code>```

You can also take a look at this twiddle for this usage.

Body:
I am writing a web application in ember.js for the first time. I'm using ember-leaflet in order to create a map, which is the main page of the application. The map is located in a component called main-map and looks like:

{{#leaflet-map lat=lat lng=lng zoom=zoom class="max-height" }}

  {{#each availableBasemaps as |basemap|}}
    {{#layer-group name=basemap.name default=basemap.default baselayer=true}}
      {{tile-layer url=basemap.url attribution=basemap.attrib}}
    {{/layer-group}}
  {{/each}}

  {{#each availableLayers as |lr|}}
    {{#layer-group name=lr.name default=lr.default}}
      {{wms-tile-layer url=lr.url version=lr.version layers=lr.layers format=lr.format styles=lr.styles transparent=lr.transparent}}
    {{/layer-group}}
  {{/each}}

  {{layer-control handler=(action "layerControlEvent")}}
{{/leaflet-map}}

This main-map component is located in my application.hbs so it is present in all routes in my website. In one route that I have, called search-address, I need to add a marker to the map based on the user input. The marker will look something like:

{{#marker-layer location=Location}}
   {{#popup-layer}}

 My address

   {{/popup-layer}}
 {{/marker-layer}}

I need a way to modify the main-map from within my search-address.js file in order to add these markers to my map. How can I accomplish this in Ember?

Body:
Ember's application controller has currentRouteName property. Therefore you can reach current route's name in your application.hbs template or application.js controller anytime. In your case, in your application.js, you can define a computed property such as:

inSearchAddress: Ember.computed('currentRouteName', function(){
    return this.get('currentRouteName') === 'search-address';
})

And in your application.hbs, you can pass this computed property to your main-map component such as {{main-map inSearchAddress=inSearchAddress}} and then use it in the component like:

{{#if inSearchAddress}}
    {{#marker-layer location=Location}}
        {{#popup-layer}}
           <h4> My address </h4>
        {{/popup-layer}}
     {{/marker-layer}}
{{/if}}

You can also take a look at this twiddle for this usage.


问:
posting automation
I use Joomla. I could use something other than Joomla if you recommend.

The scenario is: I want my website to automatically take new articles from various news websites (as soon as they are published) and post them on my website.

Or at least I want a mechanism of easing the process of taking articles from tens of websites and posting them on my website.

Thank you,

答:
This is a built in core function in 1.5. You can display RSS feeds in module positions or as a component.

You can find instructions here - http://docs.joomla.org/How_do_you_display_an_RSS_feed%3F

Title: posting automation


问:
Specify the dimensions of a Tkinter text box in pixels
How would I specify the dimensions of a Tkinter text box using pixels? I am not trying to change the font size, I am using this to help me scale it to the size of the window.</p>

答:
I've had the same question, and it seems that the simplest answer is to instantiate a Frame object of a specified size, pack it, and then use the place method to place and size widgets within it. I've found that the invocation of the pack_propagate(0) method on the Frame object is unnecessary.

Here's a short piece of code that exemplifies this method on several widgets.

The last widget instantiated in this script is a text box widget with the size specified in pixels, as per your question.

```<code>from Tkinter import * #For python 3 use: from Tkinter import *

root = Tk()
root.title("Fee Fie Foe Fum")
frame=Frame(root, width=300, height=160)
frame.pack()
button1 = Button(frame, text="Mercy!")
button1.place(x=10, y=10, height=30, width=100)
button2 = Button(frame, text="Justice!")
button2.place(x=10, y=50, height=30, width=100)
text1 = Label(text="Verdict:")
text1.place(x=10, y=90)
tbox1 = Text(frame)
tbox1.place(x=10, y=115, height=30, width=200)

root.mainloop()
</code>```

This does, of course, lock you into the place method for designing your Tkinter UI, but it does allow you to specify the dimensions of many widgets in pixels. Subsequent use of the pack method on child widgets will overwrite your placements and sizing.

Your code will probably be better organized if you express it in an object-oriented fashion, but this example simply shows the sequence of operations necessary to accomplish the sizing of widgets in pixels rather than other units.

Body:
I've had the same question, and it seems that the simplest answer is to instantiate a Frame object of a specified size, pack it, and then use the place method to place and size widgets within it. I've found that the invocation of the pack_propagate(0) method on the Frame object is unnecessary.

Here's a short piece of code that exemplifies this method on several widgets.

The last widget instantiated in this script is a text box widget with the size specified in pixels, as per your question.

from Tkinter import * #For python 3 use: from Tkinter import *

root = Tk()
root.title("Fee Fie Foe Fum")
frame=Frame(root, width=300, height=160)
frame.pack()
button1 = Button(frame, text="Mercy!")
button1.place(x=10, y=10, height=30, width=100)
button2 = Button(frame, text="Justice!")
button2.place(x=10, y=50, height=30, width=100)
text1 = Label(text="Verdict:")
text1.place(x=10, y=90)
tbox1 = Text(frame)
tbox1.place(x=10, y=115, height=30, width=200)

root.mainloop()

This does, of course, lock you into the place method for designing your Tkinter UI, but it does allow you to specify the dimensions of many widgets in pixels. Subsequent use of the pack method on child widgets will overwrite your placements and sizing.

Your code will probably be better organized if you express it in an object-oriented fashion, but this example simply shows the sequence of operations necessary to accomplish the sizing of widgets in pixels rather than other units.


问:
A global method that finds the average, and the highest speed of cars
I created the Car class with attributes and properties. In the main part of the program, I created a series of cars and initialized the values.

My program should use the global method to find the fastest car and average speed of all cars, the method must also return two results.

I tried to make This method, I made for a loop that will pass through every speed individually and  split it with the total number of cars in a row, then added to the variable average, does this make sense?

To find the fastest car in a row, I'm not sure how to do it, so I asked myself the question.

Can anyone explain to me about this speed finding algorithm in the global method and also generally about the whole task if I made a mistake in the definition of the same method?

```<code>class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }
}
</code>```

This is main program

```<code>class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}
</code>```

答:
You should simplify your class like this:

```<code>public class Car {
    public string Name { get; set; }
    public double Price { get; set; }
    public double Speed { get; set; }
}
</code>```

To return two results, you can either return a Tuple or pass your parameters by reference.

```<code>public static void GetMaxAndAverageFromCars(IEnumerable<Car> cars, ref double maxSpeed, ref double avgSpeed) {
    maxSpeed = cars.Max(c => c.Speed);
    avgSpeed = cars.Average(c => c.Speed);
}
</code>```

Use like this:

```<code>using System.Linq;

var cars = new Car[]
{
    // ..
};

double maxSpeed = 0.0;
double avgSpeed = 0.0;

GetMaxAndAverageFromCars(cars, ref maxSpeed, ref avgSpeed);
</code>```

Body:
I created the Car class with attributes and properties. In the main part of the program, I created a series of cars and initialized the values.

My program should use the global method to find the fastest car and average speed of all cars, the method must also return two results.

I tried to make This method, I made for a loop that will pass through every speed individually and  split it with the total number of cars in a row, then added to the variable average, does this make sense?

To find the fastest car in a row, I'm not sure how to do it, so I asked myself the question.

Can anyone explain to me about this speed finding algorithm in the global method and also generally about the whole task if I made a mistake in the definition of the same method?

class Car
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int price;

    public int Price
    {
        get { return price; }
        set { price = value; }
    }

    private float speed;

    public float Speed
    {
        get { return speed; }
        set { speed = value; }
    }
}

This is main program

class Program
{
    public static void MaxSpeedCarAverage(Car[] arraycar,float Maxspeed,float average)
    {
        for(int i=0;i<10;i++)
        {
            average+= arraycar[i].Speed / 10;
        }
    }

    static void Main(string[] args)
    {
        Car[] car = new Car[10]
        {
            new Car(){Name="Bmw",Price=5888,Speed=290 },     //initialisation of array//
            new Car(){Name="Mercedes",Price=7544,Speed=300},
            new Car(){Name="Peugeot",Price=4500,Speed=190},
            new Car(){Name="Renault",Price=6784,Speed=210},
            new Car(){Name="Fiat",Price=3221,Speed=180},
            new Car(){Name="Audi",Price=4500,Speed=240},
            new Car(){Name="Golf",Price=4500,Speed=255},
            new Car(){Name="Sab",Price=4500,Speed=332},
            new Car(){Name="Range Rover",Price=4500,Speed=340},
            new Car(){Name="Honda",Price=4500,Speed=267},

        };

    }
}

Body:
You should simplify your class like this:

public class Car {
    public string Name { get; set; }
    public double Price { get; set; }
    public double Speed { get; set; }
}

To return two results, you can either return a Tuple or pass your parameters by reference.

public static void GetMaxAndAverageFromCars(IEnumerable<Car> cars, ref double maxSpeed, ref double avgSpeed) {
    maxSpeed = cars.Max(c => c.Speed);
    avgSpeed = cars.Average(c => c.Speed);
}

Use like this:

using System.Linq;

var cars = new Car[]
{
    // ..
};

double maxSpeed = 0.0;
double avgSpeed = 0.0;

GetMaxAndAverageFromCars(cars, ref maxSpeed, ref avgSpeed);


问:
Exception thrown: read access violation. Cannot print info from a header file
I am trying to print out the information from pID pointer that is located in Objects.h header file. Whatever I try to do I get the "Exception thrown: read access violation. p was 0xCEDECEDF." error in Visual Studio 2017. In other words it is unable to read memory.
This is the code part from main.cpp file. The error comes in from the For cycle where I am trying to print out the info. I have debugged the code with no success.

```<code>#include "stdio.h"
#include "DateTime.h"
#include "Objects.h"
#include "Headers.h"
#include "Structs.h"
#include "malloc.h"
#pragma warning ( disable : 4996 )  //Disables some errors that might occure

void PrintObjects(Object9 **ppStruct1);
//int InsertNewObject(HeaderA **ppStruct1, char *pNewID, int NewCode);
//Object9* RemoveExistingObject(HeaderA **pStruct1, char *pExistingID);

int main()
{
    Object9 **pStruct1 = (Object9 **)GetStruct1(9, 35);

    Object9 **p = pStruct1;
    int i;
    for (i = 0; i < 35; i++)
    {
        printf("%p\n", *(p + i));
        printf("%s\n", (*(p + i))->pID); //This is the line where the error
        //occures
    }

    if (pStruct1 == NULL)
        printf("pStrcut on NULL\n");
    else
        printf("Ok\n");
    PrintObjects(pStruct1);

    return 0;
}
</code>```

This is the part from the Objects.h file.

```<code>typedef struct ob9
{  // formatting string for printf is "%s %lu %02d %s %04d\n", the result is
      for example "Abcde 100 01 Detsember 2010"
   // or "Abcde Fghij 100 01 Detsember 2010"
    char *pID;
    unsigned long int Code;
    Date3 *pDate3; // Declaration of Date3 is in file DateTime.h
    struct ob9 *pNext;
} Object9;
</code>```

The GetStruct1 function comes from the Structure.h header file. I don't know if this helps to determine the problem or not, but just in case I'm also adding the entire Structs.h file code.
I need to use: "void **GetStruct1(int ObjectType, int nObjects);" function.

```<code>//
//            Structures: function prototypes
//            -------------------------------

void **GetStruct1(int ObjectType, int nObjects);
HeaderA *GetStruct2(int ObjectType, int nObjects);
HeaderB *GetStruct3(int ObjectType, int nObjects);
HeaderC *GetStruct4(int ObjectType, int nObjects);
HeaderA **GetStruct5(int ObjectType, int nObjects);
HeaderA *GetStruct6(int ObjectType, int nObjects);
HeaderD *GetStruct7(int ObjectType, int nObjects);

/* ObjectType - 1, 2,...10 - type of objects to be inserted into the data
 structure.
   nTypes -number of objects to be inserted into the data structure.
   ObjectType and nObjects are specified by the instructor.
   Return value - pointer to the first byte of data structure.

   Examples for structure from 25 objects of type 4:
   Object4 **pStruct1 = (Object4 **)GetStruct1(4, 25);
   HeaderA *pStruct2 = GetStruct2(4, 25);
   HeaderB *pStruct3 = GetStruct3(4, 25);
   HeaderC *pStruct4 = GetStruct4(4, 25);
   HeaderA **pStruct5 = GetStruct5(4, 25);
*/
</code>```

I can print out the address but not the info I need. I know I am doing something wrong but don't know exactly what. Any help would be appreciated.

EDIT: Changed the code a bit.

答:
The problem is that you're overwriting the pointer returned by GetStruct1 with a new pointer from malloc() and this points to uninitialized data, not the array of structures. Get rid of the line:

```<code>pStruct1 = (Object9 **)malloc(sizeof(Object9 **));
</code>```

You also don't need this line:

```<code>p = (Object9 *)malloc(sizeof(Object9));
</code>```

since you immediately overwrite p with:

```<code>p = *pStruct1;
</code>```

You're also using p wrong. pStruct1 is a pointer to an array of pointers. When you set p as above, it's set to the first pointer in the array. Adding to p doesn't get you the next pointer in the array, it points outside the object that p pointed to. You need to set p to pStruct, add to this, and then indirect through that to get the pointer in the array.

```<code>Object9 **p = pStruct1;
for (int i = 0; i < 35; i++) }
    printf("%p\n", *(p + i));
    printf("%s\n", (*(p + i))->pID);
}
</code>```

Body:
I am trying to print out the information from pID pointer that is located in Objects.h header file. Whatever I try to do I get the "Exception thrown: read access violation. p was 0xCEDECEDF." error in Visual Studio 2017. In other words it is unable to read memory.
This is the code part from main.cpp file. The error comes in from the For cycle where I am trying to print out the info. I have debugged the code with no success.

#include "stdio.h"
#include "DateTime.h"
#include "Objects.h"
#include "Headers.h"
#include "Structs.h"
#include "malloc.h"
#pragma warning ( disable : 4996 )  //Disables some errors that might occure

void PrintObjects(Object9 **ppStruct1);
//int InsertNewObject(HeaderA **ppStruct1, char *pNewID, int NewCode);
//Object9* RemoveExistingObject(HeaderA **pStruct1, char *pExistingID);

int main()
{
    Object9 **pStruct1 = (Object9 **)GetStruct1(9, 35);

    Object9 **p = pStruct1;
    int i;
    for (i = 0; i < 35; i++)
    {
        printf("%p\n", *(p + i));
        printf("%s\n", (*(p + i))->pID); //This is the line where the error
        //occures
    }

    if (pStruct1 == NULL)
        printf("pStrcut on NULL\n");
    else
        printf("Ok\n");
    PrintObjects(pStruct1);

    return 0;
}

This is the part from the Objects.h file.

typedef struct ob9
{  // formatting string for printf is "%s %lu %02d %s %04d\n", the result is
      for example "Abcde 100 01 Detsember 2010"
   // or "Abcde Fghij 100 01 Detsember 2010"
    char *pID;
    unsigned long int Code;
    Date3 *pDate3; // Declaration of Date3 is in file DateTime.h
    struct ob9 *pNext;
} Object9;

The GetStruct1 function comes from the Structure.h header file. I don't know if this helps to determine the problem or not, but just in case I'm also adding the entire Structs.h file code.
I need to use: "void **GetStruct1(int ObjectType, int nObjects);" function.

//
//            Structures: function prototypes
//            -------------------------------

void **GetStruct1(int ObjectType, int nObjects);
HeaderA *GetStruct2(int ObjectType, int nObjects);
HeaderB *GetStruct3(int ObjectType, int nObjects);
HeaderC *GetStruct4(int ObjectType, int nObjects);
HeaderA **GetStruct5(int ObjectType, int nObjects);
HeaderA *GetStruct6(int ObjectType, int nObjects);
HeaderD *GetStruct7(int ObjectType, int nObjects);

/* ObjectType - 1, 2,...10 - type of objects to be inserted into the data
 structure.
   nTypes -number of objects to be inserted into the data structure.
   ObjectType and nObjects are specified by the instructor.
   Return value - pointer to the first byte of data structure.

   Examples for structure from 25 objects of type 4:
   Object4 **pStruct1 = (Object4 **)GetStruct1(4, 25);
   HeaderA *pStruct2 = GetStruct2(4, 25);
   HeaderB *pStruct3 = GetStruct3(4, 25);
   HeaderC *pStruct4 = GetStruct4(4, 25);
   HeaderA **pStruct5 = GetStruct5(4, 25);
*/

I can print out the address but not the info I need. I know I am doing something wrong but don't know exactly what. Any help would be appreciated.

EDIT: Changed the code a bit.

Body:
The problem is that you're overwriting the pointer returned by GetStruct1 with a new pointer from malloc() and this points to uninitialized data, not the array of structures. Get rid of the line:

pStruct1 = (Object9 **)malloc(sizeof(Object9 **));

You also don't need this line:

p = (Object9 *)malloc(sizeof(Object9));

since you immediately overwrite p with:

p = *pStruct1;

You're also using p wrong. pStruct1 is a pointer to an array of pointers. When you set p as above, it's set to the first pointer in the array. Adding to p doesn't get you the next pointer in the array, it points outside the object that p pointed to. You need to set p to pStruct, add to this, and then indirect through that to get the pointer in the array.

Object9 **p = pStruct1;
for (int i = 0; i < 35; i++) }
    printf("%p\n", *(p + i));
    printf("%s\n", (*(p + i))->pID);
}


问:
Find surfaces in 3d image
I'm working on a C++ project using a ToF camera. The camera is inside a room and has to detect walls, doors or other big planar surfaces. I'm currently using OpenCV but answers using other C++ libaries are also okay. What is a good algorithmn to detect the surfaces, also if they are rotated and aren't facing the camera directly. I've heard things like making a point cloud and using RANSAC. If you suggest me doing that please explain it in detail or provide a resource for explanation, because I don't know much about this topic (I'm a beginner in computer vision).

Thanks for your responses.

答:
Are you familiar with PCL?

This tutorial shows how to find planar segments in a point-cloud using PCL.

Title: Find surfaces in 3d image


问:
How do I use a Perl module from a relative location?
I have a dir called foo, and in that I have lib and bin.  The scripts in bin need stuff in lib.  I do something like this:

```<code>#!perl
use strict;
use warnings;
use lib '../lib';
use Foo; # <-- comes from lib
</code>```

But that means I have to be in the bin dir to run the script.  Surely there is a better way.  What's the Right Way to do this?

答:
```<code>use lib './';
</code>```

has been working for me with Perl v5.14.2 on a linux box to include files in the same directory as my script.

Perhaps it would work for you to move your lib and bin directories under your script's working directory and try to reference them using

```<code>use lib './bin/';
</code>```

Body:
I have a dir called foo, and in that I have lib and bin.  The scripts in bin need stuff in lib.  I do something like this:

#!perl
use strict;
use warnings;
use lib '../lib';
use Foo; # <-- comes from lib

But that means I have to be in the bin dir to run the script.  Surely there is a better way.  What's the Right Way to do this?

Body:
use lib './';

has been working for me with Perl v5.14.2 on a linux box to include files in the same directory as my script.

Perhaps it would work for you to move your lib and bin directories under your script's working directory and try to reference them using

use lib './bin/';


问:
Installation error: Unknown failure
I just opened a new Android project thorugh eclipse, I want the application to run on my samsung galaxy s4 which has KitKat 4.4.2 on it, so I opened the project so as Target SDK is 5.0.1  and the compilation will be done with 4.4.2, just when the project opens I get errors, i fixed it by accesing both appcompat and the projects project.properties and changing the target to apk-21. the errors vanish. But ! when I try to debug with my phone or with the emulator it fails, - Installation error: Unknown failure - thats the error, as I looked through the web I saw many people that get through this problem and non of the solutions was posted solved my problem. I will be really glad if someone could help me solve this annoying thing. Thank! !

答:
We had a similar issue in Android Nougat.

Reason happened to be renaming the Project Folder.

Build -> Clean Project

Build -> Rebuild Project

Try this out in case you have altered anything related to Project Structure or Gradle Settings.

Title: Installation error: Unknown failure


问:
Django counter in loop to index list
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

```<code>{% for i in list %}
</code>```

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

答:
You can't. The simple way is to preprocess you data in a zipped list, like this

In your view

```<code>x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
</code>```

Then in you template :

```<code>{% for x, y in zipped %}
    {{ x }} - {{ y }}
{% endfor %}
</code>```

Title: Django counter in loop to index list

Body:
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

Body:
You can't. The simple way is to preprocess you data in a zipped list, like this

In your view

x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)

Then in you template :

{% for x, y in zipped %}
    {{ x }} - {{ y }}
{% endfor %}


问:
Confused about Ruby on Rails routes.rb syntax
Suppose I had the following code in my routes.rb file.

```<code>  get '/dashboard', to: 'dashboard#index', :as => 'dashboard'
</code>```

I know what's going on (a public url being mapped to a specific controller/view file which will process and return the request). That is not what I am confused about.

As a Ruby beginner, I'm confused about what Ruby code convention this is. It doesn't look like the correct way to declare a variable or call a method? What exactly is going on and is this some sort of shorthand form to call a method?

```<code>get("/dashboard", "dashboard#index", "dashboard")
</code>```

答:
You're very close.

Yes, get is a method that is being called. In ruby, you can omit the parentheses. So,

```<code>get '/dashboard', to: 'dashboard#index', :as => 'dashboard'
</code>```

Is the same as:

```<code>get("/dashboard", to: "dashboard#index", :as => "dashboard")
</code>```

Where to: and :as are named parameters which are received by get as a hash.

I think this method is defined in action_dispatch/routing/mapper.rb:

```<code>module ActionDispatch
  module Routing
    class Mapper

      module HttpHelpers
        # Define a route that only recognizes HTTP GET.
        # For supported arguments, see match[rdoc-ref:Base#match]
        #
        #   get 'bacon', to: 'food#bacon'
        def get(*args, &block)
          map_method(:get, args, &block)
        end
        ...
      end

    end
  end
end
</code>```

So, you can see that to: "dashboard#index", :as => "dashboard" are received by *args and the splat operator allows for a variable length set of arguments.

Body:
Suppose I had the following code in my routes.rb file.

  get '/dashboard', to: 'dashboard#index', :as => 'dashboard'

I know what's going on (a public url being mapped to a specific controller/view file which will process and return the request). That is not what I am confused about.

As a Ruby beginner, I'm confused about what Ruby code convention this is. It doesn't look like the correct way to declare a variable or call a method? What exactly is going on and is this some sort of shorthand form to call a method?

get("/dashboard", "dashboard#index", "dashboard")

Body:
You're very close.

Yes, get is a method that is being called. In ruby, you can omit the parentheses. So,

get '/dashboard', to: 'dashboard#index', :as => 'dashboard'

Is the same as:

get("/dashboard", to: "dashboard#index", :as => "dashboard")

Where to: and :as are named parameters which are received by get as a hash.

I think this method is defined in action_dispatch/routing/mapper.rb:

module ActionDispatch
  module Routing
    class Mapper

      module HttpHelpers
        # Define a route that only recognizes HTTP GET.
        # For supported arguments, see match[rdoc-ref:Base#match]
        #
        #   get 'bacon', to: 'food#bacon'
        def get(*args, &block)
          map_method(:get, args, &block)
        end
        ...
      end

    end
  end
end

So, you can see that to: "dashboard#index", :as => "dashboard" are received by *args and the splat operator allows for a variable length set of arguments.


问:
Angular HttpClient get, wrong this object
in my Angular App i make a simple call to a node.js server. the HttpClient "get"
function returns the right answer. This answer I want to store in a variable of my component "interfaces". But in the "subscribe" function of the get request my "this" pointer doesn't point to my component. Instead it tells me that it is of type "SafeSubscriber". Any call to my member "interfaces" lead to the following error:
TypeError: Cannot read property 'interfaces' of undefined

```<code>export class SettingsComponent implements OnInit {

public interfaces : string[];

constructor(private http: HttpClient) {
    this.interfaces = [];
    this.interfaces.push("huhu");

}

ngOnInit() : void {

    this.http.get('http://localhost:3000/settings/interfaces').subscribe((data) => {
        // Read the result field from the JSON response.
        console.log(data);
        this.interfaces.push("xxx");
        Object.keys(data).forEach(function(k) {
            console.log(k);
            this.interfaces.push("xxx");
        });
    }),
    err => {
      console.log("error " + err);
    };
}
</code>```

}

As you can see I also tried to enter some values manually into the array just to make sure, that not the server response is causing the problem.
Any help is appreciated.

I used this code as a blueprint which is from:
https://angular.io/guide/http

```<code>@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}
</code>```

答:
You're losing reference to the correct this in this statement:

```<code>Object.keys(data).forEach(function(k) {..})
</code>```

Inside the function block code this refers to the calling context , which is the subscribe method itself, that's why interfaces is undefined, since it's not a property of the subscribe method.

You can change the function for a lambda en it should be fine:

```<code>Object.keys(data).forEach((k) => {..})
</code>```

Body:
in my Angular App i make a simple call to a node.js server. the HttpClient "get"
function returns the right answer. This answer I want to store in a variable of my component "interfaces". But in the "subscribe" function of the get request my "this" pointer doesn't point to my component. Instead it tells me that it is of type "SafeSubscriber". Any call to my member "interfaces" lead to the following error:
TypeError: Cannot read property 'interfaces' of undefined

export class SettingsComponent implements OnInit {

public interfaces : string[];

constructor(private http: HttpClient) {
    this.interfaces = [];
    this.interfaces.push("huhu");

}

ngOnInit() : void {

    this.http.get('http://localhost:3000/settings/interfaces').subscribe((data) => {
        // Read the result field from the JSON response.
        console.log(data);
        this.interfaces.push("xxx");
        Object.keys(data).forEach(function(k) {
            console.log(k);
            this.interfaces.push("xxx");
        });
    }),
    err => {
      console.log("error " + err);
    };
}

}

As you can see I also tried to enter some values manually into the array just to make sure, that not the server response is causing the problem.
Any help is appreciated.

I used this code as a blueprint which is from:
https://angular.io/guide/http

@Component(...)
export class MyComponent implements OnInit {

  results: string[];

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      this.results = data['results'];
    });
  }
}

Body:
You're losing reference to the correct this in this statement:

Object.keys(data).forEach(function(k) {..})

Inside the function block code this refers to the calling context , which is the subscribe method itself, that's why interfaces is undefined, since it's not a property of the subscribe method.

You can change the function for a lambda en it should be fine:

Object.keys(data).forEach((k) => {..})


问:
Most ellegant and efficent way of returning non-empty option
I'm trying to do a method for choosing an AB test option in Rails, according to a test result. I would like to find a more efficient way of doing the first nil test:
If given option A is nil, return B
If given option B is nil, return A</p>

```<code>module AbTestHelper
  def ab_test_choice(ab_test_name, option_a, option_b, *args)
      #This part
      return option_b unless option_a
      return option_a unless option_b
      #This part

      check_test_enabled = "#{ab_test_name}_enabled?"
      test_result = send(check_test_enabled, args) if respond_to? check_test_enabled
      return option_a if result
      option_b
  end

  private

  def colour_enabled?(user = current_user)
    return unless user.is_a? User
    user.enabled_for?(:colour)
  end
end
</code>```

答:
It seems ok to me but an alternative way is to use the ^ operator like this:

```<code>...
return option_a or option_b if !!option_a ^ !!option_b
...
</code>```

The ^ operator is an exclusive or, so it would be true only if one of the options is true or not nil.

The problem with this is it's less idiomatic and harder to understand than the original version.

Body:
I'm trying to do a method for choosing an AB test option in Rails, according to a test result. I would like to find a more efficient way of doing the first nil test:
If given option A is nil, return B
If given option B is nil, return A

module AbTestHelper
  def ab_test_choice(ab_test_name, option_a, option_b, *args)
      #This part
      return option_b unless option_a
      return option_a unless option_b
      #This part

      check_test_enabled = "#{ab_test_name}_enabled?"
      test_result = send(check_test_enabled, args) if respond_to? check_test_enabled
      return option_a if result
      option_b
  end

  private

  def colour_enabled?(user = current_user)
    return unless user.is_a? User
    user.enabled_for?(:colour)
  end
end

Body:
It seems ok to me but an alternative way is to use the ^ operator like this:

...
return option_a or option_b if !!option_a ^ !!option_b
...

The ^ operator is an exclusive or, so it would be true only if one of the options is true or not nil.

The problem with this is it's less idiomatic and harder to understand than the original version.


问:
Oracle regexp pattern matching instances of a but not ab
I have seen from from oracle documentation I can do a|b which will match all instances of character 'a 'or character 'b'. I wondered if it was possible in regexp to have 'a' and not 'b' e.g. match all instances of 'a' except where a is followed by 'b'.

so with these 3 strings

AAAA

ACAD

AAAB

I want to match 1 and 2 but not 3.

答:
You could try:

```<code>with x as (
  select 'AAAA' as str from dual
  union all
  select 'ACAD' as str from dual
  union all
  select 'AAAB' as str from dual
)
select * from x
where regexp_like(str, '[aA][^bB]')
and NOT regexp_like(str, '[aA][bB]')
</code>```

Output:

```<code>AAAA
ACAD
</code>```

Note:  If you don't care if A is followed by some other non-B char, you can simply do:

```<code>with x as (
  select 'AAAA' as str from dual
  union all
  select 'ACAD' as str from dual
  union all
  select 'AAAB' as str from dual
)
select * from x
where regexp_like(str, '[aA]')
and NOT regexp_like(str, '[aA][bB]')
</code>```

which would match "AAAA" or "XYZA"

Body:
You could try:

with x as (
  select 'AAAA' as str from dual
  union all
  select 'ACAD' as str from dual
  union all
  select 'AAAB' as str from dual
)
select * from x
where regexp_like(str, '[aA][^bB]')
and NOT regexp_like(str, '[aA][bB]')

Output:

AAAA
ACAD

Note:  If you don't care if A is followed by some other non-B char, you can simply do:

with x as (
  select 'AAAA' as str from dual
  union all
  select 'ACAD' as str from dual
  union all
  select 'AAAB' as str from dual
)
select * from x
where regexp_like(str, '[aA]')
and NOT regexp_like(str, '[aA][bB]')

which would match "AAAA" or "XYZA"


问:
Bash paths calculation

I would like to know why in order to get current directory from within a script we need to use solution such as:DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" taken from here.

Instead of something like:

DIR=$("pwd")

Once I have current directory of current script, and I want to calculate its parent's parent parent directory path, how do I do that?
In terminal its simply cd ../../../, how this can be caluclated on DIR and assigned to a new variable?

What is the difference in bash assignment between NUM:=1 and NUM=1

Cheers

答:
That's not the current directory, but the directory where the script is located. Other similar solutions are readlink -f "${0%/*}" etc.

You can add the double dots to the DIR:

```<code>great_grand_parent=$DIR/../../..
</code>```

Call readlink or do the magic with cd to get rid of the double dots.

NUM:=1 is not an assignment at all.

Title: Bash paths calculation

Body:
That's not the current directory, but the directory where the script is located. Other similar solutions are readlink -f "${0%/*}" etc.

You can add the double dots to the DIR:

great_grand_parent=$DIR/../../..

Call readlink or do the magic with cd to get rid of the double dots.

NUM:=1 is not an assignment at all.


问:
Python: Making Different Parameters Global
I am having problems making some variables global in this code. I would like the outputted numbers to be 4, 8, 6, and 10. The output is always just 1, 2, 3, and 4 like the function does not process the numbers at all. I tried making each variable global before, after, and inside the function, but this did not work. If anyone has a solution to this, it would be greatly appreciated. My actual code for my project has several more pairs of variables, I just included these to simplify it. </p>

```<code>Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4
def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
function(Xone, Yone)
function(Xtwo, Ytwo)
print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)
</code>```

答:
If you want modification inside the function - you may use mutable types, like class A:

Live demo: https://repl.it/repls/ActiveSpottedArizonaalligatorlizard

Body:
I am having problems making some variables global in this code. I would like the outputted numbers to be 4, 8, 6, and 10. The output is always just 1, 2, 3, and 4 like the function does not process the numbers at all. I tried making each variable global before, after, and inside the function, but this did not work. If anyone has a solution to this, it would be greatly appreciated. My actual code for my project has several more pairs of variables, I just included these to simplify it.

Xone = 1
Yone = 2
Xtwo = 3
Ytwo = 4
def function(parameterOne, parameterTwo):
    parameterOne = parameterOne + 3
    parameterTwo = parameterTwo + 6
function(Xone, Yone)
function(Xtwo, Ytwo)
print str(Xone)
print str(Yone)
print str(Xtwo)
print str(Ytwo)


问:
Find folder of specific file
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

```<code>find 2>/dev/null / -name libgfortran.so
</code>```

... which will output something like the following to stdout (redirecting stderr to /dev/null):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

From this I want to extract just the folder (without a trailing /):

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8
</code>```

I've got as far as trying something like:

```<code>find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'
</code>```

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

```<code>/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so
</code>```

How do I achieve what I want?

答:
```<code>find / -name libgfortran.so -exec dirname {} \; 2> /dev/null
</code>```

Title: Find folder of specific file

Body:
I am trying to find the folder location of a specific file, for this example libgfortran.so.

What I've tried so far is:

find 2>/dev/null / -name libgfortran.so

... which will output something like the following to stdout (redirecting stderr to /dev/null):

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

From this I want to extract just the folder (without a trailing /):

/usr/lib/gcc/x86_64-linux-gnu/4.8

I've got as far as trying something like:

find 2>/dev/null / -name libgfortran.so | sed 's/\(\/.*\/\)/\1/'

... which I was hoping would capture what is between the first and last / (I would then need to remove the last /), but the output I get is still:

/usr/lib/gcc/x86_64-linux-gnu/4.8/libgfortran.so

How do I achieve what I want?


问:
git-svn branching without copying every subdirectory
Our project's trunk looks something like:

```<code>trunk/foo
trunk/bar
trunk/baz
</code>```

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

```<code>branches/branch1/foo
branches/branch2/foo
</code>```

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

```<code>branches/branch1/foo
branches/branch1/bar
</code>```

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

答:
svn copy will happily operate at any level in the folder structure.

Just do:

```<code>svn cp trunk/foo branches/branch1/foo
</code>```

Think of it like a typical unix filesystem.

You might have to add --parents to the cp line if branch1 doesn't exist yet.

Body:
Our project's trunk looks something like:

trunk/foo
trunk/bar
trunk/baz

The subdirectories foo, bar, and baz are actually unrelated to each other, and bar and baz are actually quite huge. How do I create a branch with just foo, such that my branches would look something like:

branches/branch1/foo
branches/branch2/foo

Right now, what I'm doing is branching the whole trunk, then deleting bar and baz, but I think that would be problematic during the merge since it would try to delete bar and baz. What I'd like is for it to be intelligent enough to know that I just want to work with foo and not do anything with bar or baz.

Secondary question, not as important, what if I want a branch with foo and bar, like:

branches/branch1/foo
branches/branch1/bar

Would the process for branching these two folders without branching the others be harder?

Edit:
It's been pointed out to me that I can use svn cp. This works, but I was hoping to work from a git svn repo, and as far as I can tell, the closest analogue git-svn has to svn cp is git svn branch, which automatically handles the copying. Unfortunately, I can't find any option in there that lets me branch just a specific subdirectory.

Body:
svn copy will happily operate at any level in the folder structure.

Just do:

svn cp trunk/foo branches/branch1/foo

Think of it like a typical unix filesystem.

You might have to add --parents to the cp line if branch1 doesn't exist yet.


问:
In matlab, how to get all edges of a polygon whose indices are labelled by integers using sets
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

```<code>faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5
</code>```

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

答:
The super quick and easy way is to use the triangulation class and edges method to find them. Given your faces connectivity matrix from above and assuming your vertex data is in vertices:

```<code>TR = triangulation(faces, vertices);
edgeMatrix = edges(TR);
</code>```

And the result:

```<code>edgeMatrix =

     1     3
     1     4
     1     5
     1     6
     2     3
     2     4
     2     5
     2     6
     3     5
     3     6
     4     5
     4     6
</code>```

Body:
To put the problem in context: I have a 3D polygon, whose vertices are all labelled by integers 1,...,N, and I have a n*3 matrix faces each of whose rows indicates one of its triangular faces. E.g.

faces =

     1     3     5
     2     4     6
     1     3     6
     2     4     5
     1     4     5
     2     3     6
     1     4     6
     2     3     5

So the first row [1 3 5] denotes the face formed by vertices 1 3 5 and so on. Now I want to get all the edges of these faces.

So I want to use the concept of a set (non-ordered, unique elements). For each row of faces there are three edges, corresponding to three sets, say, {1, 3}, {1, 5}, {3, 5} (here I'm borrowing notations from Python). And I want to create a set of all these sets for all rows. How to do it in Matlab?

In Python it seems I simply can't do a set of sets, since sets are unhashable. In Matlab, it seems everything is a matrix, so I may have to still use a 1x2 matrix to represent each edge, which is fine, but what I want is I don't get duplicated edges. For example, [1 2] and [2 1] are one same edge so I have to make sure one and only one of them is retained in the final dataset.

Body:
The super quick and easy way is to use the triangulation class and edges method to find them. Given your faces connectivity matrix from above and assuming your vertex data is in vertices:

TR = triangulation(faces, vertices);
edgeMatrix = edges(TR);

And the result:

edgeMatrix =

     1     3
     1     4
     1     5
     1     6
     2     3
     2     4
     2     5
     2     6
     3     5
     3     6
     4     5
     4     6