问:
Google Maps Autocomplete Province
I am using Google Maps APIs guide for autocomplete:

https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

but it seems it is not possible to detect Italy provinces.

For instance: typing an Italian address "Caronno Pertusella, VA, Italia", I'm not able to detect "VA".

I tried add and change parameters: https://developers.google.com/maps/documentation/javascript/geocoding

but I can not find province parameter.

答:
That could have been easier. I think you are looking for administrative_area_level_2. Because this levels differs from country to country you have to test, which level fits your need. Attached an example with administrative_area_level_2 ('short_name'). You may play a little bit with that, Reinhard

<!DOCTYPE html>

    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>

        Street address
        <input class="field" id="street_number"
              disabled="true"></input>
        <input class="field" id="route"
              disabled="true"></input>

        City

        <input class="field" id="locality"
              disabled="true"></input>

        Region
        <input class="field"
              id="administrative_area_level_2" disabled="true"></input>
        Zip code
        <input class="field" id="postal_code"
              disabled="true"></input>

        State
        <input class="field"
              id="administrative_area_level_1" disabled="true"></input>

  Country
        <input class="field"
              id="country" disabled="true"></input>

```

Title: Google Maps Autocomplete Province

Body:
That could have been easier. I think you are looking for administrative_area_level_2. Because this levels differs from country to country you have to test, which level fits your need. Attached an example with administrative_area_level_2 ('short_name'). You may play a little bit with that, Reinhard

<!DOCTYPE html>
<html>
  <head>
    <title>Place Autocomplete Address Form</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <link type="text/css" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">
    <style>
      #locationField, #controls {
        position: relative;
        width: 480px;
      }
      #autocomplete {
        position: absolute;
        top: 0px;
        left: 0px;
        width: 99%;
      }
      .label {
        text-align: right;
        font-weight: bold;
        width: 100px;
        color: #303030;
      }
      #address {
        border: 1px solid #000090;
        background-color: #f0f0ff;
        width: 480px;
        padding-right: 2px;
      }
      #address td {
        font-size: 10pt;
      }
      .field {
        width: 99%;
      }
      .slimField {
        width: 80px;
      }
      .wideField {
        width: 200px;
      }
      #locationField {
        height: 20px;
        margin-bottom: 2px;
      }
    </style>
  </head>

  <body>
    <div id="locationField">
      <input id="autocomplete" placeholder="Enter your address"
             onFocus="geolocate()" type="text"></input>
    </div>

    <table id="address">
      <tr>
        <td class="label">Street address</td>
        <td class="slimField"><input class="field" id="street_number"
              disabled="true"></input></td>
        <td class="wideField" colspan="2"><input class="field" id="route"
              disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">City</td>
        <!-- Note: Selection of address components in this example is typical.
             You may need to adjust it for the locations relevant to your app. See
             https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
        -->
        <td class="wideField" colspan="3"><input class="field" id="locality"
              disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">Region</td>
        <td class="slimField"><input class="field"
              id="administrative_area_level_2" disabled="true"></input></td>
        <td class="label">Zip code</td>
        <td class="wideField"><input class="field" id="postal_code"
              disabled="true"></input></td>
      </tr>
      <tr>
        <td class="label">State</td>
        <td class="wideField" colspan="3"><input class="field"
              id="administrative_area_level_1" disabled="true"></input></td>
   </tr>
      <tr>
  <td class="label">Country</td>
        <td class="wideField" colspan="3"><input class="field"
              id="country" disabled="true"></input></td>
      </tr>
    </table>

    <script>
      // This example displays an address form, using the autocomplete feature
      // of the Google Places API to help users fill in the information.

      // This example requires the Places library. Include the libraries=places
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">

      var placeSearch, autocomplete;
      var componentForm = {
        street_number: 'short_name',
        route: 'long_name',
        locality: 'long_name',
        administrative_area_level_1: 'short_name',
        administrative_area_level_2: 'short_name',
  country: 'long_name',
        postal_code: 'short_name'
      };

      function initAutocomplete() {
        // Create the autocomplete object, restricting the search to geographical
        // location types.
        autocomplete = new google.maps.places.Autocomplete(
            /** @type {!HTMLInputElement} */(document.getElementById('autocomplete')),
            {types: ['geocode']});

        // When the user selects an address from the dropdown, populate the address
        // fields in the form.
        autocomplete.addListener('place_changed', fillInAddress);
      }

      function fillInAddress() {
        // Get the place details from the autocomplete object.
        var place = autocomplete.getPlace();

        for (var component in componentForm) {
          document.getElementById(component).value = '';
          document.getElementById(component).disabled = false;
        }

        // Get each component of the address from the place details
        // and fill the corresponding field on the form.
        for (var i = 0; i < place.address_components.length; i++) {
          var addressType = place.address_components[i].types[0];
          if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];
            document.getElementById(addressType).value = val;
          }
        }
      }

    </script>
    <script src="https://maps.googleapis.com/maps/api/js?&libraries=places&callback=initAutocomplete"
        async defer></script>
  </body>
</html>


来源: stackexchange

问:
UICollectionView with buttons
I am using a UICollectionView and I am thinking how to add buttons for each collection view cell and I don't want all buttons to do the same actions. I need to change buttons actions. I don't know how to do that.

```<code>import UIKit

class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    var imagescv = ["cv1","cv2","cv3","cv4","cv5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imagescv.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellimagesar

        cell.layer.cornerRadius = 5

        cell.layer.borderWidth = 1

        cell.myImages.image = UIImage(named: imagescv [indexPath.row])
        cell.myImages.contentMode = .scaleToFill
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 182, height: 290)
    }
}
</code>```

答:
Assign the tag and action to the button inside the collectionviewcell.
Assign indexPath.item as button tag is the best approach to identify the particular button from the number of cells.
All you need to do within cellForItemAt delegate method.

```<code>cell.btnCounter.tag = indexPath.item
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)
</code>```

And now you just need to handle the event as below

```<code>func buttonClicked(_ sender: UIButton) {
        //Here sender.tag will give you the tapped Button index from the cell
        //You can identify the button from the tag
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: UICollectionView with buttons

Body:
I am using a UICollectionView and I am thinking how to add buttons for each collection view cell and I don't want all buttons to do the same actions. I need to change buttons actions. I don't know how to do that.

import UIKit

class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    var imagescv = ["cv1","cv2","cv3","cv4","cv5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imagescv.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellimagesar

        cell.layer.cornerRadius = 5

        cell.layer.borderWidth = 1

        cell.myImages.image = UIImage(named: imagescv [indexPath.row])
        cell.myImages.contentMode = .scaleToFill
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 182, height: 290)
    }
}

Body:
Assign the tag and action to the button inside the collectionviewcell.
Assign indexPath.item as button tag is the best approach to identify the particular button from the number of cells.
All you need to do within cellForItemAt delegate method.

cell.btnCounter.tag = indexPath.item
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

And now you just need to handle the event as below

func buttonClicked(_ sender: UIButton) {
        //Here sender.tag will give you the tapped Button index from the cell
        //You can identify the button from the tag
    }


问:
External Wordpress Blog Feed display
Working to display Blog lists of external wordpress blog.
There is a PHP issue in the code, it only shows only one</p>

```<code>  add_shortcode( 'first', 'foobar_func' );

  function foobar_func( $atts ){

    $feed = fetch_feed( 'https://wordpress.org/news/feed/' );

    if (!is_wp_error($feed)):
      $maxitems = $feed->get_item_quantity(3);
      $rss_items = $feed->get_items(CURL_HTTP_VERSION_1_0, $maxitems);
    endif;

    if ($maxitems == 0) {
      return '<li>No items.</li>';
    } else foreach ( $rss_items as $item )  {
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
      $first_img = $matches [1][0];
      $testts = esc_html($item->get_title());
    }
    return $testts;
  }
</code>```

答:
Try this instead. Notice CURL_HTTP_VERSION_1_0 has been swapped for 0.

```<code>  add_shortcode( 'first', 'foobar_func' );

  function foobar_func( $atts ){

    $feed = fetch_feed( 'https://wordpress.org/news/feed/' );

    if (!is_wp_error($feed)):
      $maxitems = $feed->get_item_quantity(3);
      $rss_items = $feed->get_items(0, $maxitems);
    endif;

    if ($maxitems == 0) {
      return '<li>No items.</li>';
    } else foreach ( $rss_items as $item )  {
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
      $first_img = $matches [1][0];
      $testts = esc_html($item->get_title());
    }
    return $testts;
  }
</code>```

Title: External Wordpress Blog Feed display

Body:
Working to display Blog lists of external wordpress blog.
There is a PHP issue in the code, it only shows only one

  add_shortcode( 'first', 'foobar_func' );

  function foobar_func( $atts ){

    $feed = fetch_feed( 'https://wordpress.org/news/feed/' );

    if (!is_wp_error($feed)):
      $maxitems = $feed->get_item_quantity(3);
      $rss_items = $feed->get_items(CURL_HTTP_VERSION_1_0, $maxitems);
    endif;

    if ($maxitems == 0) {
      return '
No items.
';
    } else foreach ( $rss_items as $item )  {
      $output = preg_match_all('//i', $item->get_content(), $matches);
      $first_img = $matches [1][0];
      $testts = esc_html($item->get_title());
    }
    return $testts;
  }

