问:
Bootstrap Glyphicon not displaying but does in Fiddle
I am trying to make the glyphicon display. It is part of a side nav and the arrow head rotates down... pretty standard barebones kinda thing.

Link to page:
http://www.nickysfolders.com/nicky-s-communicator-english.aspx?SessionThemeID=34#

The glyphicon should be on the "Nicky's Folders" top level title on the side nav.

This is the really cool snippet I adapted to get the dropdown function and arrow animation... pretty cool.
 awesome, very very lightweight, portable solution to side nav dropdowns

Things I have already tried:

I have tried moving the span around within the html and it won't display

I have put a color on it (all in DevTools)

I have looked up common problems involving glyphicons not displaying (most common... yes I am loading 3.2 from the max cdn already).

I bet it is just a simple mistake I am making...

As you can see the glyph icons in the fiddle work (unfortunately js doesn't yet):

https://jsfiddle.net/vaughnick/f4gkxx4n/

```<code><!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
      [data-toggle="collapse"][aria-expanded="true"] > .js-rotate-if-collapsed {
        -webkit-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        -o-transform: rotate(90deg);
        transform: rotate(90deg);
      }

    </style>
  </head>

  <body>

    <div id="accordion" style="cursor: pointer" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false">
        <span class="glyphicon glyphicon-triangle-right js-rotate-if-collapsed"></span>
        <a href="#">Nicky's Folders<span class="small-reg">®</span></a>
        <hr class="half-rule" />
      <ul id="collapseExample" class="collapse">
        <li style="cursor: pointer" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false">
          <span class="glyphicon glyphicon-triangle-right js-rotate-if-collapsed"></span>
          <a href="#">2-Pockets</a>
          <ul id="collapseExample" class="collapse">
            <li><a href="#">Nicky's<span class="small-reg">®</span>Version II<small>(NF VER II)</small></a></li>
            <li><a href="#">Nicky's<span class="small-reg">®</span>Communicator</a>
              <ul>
                <li><a href="#">English</a></li>
                <li><a href="#" style="overflow: wrap;">Spanish Multilanguage</a></li>
              </ul>
            </li>
            <li><a href="#">Nicky's<span class="small-reg">®</span>Class Work</a></li>
            <li><a href="#">Nicky's<span class="small-reg">®</span>Homework</a></li>
            <li><a href="#">Nicky's<span class="small-reg">®</span>CPA</a>
              <ul>
                <li><a href="#">Version 10</a></li>
                <li><a href="#">Version 11</a></li>
              </ul>
            </li>
          </ul>

        </li>
      </ul>
    </div>

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </body>

</html>
</code>```

Thanks for any advice/help! :)

答:
See the working examples of Bootstrap Glyphicon

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Zoom-in Glyph

Zoom-in icon:

Zoom-in icon as a link:

Zoom-in icon on a button:
        <button type="button" class="btn btn-default btn-sm">
           Zoom-in
        </button>

Zoom-in icon on a styled link button:

           Zoom-in

Unicode:
        

```

Body:
I am trying to make the glyphicon display. It is part of a side nav and the arrow head rotates down... pretty standard barebones kinda thing.

Link to page:
http://www.nickysfolders.com/nicky-s-communicator-english.aspx?SessionThemeID=34#

The glyphicon should be on the "Nicky's Folders" top level title on the side nav.

This is the really cool snippet I adapted to get the dropdown function and arrow animation... pretty cool.
 awesome, very very lightweight, portable solution to side nav dropdowns

Things I have already tried:

I have tried moving the span around within the html and it won't display

I have put a color on it (all in DevTools)

I have looked up common problems involving glyphicons not displaying (most common... yes I am loading 3.2 from the max cdn already).

I bet it is just a simple mistake I am making...

As you can see the glyph icons in the fiddle work (unfortunately js doesn't yet):

https://jsfiddle.net/vaughnick/f4gkxx4n/

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        Nicky's Folders®

          2-Pockets

Nicky's®Version II(NF VER II)

Nicky's®Communicator

English

Spanish Multilanguage

Nicky's®Class Work

Nicky's®Homework

Nicky's®CPA

Version 10

Version 11

Thanks for any advice/help! :)

Body:
See the working examples of Bootstrap Glyphicon

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>
    <div class="container">
      <h2>Zoom-in Glyph</h2>
      <p>Zoom-in icon: <span class="glyphicon glyphicon-zoom-in"></span></p>
      <p>Zoom-in icon as a link:
        <a href="#">
          <span class="glyphicon glyphicon-zoom-in"></span>
        </a>
      </p>
      <p>Zoom-in icon on a button:
        <button type="button" class="btn btn-default btn-sm">
          <span class="glyphicon glyphicon-zoom-in"></span> Zoom-in
        </button>
      </p>
      <p>Zoom-in icon on a styled link button:
        <a href="#" class="btn btn-info btn-lg">
          <span class="glyphicon glyphicon-zoom-in"></span> Zoom-in
        </a>
      </p>
      <p>Unicode:
        <span class="glyphicon">&#xe015;</span>
      </p>
    </div>
  </body>
</html>


来源: stackexchange

问:
Resolving pull requests with merge conflicts when using branch permissions in Bitbucket Server
We've started using Bitbucket Server on our team, and want to enforce the use of pull requests to get commits from feature branches into our main integration branches. To enforce this, we turned on the branch permissions feature that prevents merges without a pull request for those branches. This works great, until we get a pull request that has a conflict.

In this case, the instructions say to manually fetch the head of the source branch and merge it to the target, then push this up. However, the merge commit gets rejected by the branch permissions!

Are we missing something here, or is it not possible to manually merge when using branch permissions?

答:
On BitBucket server, when we get any conflict while merging any pull request, we can use git bash tool to resolve it on our local system and then we can commit and push our changes to remote feature branch and merge it to main branch.

Following steps need to be followed in order in our local system’s git bash tool.

(1) Open git bash tool and checkout or switch to your local feature branch.

(2) Pull the latest changes from the main branch (say 'master') into feature branch.

```<code>git pull origin master
</code>```

(3) If above command fails due to some local changes then use below command to stash them otherwise move to next step.

```<code>git stash
</code>```

followed by -

```<code>git pull origin master
</code>```

(4) In case of conflict, automatic merge will fail so we need to merge it manually. Use below command to resolve conflicts.

```<code>git mergetool
</code>```

By default, it will display all the available merge tools and one of them will be picked automatically.
If we feel we are much comfortable with any other tool then we can also configure that and git will open that tool for us for conflict resolution.

(5) Once the conflicts are resolved then commit the changes into feature branch.

```<code>git commit
</code>```

(6) Push the changes to remote feature branch.

```<code>git push
</code>```

Verify on BitBucket server, now pull request should get updated automatically.

Again try to merge it; in case of no conflict it will get merged successfully.

If it has merge conflict again (if someone has committed new changes in main branch during we were resolving conflict on our local system) then follow the above steps again to resolve them.

We should be able to successfully resolve any conflicts if we have followed the above steps in order.

Thanks, hope it helps.

ContentLicense: CC BY-SA 4.0

Body:
On BitBucket server, when we get any conflict while merging any pull request, we can use git bash tool to resolve it on our local system and then we can commit and push our changes to remote feature branch and merge it to main branch.

Following steps need to be followed in order in our local system’s git bash tool.

(1) Open git bash tool and checkout or switch to your local feature branch.

(2) Pull the latest changes from the main branch (say 'master') into feature branch.

git pull origin master

(3) If above command fails due to some local changes then use below command to stash them otherwise move to next step.

git stash

followed by -

git pull origin master

(4) In case of conflict, automatic merge will fail so we need to merge it manually. Use below command to resolve conflicts.

git mergetool

By default, it will display all the available merge tools and one of them will be picked automatically.
If we feel we are much comfortable with any other tool then we can also configure that and git will open that tool for us for conflict resolution.

(5) Once the conflicts are resolved then commit the changes into feature branch.

git commit

(6) Push the changes to remote feature branch.

git push

Verify on BitBucket server, now pull request should get updated automatically.

Again try to merge it; in case of no conflict it will get merged successfully.

If it has merge conflict again (if someone has committed new changes in main branch during we were resolving conflict on our local system) then follow the above steps again to resolve them.

We should be able to successfully resolve any conflicts if we have followed the above steps in order.

Thanks, hope it helps.

ContentLicense: CC BY-SA 3.0


问:
Multitouch two imageviews at the same position
I am using two image views in my activity, and the moment i double tap/pinch zoom i am zooming only the image which i have touched.
how can i zoom the other image also exactly at same time & same position.

I am only achieving multi-touch/pinch zoom only on one image view.

PS: I searched before posting, but to no avail.

Because of code lenth i cant paste it. Here's the link for the same which i have used: TouchImageView.java

答:
On your TouchImageView add:

```<code>TouchImageView other;
public void setOther(TouchImageView other) {
    this.other = other;
}
</code>```

So in your activity.onCreate:

```<code>TouchImageView one = //findViewById
TouchImageView two = //findViewById
one.setOther(two);
two.setOther(one);
</code>```

And add to the listener of the double tap a copy of the event to the other one:

```<code>public boolean onDoubleTap(MotionEvent e) {
    other.onDoubleTap(MotionEvent.obtain(e));
</code>```

Body:
On your TouchImageView add:

TouchImageView other;
public void setOther(TouchImageView other) {
    this.other = other;
}

So in your activity.onCreate:

TouchImageView one = //findViewById
TouchImageView two = //findViewById
one.setOther(two);
two.setOther(one);

And add to the listener of the double tap a copy of the event to the other one:

public boolean onDoubleTap(MotionEvent e) {
    other.onDoubleTap(MotionEvent.obtain(e));


问:
Select row using the length of list in pandas cell
I have a table df

```<code>    a   b    c
1   x   y   [x]

2   x   z   [c,d]

3   x   t   [e,f,g]
</code>```

Just wondering how to select the row using the length of c column

such as

```<code>df.loc[len(df.c) >1]
</code>```

I know this is not right.... what should be the right one?

答:
You can using </p>

```<code>df.loc[np.array(list(map(len,df.c.values)))>1]
</code>```

Body:
I have a table df

    a   b    c
1   x   y   [x]

2   x   z   [c,d]

3   x   t   [e,f,g]

Just wondering how to select the row using the length of c column

such as

df.loc[len(df.c) >1]

I know this is not right.... what should be the right one?

Body:
You can using

df.loc[np.array(list(map(len,df.c.values)))>1]


问:
Subscribe in Angular2 doesn't work
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

```<code>   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }
</code>```

Now I need to use the value this. mapCenter of this function as a parameter in second function.

```<code>this.mapInitialize(this.mapCenter);
</code>```

The both functions are in the ngOnInit

```<code>  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }
</code>```

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

答:
One of the problems with the prevId() method is that it's got too many repsonsibilities, it

calculates this.mapCenter

invokes the popup

sets the new value of this.previousUrl

The first thing you might do is extract the logic for mapCenter, like so

getMapCenter() {
  let mapCenter = { name: '', id: '', lat: 48.145, lng: 11.58, latLng: null };
  if (this.previousUrl === undefined) {

    this.clickedMarker = this.previousUrl.substring(10);

    for (let i = 0; i < this.data.length; i++) {
      if(this.data[i].code === this.clickedMarker) {
        id = this.data[i].code;
        mapCenter.name = this.data[i].displayName;
        mapCenter.lat = parseFloat(this.data[i].lat);
        mapCenter.lng = parseFloat(this.data[i].lng);
      }
    }
  } else {
    console.log('not yet');
  }
  mapCenter.latLng = L.latLng([mapCenter.lat, mapCenter.lng]);
  return mapCenter
}
```