Body:
Try this instead. Notice CURL_HTTP_VERSION_1_0 has been swapped for 0.

  add_shortcode( 'first', 'foobar_func' );

  function foobar_func( $atts ){

    $feed = fetch_feed( 'https://wordpress.org/news/feed/' );

    if (!is_wp_error($feed)):
      $maxitems = $feed->get_item_quantity(3);
      $rss_items = $feed->get_items(0, $maxitems);
    endif;

    if ($maxitems == 0) {
      return '<li>No items.</li>';
    } else foreach ( $rss_items as $item )  {
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $item->get_content(), $matches);
      $first_img = $matches [1][0];
      $testts = esc_html($item->get_title());
    }
    return $testts;
  }


问:
I am trying to use custom php function in twig, what am I doing wrong?
I tried to use my custom php function in twig.
When I type {{current_url}} in my page.html.twig nothing happens.
I also tried {{kint(current_url)}}, it outputs NULL
This is my code

```<code><?php
namespace Drupal\nextprev\plugin\block\customtwigoutput;

use Drupal\Core\Template\TwigExtension;
use  Drupal\nextprev\nextprevmodule\path;
use \Symfony\Component\HttpFoundation\Request;

class AppExtension extends \Twig_Extension {

public function url() {
   $current_path = \Drupal::service('path.current')->getPath();
   return $current_path;
}

  public function getFilters() {
     return array(
       'current_url' => new \Twig_Function_Function(array('Drupal\nextprev\plugin\block\customtwigoutput\AppExtension', 'url')),
     );
   }
}
</code>```

What am I doing wrong?

答:
Maybe you should try with a twig function instead :

In your extension :

```<code>public function getFunctions()
{
    return array(
        new \Twig_SimpleFunction('current_url', array($this, 'url')),
    );
}
</code>```

In your view

```<code> {{ current_url() }}
</code>```

Body:
I tried to use my custom php function in twig.
When I type {{current_url}} in my page.html.twig nothing happens.
I also tried {{kint(current_url)}}, it outputs NULL
This is my code

<?php
namespace Drupal\nextprev\plugin\block\customtwigoutput;

use Drupal\Core\Template\TwigExtension;
use  Drupal\nextprev\nextprevmodule\path;
use \Symfony\Component\HttpFoundation\Request;

class AppExtension extends \Twig_Extension {

public function url() {
   $current_path = \Drupal::service('path.current')->getPath();
   return $current_path;
}

  public function getFilters() {
     return array(
       'current_url' => new \Twig_Function_Function(array('Drupal\nextprev\plugin\block\customtwigoutput\AppExtension', 'url')),
     );
   }
}

What am I doing wrong?

Body:
Maybe you should try with a twig function instead :

In your extension :

public function getFunctions()
{
    return array(
        new \Twig_SimpleFunction('current_url', array($this, 'url')),
    );
}

In your view

 {{ current_url() }}


问:
Can't get rid of non-unicode characters in numpy array
I have a table:
vals = table.iloc[sum(which(pa_i),[1]),1:]
content:

```<code>Out[249]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]
</code>```

When I write vals.values I get:
vals

```<code>Out[250]: array([['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']], dtype=object)
</code>```

I simply want to get this table to an array or list but earlier want to replace \xa0 values. When I apply:
v = print(map(lambda s: s.replace('\xa0' , ' '), vals)) I don't know how to read this object or when
np.char.replace(vals[0],'\xa0' , ' ') I get error "TypeError: string operation on non-string array".

What is the easiest way to convert the content to array or to replace unwanted chars??

EDIT

I've got a solution: v = vals.astype('str') and v = np.char.replace(v,'\xa0' , ' ').

```<code>Out[306]: array([['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']], dtype='<U20')
</code>```

But I'm not fully satisfied of this answer. I need something to work directly on vals variable - for example by doing this:
a = vals[1:].toarray(?)
expected result:

```<code>a
Out[318]: ['(16.0 to N/A)', '12.0 [2]', 'NA [1]]']
</code>```

答:
I have found the best way:

```<code>vals
Out[357]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]
</code>```

a = vals.values.tolist()

```<code>a
Out[358]: [['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']]
</code>```

a1 = [w.replace('\xa0', ' ') for w in a[0]]

```<code>a1
Out[359]: ['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']
</code>```

Pffff. Maybe not the prettiest in terms of coding habits but what can we do.

Body:
I have a table:
vals = table.iloc[sum(which(pa_i),[1]),1:]
content:

Out[249]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]

When I write vals.values I get:
vals

Out[250]: array([['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']], dtype=object)

I simply want to get this table to an array or list but earlier want to replace \xa0 values. When I apply:
v = print(map(lambda s: s.replace('\xa0' , ' '), vals)) I don't know how to read this object or when
np.char.replace(vals[0],'\xa0' , ' ') I get error "TypeError: string operation on non-string array".

What is the easiest way to convert the content to array or to replace unwanted chars??

EDIT

I've got a solution: v = vals.astype('str') and v = np.char.replace(v,'\xa0' , ' ').

Out[306]: array([['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']], dtype='<U20')

But I'm not fully satisfied of this answer. I need something to work directly on vals variable - for example by doing this:
a = vals[1:].toarray(?)
expected result:

a
Out[318]: ['(16.0 to N/A)', '12.0 [2]', 'NA [1]]']

Body:
I have found the best way:

vals
Out[357]:
                      1         2       3
2  NA [1] (16.0 to N/A)  12.0 [2]  NA [1]

a = vals.values.tolist()

a
Out[358]: [['NA\xa0[1] (16.0\xa0to\xa0N/A)', '12.0\xa0[2]', 'NA\xa0[1]']]

a1 = [w.replace('\xa0', ' ') for w in a[0]]

a1
Out[359]: ['NA [1] (16.0 to N/A)', '12.0 [2]', 'NA [1]']

Pffff. Maybe not the prettiest in terms of coding habits but what can we do.


问:
Apply recurring conditional check to all derived classes
I got a job base class with an abstract Work() method. This gets overridden/implemented in my inherited classes.

What I want to achieve is applying an abort condition to all derived classes. The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()-class.

A workaround would be making Work() virtual, but then I'm no longer forcing the implementation of it (what I want to do):

```<code>public abstract class First
{
    protected virtual void Work()
    {
        //do stuff
    }
}

public class Second : First
{
    protected override void Work()
    {
        base.Work();
    }
}
</code>```

Is there any way to achieve my goal?

答:
The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()

You picked the right pattern, but you did not apply it properly.

The idea behind the template method pattern is to make Work non-virtual, and provide a separate method, virtual or abstract, for subclasses to override. This way all the checks that could abort a job would be performed in the Work function of the base class, while the derived classes would provide actual implementations for what to do when the checks have succeeded:

```<code>public abstract class First {
    public void Work() {
        if (!CheckPreconditions()) {
            // Abort the job
            return;
        }
        DoWork();
    }
    protected abstract void DoWork();
}

public class Second : First {
    protected override void DoWork() {
        // Do the actual work here
    }
}
</code>```

Body:
I got a job base class with an abstract Work() method. This gets overridden/implemented in my inherited classes.

What I want to achieve is applying an abort condition to all derived classes. The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()-class.

A workaround would be making Work() virtual, but then I'm no longer forcing the implementation of it (what I want to do):

public abstract class First
{
    protected virtual void Work()
    {
        //do stuff
    }
}

public class Second : First
{
    protected override void Work()
    {
        base.Work();
    }
}

Is there any way to achieve my goal?

Body:
The template method pattern doesn't seem to help me here, because I need this check to occur in my abstract Work()

You picked the right pattern, but you did not apply it properly.

The idea behind the template method pattern is to make Work non-virtual, and provide a separate method, virtual or abstract, for subclasses to override. This way all the checks that could abort a job would be performed in the Work function of the base class, while the derived classes would provide actual implementations for what to do when the checks have succeeded:

public abstract class First {
    public void Work() {
        if (!CheckPreconditions()) {
            // Abort the job
            return;
        }
        DoWork();
    }
    protected abstract void DoWork();
}

public class Second : First {
    protected override void DoWork() {
        // Do the actual work here
    }
}


问:
Prolog recursively replace elements of list with elements of another list
Apologies for lack of clarity in title. The following is a very specific predicate I'm building, which is only partially working as intended.

```<code>% replace_elements(+SearchingElementsList,+ReplacementsList,+OriginalList,-ResultingList).
% ResultingList consists of all elements of SearchingElementsList replaced by elements of ReplacementsList respectively.

replace_elements([],[],_,_).
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H \= H3,                                 % H is not H3, therefore
    replace_elements([H|T],[H2|T2],T3,List). % Skip this element and continue with T3.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).          % H is found in OriginalList. Continue with tails.
</code>```

Currently:

```<code>?- replace_elements([1,2,3],[one,two,three],[1,2,3,4,5],Result).
?- Result = [one,two,three|_7636].
</code>```

Expected:

```<code>?- Result = [one,two,three,4,5].
</code>```

Any hint would be appreciated!

Edit: Came up with a working answer for my specific problem.

```<code>% Eventually, recursion starts from all empty lists.
replace_elements([],[],[],[]).
% Rules are empty, push remaining H to List.
replace_elements([],[],[H|T],[H|List]) :-
    replace_elements([],[],T,List).
% Empty list, just go through remaining rules.
replace_elements([H|T],[H2|T2],[],List) :-
    replace_elements(T,T2,[],List).
% H < H3, move to next element in rules.
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H < H3,
    replace_elements(T,T2,[H3|T3],List).
% H > H3, move to next element in original list.
replace_elements([H|T],[H2|T2],[H3|T3],[H3|List]) :-
    H > H3,
    replace_elements([H|T],[H2|T2],T3,List).
% Element is the same, push replacement H2 to List.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).
</code>```