<p><br/>
We can also extract the popup logic</p>

<pre class="lang-js prettyprint-override"><code>showPopup(mapCenter) {
  // Open up the popup, when user comes back
  let myMarker = new L.Marker(mapCenter.latLng, {icon: mapUI.marker}).addTo(this.map);
  let mark = this.popupHtmlGenerate( mapCenter.name, mapCenter.id, mapCenter.latLng );
  myMarker.bindPopup(mark).openPopup();
}
</code>```

Now prevId() only does what it's label says

prevId () {
  this.router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(e => {
      this.previousUrl = (e as NavigationEnd).url;
    });
  }
```

<p><br/>
Now we can see that <code>this.mapCenter</code> does not depend on the subscribed value of <code>router.events</code>, so it can run synchronously and get passed in to  <code>this.mapInitialize()</code>,</p>

```ngOnInit() {
  const mapCenter = this.getMapCenter();
  this.mapCenter = mapCenter.latLng;
  this.showPopup(mapCenter);
  this.prevId();
  this.mapInitialize(this.mapCenter);
}
```

Title: Subscribe in Angular2 doesn't work

Body:
I have a question about subscribe in Angular2, please, help me...

I have two functions, first function return the value and the second function has to use it.

Here is my example

This is the first function, everything is ok and works works, and it returns this.mapCenter, this value I need later

   prevId () {
     let name, id, lat, lng;
     this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(e => {

        if (this.previousUrl !== undefined) {

          this.clickedMarker = this.previousUrl.substring(10);

          for (let i = 0; i < this.data.length; i++) {
            if(this.data[i].code === this.clickedMarker) {
              id = this.data[i].code;
              name = this.data[i].displayName;
              lat = parseFloat(this.data[i].lat);
              lng = parseFloat(this.data[i].lng);
              this.mapCenter = L.latLng([lat, lng]);
            }
          }
          // Open up the popup, when user comes back
          let myMarker = new L.Marker(this.mapCenter, {icon: mapUI.marker}).addTo(this.map);
          let mark = this.popupHtmlGenerate( name, id, this.mapCenter );
          myMarker.bindPopup(mark).openPopup();
        } else {
          console.log('not yet');
          this.mapCenter = L.latLng([48.145, 11.58]);
        }
        this.previousUrl = (e as NavigationEnd).url;
        return this.mapCenter;

      });
  }

Now I need to use the value this. mapCenter of this function as a parameter in second function.

this.mapInitialize(this.mapCenter);

The both functions are in the ngOnInit

  ngOnInit() {
    this.prevId();

    this.mapInitialize(this.mapCenter);
  }

I tried something like this.prevId().subscribe, but I get error subscribe doesn't exist on type void ...

UPD: I can't assign second function in the first function. I need the second function later and if I assign it inside another function, everything brakes

Body:
One of the problems with the prevId() method is that it's got too many repsonsibilities, it

calculates this.mapCenter

invokes the popup

sets the new value of this.previousUrl

The first thing you might do is extract the logic for mapCenter, like so

getMapCenter() {
  let mapCenter = { name: '', id: '', lat: 48.145, lng: 11.58, latLng: null };
  if (this.previousUrl === undefined) {

    this.clickedMarker = this.previousUrl.substring(10);

    for (let i = 0; i < this.data.length; i++) {
      if(this.data[i].code === this.clickedMarker) {
        id = this.data[i].code;
        mapCenter.name = this.data[i].displayName;
        mapCenter.lat = parseFloat(this.data[i].lat);
        mapCenter.lng = parseFloat(this.data[i].lng);
      }
    }
  } else {
    console.log('not yet');
  }
  mapCenter.latLng = L.latLng([mapCenter.lat, mapCenter.lng]);
  return mapCenter
}

We can also extract the popup logic

showPopup(mapCenter) {
  // Open up the popup, when user comes back
  let myMarker = new L.Marker(mapCenter.latLng, {icon: mapUI.marker}).addTo(this.map);
  let mark = this.popupHtmlGenerate( mapCenter.name, mapCenter.id, mapCenter.latLng );
  myMarker.bindPopup(mark).openPopup();
}

Now prevId() only does what it's label says

prevId () {
  this.router.events
    .filter(event => event instanceof NavigationEnd)
    .subscribe(e => {
      this.previousUrl = (e as NavigationEnd).url;
    });
  }

Now we can see that this.mapCenter does not depend on the subscribed value of router.events, so it can run synchronously and get passed in to  this.mapInitialize(),

ngOnInit() {
  const mapCenter = this.getMapCenter();
  this.mapCenter = mapCenter.latLng;
  this.showPopup(mapCenter);
  this.prevId();
  this.mapInitialize(this.mapCenter);
}


问:
Module not found: Can't resolve 'react-bootstrap-carousel/dist/react-bootstrap-carousel.css'
I am using Reactjs to writing a web application. It works find when I run npm start on localhost, but it is not working when I deploy and run my repository to Heroku. Heroku open gives me this message Module not found: Can't resolve 'react-bootstrap-carousel/dist/react-bootstrap-carousel.css' in '/app/src/components/pages' I have check my GitHub repository that I have this file and also run normally on localhost.

答: I think that is because your build doesn’t have the file. Use —copy-files option</p>


问:
Clearing Last Selected Value JCombobox when ComboBoxModel Becomes Empty
Here is a scenario:

I have two JComboBoxes (call them combo1 and combo2 ) that get their values from a database[In the DB, these two have a 1:M relationship]. When the screen shows up I populate combo1 with values from the database and then take the first entry in the list and get its corresponding values to populate combo2.

Since the values of combo2 depend on what is selected in combo1, every time the selection changes in combo1 a call is made to the database to get matching values to populate combo2.

Now here is a problem:

Say I have two entries in combo1 and the second entry has no corresponding values for combo2. When I select the second entry of combo1, the last selected value on combo2 does not clear. [Remember the model for combo2 is empty and therefore there shouldn't anything selected]

Qeustion: How do I clear the text in combo2 if the model is empty?

Here is a sample code:

```<code>public void select(final Entry entry) {
      if (entry == null)
         return;

         int index = entryList.indexOf(entry); // instance of SelectionInList from JGoodies
         boolean positive = index >= 0 && index <= entryList.getSize() - 1;

         if (positive) {

              entryList.setSelection(entry);

               subEntryList.setList(entryList.loadSubEntries(entry.getID()));
               if (!subEntryList.isEmpty()) {
                    SubEntry e = subEntryList.getElementAt(0);
                    select(e);
                 }
        }
</code>```

}

答:
Just do this:

```<code>jcombobox.setSelectedIndex(-1);
</code>```

after:

```<code>jcombobox.getSelectedIndex();
</code>```

Body:
Here is a scenario:

I have two JComboBoxes (call them combo1 and combo2 ) that get their values from a database[In the DB, these two have a 1:M relationship]. When the screen shows up I populate combo1 with values from the database and then take the first entry in the list and get its corresponding values to populate combo2.

Since the values of combo2 depend on what is selected in combo1, every time the selection changes in combo1 a call is made to the database to get matching values to populate combo2.

Now here is a problem:

Say I have two entries in combo1 and the second entry has no corresponding values for combo2. When I select the second entry of combo1, the last selected value on combo2 does not clear. [Remember the model for combo2 is empty and therefore there shouldn't anything selected]

Qeustion: How do I clear the text in combo2 if the model is empty?

Here is a sample code:

public void select(final Entry entry) {
      if (entry == null)
         return;

         int index = entryList.indexOf(entry); // instance of SelectionInList from JGoodies
         boolean positive = index >= 0 && index <= entryList.getSize() - 1;

         if (positive) {

              entryList.setSelection(entry);

               subEntryList.setList(entryList.loadSubEntries(entry.getID()));
               if (!subEntryList.isEmpty()) {
                    SubEntry e = subEntryList.getElementAt(0);
                    select(e);
                 }
        }

}

Body:
Just do this:

jcombobox.setSelectedIndex(-1);

after:

jcombobox.getSelectedIndex();


问:
TSQL How to select SQL records with following where condition
I have a table Test with records

```<code>ID             Date
1            12/08/2017
1            11/10/2016
1            06/09/2010
1            06/29/2009
2            05/29/2009
2            03/29/2009
2            02/29/2009
</code>```

I want to select id's where Date >2010 but I want to include all record dates
I tried this

```<code>select * from Test
where Date >='01/01/2010'
</code>```

but this return only 3 records of id 1. If only all dates of id are less than 2010 then my select query should not select that ID. if the id has one or more dates >2010 then include in select. Do I need to put in a sub query?

答:
Try the query below.  You have to exclude any IDs that have record before '01/01/2010'</p>

```<code>SELECT *
FROM Test t
WHERE NOT EXISTS (
    SELECT 1
    FROM Test
    WHERE ID = t.ID AND Date < '01/01/2010'
)
</code>```

Body:
I have a table Test with records

ID             Date
1            12/08/2017
1            11/10/2016
1            06/09/2010
1            06/29/2009
2            05/29/2009
2            03/29/2009
2            02/29/2009

I want to select id's where Date >2010 but I want to include all record dates
I tried this

select * from Test
where Date >='01/01/2010'

but this return only 3 records of id 1. If only all dates of id are less than 2010 then my select query should not select that ID. if the id has one or more dates >2010 then include in select. Do I need to put in a sub query?

Body:
Try the query below.  You have to exclude any IDs that have record before '01/01/2010'

SELECT *
FROM Test t
WHERE NOT EXISTS (
    SELECT 1
    FROM Test
    WHERE ID = t.ID AND Date < '01/01/2010'
)


问:
How can I fix Webpack related error: Cannot assign to read only property 'exports' of object '#<Object>'?
I'm using webpack, which, if I understand correctly, doesn't support native webworker syntax, so I'm trying to use the worker-loader npm module, but I'm getting a weird error.

The module can be found here.

My webpack config:

```<code>module.exports = {
    entry: "./app",
    output: {
        path: __dirname + "/build",
        filename: "bundle.js"
    },
    watch: true,
    module: {
        rules: [{
            test: /\.worker\.js$/,
            use: {
                loader: 'worker-loader'
            }
        }]
    }
}
</code>```

My code triggering the error:

```<code>import Worker from '../workers/sim.js';

class Synapse {
  // ...
}

module.exports = Synapse;
</code>```

Error:

```<code>Cannot assign to read only property 'exports' of object '#<Object>'?
</code>```

which points to module.exports = Synapse

答:
You'll get this error when mixing the CommonJS module.exports with ES Modules. You'll have to change module.exports to its ES Module counterpart export default:

```<code>import Worker from '../workers/sim.js';

class Synapse {
  // ...
}

export default Synapse; // ES Module syntax
</code>```

Body:
I'm using webpack, which, if I understand correctly, doesn't support native webworker syntax, so I'm trying to use the worker-loader npm module, but I'm getting a weird error.

The module can be found here.

My webpack config:

module.exports = {
    entry: "./app",
    output: {
        path: __dirname + "/build",
        filename: "bundle.js"
    },
    watch: true,
    module: {
        rules: [{
            test: /\.worker\.js$/,
            use: {
                loader: 'worker-loader'
            }
        }]
    }
}

My code triggering the error:

import Worker from '../workers/sim.js';

class Synapse {
  // ...
}

module.exports = Synapse;

Error:

Cannot assign to read only property 'exports' of object '#<Object>'?

which points to module.exports = Synapse

Body:
You'll get this error when mixing the CommonJS module.exports with ES Modules. You'll have to change module.exports to its ES Module counterpart export default:

import Worker from '../workers/sim.js';

class Synapse {
  // ...
}

export default Synapse; // ES Module syntax


问:
logging apache2 to mongodb: apache hook? something out there?
i just found a great blog posting on http://simonwillison.net/2009/Aug/26/logging/ stating the following

MongoDB is fantastic for logging".
  Sounds tempting... high performance
  inserts, JSON structured records and
  capped collections if you only want to
  keep the past X entries. If you care
  about older historic data but still
  want to preserve space you could run
  periodic jobs to roll up log entries
  in to summarised records. It shouldn’t
  be too hard to write a command-line
  script that hooks in to Apache’s
  logging directive and writes records
  to MongoDB.

is there anything out there already? anyone already using apache logging with mongodb?

答: A relatively recent option is to use Flume to collect the logs and use the MongoDB sink plugin for Flume to write the events to MongoDB.</p>

ContentLicense: CC BY-SA 2.5


问:
Inverse of numpy.recarray.tobytes
What's the inverse to numpy.recarray.tobytes?

```<code>>>> import numpy as np
>>> A = np.array([(28483,27759)],dtype=[('x','<u2'),('y','<u2')])
>>> A.tobytes()
'Cool'
</code>```

Here A is a 4-byte structured array, and tobytes lets me serialize it in binary form. How can I take a binary string of the proper size and deserialize it given a dtype object?

答:
I suspect you want frombuffer, which interprets a bytestring (or, more generally, any Python object that supports the buffer protocol) as an array. By default it assumes a dtype of np.float64, but you can specify a particular dtype, including a structured dtype.

```<code>>>> import numpy as np
>>> A = np.frombuffer(b"Cool", dtype=[('x','<u2'),('y','<u2')])
>>> A
array([(28483, 27759)],
      dtype=[('x', '<u2'), ('y', '<u2')])
</code>```

One quirk of frombuffer is that it creates an array that refers directly to the bytes you gave it, rather than copying them. That means that if you've used it on a Python bytestring (for example), the resulting array will be readonly:

```<code>>>> A["x"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only
</code>```

If you want something writable, use np.fromstring instead of np.frombuffer:

```<code>>>> A = np.fromstring(b"Cool", dtype=[('x','<u2'),('y','<u2')])
>>> A["x"] = 23
>>> A
array([(23, 27759)],
      dtype=[('x', '<u2'), ('y', '<u2')])
</code>```

See this answer for more information.

If you want a genuine NumPy record array (rather than a structured array, which is just a regular ndarray with structured dtype), you can pass the result to nd.rec.array:

```<code>>>> np.rec.array(A)
rec.array([(28483, 27759)],
          dtype=[('x', '<u2'), ('y', '<u2')])
</code>```

Record arrays are much like structured arrays, but have their own ndarray subclass, and allow retrieval of fields via attribute access:

```<code>>>> B = np.rec.array(A)
>>> B.x
array([28483], dtype=uint16)
</code>```

Title: Inverse of numpy.recarray.tobytes

Body:
What's the inverse to numpy.recarray.tobytes?

>>> import numpy as np
>>> A = np.array([(28483,27759)],dtype=[('x','<u2'),('y','<u2')])
>>> A.tobytes()
'Cool'

Here A is a 4-byte structured array, and tobytes lets me serialize it in binary form. How can I take a binary string of the proper size and deserialize it given a dtype object?

Body:
I suspect you want frombuffer, which interprets a bytestring (or, more generally, any Python object that supports the buffer protocol) as an array. By default it assumes a dtype of np.float64, but you can specify a particular dtype, including a structured dtype.

>>> import numpy as np
>>> A = np.frombuffer(b"Cool", dtype=[('x','<u2'),('y','<u2')])
>>> A
array([(28483, 27759)],
      dtype=[('x', '<u2'), ('y', '<u2')])

One quirk of frombuffer is that it creates an array that refers directly to the bytes you gave it, rather than copying them. That means that if you've used it on a Python bytestring (for example), the resulting array will be readonly:

>>> A["x"] = 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: assignment destination is read-only

If you want something writable, use np.fromstring instead of np.frombuffer:

>>> A = np.fromstring(b"Cool", dtype=[('x','<u2'),('y','<u2')])
>>> A["x"] = 23
>>> A
array([(23, 27759)],
      dtype=[('x', '<u2'), ('y', '<u2')])

See this answer for more information.

If you want a genuine NumPy record array (rather than a structured array, which is just a regular ndarray with structured dtype), you can pass the result to nd.rec.array:

>>> np.rec.array(A)
rec.array([(28483, 27759)],
          dtype=[('x', '<u2'), ('y', '<u2')])

Record arrays are much like structured arrays, but have their own ndarray subclass, and allow retrieval of fields via attribute access:

>>> B = np.rec.array(A)
>>> B.x
array([28483], dtype=uint16)


问:
How to convert a nested lists to dataframe in R?
I'm have a nested list I would like to convert to a dataframe.

```<code>iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe
</code>```

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

```<code>> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1
</code>```

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

答:
Would lapply do what you want ?:

```<code>iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)
</code>```

And then:

```<code>df <- as.data.frame(lapply(All, unlist))

> str(df)
'data.frame':   2 obs. of  2 variables:
 $ iter1: Factor w/ 2 levels "1","a": 1 2
 $ iter2: Factor w/ 2 levels "1","b": 1 2
</code>```

Body:
I'm have a nested list I would like to convert to a dataframe.

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

Body:
Would lapply do what you want ?:

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

And then:

df <- as.data.frame(lapply(All, unlist))

> str(df)
'data.frame':   2 obs. of  2 variables:
 $ iter1: Factor w/ 2 levels "1","a": 1 2
 $ iter2: Factor w/ 2 levels "1","b": 1 2


问:
Nuget Dependencies not getting installed
I am running a private Nuget Server locally on IIS.
I am creating packages and uploading them all via commadline using nuget.exe (Later on I have to put this on build server, hence the command line). However there is one issue I am stuck at.

I am trying to declare dependencies. I generate the nuspec file in the folder where the .csproj file is there. Then I manually edit the nuspec file to add this under the metadata tag:

```<code><metadata>
    <dependencies>
        <group targetFramework=".NETFramework4.5">
            <dependency id="DemoProject" version="2.0.0.0" />
        </group>
   </dependencies>
</metadata>
</code>```

DemoProject, version 2.0.0.0 is present on the Nuget Server.
The project I am creating package for, MyProj.csproj does not have the reference to the DemoProject added to it via Visual Studio. It is just at the packing time I want to create the dependency. It sounds strange but is needed for some initial validation.

Then I run pack command:

"C:\nuget\NuGet.exe" pack MyProj.csproj -IncludeReferencedProjects -Prop Configuration=Release

Then I push it to NuGet server using command line.
When I do an install via command line, then only MyProj package is present at the install location.

When I use Nuget Package Explorer and create a package, I can use the Package Dependency Editor to specify the dependency. It asks for the URL of my local Nuget Server and then adds the dependency. And when I install that package, it works !!

There seem to be no difference in the generated nuspec file in both the cases.
Obviously Nuget Package manager is doing something which I am missing out on.

Any hints?

More details: When I create a lib folder in the Package manager console and put my dll manually, lib->net45->MyProj.dll, then when I install the package thus created also "does not" install the dependency. Back to reading documentation again.

答:
Late answer but the issue with this nuspec is <group targetFramework=".NETFramework4.5">. I feel confident that ".NETFramework4.5" is an invalid targetFramework. A full list of the available Target Frameworks is here.

When working with the Dependency section, you may not need to use the group tag. Any users who encounter similar errors would do well to read through that section. They have samples of proper usage.

Body:
I am running a private Nuget Server locally on IIS.
I am creating packages and uploading them all via commadline using nuget.exe (Later on I have to put this on build server, hence the command line). However there is one issue I am stuck at.

I am trying to declare dependencies. I generate the nuspec file in the folder where the .csproj file is there. Then I manually edit the nuspec file to add this under the metadata tag:

<metadata>
    <dependencies>
        <group targetFramework=".NETFramework4.5">
            <dependency id="DemoProject" version="2.0.0.0" />
        </group>
   </dependencies>
</metadata>

DemoProject, version 2.0.0.0 is present on the Nuget Server.
The project I am creating package for, MyProj.csproj does not have the reference to the DemoProject added to it via Visual Studio. It is just at the packing time I want to create the dependency. It sounds strange but is needed for some initial validation.

Then I run pack command:

"C:\nuget\NuGet.exe" pack MyProj.csproj -IncludeReferencedProjects -Prop Configuration=Release

Then I push it to NuGet server using command line.
When I do an install via command line, then only MyProj package is present at the install location.

When I use Nuget Package Explorer and create a package, I can use the Package Dependency Editor to specify the dependency. It asks for the URL of my local Nuget Server and then adds the dependency. And when I install that package, it works !!

There seem to be no difference in the generated nuspec file in both the cases.
Obviously Nuget Package manager is doing something which I am missing out on.

Any hints?

More details: When I create a lib folder in the Package manager console and put my dll manually, lib->net45->MyProj.dll, then when I install the package thus created also "does not" install the dependency. Back to reading documentation again.


问:
ASP.NET MVC and Angular 4 mini SPA - Footer issue
Application Background: My application is built up using ASP .net MVC (.net framework 4.6) and several Angular 4 mini SPAs

Mini SPA is loaded from one of the view, say Subscription.cshtml. Please note my comments in code below:

```<code>@section styles{
    <link href="~/apps/userSubscription/styles.e8e9c3a3817e92de1e39.bundle.css" rel="stylesheet" />
}
@*This is mini SPA*@
<sb-subcription-app-root>
    @*This is loader to show while mini SPA is bootstrapped*@
    <div class="loading-icon">
        <div class="text-center">
            <i class="fa fa-spinner fa-spin fa-fw" style="font-size:55px;"></i>
        </div>
    </div>
</sb-subcription-app-root>

@section scripts{
    <script src="~/apps/userSubscription/inline.4306fb1489008775a724.bundle.js"></script>
    <script src="~/apps/userSubscription/polyfills.b92561b85131ad96e15f.bundle.js"></script>
    <script src="~/apps/userSubscription/vendor.d7d84c623190e8bb1494.bundle.js"></script>
    <script src="~/apps/userSubscription/main.c9d275f7937435642d76.bundle.js"></script>
}
</code>```

Issue: Footer is pushed to top. My footer is in _Layout.cshtml:

```<code><footer class="footer">
    <div class="top-footer">
        <div class="container">
        </div>
    </div>
</footer>
</code>```

Problem description:

When view Subscription.cshtml is being loaded. UI appears as shown in picture below. I believe at this point of time my angular app is getting bootstrapped

After angular app is bootstrapped, loader disappears (which I think is correct) and then footer is pushed to top for 2-3 sec until DOM is loaded as shown in picture

What I need: I would like to hide footer until DOM (which includes angular mini SPA) is loaded. Any CSS and JS solution would work for me.

答:
As a workaround you may try following approach.

1) Hide footer by default:

```<code><footer class="footer hide" id="footer">
</code>```

2) Mark the element that must be rendered before the footer could be shown:

```<code><div id="bootstraper">
</code>```

3) Run javascript polling process to switch footer visibility:

```<code>(function() {
  var timer = setInterval(function() {
     if(document.getElementById('bootstraper')) {
       clearInterval(timer);
       document.getElementById('footer').classList.remove("hide");
     }
  }, 40);
})();
</code>```

As you see, we just show the footer after some (needed) element has been rendered and become accessible via document. This solution is a bit hacky and I would recommend you to look for a way that would be more specific to your situation, to your environment. This would require more deep research:

who loads that DOM which is 2-3 sec late?

if it's the Angular App responsibility, then the App must handle this process;

and this process may not be just a primitive polling, for example the delaying entity may itself tell that it is done...

maybe DOMContentLoaded event would be enough? (just show the footer when it's fired)

Body:
Application Background: My application is built up using ASP .net MVC (.net framework 4.6) and several Angular 4 mini SPAs

Mini SPA is loaded from one of the view, say Subscription.cshtml. Please note my comments in code below:

@section styles{
    <link href="~/apps/userSubscription/styles.e8e9c3a3817e92de1e39.bundle.css" rel="stylesheet" />
}
@*This is mini SPA*@
<sb-subcription-app-root>
    @*This is loader to show while mini SPA is bootstrapped*@

</sb-subcription-app-root>

@section scripts{

}

Issue: Footer is pushed to top. My footer is in _Layout.cshtml:

Problem description:

When view Subscription.cshtml is being loaded. UI appears as shown in picture below. I believe at this point of time my angular app is getting bootstrapped

After angular app is bootstrapped, loader disappears (which I think is correct) and then footer is pushed to top for 2-3 sec until DOM is loaded as shown in picture

What I need: I would like to hide footer until DOM (which includes angular mini SPA) is loaded. Any CSS and JS solution would work for me.

Body:
As a workaround you may try following approach.

1) Hide footer by default:

<footer class="footer hide" id="footer">

2) Mark the element that must be rendered before the footer could be shown:

<div id="bootstraper">

3) Run javascript polling process to switch footer visibility:

(function() {
  var timer = setInterval(function() {
     if(document.getElementById('bootstraper')) {
       clearInterval(timer);
       document.getElementById('footer').classList.remove("hide");
     }
  }, 40);
})();

As you see, we just show the footer after some (needed) element has been rendered and become accessible via document. This solution is a bit hacky and I would recommend you to look for a way that would be more specific to your situation, to your environment. This would require more deep research:

who loads that DOM which is 2-3 sec late?

if it's the Angular App responsibility, then the App must handle this process;

and this process may not be just a primitive polling, for example the delaying entity may itself tell that it is done...