答:
I'll provide a thought process for solving the problem. A couple of principles would be:

Thinking relationally rather than imperatively

Top down design

You want:

```<code>replace_elements(+SearchingElementsList, +ReplacementsList, +OriginalList, -ResultingList).
</code>```

I'll rename it a little to make it not be as imperative:

```<code>translated_list(Trans1, Trans2, List1, List2).
</code>```

I removed the + and - because, ideally, we'd like this to be as general a relation as possible. This is a relation that the corresponding elements in List1 and List2 are related to each other via the "translation table" defined by corresponding elements in Trans1 and Trans2.

In Prolog, when considering corresponding list elements, that makes me immediately think of using something like maplist. Also, it's awkward handling two independent lists to define a 1-1 relationship between terms. It is easier and cleaner to use a single translation table with elements that look like, say, t1-t2.

```<code>translated_list(Trans1, Trans2, List1, List2) :-
    % TransTable is a translation table consisting of t1-t2 pairs from Trans1 and Trans2
    maplist(trans_table_element, Trans1, Trans2, TransTable),

    % List1 and List2 are related using the translation table, TransTable
    maplist(corresponding_element(TransTable), List1, List2).
</code>```

Now we need a predicate trans_table that provides a relationship between translation table elements. This relation says that an element in the translation table is E1-E2 where the corresponding individual elements are E1 and E2:

```<code>trans_table_element(E1, E2, E1-E2).
</code>```

And we need a predicate that describes two corresponding elements using a translation table.

```<code>corresponding_element(TransTable, E1, E2) :-
(    member(E1-E2, TransTable)
->   true            % Translation exists
;    E1 = E2         % Translation doesn't exist
).
</code>```

From this, you get:

```<code>| ?- translated_list([1,2,3], [one, two, three], [4,1,3,5,2,1,3], L).

L = [4,one,three,5,two,one,three]

yes
| ?-
</code>```

As well as:

```<code>| ?- translated_list([1,2,3], [one, two, three], L, [4,one,three,5,two,one,three]).

L = [4,1,3,5,2,1,3] ? a

no
</code>```

And

```<code>| ?- translated_list(A, B, [4,1,3,5,2,1,3], [4,one,three,5,two,one,three]).

A = [4,1,3,5,2]
B = [4,one,three,5,two] ? ;

A = [4,1,3,5,2,_]
B = [4,one,three,5,two,_] ? ;

...
</code>```

If you want to enforce in your rules that the translation table only translates between different elements, then you could define:

```<code>trans_table_element(E1, E2, E1-E2) :- dif(E1, E2).
</code>```

And then you'd get (using SWI Prolog this time):

```<code>2 ?-  translated_list(A, B, [4,1,3,5,2,1,3], [4,one,three,5,two,one,three]).
A = [1, 3, 2],
B = [one, three, two] ;
A = [1, 3, 2, _1240],
B = [one, three, two, _1276],
dif(_1240, _1276) ;
A = [1, 3, 2, _1492, _1498],
B = [one, three, two, _1534, _1540],
dif(_1492, _1534),
dif(_1498, _1540) ;
...
</code>```

UPDATE

A possible improvement in the above implementation to make it more relational by avoiding the ->/; construct, we can define non-membership relationally using maplist.

```<code>corresponding_element(TransTable, E1, E2) :-
    member(E1-E2, TransTable).
corresponding_element(TransTable, E1, E2) :-
    maplist(dif(E1-E2), TransTable),
    E1 = E2.
</code>```

In addition to the above results, yields:

```<code>6 ?- translated_list([1,2,3],Ts,[1,2,3,4,5],R).
Ts = [_9016, _9034, _9052],
R = [_9016, _9034, _9052, 4, 5] ;
Ts = [_9640, _9646, _9652],
R = [_9640, _9646, 3, 4, 5],
dif(3, _9652) ;
Ts = [_9640, _9646, _9652],
R = [_9640, 2, _9652, 4, 5],
dif(2, _9646) ;
Ts = [_9856, _9862, _9868],
R = [_9856, 2, 3, 4, 5],
dif(2, _9862),
dif(3, _9868)
...
</code>```

Body:
Apologies for lack of clarity in title. The following is a very specific predicate I'm building, which is only partially working as intended.

% replace_elements(+SearchingElementsList,+ReplacementsList,+OriginalList,-ResultingList).
% ResultingList consists of all elements of SearchingElementsList replaced by elements of ReplacementsList respectively.

replace_elements([],[],_,_).
replace_elements([H|T],[H2|T2],[H3|T3],List) :-
    H \= H3,                                 % H is not H3, therefore
    replace_elements([H|T],[H2|T2],T3,List). % Skip this element and continue with T3.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).          % H is found in OriginalList. Continue with tails.

Currently:

?- replace_elements([1,2,3],[one,two,three],[1,2,3,4,5],Result).
?- Result = [one,two,three|_7636].

Expected:

?- Result = [one,two,three,4,5].

Any hint would be appreciated!

Edit: Came up with a working answer for my specific problem.

% Eventually, recursion starts from all empty lists.
replace_elements([],[],[],[]).
% Rules are empty, push remaining H to List.
replace_elements([],[],[H|T],[H|List]) :-
    replace_elements([],[],T,List).
% Empty list, just go through remaining rules.
replace_elements([H|T],[H2|T2],[],List) :-
    replace_elements(T,T2,[],List).
% H  H3,
    replace_elements([H|T],[H2|T2],T3,List).
% Element is the same, push replacement H2 to List.
replace_elements([H|T],[H2|T2],[H|T3],[H2|List]) :-
    replace_elements(T,T2,T3,List).

Body:
I'll provide a thought process for solving the problem. A couple of principles would be:

Thinking relationally rather than imperatively

Top down design

You want:

replace_elements(+SearchingElementsList, +ReplacementsList, +OriginalList, -ResultingList).

I'll rename it a little to make it not be as imperative:

translated_list(Trans1, Trans2, List1, List2).

I removed the + and - because, ideally, we'd like this to be as general a relation as possible. This is a relation that the corresponding elements in List1 and List2 are related to each other via the "translation table" defined by corresponding elements in Trans1 and Trans2.

In Prolog, when considering corresponding list elements, that makes me immediately think of using something like maplist. Also, it's awkward handling two independent lists to define a 1-1 relationship between terms. It is easier and cleaner to use a single translation table with elements that look like, say, t1-t2.

translated_list(Trans1, Trans2, List1, List2) :-
    % TransTable is a translation table consisting of t1-t2 pairs from Trans1 and Trans2
    maplist(trans_table_element, Trans1, Trans2, TransTable),

    % List1 and List2 are related using the translation table, TransTable
    maplist(corresponding_element(TransTable), List1, List2).

Now we need a predicate trans_table that provides a relationship between translation table elements. This relation says that an element in the translation table is E1-E2 where the corresponding individual elements are E1 and E2:

trans_table_element(E1, E2, E1-E2).

And we need a predicate that describes two corresponding elements using a translation table.

corresponding_element(TransTable, E1, E2) :-
(    member(E1-E2, TransTable)
->   true            % Translation exists
;    E1 = E2         % Translation doesn't exist
).

From this, you get:

| ?- translated_list([1,2,3], [one, two, three], [4,1,3,5,2,1,3], L).

L = [4,one,three,5,two,one,three]

yes
| ?-

As well as:

| ?- translated_list([1,2,3], [one, two, three], L, [4,one,three,5,two,one,three]).

L = [4,1,3,5,2,1,3] ? a

no

And

| ?- translated_list(A, B, [4,1,3,5,2,1,3], [4,one,three,5,two,one,three]).

A = [4,1,3,5,2]
B = [4,one,three,5,two] ? ;

A = [4,1,3,5,2,_]
B = [4,one,three,5,two,_] ? ;

...

If you want to enforce in your rules that the translation table only translates between different elements, then you could define:

trans_table_element(E1, E2, E1-E2) :- dif(E1, E2).

And then you'd get (using SWI Prolog this time):

2 ?-  translated_list(A, B, [4,1,3,5,2,1,3], [4,one,three,5,two,one,three]).
A = [1, 3, 2],
B = [one, three, two] ;
A = [1, 3, 2, _1240],
B = [one, three, two, _1276],
dif(_1240, _1276) ;
A = [1, 3, 2, _1492, _1498],
B = [one, three, two, _1534, _1540],
dif(_1492, _1534),
dif(_1498, _1540) ;
...

UPDATE

A possible improvement in the above implementation to make it more relational by avoiding the ->/; construct, we can define non-membership relationally using maplist.

corresponding_element(TransTable, E1, E2) :-
    member(E1-E2, TransTable).
corresponding_element(TransTable, E1, E2) :-
    maplist(dif(E1-E2), TransTable),
    E1 = E2.

In addition to the above results, yields:

6 ?- translated_list([1,2,3],Ts,[1,2,3,4,5],R).
Ts = [_9016, _9034, _9052],
R = [_9016, _9034, _9052, 4, 5] ;
Ts = [_9640, _9646, _9652],
R = [_9640, _9646, 3, 4, 5],
dif(3, _9652) ;
Ts = [_9640, _9646, _9652],
R = [_9640, 2, _9652, 4, 5],
dif(2, _9646) ;
Ts = [_9856, _9862, _9868],
R = [_9856, 2, 3, 4, 5],
dif(2, _9862),
dif(3, _9868)
...


问:
How to manage annotation based Hibernate versioning for time stamp column in which value generated by DB
We can generate version column's value by using below tag in our hbm file:

<timestamp column="MODIFICATION_DATE"
           name="modificationDate"
           access="property"
           unsaved-value="undefined"
           source="db"
           generated="always"/>
```

<p>What is the corresponding hibernate notation to generate value for time stamp column which date type?</p>

```private java.util.Date modificationDate;
```

答:
You may want to use the appropriate JPA annotations to achieve the desired result, for example, as follows:

```<code>@Version
@Temporal(TemporalType.TIMESTAMP)
private Date modificationDate;
</code>```

Please note:

An entity may access the state of its version field or property or export a method for use by the application to access the version, but must not modify the version value[34]. With the exception noted in section 4.10, only the persistence provider is permitted to set or update the value of the version attribute in the object.

The version attribute is updated by the persistence provider runtime when the object is written to the database. All non-relationship fields and properties and all relationships owned by the entity are included in version checks[35].

[34] Bulk update statements, however, are permitted to set the value of version attributes. See section 4.10.

[35] This includes owned relationships maintained in join tables.

— JSR 338: Java™ Persistence 2.1, Final Release, page 90.

Body:
We can generate version column's value by using below tag in our hbm file:

<timestamp column="MODIFICATION_DATE"
           name="modificationDate"
           access="property"
           unsaved-value="undefined"
           source="db"
           generated="always"/>

What is the corresponding hibernate notation to generate value for time stamp column which date type?

private java.util.Date modificationDate;

Body:
You may want to use the appropriate JPA annotations to achieve the desired result, for example, as follows:

@Version
@Temporal(TemporalType.TIMESTAMP)
private Date modificationDate;

Please note:

An entity may access the state of its version field or property or export a method for use by the application to access the version, but must not modify the version value[34]. With the exception noted in section 4.10, only the persistence provider is permitted to set or update the value of the version attribute in the object.

The version attribute is updated by the persistence provider runtime when the object is written to the database. All non-relationship fields and properties and all relationships owned by the entity are included in version checks[35].

[34] Bulk update statements, however, are permitted to set the value of version attributes. See section 4.10.

[35] This includes owned relationships maintained in join tables.

— JSR 338: Java™ Persistence 2.1, Final Release, page 90.


问:
Override Method or EventListener: stop creation process and show warning just the first time in EasyAdmin?
I am using EasyAdmin in my SF 3.3 project but I need to achieve something different from how EasyAdmin has been built for. Take a look at the following picture:

As you might notice a user can be in more than one GroupingRole. Having that information the challenge is:

Check if the user has been assigned to any other GroupingRole

If the criteria meets the condition then show a warning message saying "The user A is already assigned to GroupingRole A" and prevent the record to be created. (this message could be in a popup, a javascript alert or an alert from Bootstrap - since EA already uses it)

When the admin click once again on "Save changes" the record should be created.

What I want to achieve with this approach is to alert the admin that the user is already to any other group but not stop him for create the record.

I have achieve some part of it already by override the prePersist method for just that entity (see below):

```<code>class AdminController extends BaseAdminController
{
    /**
     * Check if the users has been assigned to any group
     */
    protected function prePersistGroupingRoleEntity($entity)
    {
        $usersToGroupRoleEntities = $this->em->getRepository('CommonBundle:UsersToGroupRole')->findAll();
        $usersToGroupRole         = [];

        /** @var UsersToGroupRole $groupRole */
        foreach ($usersToGroupRoleEntities as $groupRole) {
            $usersToGroupRole[$groupRole->getGroupingRoleId()][] = $groupRole->getUsersId();
        }

        $usersInGroup = [];

        /** @var Users $userEntity */
        foreach ($entity->getUsersInGroup() as $userEntity) {
            foreach ($usersToGroupRole as $group => $users) {
                if (\in_array($userEntity->getId(), $users, true)) {
                    $usersInGroup[$group][] = $userEntity->getId();
                }
            }
        }

        $groupingRoleEnt = $this->em->getRepository('CommonBundle:GroupingRole');
        $usersEnt        = $this->em->getRepository('CommonBundle:Users');

        $message = [];
        foreach ($usersInGroup as $group => $user) {
            foreach($user as $usr) {
                $message[] = sprintf(
                    'The user %s already exists in %s group!',
                    $usersEnt->find($usr)->getEmail(),
                    $groupingRoleEnt->find($group)->getName()
                );
            }
        }
    }
}
</code>```

What I don't know is how to stop the record to be created and instead show the warning just the first time the button is clicked because the second time and having the warning in place I should allow to create the record.

Can any give me some ideas and/or suggestions?

UPDATE: adding entities information

In addition to the code displayed above here is the entities involved in such process:

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="grouping_role")
 */
class GroupingRole
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="integer",unique=true,nullable=false)
     * @ORM\GeneratedValue
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="role_name", type="string", nullable=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="role_description", type="string", nullable=false)
     */
    private $description;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Schneider\QuoteBundle\Entity\Distributor", inversedBy="groupingRole")
     * @ORM\JoinTable(name="grouping_to_role",
     *   joinColumns={
     *     @ORM\JoinColumn(name="grouping_role_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="DistributorID", referencedColumnName="DistributorID", nullable=false)
     *   }
     * )
     *
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "You must select at least one Distributor"
     * )
     */
    private $distributorGroup;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="CommonBundle\Entity\Users", inversedBy="usersGroup")
     * @ORM\JoinTable(name="users_to_group_role",
     *   joinColumns={
     *     @ORM\JoinColumn(name="grouping_role_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="users_id", referencedColumnName="users_id", nullable=false)
     *   }
     * )
     *
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "You must select at least one user"
     * )
     */
    private $usersInGroup;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->distributorGroup = new ArrayCollection();
        $this->usersInGroup     = new ArrayCollection();
    }
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="users_to_group_role")
 */
class UsersToGroupRole
{
    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\Column(type="integer",nullable=false)
     * @Assert\Type(type="integer")
     * @Assert\NotNull()
     */
    protected $usersId;

    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\Column(type="integer", nullable=false)
     * @Assert\Type(type="integer")
     * @Assert\NotNull()
     */
    protected $groupingRoleId;
}
</code>```

答:
A little example by using form validation approach in EasyAdminBundle:

```<code>class AdminController extends EasyAdminController
{
    // ...

    protected function create<EntityName>EntityFormBuilder($entity, $view)
    {
        $builder = parent::createEntityFormBuilder($entity, $view);

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();

            $flag = false;
            if (isset($data['flag'])) {
                $flag = $data['flag'];
                unset($data['flag']);
            }
            $key = md5(json_encode($data));

            if ($flag !== $key) {
                $event->getForm()->add('flag', HiddenType::class, ['mapped' => false]);
                $data['flag'] = $key;
                $event->setData($data);
            }
        });

        return $builder;
    }

    protected function get<EntityName>EntityFormOptions($entity, $view)
    {
        $options = parent::getEntityFormOptions($entity, $view);

        $options['validation_groups'] = function (FormInterface $form) {
            if ($form->has('flag')) {
                return ['Default', 'CheckUserGroup'];
            }

            return ['Default'];
        };

        $options['constraints'] = new Callback([
            'callback' => function($entity, ExecutionContextInterface $context) {
                // validate here and adds the violation if applicable.

                $context->buildViolation('Warning!')
                    ->atPath('<field>')
                    ->addViolation();
            },
            'groups' => 'CheckUserGroup',
        ]);

        return $options;
    }
}
</code>```

Note that PRE_SUBMIT event is triggered before the validation process happen.

The flag field is added (dynamically) the first time upon submitted the form, so the validation group CheckUserGroup is added and the callback constraint do its job. Later, the second time the submitted data contains the flag hash (if the data does not changes) the flag field is not added, so the validation group is not added either and the entity is saved (same if the callback constraint does not add the violation the first time).

Also (if you prefer) you can do all this inside a custom form type for the target entity.

Body:
I am using EasyAdmin in my SF 3.3 project but I need to achieve something different from how EasyAdmin has been built for. Take a look at the following picture:

As you might notice a user can be in more than one GroupingRole. Having that information the challenge is:

Check if the user has been assigned to any other GroupingRole

If the criteria meets the condition then show a warning message saying "The user A is already assigned to GroupingRole A" and prevent the record to be created. (this message could be in a popup, a javascript alert or an alert from Bootstrap - since EA already uses it)

When the admin click once again on "Save changes" the record should be created.

What I want to achieve with this approach is to alert the admin that the user is already to any other group but not stop him for create the record.

I have achieve some part of it already by override the prePersist method for just that entity (see below):

class AdminController extends BaseAdminController
{
    /**
     * Check if the users has been assigned to any group
     */
    protected function prePersistGroupingRoleEntity($entity)
    {
        $usersToGroupRoleEntities = $this->em->getRepository('CommonBundle:UsersToGroupRole')->findAll();
        $usersToGroupRole         = [];

        /** @var UsersToGroupRole $groupRole */
        foreach ($usersToGroupRoleEntities as $groupRole) {
            $usersToGroupRole[$groupRole->getGroupingRoleId()][] = $groupRole->getUsersId();
        }

        $usersInGroup = [];

        /** @var Users $userEntity */
        foreach ($entity->getUsersInGroup() as $userEntity) {
            foreach ($usersToGroupRole as $group => $users) {
                if (\in_array($userEntity->getId(), $users, true)) {
                    $usersInGroup[$group][] = $userEntity->getId();
                }
            }
        }

        $groupingRoleEnt = $this->em->getRepository('CommonBundle:GroupingRole');
        $usersEnt        = $this->em->getRepository('CommonBundle:Users');

        $message = [];
        foreach ($usersInGroup as $group => $user) {
            foreach($user as $usr) {
                $message[] = sprintf(
                    'The user %s already exists in %s group!',
                    $usersEnt->find($usr)->getEmail(),
                    $groupingRoleEnt->find($group)->getName()
                );
            }
        }
    }
}

What I don't know is how to stop the record to be created and instead show the warning just the first time the button is clicked because the second time and having the warning in place I should allow to create the record.

Can any give me some ideas and/or suggestions?

UPDATE: adding entities information

In addition to the code displayed above here is the entities involved in such process:

/**
 * @ORM\Entity
 * @ORM\Table(name="grouping_role")
 */
class GroupingRole
{
    /**
     * @ORM\Id
     * @ORM\Column(name="id", type="integer",unique=true,nullable=false)
     * @ORM\GeneratedValue
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="role_name", type="string", nullable=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="role_description", type="string", nullable=false)
     */
    private $description;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Schneider\QuoteBundle\Entity\Distributor", inversedBy="groupingRole")
     * @ORM\JoinTable(name="grouping_to_role",
     *   joinColumns={
     *     @ORM\JoinColumn(name="grouping_role_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="DistributorID", referencedColumnName="DistributorID", nullable=false)
     *   }
     * )
     *
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "You must select at least one Distributor"
     * )
     */
    private $distributorGroup;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="CommonBundle\Entity\Users", inversedBy="usersGroup")
     * @ORM\JoinTable(name="users_to_group_role",
     *   joinColumns={
     *     @ORM\JoinColumn(name="grouping_role_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="users_id", referencedColumnName="users_id", nullable=false)
     *   }
     * )
     *
     * @Assert\Count(
     *      min = 1,
     *      minMessage = "You must select at least one user"
     * )
     */
    private $usersInGroup;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->distributorGroup = new ArrayCollection();
        $this->usersInGroup     = new ArrayCollection();
    }
}

/**
 * @ORM\Entity()
 * @ORM\Table(name="users_to_group_role")
 */
class UsersToGroupRole
{
    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\Column(type="integer",nullable=false)
     * @Assert\Type(type="integer")
     * @Assert\NotNull()
     */
    protected $usersId;

    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\Column(type="integer", nullable=false)
     * @Assert\Type(type="integer")
     * @Assert\NotNull()
     */
    protected $groupingRoleId;
}

Body:
A little example by using form validation approach in EasyAdminBundle:

class AdminController extends EasyAdminController
{
    // ...

    protected function create<EntityName>EntityFormBuilder($entity, $view)
    {
        $builder = parent::createEntityFormBuilder($entity, $view);

        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
            $data = $event->getData();

            $flag = false;
            if (isset($data['flag'])) {
                $flag = $data['flag'];
                unset($data['flag']);
            }
            $key = md5(json_encode($data));

            if ($flag !== $key) {
                $event->getForm()->add('flag', HiddenType::class, ['mapped' => false]);
                $data['flag'] = $key;
                $event->setData($data);
            }
        });

        return $builder;
    }

    protected function get<EntityName>EntityFormOptions($entity, $view)
    {
        $options = parent::getEntityFormOptions($entity, $view);

        $options['validation_groups'] = function (FormInterface $form) {
            if ($form->has('flag')) {
                return ['Default', 'CheckUserGroup'];
            }

            return ['Default'];
        };

        $options['constraints'] = new Callback([
            'callback' => function($entity, ExecutionContextInterface $context) {
                // validate here and adds the violation if applicable.

                $context->buildViolation('Warning!')
                    ->atPath('<field>')
                    ->addViolation();
            },
            'groups' => 'CheckUserGroup',
        ]);

        return $options;
    }
}

Note that PRE_SUBMIT event is triggered before the validation process happen.

The flag field is added (dynamically) the first time upon submitted the form, so the validation group CheckUserGroup is added and the callback constraint do its job. Later, the second time the submitted data contains the flag hash (if the data does not changes) the flag field is not added, so the validation group is not added either and the entity is saved (same if the callback constraint does not add the violation the first time).

Also (if you prefer) you can do all this inside a custom form type for the target entity.


问:
Python double for loop
I'm having trouble with my loops. I get an error for 400 being out of range. Am I applying something that is not allowed, or what is my issue? It looks like legal syntax to me? </p>

```<code>survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)
</code>```

答:
You're confusing values with indexes. In Python, the for x in ... syntax returns each of the elements in an iterable object, not the indexes. Try this instead:

```<code>for t in survTime:
     for a in age:
        if t > 365 and a < 50:
        # and so on
</code>```

Notice that you intended to iterate over the values of each array, but in reality you're using each item as an index, which is way out of bounds - for instance: survTime doesn't have 400 elements! For completeness' sake: if you really needed the indexes, the way to traverse a list called lst would be:

```<code>for i in range(len(lst)):
    ele = lst[i] # do something with the element
</code>```

Title: Python double for loop

Body:
I'm having trouble with my loops. I get an error for 400 being out of range. Am I applying something that is not allowed, or what is my issue? It looks like legal syntax to me?

survTime=np.array([400, 800, 1100, 900])
age=np.array([40, 40, 40, 40])
counter_1yr=0
counter_2yr=0
counter_3yr=0
n=1
for i in survTime:
     for j in age:
        if survTime[i] > 365 and age[j] < 50:
            counter_1yr+=1
            n+=1
            continue
        elif survTime[i] > 730 and age[j] < 50:
            counter_2yr+=1
            n+=1
            continue
        elif survTime[i] > 1095 and age[j] < 50:
            counter_3yr+=1
            n+=1
            continue
print("1 year probability: ", counter_1yr/n)
print("2 year probability: ", counter_2yr/n)
print("3 year probability: ", counter_3yr/n)

Body:
You're confusing values with indexes. In Python, the for x in ... syntax returns each of the elements in an iterable object, not the indexes. Try this instead:

for t in survTime:
     for a in age:
        if t > 365 and a < 50:
        # and so on

Notice that you intended to iterate over the values of each array, but in reality you're using each item as an index, which is way out of bounds - for instance: survTime doesn't have 400 elements! For completeness' sake: if you really needed the indexes, the way to traverse a list called lst would be:

for i in range(len(lst)):
    ele = lst[i] # do something with the element


问:
Unable to parse timezone string provided by twitter API
Twitter's user timeline API is giving me timezone information in its response payload in two different ways - utc_offset (integer) and time_zone (string)

e.g.
"utc_offset": -18000,
"time_zone": "Eastern Time (US & Canada)",

I intend to store timezone string field in PostgreSQL via my Spring application and want to be able to derive the correct timestamp later using the same.

That would mean I should be able to parse the time_zone field to obtain the timezone information but its format doesn't adhere to what java.util.TimeZone expects. I tried it and because its unable to parse the above format, it falls back to UTC.

Is there a java library that understands the format given by twitter? Its hard to imagine that Twitter will use a non-standard timezone format in its feed.

NOTE:- I am looking for pure Java based solution and not Rails

答:
```<code>    DateTimeFormatter parser = DateTimeFormatter.ofPattern("zzzz");
    String timeZoneFromTwitter = "Eastern Time (US & Canada)";
    ParsePosition position = new ParsePosition(0);
    ZoneId zid = ZoneId.from(parser.parse(timeZoneFromTwitter, position));
    System.out.println(zid);
</code>```

This prints (at least on my computer)

```<code>America/New_York
</code>```

I honestly don’t know how far it will help you, and I admit it’s on the edge of cheating. What really happens is the formatter parses “Eastern Time” only and stops. This is enough that it can recognize the time zone as America/New_York. The ParsePosition is there to specify that we do not require it to parse all of the string.

You mentioned java.util.TimeZone. I encourage you to drop that class and its friends, they are long outdated. java.time, the modern Java date and time API also known as JSR-310 is generally much nicer to work with, so why don’t you make this your habit?

Body:
    DateTimeFormatter parser = DateTimeFormatter.ofPattern("zzzz");
    String timeZoneFromTwitter = "Eastern Time (US & Canada)";
    ParsePosition position = new ParsePosition(0);
    ZoneId zid = ZoneId.from(parser.parse(timeZoneFromTwitter, position));
    System.out.println(zid);

This prints (at least on my computer)

America/New_York

I honestly don’t know how far it will help you, and I admit it’s on the edge of cheating. What really happens is the formatter parses “Eastern Time” only and stops. This is enough that it can recognize the time zone as America/New_York. The ParsePosition is there to specify that we do not require it to parse all of the string.

You mentioned java.util.TimeZone. I encourage you to drop that class and its friends, they are long outdated. java.time, the modern Java date and time API also known as JSR-310 is generally much nicer to work with, so why don’t you make this your habit?


问:
How to generate and copy a SSH key in one line on macOS?
I use this command to generate a key:

```<code>ssh-keygen -t rsa -b 4096 -C "your_email@example.com"`
</code>```

However I do not want to save it as a file, instead I would like to copy it to my clipboard so it is ready to be pasted.

How can I do that? How to combine this with some sort of copy to clipboard command?

I tried the following command but it didn't work:

```<code>pbcopy ssh-keygen -t rsa -b 4096 -C "your_email@example.com"ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
</code>```

答:
You should create a script (or a function) to achieve this. Example with a script:

genkey.sh

```<code>#!/bin/bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f $1 && pbcopy < $1.pub
</code>```

The first command generates a key at the location given in the first argument of the script. The second one, pbcopy, copies the content of the newly-generated public key in your clipboard.

When running the script, feed it the path to the private key you want to generate:

```<code>sh genkey.sh ~/.ssh/id_rsa
</code>```

Body:
I use this command to generate a key:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"`