maybe DOMContentLoaded event would be enough? (just show the footer when it's fired)


问:
Using session context manager and stream=True at the same time
I was wondering if this code is safe:

```<code>import requests
with requests.Session() as s:
    response = s.get("http://google.com", stream=True)
content = response.content
</code>```

For example simple like this, this does not fail (note I don't write "it works" :p), since the pool does not close instantly the connection anyway (that's a point of a session/pool right?).

Using stream=True, the response object is supposed to have its raw attribute that contains the connection, but I'm unsure if the connection is owned by the session or not, and then if at some point if I don't read the content right now but later, it might have been closed.

My current 2 cents is that it's unsafe, but I'm not 100% sure.

Thanks!

[Edit after reading requests code]

After reading the requests code in more details, it seems that it's what requests.get is doing itself:

https://github.com/requests/requests/blob/master/requests/api.py

```<code>def request(method, url, **kwargs):
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)
</code>```

Being that kwargs might contain stream.

So I guess the answer is "it's safe".

答:
Ok, I got my answer by digging in requests and urllib3

The Response object own the connection until the close() method is explicitly called:

https://github.com/requests/requests/blob/24092b11d74af0a766d9cc616622f38adb0044b9/requests/models.py#L937-L948

```<code>def close(self):
    """Releases the connection back to the pool. Once this method has been
    called the underlying ``raw`` object must not be accessed again.
    *Note: Should not normally need to be called explicitly.*
    """
    if not self._content_consumed:
        self.raw.close()

    release_conn = getattr(self.raw, 'release_conn', None)
    if release_conn is not None:
        release_conn()
</code>```

release_conn() is a urllib3 method, this releases the connection and put it back in the pool

```<code>def release_conn(self):
    if not self._pool or not self._connection:
        return

    self._pool._put_conn(self._connection)
    self._connection = None
</code>```

If the Session was destroyed (like using the with), the pool was destroyed, the connection cannot be put back and it's just closed.

TL;DR; This is safe.

Note that this also means that in stream mode, the connection is not available for the pool until the response is closed explicitly or the content read entirely.

Body:
I was wondering if this code is safe:

import requests
with requests.Session() as s:
    response = s.get("http://google.com", stream=True)
content = response.content

For example simple like this, this does not fail (note I don't write "it works" :p), since the pool does not close instantly the connection anyway (that's a point of a session/pool right?).

Using stream=True, the response object is supposed to have its raw attribute that contains the connection, but I'm unsure if the connection is owned by the session or not, and then if at some point if I don't read the content right now but later, it might have been closed.

My current 2 cents is that it's unsafe, but I'm not 100% sure.

Thanks!

[Edit after reading requests code]

After reading the requests code in more details, it seems that it's what requests.get is doing itself:

https://github.com/requests/requests/blob/master/requests/api.py

def request(method, url, **kwargs):
    with sessions.Session() as session:
        return session.request(method=method, url=url, **kwargs)

Being that kwargs might contain stream.

So I guess the answer is "it's safe".

Body:
Ok, I got my answer by digging in requests and urllib3

The Response object own the connection until the close() method is explicitly called:

https://github.com/requests/requests/blob/24092b11d74af0a766d9cc616622f38adb0044b9/requests/models.py#L937-L948

def close(self):
    """Releases the connection back to the pool. Once this method has been
    called the underlying ``raw`` object must not be accessed again.
    *Note: Should not normally need to be called explicitly.*
    """
    if not self._content_consumed:
        self.raw.close()

    release_conn = getattr(self.raw, 'release_conn', None)
    if release_conn is not None:
        release_conn()

release_conn() is a urllib3 method, this releases the connection and put it back in the pool

def release_conn(self):
    if not self._pool or not self._connection:
        return

    self._pool._put_conn(self._connection)
    self._connection = None

If the Session was destroyed (like using the with), the pool was destroyed, the connection cannot be put back and it's just closed.

TL;DR; This is safe.

Note that this also means that in stream mode, the connection is not available for the pool until the response is closed explicitly or the content read entirely.


问:
Mutable class as a child of an immutable class
I want to have immutable Java objects like this (strongly simplified):

```<code>class Immutable {

    protected String name;

    public Immutable(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}
</code>```

In some cases the object should not only be readable but mutable, so I could add mutability through inheritance:

```<code>public class Mutable extends Immutable {

    public Mutable(String name) {
        super(name);
    }

    public void setName(String name) {
        super.name = name;
    }

}
</code>```

While this is technically fine, I wonder if it conforms with OOP and inheritance that mutable is also of type immutable. I want to avoid the OOP crime to throw UnsupportedOperationException for immutable object, like the Java collections API does.

What do you think? Any other ideas?

答:
I would suggest that you should have an inheritable base "ReadableFoo" class, a derived sealed ImmutableFoo class, and other derived MutableFoo classes.  Code which doesn't care whether a Foo is mutable or not can accept a ReadableFoo.  Code that wants a Foo that is guaranteed not to change can accept an ImmutableFoo.  Code which can need to change a Foo can accept a MutableFoo.

Note that the constructors for both ImmutableFoo and MutableFoo should typically accept a ReadableFoo.  That way, any Foo will be convertible to a mutable or immutable version.

Body:
I want to have immutable Java objects like this (strongly simplified):

class Immutable {

    protected String name;

    public Immutable(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

In some cases the object should not only be readable but mutable, so I could add mutability through inheritance:

public class Mutable extends Immutable {

    public Mutable(String name) {
        super(name);
    }

    public void setName(String name) {
        super.name = name;
    }

}

While this is technically fine, I wonder if it conforms with OOP and inheritance that mutable is also of type immutable. I want to avoid the OOP crime to throw UnsupportedOperationException for immutable object, like the Java collections API does.

What do you think? Any other ideas?


问:
How to catch all exceptions in Try/Catch Block Python?
I am writing python code to install all the library packages required by my program in the linux environment.So the linux may contain python 2.7 or 2.6 or both so I have developed a try and except block codes that will install pip packages in linux. Try block code consists of python 2.7 version pip install and Catch block contains python 2.6 version pip install. My Problem is the peace of code is working fine, when i tried to install pandas in python 2.6 its getting me some errror. I want to catch that exception. Can you please tell me how to improve my try except blocks to catch that exception</p>

```<code>required_libraries = ['pytz','requests','pandas']
try:
   from subprocess import check_output
   pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
   lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
   p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
   lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]
</code>```

答:
You can catch several exceptions using one block. Let's use Exception and ArithmeticError for exceptions.

```<code>try:
    # Do something
    print(q)

# Catch exceptions
except (Exception, ArithmeticError) as e:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(e).__name__, e.args)
    print (message)
</code>```

If you need to catch several exceptions and handle each one on its own then you'd write an except statement for each one.

```<code>try:
    # Do something
    print(q)

# Catch exceptions
except Exception as e:
    print (1)

except ArithmeticError as e:
    print (2)

# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement

else:
    print (3)
</code>```

You can also check if the exception is of type "MyCustomException" for example using if statements.

```<code>if isinstance(e, MyCustomException):
    # Do something
    print(1)
</code>```

As for your problem, I suggest splitting the code into two functions.

```<code>install(required_libraries)

def install(required_libraries, version='pip2.7'):
    # Perform installation
    try:
        from subprocess import check_output
        pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
        lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        backup(required_libraries)

def backup(required_libraries, version='pip2.6'):
    try:
        p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
        lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(e).__name__, e.args)
        print (message)

        #Handle exception
</code>```

Note: I didn't test this, I'm no expert as well so I hope I can help.

Useful links:

Built-in Exceptions

Errors and Exceptions

Compound statements

Body:
I am writing python code to install all the library packages required by my program in the linux environment.So the linux may contain python 2.7 or 2.6 or both so I have developed a try and except block codes that will install pip packages in linux. Try block code consists of python 2.7 version pip install and Catch block contains python 2.6 version pip install. My Problem is the peace of code is working fine, when i tried to install pandas in python 2.6 its getting me some errror. I want to catch that exception. Can you please tell me how to improve my try except blocks to catch that exception

required_libraries = ['pytz','requests','pandas']
try:
   from subprocess import check_output
   pip27_path = subprocess.check_output(['sudo','find','/','-name','pip2.7'])
   lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]
except:
   p = subprocess.Popen(['sudo','find','/','-name','pip2.6'], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
   lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

Body:
You can catch several exceptions using one block. Let's use Exception and ArithmeticError for exceptions.

try:
    # Do something
    print(q)

# Catch exceptions
except (Exception, ArithmeticError) as e:
    template = "An exception of type {0} occurred. Arguments:\n{1!r}"
    message = template.format(type(e).__name__, e.args)
    print (message)

If you need to catch several exceptions and handle each one on its own then you'd write an except statement for each one.

try:
    # Do something
    print(q)

# Catch exceptions
except Exception as e:
    print (1)

except ArithmeticError as e:
    print (2)

# Code to be executed if the try clause succeeded with no errors or no return/continue/break statement

else:
    print (3)

You can also check if the exception is of type "MyCustomException" for example using if statements.

if isinstance(e, MyCustomException):
    # Do something
    print(1)

As for your problem, I suggest splitting the code into two functions.

install(required_libraries)

def install(required_libraries, version='pip2.7'):
    # Perform installation
    try:
        from subprocess import check_output
        pip27_path = subprocess.check_output(['sudo','find','/','-name', version])
        lib_installs = [subprocess.call((['sudo',pip27_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        backup(required_libraries)

def backup(required_libraries, version='pip2.6'):
    try:
        p = subprocess.Popen(['sudo','find','/','-name',version]], stdout=subprocess.PIPE);pip26_path, err = p.communicate()
        lib_installs = [subprocess.call((['sudo',pip26_path.replace('\n',''),'install', i])) for i in required_libraries]

    except Exception as e:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(e).__name__, e.args)
        print (message)

        #Handle exception

Note: I didn't test this, I'm no expert as well so I hope I can help.

Useful links:

Built-in Exceptions

Errors and Exceptions

Compound statements


问:
How to automate fiddler and export results to local directory
I am working on a client request where I need to capture web browser traffic using fiddler and export it to local drive.

I am enter some data in web browser and the same is captured as request in Fiddler session.

As per my understanding of Fiddler the script should execute as soon as any web session is captured.

In order to export the request from Fiddler I am using the below code in OnBeforeRequest function in Fiddler script

```<code>if(oSession.url =="www.google.com"){
oSession.utilDecodeRequest();
oSession.SaveRequest("C:\\Downloads\request.txt",true);
oSession.SaveRequestBody("C:\\Downloads\requestBody.txt");
</code>```

}

Any suggestion why the request is not getting saved as a text file as I have mentioned in the above code.

答:
The file is getting generated successfully. There was admin right issue.

Re installed fiddler with admin rights and the files got generated successfully.

Body:
I am working on a client request where I need to capture web browser traffic using fiddler and export it to local drive.

I am enter some data in web browser and the same is captured as request in Fiddler session.

As per my understanding of Fiddler the script should execute as soon as any web session is captured.

In order to export the request from Fiddler I am using the below code in OnBeforeRequest function in Fiddler script

if(oSession.url =="www.google.com"){
oSession.utilDecodeRequest();
oSession.SaveRequest("C:\\Downloads\request.txt",true);
oSession.SaveRequestBody("C:\\Downloads\requestBody.txt");

}

Any suggestion why the request is not getting saved as a text file as I have mentioned in the above code.


问:
How can I detect if a git patch is already applied?
I have several git branches that have commits cherry-picked between them. Commits are sometimes squashed.

In order to decide whether to apply a commit abcdef to the live branch, I want to find out if an equivalent commit has already been applied to the preprod branch.

If preprod never squashed commits, I would use patch IDs, as discussed in this question. Since preprod may squash sequences of commits, I want to see if abcdef would be an empty commit on preprod.

```<code>$ git checkout preprod
$ git cherry-pick abcdef
On branch preprod
Your branch is up-to-date with 'origin/preprod'.
You are currently cherry-picking commit abcdef.

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

Otherwise, please use 'git reset'
</code>```

How can I programmatically detect if cherry-picking a commit would result in an empty commit?

(I know this is an imperfect heuristic for detecting whether the patch has been applied, but it's good enough for my use case.)

答:
Take a look at git cherry:

Find commits yet to be applied to upstream

Something like this should do the trick by displaying commit abcdef if a cherry-pick is necessary else nothing (didn't check):

```<code>git cherry abcdef preprod abcdef^
</code>```

Body:
I have several git branches that have commits cherry-picked between them. Commits are sometimes squashed.

In order to decide whether to apply a commit abcdef to the live branch, I want to find out if an equivalent commit has already been applied to the preprod branch.

If preprod never squashed commits, I would use patch IDs, as discussed in this question. Since preprod may squash sequences of commits, I want to see if abcdef would be an empty commit on preprod.

$ git checkout preprod
$ git cherry-pick abcdef
On branch preprod
Your branch is up-to-date with 'origin/preprod'.
You are currently cherry-picking commit abcdef.

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

Otherwise, please use 'git reset'

How can I programmatically detect if cherry-picking a commit would result in an empty commit?

(I know this is an imperfect heuristic for detecting whether the patch has been applied, but it's good enough for my use case.)

Body:
Take a look at git cherry:

Find commits yet to be applied to upstream

Something like this should do the trick by displaying commit abcdef if a cherry-pick is necessary else nothing (didn't check):

git cherry abcdef preprod abcdef^


问:
Custom Membership Provider and Domain-Driven-Design
I have a concern where I am writing a custom membership provider, but I'm not sure where to put it. I don't really have any code to show you, but basically the provider needs access to System.Web.Security in order to inherit the class, but it also needs data access (i.e. a connection string + LINQ to SQL) to do simple tasks such as ValidateUser.

How can I write a membership provider that adheres to the principles of DDD that I've read about in Pro ASP.NET MVC2 Framework by Apress? My one thought was to write another class in my domain project which does all the "work" related to database stuff. In essence I would have double the number of methods. Also, can this work with dependency injection (IoC)?

Hope this isn't too general ...

Look forward to the hive-mind's responses!

Edit: I just noticed in a default MVC2 project there is an AccountController which has a wrapper around an IMembershipService. Is this where my answer lies? The AccountController seems to have no database access component to it.

答:
Asp.net user management features are super invasive.

They even spam database with profile tables and what not.

When I had to implement users management of my application, I successfully avoided all that mess and still was able to use asp.net in-built roles, user identities etc. Moving away from all that though cause my domain is getting smart enough to decide what can be seen and done so it makes no sense to duplicate that in UI client.

So... yeah. Still have zero problems with this approach. Haven't changed anything for ~4 months.

 Works like a charm.


问:
In Excel, how to identify matching data in order to report shared quantities?
So, I have a list of products where I report which manufacturing facility currently makes it, as well as the QTY I need to make. Separately, I have a list that tells me ALL facilities that are equipped to manufacture that product.

What I'm looking to do is make a report that can show me, at a glance, how much work is available to offload from one facility to another.

Current Manufacturer Builds

```<code>  Product  ||  MFGR  ||  QTY to Build
     A     ||   1    ||      100
     B     ||   2    ||      50
     C     ||   3    ||      100
</code>```

All Product/Manufacturer Combos

```<code>  Product  ||  MFGR
     A     ||   1
     A     ||   2
     B     ||   2
     B     ||   3
     C     ||   3
</code>```

So, from the above lists we can infer:

Product A can be made at either facility 1 or 2, but it's currently set to build at facility 1

Product B can be made at either facility 2 or 3, but it's currently set to build at facility 2

product C can only be made at facility 3

From all this, I would like to have a report that shows the following information:

```<code>  From MFGR  ||  To MFGR  ||  Avail QTY
      1      ||     2     ||     100
      1      ||     3     ||      0
      2      ||     1     ||      0
      2      ||     3     ||     50
      3      ||     1     ||      0
      3      ||     2     ||      0
</code>```

Where, in this report, it recognizes that:

Product A's build QTY CAN be offloaded from facility 1 to 2, so it reports a possible move of 100 from 1 to 2

Product B's build QTY CAN be offloaded from facility 2 to 3, so it reports a possible move of 50 from 2 to 3

Note that the report ignores the product (it will need to since my actual file has 100's of products, and like 10 facilities), though I recognize it needs to take it into consideration in the formula.

Is there a single-cell formula that can get this done? I was using SUMIFS() to grab the Build QTY of the "From MFGR", but I wasn't sure how to incorporate that with anything else.

答:
You can use this array formula:

```<code>=SUM(SUMIFS(C:C,A:A,INDEX(E:E,N(IF({1},MODE.MULT(IF($F$2:$F$6=I2,ROW($F$2:$F$6)*{1,1}))))),B:B,H2))
</code>```

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.

Body:
So, I have a list of products where I report which manufacturing facility currently makes it, as well as the QTY I need to make. Separately, I have a list that tells me ALL facilities that are equipped to manufacture that product.

What I'm looking to do is make a report that can show me, at a glance, how much work is available to offload from one facility to another.

Current Manufacturer Builds

  Product  ||  MFGR  ||  QTY to Build
     A     ||   1    ||      100
     B     ||   2    ||      50
     C     ||   3    ||      100

All Product/Manufacturer Combos

  Product  ||  MFGR
     A     ||   1
     A     ||   2
     B     ||   2
     B     ||   3
     C     ||   3

So, from the above lists we can infer:

Product A can be made at either facility 1 or 2, but it's currently set to build at facility 1

Product B can be made at either facility 2 or 3, but it's currently set to build at facility 2

product C can only be made at facility 3

From all this, I would like to have a report that shows the following information:

  From MFGR  ||  To MFGR  ||  Avail QTY
      1      ||     2     ||     100
      1      ||     3     ||      0
      2      ||     1     ||      0
      2      ||     3     ||     50
      3      ||     1     ||      0
      3      ||     2     ||      0

Where, in this report, it recognizes that:

Product A's build QTY CAN be offloaded from facility 1 to 2, so it reports a possible move of 100 from 1 to 2

Product B's build QTY CAN be offloaded from facility 2 to 3, so it reports a possible move of 50 from 2 to 3

Note that the report ignores the product (it will need to since my actual file has 100's of products, and like 10 facilities), though I recognize it needs to take it into consideration in the formula.

Is there a single-cell formula that can get this done? I was using SUMIFS() to grab the Build QTY of the "From MFGR", but I wasn't sure how to incorporate that with anything else.

Body:
You can use this array formula:

=SUM(SUMIFS(C:C,A:A,INDEX(E:E,N(IF({1},MODE.MULT(IF($F$2:$F$6=I2,ROW($F$2:$F$6)*{1,1}))))),B:B,H2))

Being an array formula it needs to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


问:
Importing blank Excel columns using SSIS
I'm creating an SSIS package to import Excel files (which have different layouts) into a SQL Server table with 150 columns.

The SSIS package has a Foreach Loop Container within which is a Data Flow Task which has an Excel Source component and an OLE DB Destination component.

The Data Flow Task will be ran for each Excel file so the Excel Source component needs to work for every file.

I've set up the Excel Source component with 150 Unicode string columns of length 255, and I've set ValidateExternalMetadata to False, however I'm getting the error: 'Column "F143" cannot be found at the datasource' when testing the package on an Excel file with 142 columns of data.

My question is: How do I get the package to ignore this error and import the columns that exist, or is there another way of dealing with the above situation?

答:
Try using the following sql command in Excel source

```<code>SELECT * FROM [Sheet1$A1:B]
</code>```

Substitute B for whatever the 150th column is.

Body:
Try using the following sql command in Excel source

SELECT * FROM [Sheet1$A1:B]

Substitute B for whatever the 150th column is.


问:
Sort(), confusing about condition in comparision function
I get this code from a basic javascript lesson on Codewar, but I don't understand how it work, I tried one by one condition but it doesn't show output as I expected. Thank you so much.</p>

```<code>var arr=[1,2,3,4,5,6,100,999]
arr.sort((a,b)=>{
  if (a%2==b%2) return a-b;
  if (a%2>b%2) return -1;
  return 1;
})
console.log(arr)

//output: [ 1, 3, 5, 999, 2, 4, 6, 100 ]
</code>```

答:
it should print the odd numbers first then even numbers, each is sorted

if (a%2==b%2) return a-b;

if a, b are both even or both odd then sort them in increasing order

if (a%2>b%2) return -1;

else if they are different [ one odd and the other is even ] put the odd numbers first

else a, b are equal

Body:
I get this code from a basic javascript lesson on Codewar, but I don't understand how it work, I tried one by one condition but it doesn't show output as I expected. Thank you so much.

var arr=[1,2,3,4,5,6,100,999]
arr.sort((a,b)=>{
  if (a%2==b%2) return a-b;
  if (a%2>b%2) return -1;
  return 1;
})
console.log(arr)

//output: [ 1, 3, 5, 999, 2, 4, 6, 100 ]


问:
Smooth scroll to ID using jQuery
Struggling to implement a smooth scroll feature when navigating to an ID using my navbar.  Instead, it makes the default jump, which is a bit of an eye sore.

I am very inexperienced using jQuery, so any pointers in the right direction would be much appreciated.

I have made an attempt to get this implemented however, as I have said, it is 'jumping' as opposed to scrolling.

HTML

```<code><li>
  <a href="#popular">Most Popular</a>
</li>
<div class="col-sm-12" id="popular">
<h3><i aria-hidden="true" class="fa fa-fire"></i> Most Popular</h3>
</div>
</code>```

jQuery

```<code>$(document).ready(function() {
  $("#popular").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('col-sm-12').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });
    }
</code>```

答:
```<code>    $(document).ready(function(){
  $('a[href^="#"]').on('click',function (e) {
      e.preventDefault();

      var target = this.hash;
      var $target = $(target);

      $('html, body').stop().animate({
          'scrollTop': $target.offset().top
      }, 900, 'swing', function () {
          window.location.hash = target;
      });
  });
});
</code>```

Add the above in your $(document).ready function in your jQuery file and all links which start with a # will have an animated scroll to the target.

Title: Smooth scroll to ID using jQuery

Body:
Struggling to implement a smooth scroll feature when navigating to an ID using my navbar.  Instead, it makes the default jump, which is a bit of an eye sore.

I am very inexperienced using jQuery, so any pointers in the right direction would be much appreciated.

I have made an attempt to get this implemented however, as I have said, it is 'jumping' as opposed to scrolling.

HTML

  Most Popular

 Most Popular

jQuery

$(document).ready(function() {
  $("#popular").on('click', function(event) {
    if (this.hash !== "") {
      event.preventDefault();
      var hash = this.hash;
      $('col-sm-12').animate({
        scrollTop: $(hash).offset().top
      }, 800, function() {
        window.location.hash = hash;
      });
    }

Body:
    $(document).ready(function(){
  $('a[href^="#"]').on('click',function (e) {
      e.preventDefault();

      var target = this.hash;
      var $target = $(target);

      $('html, body').stop().animate({
          'scrollTop': $target.offset().top
      }, 900, 'swing', function () {
          window.location.hash = target;
      });
  });
});

Add the above in your $(document).ready function in your jQuery file and all links which start with a # will have an animated scroll to the target.


问:
Eloquent relation clarification
Following is my query

```<code> $user = User::with(['session' => function ($query) {
            $query->select('id','device_id');
            $query->where('api_token', '=', '123456');
          }])->get();
</code>```

session: hasMany relation with User.

I am expecting a user with a session having api_token = 123456. Instead I am getting whole users here. I know I am doing something wrong.

I am referring this doc. In the doc it is saying that we can add constraint to the query. But here $query->where('api_token', '=', '123456'); this where is not working.

答:
You are not filtering the User, you are filtering the result of the eager loading of 'session'. Eager loading does not have any effect on the base result set in anyway.

It sounds like you want to filter User by the 'existence' of a relationship in the database.

```<code>User::whereHas('session', function ($q) {
    $q->where('api_token', '12345');
})->get(); // ->first();
</code>```

Get all Users that have a Session where 'api_token' == '12345'.

Laravel 5.5 Docs - Eloquent - Relationships - Querying Relationship Existence

Title: Eloquent relation clarification

Body:
Following is my query

 $user = User::with(['session' => function ($query) {
            $query->select('id','device_id');
            $query->where('api_token', '=', '123456');
          }])->get();

session: hasMany relation with User.

I am expecting a user with a session having api_token = 123456. Instead I am getting whole users here. I know I am doing something wrong.

I am referring this doc. In the doc it is saying that we can add constraint to the query. But here $query->where('api_token', '=', '123456'); this where is not working.

Body:
You are not filtering the User, you are filtering the result of the eager loading of 'session'. Eager loading does not have any effect on the base result set in anyway.

It sounds like you want to filter User by the 'existence' of a relationship in the database.

User::whereHas('session', function ($q) {
    $q->where('api_token', '12345');
})->get(); // ->first();

Get all Users that have a Session where 'api_token' == '12345'.

Laravel 5.5 Docs - Eloquent - Relationships - Querying Relationship Existence


问:
JavaScript override class method conditionally
I have a class that I have defined that I use all over my application.  I have one page where I would like to change override some of the methods on all instances of the class.  Here is some code to illustrate.

myclass-script.js

```<code>var MyClass = new Class({
    foo: function() {
        return 1;
    },

    bar: function() {
        return this.foo() + 9;
    },
});
</code>```

change-myclass-script.js

```<code>MyClass.implement({
    foo: function() {
        return this.parent() * -1;
    },
});
</code>```

If I include on a page myclass-script.js I should see:

```<code>var test = new MyClass();
test.bar() === 10; //true
</code>```

If I include myclass-script.js and then change-myclass-script.js I should see:

```<code>var test = new MyClass();
test.bar() === 8; //true
</code>```

The issue I am having is that MyClass.implement applies to all instances of MyClass but it doesn't "override" the method, it replaces it.  So the this.parent() call fails because there is no parent for that method.  If I do MyClass.extend it does not apply like I want and I do not see the instances of MyClass calling the overridden method.

答:
not sure if this is the best practice but it will allow you to run whatever logic you want or just return original method if not required...

```<code>var MyClass = new Class({
    foo: function() {
        return 1;
    },
    bar: function() {
        return this.foo() + 9;
    }
});

var f = new MyClass();
console.log(f.bar()); // 10

(function() {
    var orig = MyClass.prototype.foo;
    MyClass.prototype.foo = function() {
        return orig.apply(this, arguments) * -1;
    };
})();

console.log(f.bar()); // 8
</code>```

http://www.jsfiddle.net/dimitar/cXTrD/7/

Body:
I have a class that I have defined that I use all over my application.  I have one page where I would like to change override some of the methods on all instances of the class.  Here is some code to illustrate.

myclass-script.js

var MyClass = new Class({
    foo: function() {
        return 1;
    },

    bar: function() {
        return this.foo() + 9;
    },
});

change-myclass-script.js

MyClass.implement({
    foo: function() {
        return this.parent() * -1;
    },
});

If I include on a page myclass-script.js I should see:

var test = new MyClass();
test.bar() === 10; //true

If I include myclass-script.js and then change-myclass-script.js I should see:

var test = new MyClass();
test.bar() === 8; //true

The issue I am having is that MyClass.implement applies to all instances of MyClass but it doesn't "override" the method, it replaces it.  So the this.parent() call fails because there is no parent for that method.  If I do MyClass.extend it does not apply like I want and I do not see the instances of MyClass calling the overridden method.

Body:
not sure if this is the best practice but it will allow you to run whatever logic you want or just return original method if not required...

var MyClass = new Class({
    foo: function() {
        return 1;
    },
    bar: function() {
        return this.foo() + 9;
    }
});

var f = new MyClass();
console.log(f.bar()); // 10

(function() {
    var orig = MyClass.prototype.foo;
    MyClass.prototype.foo = function() {
        return orig.apply(this, arguments) * -1;
    };
})();

console.log(f.bar()); // 8

http://www.jsfiddle.net/dimitar/cXTrD/7/


问:
Angular5 HttpClient returning undefined in component view
I'm trying to access an API that returns a JSON with some data that I then need to present in my component html by using ngFor because it's an object. Inside the http.get function if I console.log the returned data, it appears fine. But when I try to present it in my view, it's not working.

Here is my component.ts:

```<code>import { HttpClient } from '@angular/common/http';

export class AnonimoComponent implements OnInit {
    public medicamentos: Object;

    private baseURL = 'http://website.com/api/medicamentos';

    constructor(private http: HttpClient) {  }

    ngOnInit() {
         this.getMedicamentos();
    }

    getMedicamentos(){
        interface MedicamentoResponse {
            id: number;
            Name: string;
            Preco: number;
        }

        this.http.get<MedicamentoResponse>(this.baseURL).subscribe((data) => {
             this.medicamentos = data;
             console.log("First:\n" + this.medicamentos);
        });
    }
}
</code>```

Here is my html:

```<code><ul>
    <li *ngFor="let med of medicamentos$ | async">
        {{med}}
    </li>
</ul>
</code>```

However, it's not presenting anything. Any ideas?

答:
*ngFor is not work with JSON..

You have to Convert it to Array.

Try This

```<code>this.medicamentos = data.json();
</code>```

Body:
I'm trying to access an API that returns a JSON with some data that I then need to present in my component html by using ngFor because it's an object. Inside the http.get function if I console.log the returned data, it appears fine. But when I try to present it in my view, it's not working.

Here is my component.ts:

import { HttpClient } from '@angular/common/http';

export class AnonimoComponent implements OnInit {
    public medicamentos: Object;

    private baseURL = 'http://website.com/api/medicamentos';

    constructor(private http: HttpClient) {  }

    ngOnInit() {
         this.getMedicamentos();
    }

    getMedicamentos(){
        interface MedicamentoResponse {
            id: number;
            Name: string;
            Preco: number;
        }

        this.http.get<MedicamentoResponse>(this.baseURL).subscribe((data) => {
             this.medicamentos = data;
             console.log("First:\n" + this.medicamentos);
        });
    }
}

Here is my html:

        {{med}}

However, it's not presenting anything. Any ideas?

Body:
*ngFor is not work with JSON..

You have to Convert it to Array.

Try This

this.medicamentos = data.json();


答:
Change

```<code>*ngFor="let med of medicamentos$ | async"
</code>```

to

```<code>*ngFor="let med of medicamentos"
</code>```

You can't use async because medicamentos is not an Observable, you assigned the result directly in the subscribe in your component's code

Casing and variable name are critical, you can't add a character like $ at the end of the variable name in the template and have it still work.

Finally you should validate that what is being assigned to medicamentos is actually an array, verify the response in your browser's debugger.

Title: Angular5 HttpClient returning undefined in component view

Body:
Change

*ngFor="let med of medicamentos$ | async"

to

*ngFor="let med of medicamentos"

You can't use async because medicamentos is not an Observable, you assigned the result directly in the subscribe in your component's code

Casing and variable name are critical, you can't add a character like $ at the end of the variable name in the template and have it still work.

Finally you should validate that what is being assigned to medicamentos is actually an array, verify the response in your browser's debugger.


答:
If you use the |async pipe, you can't use .subscribe().

It should be

```<code>getMedicamentos(){
    this.medicamentos = this.http.get<MedicamentoResponse>(this.baseURL);
}
</code>```

If you use

```<code> this.medicamentos = data;
</code>```

then you don't need |async

Body:
If you use the |async pipe, you can't use .subscribe().

It should be

getMedicamentos(){
    this.medicamentos = this.http.get<MedicamentoResponse>(this.baseURL);
}

If you use

 this.medicamentos = data;

then you don't need |async


问:
NSTimer not working with AsyncSocket library
I am using the AsyncSocket library and I tried creating an NSTimer but it is not firing. When I remove the Async socket code, my timer works. I am pretty sure AsyncSockets is causing this, so how can I use NSTimers and what might be the cause of this?</p>

答: I found a method addTimerToRunloop in the AsyncSocket library that fixes this.


问:
How to know if a Javascript Callback is Synchronous or Asynchronous?

Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

```<code>$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});
</code>```

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

答:
Short answer:
You need to examine the caller and look for async operations.

Long answer:

A callback is a simple pattern by which a function is passed as a parameter to an higher order function and is called back it or further down the stack.

```<code>let mySynchronousFunction = () => 'Hello';
let myHigherOrderFunction = aFunc => {
    return (aFunc() || 'Goodbye') + ' world!';
};
</code>```

As soon as there is an I/O operation that would block the main thread, it instead will "branch out" and continue execution.

If we continue with our previous example, we would observe the following behavior:

```<code>let myAsyncFunction = () => {
    return http.get('http://some.document')
       .then(response => console.log(response)
    );
};
myHigherOrderFunction(mySynchronousFunction); // 'Hello world!'
myHigherOrderFunction(myAsyncFunction); // 'Goodbye world!'
</code>```

What happened here is that the main thread continued all the way until it had to wait for I/O and instead of blocking there, it went to the next instruction and took note of the point at which it needs to go when the I/O operation is no longer blocked.

So the next expression to evaluation in our code is:

```<code>return expression
</code>```

But our expression branched out, as such it returns undefined. So we are left with:

```<code>return undefined
</code>```

This means that our higher order function that was passed an async function got undefined when it called aFunc().

Once the I/O is done, the main thread returns to where it left off which is the function passed to Promise handler then. At this point the execution thread has branched out and is separated from main "thread".

Now for your question

The callback will be synchronous when the higher order function which calls it is calling it synchronously. Inversely if it is called within the context of the execution branch of an asynchronous operation it will be asynchronous.

This mean that you need to examine what the higher order function to which you pass your callback is doing and look for async operations.

In the context of your question let us examine the following code (HOF = Higher order function):

```<code>let mySynchronousHOC = aFunc => aFunc('Hello world!');
let myAsyncHOC = aFunc => {
    http.get('http://hello.com')
        .then(response => aFunc('Goodbye world!')
    );
};

myAsyncHOC(msg => {
    console.log(msg);
});

mySynchronousHOC(msg => {
   console.log(msg);
});
</code>```

The result of which will be:

```<code>'Hello world'
'Goodbye world'
</code>```

Here we know that myAsyncHOC is asynchronous because it does an I/O operation.

Body:
Hi! I am learning about callbacks and I understand that callbacks can be either synchronous or asynchronous.

I was reading about callbacks on https://www.w3schools.com/jquery/jquery_callback.asp and was quite confused.

There is this code:

$("button").click(function(){
    $("p").hide("slow", function(){
        alert("The paragraph is now hidden");
    });
});

Can I check if there is a way to know if the above callback is Synchronous or Asynchronous?

I am guessing it is Synchronous above because it has to wait till the "slow" animation is over before the alert comes up. Is it by default in Javascript or Node.js all callbacks are synchronous unless you do something like setTimeOut or process.nextTick?

Body:
Short answer:
You need to examine the caller and look for async operations.

Long answer:

A callback is a simple pattern by which a function is passed as a parameter to an higher order function and is called back it or further down the stack.

let mySynchronousFunction = () => 'Hello';
let myHigherOrderFunction = aFunc => {
    return (aFunc() || 'Goodbye') + ' world!';
};

As soon as there is an I/O operation that would block the main thread, it instead will "branch out" and continue execution.

If we continue with our previous example, we would observe the following behavior:

let myAsyncFunction = () => {
    return http.get('http://some.document')
       .then(response => console.log(response)
    );
};
myHigherOrderFunction(mySynchronousFunction); // 'Hello world!'
myHigherOrderFunction(myAsyncFunction); // 'Goodbye world!'

What happened here is that the main thread continued all the way until it had to wait for I/O and instead of blocking there, it went to the next instruction and took note of the point at which it needs to go when the I/O operation is no longer blocked.

So the next expression to evaluation in our code is:

return expression

But our expression branched out, as such it returns undefined. So we are left with:

return undefined

This means that our higher order function that was passed an async function got undefined when it called aFunc().

Once the I/O is done, the main thread returns to where it left off which is the function passed to Promise handler then. At this point the execution thread has branched out and is separated from main "thread".

Now for your question

The callback will be synchronous when the higher order function which calls it is calling it synchronously. Inversely if it is called within the context of the execution branch of an asynchronous operation it will be asynchronous.

This mean that you need to examine what the higher order function to which you pass your callback is doing and look for async operations.

In the context of your question let us examine the following code (HOF = Higher order function):

let mySynchronousHOC = aFunc => aFunc('Hello world!');
let myAsyncHOC = aFunc => {
    http.get('http://hello.com')
        .then(response => aFunc('Goodbye world!')
    );
};

myAsyncHOC(msg => {
    console.log(msg);
});

mySynchronousHOC(msg => {
   console.log(msg);
});

The result of which will be:

'Hello world'
'Goodbye world'

Here we know that myAsyncHOC is asynchronous because it does an I/O operation.


问:
How to update post meta data with multiple values
I have an array I am looping through and each loop I figured it would either update or add to the database so I could have multiple product IDs in the postmeta table but it only adds the last one and overrides all the other values.

Is there a way to loop through and add each one without the previous loops being overridden?  I have tried both update_ and add_ post_meta both with the same result.

```<code>    $number_products = get_price_cart_count();
    $productIDsInCart = get_product_ids();

    $throwback_ids = get_post_meta( '13376', 'product_ids', true );
    $throwbackProducts = explode( ',', $throwback_ids );

    $result = array_intersect($throwbackProducts, $productIDsInCart);

    foreach($result as $res){

            add_post_meta( '683934', 'exclude_product_ids',$res);

    }
</code>```

答:
Hmm this seemed to do the trick.  No looping just imploding the data and pushing them all in at once.</p>

```<code>    $number_products = get_price_cart_count();
    $productIDsInCart = get_product_ids();

    $throwback_ids = get_post_meta( '13376', 'product_ids', true );
    $throwbackProducts = explode( ',', $throwback_ids );

    $result = array_intersect($throwbackProducts, $productIDsInCart);

    $data = implode( ',', $result);

    update_post_meta( '683934', 'exclude_product_ids',$data);
</code>```

Body:
I have an array I am looping through and each loop I figured it would either update or add to the database so I could have multiple product IDs in the postmeta table but it only adds the last one and overrides all the other values.

Is there a way to loop through and add each one without the previous loops being overridden?  I have tried both update_ and add_ post_meta both with the same result.

    $number_products = get_price_cart_count();
    $productIDsInCart = get_product_ids();

    $throwback_ids = get_post_meta( '13376', 'product_ids', true );
    $throwbackProducts = explode( ',', $throwback_ids );

    $result = array_intersect($throwbackProducts, $productIDsInCart);

    foreach($result as $res){

            add_post_meta( '683934', 'exclude_product_ids',$res);

    }

Body:
Hmm this seemed to do the trick.  No looping just imploding the data and pushing them all in at once.

    $number_products = get_price_cart_count();
    $productIDsInCart = get_product_ids();

    $throwback_ids = get_post_meta( '13376', 'product_ids', true );
    $throwbackProducts = explode( ',', $throwback_ids );

    $result = array_intersect($throwbackProducts, $productIDsInCart);

    $data = implode( ',', $result);

    update_post_meta( '683934', 'exclude_product_ids',$data);