However I do not want to save it as a file, instead I would like to copy it to my clipboard so it is ready to be pasted.

How can I do that? How to combine this with some sort of copy to clipboard command?

I tried the following command but it didn't work:

pbcopy ssh-keygen -t rsa -b 4096 -C "your_email@example.com"ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Body:
You should create a script (or a function) to achieve this. Example with a script:

genkey.sh

#!/bin/bash
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" -f $1 && pbcopy < $1.pub

The first command generates a key at the location given in the first argument of the script. The second one, pbcopy, copies the content of the newly-generated public key in your clipboard.

When running the script, feed it the path to the private key you want to generate:

sh genkey.sh ~/.ssh/id_rsa


问:
What are MVP and MVC and what is the difference?
When looking beyond the RAD (drag-drop and configure) way of building user interfaces that many tools encourage you are likely to come across three design patterns called Model-View-Controller, Model-View-Presenter and Model-View-ViewModel. My question has three parts to it:

What issues do these patterns address?

How are they similar?

How are they different?

答: The simplest answer is how the view interacts with the model. In MVP the view is updated by the presenter, which acts as as intermediary between the view and the model. The presenter takes the input from the view, which retrieves the data from the model and then performs any business logic required and then updates the view. In MVC the model updates the view directly rather than going back through the controller.</p>

LastEditorDisplayName: Steve M

ContentLicense: CC BY-SA 4.0


问:
Custom Elements data attributes not working
I am trying to make a custom html element and pass along with its instantiation some custom data tags.  The problem is its dataset is always empty, and I can't figure out what I am doing wrong.  I'm following the example from MDN on custom elements.. and this example does work in my browsers.. Additionally, I can successfully pass custom data tags when I add a standard img on my page, but not when I use my custom html element.

Below are my js file (defined in MyImage.js) and my html file.  Along side these is an image called small.jpg.

class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);
  }
}

// Define the new element
customElements.define('my-image', MyImage);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script src="MyImage.js"></script>
    </head>
    <body>
        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

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

答:
The snippet works if I change the location that the script is loaded.  If I put the script element at the end of the body, the example works fine.  See snippet below:

// Create a class for the element
class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);

  }
}

// Define the new element
customElements.define('my-image', MyImage);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>
    <body>
        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

        <script src="MyImage.js"></script>
    </body>
</html></code>```

So now my question becomes: why?  I know that the location of a script declaration/reference will affect when it's loaded in a page, but does anyone know exactly what is happening here that is causing it to not pass the custom attributes correctly when instantiating my custom element?

Body:
I am trying to make a custom html element and pass along with its instantiation some custom data tags.  The problem is its dataset is always empty, and I can't figure out what I am doing wrong.  I'm following the example from MDN on custom elements.. and this example does work in my browsers.. Additionally, I can successfully pass custom data tags when I add a standard img on my page, but not when I use my custom html element.

Below are my js file (defined in MyImage.js) and my html file.  Along side these is an image called small.jpg.

class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);
  }
}

// Define the new element
customElements.define('my-image', MyImage);

        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

Body:
The snippet works if I change the location that the script is loaded.  If I put the script element at the end of the body, the example works fine.  See snippet below:

// Create a class for the element
class MyImage extends HTMLElement {
  constructor() {
    // Always call super first in constructor
    super();

    // Create a dom shadow root
    var domShadow = this.attachShadow({mode: 'open'});

    // Create a standard img element and set its attributes.
    var img = document.createElement('img');
    img.alt = this.dataset.name;
    img.src = this.dataset.img;

    // Add the image to the shadow root.
    domShadow.appendChild(img);

  }
}

// Define the new element
customElements.define('my-image', MyImage);

<html>
    <head>
        <title>myimage</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>
    <body>
        <my-image data-name="My special image name" data-img="small.jpg"></my-image>

        <script src="MyImage.js"></script>
    </body>
</html>

So now my question becomes: why?  I know that the location of a script declaration/reference will affect when it's loaded in a page, but does anyone know exactly what is happening here that is causing it to not pass the custom attributes correctly when instantiating my custom element?


问:
Binding attribute causes duplicate component ID found in the view
Here is JSF code:

```<code><h:inputText binding="#{bean.input}" />
</code>```

And here is a part of backing bean for binding support:

```<code>private HtmlInputText input;

public void setInput(HtmlInputText input) {
    this.input = input;
}

public HtmlInputText getInput() {
    return this.input;
}
</code>```

When I open page at first time everything works fine but when I open it at second time (refresh or open the same url in another tab or any other way) I get duplicate ID error. Error message says that <h:inputText> has no unique ID. Here is a part of long error message:

```<code>java.lang.IllegalArgumentException: Component ID formId:inputId has already been found in the view
    +id: inputId type: javax.faces.component.html.HtmlInputText@cafebabe
</code>```

The problem occured after I added binding attribute. If I remove it, everything will work fine again. How do I properly use binding attribute?

答:
I had   the  same  problem until found this tag that evit  the duplicate component id        </p>

```<code><f:subview id="top">
    <p:outputPanel id="panelHeader1"
        binding="#{circularRequestBean.panelHeader}" autoUpdate="true"
        class="col-md-12 col-sm-12 col-xs-12 col-lg-12 wihtoutPadding"
        style="padding:0px; !important; display:block;" />

</f:subview>
</code>```

Body:
Here is JSF code:

<h:inputText binding="#{bean.input}" />

And here is a part of backing bean for binding support:

private HtmlInputText input;

public void setInput(HtmlInputText input) {
    this.input = input;
}

public HtmlInputText getInput() {
    return this.input;
}

When I open page at first time everything works fine but when I open it at second time (refresh or open the same url in another tab or any other way) I get duplicate ID error. Error message says that <h:inputText> has no unique ID. Here is a part of long error message:

java.lang.IllegalArgumentException: Component ID formId:inputId has already been found in the view
    +id: inputId type: javax.faces.component.html.HtmlInputText@cafebabe

The problem occured after I added binding attribute. If I remove it, everything will work fine again. How do I properly use binding attribute?

Body:
I had   the  same  problem until found this tag that evit  the duplicate component id

<f:subview id="top">
    <p:outputPanel id="panelHeader1"
        binding="#{circularRequestBean.panelHeader}" autoUpdate="true"
        class="col-md-12 col-sm-12 col-xs-12 col-lg-12 wihtoutPadding"
        style="padding:0px; !important; display:block;" />

</f:subview>


问:
Simple join table assigning default values for each row (sql fiddle included)
I'm sure there is a very simple answer to this question, but I'm having a hard time finding it.

I have a table with settings belonging to users.

```<code>| user_id | setting  | value  |
-------------------------------
| 1       | paying?  | true   |
| 2       | paying?  | false  |
| 2       | demo?    | true   |
| 2       | active?  | true   |
</code>```

I also have a table with default settings, in case the setting doesn't exist for a particular user.

```<code>| setting  | value  |
---------------------
| paying?  | true   |
| demo?    | true   |
| active?  | false  |
| hidden?  | false  |
</code>```

And what I need to do is return all settings for each user (using the default setting only if none is assigned to that user):

```<code>| user_id | category | value  |
-------------------------------
| 1       | paying?  | true   |
| 1       | demo?    | true   |
| 1       | active?  | false  |
| 1       | hidden?  | false  |
| 2       | paying?  | false  |
| 2       | demo?    | true   |
| 2       | active?  | true   |
| 2       | hidden?  | false  |
</code>```

This join is not returning results for each user. What am I doing wrong?

```<code>SELECT u.user_id, COALESCE(u.category, g.category) as category, COALESCE(u.value, g.value) as value
FROM user_settings as u
FULL OUTER JOIN global_settings as g on u.category = g.category
ORDER BY u.user_id, u.category
</code>```

SQLFiddle here

答:
Cross join distinct users with global_settings and left join the user_settings table on to this.</p>

```<code>SELECT u.user_id, COALESCE(us.category, g.category) as category,
COALESCE(us.value, g.value) as value
FROM (select distinct user_id from user_settings) as u
cross join global_settings g
left join user_settings as us on us.category = g.category and us.user_id=u.user_id
order by 1,2
</code>```

Body:
I'm sure there is a very simple answer to this question, but I'm having a hard time finding it.

I have a table with settings belonging to users.

| user_id | setting  | value  |
-------------------------------
| 1       | paying?  | true   |
| 2       | paying?  | false  |
| 2       | demo?    | true   |
| 2       | active?  | true   |

I also have a table with default settings, in case the setting doesn't exist for a particular user.

| setting  | value  |
---------------------
| paying?  | true   |
| demo?    | true   |
| active?  | false  |
| hidden?  | false  |

And what I need to do is return all settings for each user (using the default setting only if none is assigned to that user):

| user_id | category | value  |
-------------------------------
| 1       | paying?  | true   |
| 1       | demo?    | true   |
| 1       | active?  | false  |
| 1       | hidden?  | false  |
| 2       | paying?  | false  |
| 2       | demo?    | true   |
| 2       | active?  | true   |
| 2       | hidden?  | false  |

This join is not returning results for each user. What am I doing wrong?

SELECT u.user_id, COALESCE(u.category, g.category) as category, COALESCE(u.value, g.value) as value
FROM user_settings as u
FULL OUTER JOIN global_settings as g on u.category = g.category
ORDER BY u.user_id, u.category

SQLFiddle here

Body:
Cross join distinct users with global_settings and left join the user_settings table on to this.

SELECT u.user_id, COALESCE(us.category, g.category) as category,
COALESCE(us.value, g.value) as value
FROM (select distinct user_id from user_settings) as u
cross join global_settings g
left join user_settings as us on us.category = g.category and us.user_id=u.user_id
order by 1,2


问:
Jenkins 2.0: Running SBT in a docker container
I have the following Jenkinsfile:

```<code>def notifySlack = { String color, String message ->
    slackSend(color: color, message: "${message}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}] (${env.BUILD_URL})")
}

node {
    try {
        notifySlack('#FFFF00', 'STARTED')
        stage('Checkout project') {
            checkout scm
        }
        scalaImage = docker.image('<myNexus>/centos-sbt:2.11.8')
        stage('Test project') {
            docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                    sh 'sbt clean test'
                }
            }
        }
        if (env.BRANCH_NAME == 'master') {
            stage('Release new version') {
                docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                    scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                        sh 'sbt release'
                    }
                }
            }
        }
        notifySlack('#00FF00', 'SUCCESSFUL')
    } catch (e) {
        currentBuild.result = "FAILED"
        notifySlack('#FF0000', 'FAILED')
        throw e
    }

}
</code>```

Unfortunately when I reach the sbt clean test line I end up with the following error:

```<code>java.lang.IllegalArgumentException: URI has a query component
    at java.io.File.<init>(File.java:427)
    at sbt.IO$.uriToFile(IO.scala:160)
    at sbt.IO$.toFile(IO.scala:135)
    at sbt.Classpaths$.sbt$Classpaths$$bootRepository(Defaults.scala:1942)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:34)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
    at scala.collection.AbstractTraversable.map(Traversable.scala:105)
    at sbt.Classpaths$.appRepositories(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1193)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1190)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:175)
    at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
    at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:69)
    at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:78)
    at sbt.EvaluateSettings$$anon$3.run(INode.scala:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

If I run the simple docker run ... followed by docker exec I get what I want but I would like to work with the defined Jenkins functionality.

So this seems to be an SBT issue. I use version 0.13.16 inside the docker image. From what I understand the classpath contains a query parameter that SBT:

doesn't like

doesn't know how to handle

is illegal

I put no such query parameters myself so I thought that this .inside method does that. I checked the env in the container and found a single entry RUN_CHANGES_DISPLAY_URL=<my_ip>/job/scheduler/job/fix-jenkins-pipeline/23/display/redirect?page=changes. I tried to unset it but didn't manage to.

I'm out of ideas and am not really sure I'm in the right direction. Any help would be appreciated.

答:
I fixed this by setting ivys cache directory -> How to override the location of Ivy's Cache?

The problem was that it wasn't set and by default it creates a ? folder which in return can't be handled by sbt itself.

I created a custom Dockerfile to have more control over sbt.
Here are the steps I executed to solve the issue:

I created a file called ivysettings.xml with the following contents:

```<code><ivysettings>
    <properties environment="env" />
    <caches defaultCacheDir="/home/jenkins/.ivy2/cache" />
</ivysettings>
</code>```

and a Dockerfile:

```<code>FROM openjdk:8

RUN wget -O- "http://downloads.lightbend.com/scala/2.11.11/scala-2.11.11.tgz" \
    | tar xzf - -C /usr/local --strip-components=1

RUN curl -Ls https://git.io/sbt > /usr/bin/sbt && chmod 0755 /usr/bin/sbt

RUN adduser -u 1000 --disabled-password --gecos "" jenkins

ADD ./files/ivysettings.xml /home/jenkins/.ivy2/ivysettings.xml
RUN chown -R jenkins:jenkins /home/jenkins

USER jenkins

CMD ["sbt"]
</code>```

I then pushed the image to our private docker repository and our pipeline finally works!

Body:
I have the following Jenkinsfile:

def notifySlack = { String color, String message ->
    slackSend(color: color, message: "${message}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}] (${env.BUILD_URL})")
}

node {
    try {
        notifySlack('#FFFF00', 'STARTED')
        stage('Checkout project') {
            checkout scm
        }
        scalaImage = docker.image('<myNexus>/centos-sbt:2.11.8')
        stage('Test project') {
            docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                    sh 'sbt clean test'
                }
            }
        }
        if (env.BRANCH_NAME == 'master') {
            stage('Release new version') {
                docker.withRegistry('<myNexus>', 'jenkins-nexus') {
                    scalaImage.inside('-v /var/lib/jenkins/.ivy2:/root/.ivy2') { c ->
                        sh 'sbt release'
                    }
                }
            }
        }
        notifySlack('#00FF00', 'SUCCESSFUL')
    } catch (e) {
        currentBuild.result = "FAILED"
        notifySlack('#FF0000', 'FAILED')
        throw e
    }

}

Unfortunately when I reach the sbt clean test line I end up with the following error:

java.lang.IllegalArgumentException: URI has a query component
    at java.io.File.<init>(File.java:427)
    at sbt.IO$.uriToFile(IO.scala:160)
    at sbt.IO$.toFile(IO.scala:135)
    at sbt.Classpaths$.sbt$Classpaths$$bootRepository(Defaults.scala:1942)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$appRepositories$1.apply(Defaults.scala:1912)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:34)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
    at scala.collection.AbstractTraversable.map(Traversable.scala:105)
    at sbt.Classpaths$.appRepositories(Defaults.scala:1912)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1193)
    at sbt.Classpaths$$anonfun$58.apply(Defaults.scala:1190)
    at scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
    at sbt.EvaluateSettings$MixedNode.evaluate0(INode.scala:175)
    at sbt.EvaluateSettings$INode.evaluate(INode.scala:135)
    at sbt.EvaluateSettings$$anonfun$sbt$EvaluateSettings$$submitEvaluate$1.apply$mcV$sp(INode.scala:69)
    at sbt.EvaluateSettings.sbt$EvaluateSettings$$run0(INode.scala:78)
    at sbt.EvaluateSettings$$anon$3.run(INode.scala:74)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

If I run the simple docker run ... followed by docker exec I get what I want but I would like to work with the defined Jenkins functionality.

So this seems to be an SBT issue. I use version 0.13.16 inside the docker image. From what I understand the classpath contains a query parameter that SBT:

doesn't like

doesn't know how to handle

is illegal

I put no such query parameters myself so I thought that this .inside method does that. I checked the env in the container and found a single entry RUN_CHANGES_DISPLAY_URL=<my_ip>/job/scheduler/job/fix-jenkins-pipeline/23/display/redirect?page=changes. I tried to unset it but didn't manage to.

I'm out of ideas and am not really sure I'm in the right direction. Any help would be appreciated.

Body:
I fixed this by setting ivys cache directory -> How to override the location of Ivy's Cache?

The problem was that it wasn't set and by default it creates a ? folder which in return can't be handled by sbt itself.

I created a custom Dockerfile to have more control over sbt.
Here are the steps I executed to solve the issue:

I created a file called ivysettings.xml with the following contents:

<ivysettings>
    <properties environment="env" />
    <caches defaultCacheDir="/home/jenkins/.ivy2/cache" />
</ivysettings>

and a Dockerfile:

FROM openjdk:8

RUN wget -O- "http://downloads.lightbend.com/scala/2.11.11/scala-2.11.11.tgz" \
    | tar xzf - -C /usr/local --strip-components=1

RUN curl -Ls https://git.io/sbt > /usr/bin/sbt && chmod 0755 /usr/bin/sbt

RUN adduser -u 1000 --disabled-password --gecos "" jenkins

ADD ./files/ivysettings.xml /home/jenkins/.ivy2/ivysettings.xml
RUN chown -R jenkins:jenkins /home/jenkins

USER jenkins

CMD ["sbt"]

I then pushed the image to our private docker repository and our pipeline finally works!


问:
Not sure how to handle this in react - multiple promises
So the easiest way to explain this is that I am trying to search your package.json for all your packages, then use the npm registry to see if there are new updates. I have most of that done. Accept for the following for loop:

```<code>import request from 'request'

export const findAllUpdates = (packageInfo) => {
  for(prop in packageInfo) {
    request('https://registry.npmjs.org/' + prop, function(err, resp) {
      json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }
    });
  }
}
</code>```

Your packageInfo is a object of key=>value which represents either a dependency or a dev dependency from the package.json and the package-lock.json or the yarn.lock

The important part is we look at, in the above function, what you have installed, we then use the registry to get that package info and compare the latest version on the registry to that of what you have installed and then we want, ideally, to update the state of the component with the total count.

how ever the issue is that we have entered callback hell, especially with a for loop, looping over every package, making a request.

I cannot create a variable and store the response in there because it cannot be accessed after the request is made. I cannot see how using events here would work because you might have 40 packages installed as either dep or dev and thats a lot of events to fire.

And finally the proper solution might be to use promises, but the whole concept of promises is yet more callbacks with the .then(() => {}), .catch(() => {}) which puts me back at square one.

The goal is to call this in a component and have the state of that component be updated with the total amount of packages that have to be updated (or at least have new versions)

Any ideas? Am I going about this all wrong?

答:
You're right to be looking at promises.

The first thing is to give yourself a promise-enabled version of request. There's a promisify function in util that takes a Node-callback-style function and returns a promise-enabled version. So:

```<code>import util from 'util';
// ...
const prequest = util.promisify(request);
</code>```

(There's also an npm module, promisify, that can do entire APIs all at once.)

Then, do your requests, gathering the promises in an array (and using then on them to do any post-processing; then returns a new promise, so we're still good), and use Promise.all to wait until they all resolve (or any of them rejects);

So all together:

```<code>import request from 'request';
import util from 'util';

const prequest = util.promisify(request);

export const findAllUpdates = (packageInfo) => {
  const updates = []
  for (const prop in packageInfo) {
    updates.push(prequest('https://registry.npmjs.org/' + prop).then(resp => {
      const json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }

      // Perhaps return something here, it will be the resolution
      // for the promise for this request; otherwise, the promise
      // will resolve with `undefined`.
    }));
  }
  return Promise.all(updates);
};
</code>```

That overall function's promise will resolve to an array of the results of each promise in the array (in order), or (again) reject if any of them rejects.

I want to be able to suggest async/await, but it doesn't currently bring much to the table for a bunch of parallel promises. (There's been the occasional talk of await.all to do what Promise.all does, but it hasn't caught on [yet?].)

Having said that, though, if we break things up a bit it is a bit nicer with async/await:

```<code>import request from 'request';
import util from 'util';

const prequest = util.promisify(request);

const checkOne = async (prop) => {
  const resp = await prequest('https://registry.npmjs.org/' + prop);
  const json = JSON.parse(resp.body);
  if (json['dist-tags'].latest !== packageInfo[prop].version) {
    // Do something, we are not the same version so we should
    // update some counter.
  }

  // Perhaps return something here, it will be the resolution
  // for the promise for this request; otherwise, the promise
  // will resolve with `undefined`.
};

export const findAllUpdates = (packageInfo) => {
  const updates = []
  for (const prop in packageInfo) {
    updates.push(checkOne(prop);
  }
  return Promise.all(updates);
};
</code>```

And of course, if all the properties in packageInfo are "own" properties (not inherited), findAllUpdates gets a lot simpler:

```<code>export const findAllUpdates = (packageInfo) => {
  return Promise.all(Object.keys(packageInfo).map(checkOne));
};
</code>```

Side note: I've added a few missing declarations above.

Body:
So the easiest way to explain this is that I am trying to search your package.json for all your packages, then use the npm registry to see if there are new updates. I have most of that done. Accept for the following for loop:

import request from 'request'

export const findAllUpdates = (packageInfo) => {
  for(prop in packageInfo) {
    request('https://registry.npmjs.org/' + prop, function(err, resp) {
      json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }
    });
  }
}

Your packageInfo is a object of key=>value which represents either a dependency or a dev dependency from the package.json and the package-lock.json or the yarn.lock

The important part is we look at, in the above function, what you have installed, we then use the registry to get that package info and compare the latest version on the registry to that of what you have installed and then we want, ideally, to update the state of the component with the total count.

how ever the issue is that we have entered callback hell, especially with a for loop, looping over every package, making a request.

I cannot create a variable and store the response in there because it cannot be accessed after the request is made. I cannot see how using events here would work because you might have 40 packages installed as either dep or dev and thats a lot of events to fire.

And finally the proper solution might be to use promises, but the whole concept of promises is yet more callbacks with the .then(() => {}), .catch(() => {}) which puts me back at square one.

The goal is to call this in a component and have the state of that component be updated with the total amount of packages that have to be updated (or at least have new versions)

Any ideas? Am I going about this all wrong?

Body:
You're right to be looking at promises.

The first thing is to give yourself a promise-enabled version of request. There's a promisify function in util that takes a Node-callback-style function and returns a promise-enabled version. So:

import util from 'util';
// ...
const prequest = util.promisify(request);

(There's also an npm module, promisify, that can do entire APIs all at once.)

Then, do your requests, gathering the promises in an array (and using then on them to do any post-processing; then returns a new promise, so we're still good), and use Promise.all to wait until they all resolve (or any of them rejects);

So all together:

import request from 'request';
import util from 'util';

const prequest = util.promisify(request);

export const findAllUpdates = (packageInfo) => {
  const updates = []
  for (const prop in packageInfo) {
    updates.push(prequest('https://registry.npmjs.org/' + prop).then(resp => {
      const json = JSON.parse(resp.body);

      if (json['dist-tags'].latest !== packageInfo[prop].version) {
        // Do something, we are not the same version so we should
        // update some counter.
      }

      // Perhaps return something here, it will be the resolution
      // for the promise for this request; otherwise, the promise
      // will resolve with `undefined`.
    }));
  }
  return Promise.all(updates);
};

That overall function's promise will resolve to an array of the results of each promise in the array (in order), or (again) reject if any of them rejects.

I want to be able to suggest async/await, but it doesn't currently bring much to the table for a bunch of parallel promises. (There's been the occasional talk of await.all to do what Promise.all does, but it hasn't caught on [yet?].)

Having said that, though, if we break things up a bit it is a bit nicer with async/await:

import request from 'request';
import util from 'util';

const prequest = util.promisify(request);

const checkOne = async (prop) => {
  const resp = await prequest('https://registry.npmjs.org/' + prop);
  const json = JSON.parse(resp.body);
  if (json['dist-tags'].latest !== packageInfo[prop].version) {
    // Do something, we are not the same version so we should
    // update some counter.
  }

  // Perhaps return something here, it will be the resolution
  // for the promise for this request; otherwise, the promise
  // will resolve with `undefined`.
};

export const findAllUpdates = (packageInfo) => {
  const updates = []
  for (const prop in packageInfo) {
    updates.push(checkOne(prop);
  }
  return Promise.all(updates);
};

And of course, if all the properties in packageInfo are "own" properties (not inherited), findAllUpdates gets a lot simpler:

export const findAllUpdates = (packageInfo) => {
  return Promise.all(Object.keys(packageInfo).map(checkOne));
};

Side note: I've added a few missing declarations above.


问:
Initializing *ngFor with a new Array()
Angular v5

My search component retrieves data from a service returning a search result promise. On page load my "searchResults" array is empty (= new Array()) until the search is called in page and the promise is returned.

*ngFor is throwing an error because the above mentioned "searchResults" is empty on page load. How do I circumvent this until the search results are populated?

Service:

```<code>getSearchResults(searchTerm: string, resourceType: string, pageSize: number = 9999, pageNumber: number = 1): Promise<object> {
const search = {
  Term: searchTerm,
  ResourceType: resourceType,
  PageSize: pageSize,
  PageNum: pageNumber,
  ModuleId: moduleId
};
const searchHeader = {headers: this.getHttpHeaders()};
const promise = new Promise((resolve, reject): void => {
  this.http.post(this.apiRoot, search, searchHeader).toPromise()
    .then(response => {
      resolve(JSON.parse(response['_body']));
    })
    .catch(error => {
      reject(error);
    });
});
return promise;
}
</code>```

Component:

```<code>submitSearch(): void {
this.siteSearchService.getSearchResults(this.searchString, this.selectedResourceType)
  .then(response => {
    let dto: DTO.SearchResults = <DTO.SearchResults>response;
    this.totalHits = dto.TotalHits;
    this.searchResults = dto.Results;
  }).catch(error => {
    console.log(error);
  });
}
</code>```

Template:

```<code><div class="row" *ngIf="searchResults" style="margin:25px;">
    <div class="col-xs-12 result-row" *ngFor="let result in searchResults">
      <div class="row">
        <div class="col-xs-12 col-sm-10">
          <a href [href]="result.Url" target="_blank" class="search-result-link">
            <h3>{{result.Title}}</h3>
          </a>
          <p>{{result.Description}}</p>
        </div>
        <div class="col-xs-12 col-sm-2">
          ToDo: Button
        </div>
      </div>
    </div>
  </div>
</code>```

答:
Just try with *ngIf="searchResults" and also in your code replace
*ngFor="let result in searchResults" with *ngFor="let result of searchResults"

Hope that solves your problem

Title: Initializing *ngFor with a new Array()

Body:
Angular v5

My search component retrieves data from a service returning a search result promise. On page load my "searchResults" array is empty (= new Array()) until the search is called in page and the promise is returned.

*ngFor is throwing an error because the above mentioned "searchResults" is empty on page load. How do I circumvent this until the search results are populated?

Service:

getSearchResults(searchTerm: string, resourceType: string, pageSize: number = 9999, pageNumber: number = 1): Promise<object> {
const search = {
  Term: searchTerm,
  ResourceType: resourceType,
  PageSize: pageSize,
  PageNum: pageNumber,
  ModuleId: moduleId
};
const searchHeader = {headers: this.getHttpHeaders()};
const promise = new Promise((resolve, reject): void => {
  this.http.post(this.apiRoot, search, searchHeader).toPromise()
    .then(response => {
      resolve(JSON.parse(response['_body']));
    })
    .catch(error => {
      reject(error);
    });
});
return promise;
}

Component:

submitSearch(): void {
this.siteSearchService.getSearchResults(this.searchString, this.selectedResourceType)
  .then(response => {
    let dto: DTO.SearchResults = <DTO.SearchResults>response;
    this.totalHits = dto.TotalHits;
    this.searchResults = dto.Results;
  }).catch(error => {
    console.log(error);
  });
}

Template:

{{result.Title}}

{{result.Description}}

          ToDo: Button


问:
RichTextbox MaxLength too small
I need to open a text file with ~4MB in a RichTextBox, but the end of the text was "trimmed".

How do I override a RichTextBox.MaxLength Int32 limit?

答: OK the max size of the RichTextBox is 2,147,483,647 that is a lot of typing, if you are thinking copy past it may better to read in the data as opposed to copying to a RichTextBox. </p>

ContentLicense: CC BY-SA 2.5

Title: RichTextbox MaxLength too small