问:
Browserslist: caniuse-lite is outdated. Please run next command `npm update caniuse-lite browserslist`
Recently, when I compile my scss files I get an error. The error message says:

Browserslist: caniuse-lite is outdated. Please run next command npm update caniuse-lite browserslist

First, as the message says, I ran npm update caniuse-lite browserslist but it didn't fix the issue.
I deleted the whole node_modules directory and installed again, also I updated the whole folder by npm update but none of them solved the issue.
I also reinstalled autoprefixer and browserslist but none of them solved the issue.

If I remove

```<code>"options": {
      "autoPrefix": "> 1%"
    }
</code>```

from my compilerconfig.json, everything works fine which means probably it is related to autoprefixer. Also, I manually changed the package version to the latest version on package.json and reinstalled but no luck.

答:
I found a short cut rather than going through vs code appData/webCompiler, I added it as a dependency to my project with this cmd npm i caniuse-lite browserslist. But you might install it globally to avoid adding it to each project.

After installation, you could remove it from your project package.json and do npm i.

Update:

In case, Above solution didn't fix it. You could run npm update, as this would upgrade deprecated/outdated packages.

Note:

After you've run the npm update, there may be missing dependencies. Trace the error and install the missing dependencies. Mine was nodemon, which I fix by npm i nodemon -g

Body:
Recently, when I compile my scss files I get an error. The error message says:

Browserslist: caniuse-lite is outdated. Please run next command npm update caniuse-lite browserslist

First, as the message says, I ran npm update caniuse-lite browserslist but it didn't fix the issue.
I deleted the whole node_modules directory and installed again, also I updated the whole folder by npm update but none of them solved the issue.
I also reinstalled autoprefixer and browserslist but none of them solved the issue.

If I remove

"options": {
      "autoPrefix": "> 1%"
    }

from my compilerconfig.json, everything works fine which means probably it is related to autoprefixer. Also, I manually changed the package version to the latest version on package.json and reinstalled but no luck.


来源: stackexchange

问:
Spark efficient groupby operation - repartition?
I'm working in pyspark 2.3 and I'm trying to figure out the most efficient way to get some aggregate statistics from a dataframe.

I have a dataframe with 1.5bn records spread out over a relatively small cluster of 10 nodes. Each has 16gb of ram and 4 cores. My replication factor is set to 2.

My dataframe has maybe 15 columns, which are a mixture of data types, but I'm only interested in two columns - ID and eventDate. The code I'd like to run is pretty simple:

```<code>output = df.groupby(['ID']).agg(F.min('eventDate').alias("firstDate"),F.max('eventDate').alias("lastDate"))
output.write.parquet('hdfs:///somewhere/dateFile.parquet',mode='overwrite')
</code>```

What I'm trying to figure out is the most efficient way to do this operation. ID, which is the field I'm grouping by, has 12m values, and df.rdd.getNumPartitions() is currently 642.

Am I better off first projecting my dataframe down to just the two columns I want? With so many IDs, should I repartition my dataset first? Should I drop duplicates? I could run something like this before my groupby:

```<code>df = df[['ID','eventDate']].drop_duplicates().repartition(x)
</code>```

or

```<code>df = df[['ID','eventDate']].repartition(x)
</code>```

I'm struggling a little bit to figure out what will optimize the run-time. Any guidance on predetermining run-time would be greatly appreciated. I'd prefer not to just "test it out" if possible because I have a couple of these queries to run, and each will take a while.

答:
@flyingmeatball,

Before doing aggregation do the following steps

1 - drop unwanted data (It will eat your resources).

2-  Repartition and cache  the data according to your data (It Will eliminate the execution time)

hint: If data is from Cassandra repartition the data by partition key so that it will avoid data shuffling

Now you are good to go for the aggregation logic ;)

Thanks,

Vimalesh

ContentLicense: CC BY-SA 4.0

Body:
I'm working in pyspark 2.3 and I'm trying to figure out the most efficient way to get some aggregate statistics from a dataframe.

I have a dataframe with 1.5bn records spread out over a relatively small cluster of 10 nodes. Each has 16gb of ram and 4 cores. My replication factor is set to 2.

My dataframe has maybe 15 columns, which are a mixture of data types, but I'm only interested in two columns - ID and eventDate. The code I'd like to run is pretty simple:

output = df.groupby(['ID']).agg(F.min('eventDate').alias("firstDate"),F.max('eventDate').alias("lastDate"))
output.write.parquet('hdfs:///somewhere/dateFile.parquet',mode='overwrite')

What I'm trying to figure out is the most efficient way to do this operation. ID, which is the field I'm grouping by, has 12m values, and df.rdd.getNumPartitions() is currently 642.

Am I better off first projecting my dataframe down to just the two columns I want? With so many IDs, should I repartition my dataset first? Should I drop duplicates? I could run something like this before my groupby:

df = df[['ID','eventDate']].drop_duplicates().repartition(x)

or

df = df[['ID','eventDate']].repartition(x)

I'm struggling a little bit to figure out what will optimize the run-time. Any guidance on predetermining run-time would be greatly appreciated. I'd prefer not to just "test it out" if possible because I have a couple of these queries to run, and each will take a while.


问:
Difference between capturing and passing an argument in lambda functions
I understand the lambda function and the purpose of it in c++ 11. But i do not understand the difference between "Capturing the value" and "Passing an argument".
For Instance..

```<code>#include <iostream>
#include <functional>
using namespace std;

int add(int a,int b){
    return a+b;
}

int main(int argc, char** argv){

    function <int(int,int)> cppstyle;
    cppstyle = add;

    auto l = [] (function <int(int,int)> f,int a, int b) {return f(a,b);};

    cout << l(cppstyle,10,30) <<"\n";
}
</code>```

The output of the code above is same as the code below..

```<code>#include <iostream>
#include <functional>
using namespace std;

int add(int a,int b){
    return a+b;
}

int main(int argc, char** argv){

    function <int(int,int)> cppstyle;
    cppstyle = add;

    auto l = [cppstyle] (int a, int b) {return cppstyle(a,b);};

    cout << l(10,30) <<"\n";
}
</code>```

Is "capturing a value" similar to "passing a value as an argument"? or capture has some special meaning?

答:
The capture of i value is set when the lambda was defined, while when i is passed as argument (j), it is changing in the loop.

```<code>#include <iostream>
using namespace std;

int main(int argc,char **argv)   {
    auto i=5;
    auto f = [=](int j) {cout<<"capture i="<<i<<", passing i as j="<<j<< endl; };
    while (i<30) {
        i += 10;
        f(i);
    }
}
</code>```

--- This will be the output:

lambda capture i=5, passing i as argument j=15

lambda capture i=5, passing i as argument j=25

lambda capture i=5, passing i as argument j=35

Body:
I understand the lambda function and the purpose of it in c++ 11. But i do not understand the difference between "Capturing the value" and "Passing an argument".
For Instance..

#include <iostream>
#include <functional>
using namespace std;

int add(int a,int b){
    return a+b;
}

int main(int argc, char** argv){

    function <int(int,int)> cppstyle;
    cppstyle = add;

    auto l = [] (function <int(int,int)> f,int a, int b) {return f(a,b);};

    cout << l(cppstyle,10,30) <<"\n";
}

The output of the code above is same as the code below..

#include <iostream>
#include <functional>
using namespace std;

int add(int a,int b){
    return a+b;
}

int main(int argc, char** argv){

    function <int(int,int)> cppstyle;
    cppstyle = add;

    auto l = [cppstyle] (int a, int b) {return cppstyle(a,b);};

    cout << l(10,30) <<"\n";
}

Is "capturing a value" similar to "passing a value as an argument"? or capture has some special meaning?

Body:
The capture of i value is set when the lambda was defined, while when i is passed as argument (j), it is changing in the loop.

#include <iostream>
using namespace std;

int main(int argc,char **argv)   {
    auto i=5;
    auto f = [=](int j) {cout<<"capture i="<<i<<", passing i as j="<<j<< endl; };
    while (i<30) {
        i += 10;
        f(i);
    }
}

--- This will be the output:

lambda capture i=5, passing i as argument j=15

lambda capture i=5, passing i as argument j=25

lambda capture i=5, passing i as argument j=35


问:
Find out whether ActionScript Function has varargs / optional arguments using reflection?
Given an ActionScript Function object, is there any way to determine whether that function has one or more optional parameters, or vararg parameters?  The length property seems to return the minimum number of arguments accepted:

```<code>function vararg(a:*, b:*, ...rest):void {}
function optional(a:*, b:* = null, c:* = null):void {}

trace(vararg.length);   // 2
trace(optional.length); // 1
</code>```

I've tried reflecting over the function properties:

```<code>for (var name:String in optional) {
  trace(name + ": " + optional[name];
}
</code>```

However this did not output anything at all.

Does anyone know how to discover this information through reflection?

答: http://bugs.adobe.com/jira/browse/FP-1472 is the bug to add varargs to describeType. It's got a priority of "none", which doesn't give much hope that this will be fixed. Maybe voting it up will help though.</p>

ContentLicense: CC BY-SA 3.0

Body:
Given an ActionScript Function object, is there any way to determine whether that function has one or more optional parameters, or vararg parameters?  The length property seems to return the minimum number of arguments accepted:

function vararg(a:*, b:*, ...rest):void {}
function optional(a:*, b:* = null, c:* = null):void {}

trace(vararg.length);   // 2
trace(optional.length); // 1

I've tried reflecting over the function properties:

for (var name:String in optional) {
  trace(name + ": " + optional[name];
}

However this did not output anything at all.

Does anyone know how to discover this information through reflection?


问:
Inserting multiple buttons onto a page in one line
I'm trying to insert a few buttons onto a page using a Chrome Extension. I don't own the page and can't control the CSS.

I want them all in one line. Right now they are all appearing on their own line and taking up the entire width.

```<code>var inMailButton = $('<button  type="button">Add to Response</button>')
var notInterested = $('<button class="column" type=button>Not Interested</button>')
var noRelo = $('<button class="column" type=button">No Relo</button>')
var interested = $('<button class="column" type=button">Interested</button>')

var responseLocation = $('#mailbox-main')

responseLocation.prepend(notInterested)
responseLocation.prepend(noRelo)
responseLocation.prepend(interested)
responseLocation.prepend(inMailButton)
</code>```

This appears on the page like:

```<code>Add To Response
Not Interested
No Relo
Interested
</code>```

Whereas I want them to be side by side

```<code>Add to Response | Not Interested | No Relo | Interested
</code>```

I was trying to add them to a  first, and then add that to responseLocation but I can't get it working as I wanted.

How would I do this?

答:
Try adding display flex to your responseLocation</p>

```<code>#mailbox-main{
display:flex;
}
</code>```

Body:
I'm trying to insert a few buttons onto a page using a Chrome Extension. I don't own the page and can't control the CSS.

I want them all in one line. Right now they are all appearing on their own line and taking up the entire width.

var inMailButton = $('<button  type="button">Add to Response</button>')
var notInterested = $('<button class="column" type=button>Not Interested</button>')
var noRelo = $('<button class="column" type=button">No Relo</button>')
var interested = $('<button class="column" type=button">Interested</button>')

var responseLocation = $('#mailbox-main')

responseLocation.prepend(notInterested)
responseLocation.prepend(noRelo)
responseLocation.prepend(interested)
responseLocation.prepend(inMailButton)

This appears on the page like:

Add To Response
Not Interested
No Relo
Interested

Whereas I want them to be side by side

Add to Response | Not Interested | No Relo | Interested

I was trying to add them to a  first, and then add that to responseLocation but I can't get it working as I wanted.

How would I do this?

Body:
Try adding display flex to your responseLocation

#mailbox-main{
display:flex;
}


问:
how to get request path with express req object
I'm using express + node.js and I have a req object, the request in the browser is /account but when I log req.path I get '/' --- not '/account'.

```<code>  //auth required or redirect
  app.use('/account', function(req, res, next) {
    console.log(req.path);
    if ( !req.session.user ) {
      res.redirect('/login?ref='+req.path);
    } else {
      next();
    }
  });
</code>```

req.path is / when it should be /account ??

答:
Here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

```<code>app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})
</code>```

Based on: https://expressjs.com/en/api.html#req.originalUrl

Conclusion: As c1moore's answer states, use:

```<code>var fullPath = req.baseUrl + req.path;
</code>```

Body:
I'm using express + node.js and I have a req object, the request in the browser is /account but when I log req.path I get '/' --- not '/account'.

  //auth required or redirect
  app.use('/account', function(req, res, next) {
    console.log(req.path);
    if ( !req.session.user ) {
      res.redirect('/login?ref='+req.path);
    } else {
      next();
    }
  });

req.path is / when it should be /account ??

Body:
Here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

Based on: https://expressjs.com/en/api.html#req.originalUrl

Conclusion: As c1moore's answer states, use:

var fullPath = req.baseUrl + req.path;


问:
Handling JSON Post request in Go - error
My client side javascript posts this JSON to the server side:

```<code>{ username: 'hello', password: 'world' }
</code>```

My Go server side code:

```<code>type AuthJSON struct {
  Username    string `json:"username"`
  Password  string `json:"password"`
}

func AuthenticationHandler(w http.ResponseWriter, r *http.Request) {

   // Parse the incoming user/pass from the request body
   var body AuthJSON
   err := json.NewDecoder(r.Body).Decode(&body)
   log.Println(body)
   log.Println(body.Username)
   if err != nil {
      log.Println(err)
      panic(err)
   }
   ...
}
</code>```

My terminal looks like the following:

```<code>2013/07/31 20:26:53 { }
2013/07/31 20:26:53
2013/07/31 20:26:53 invalid character 'u' looking for beginning of value
2013/07/31 20:26:53 http: panic serving [::1]:58141: invalid character 'u' looking for beginning of value
goroutine 9 [running]:
net/http.func·007()
...
</code>```

Obviously there is something wrong with the parsing of my JSON and I'm getting an error and panic(err) is being called.

The invalid character 'u' is coming from the username part in my JSON.

I've tested the client side with a Node server and it works great.
Very new to Go. Any help would be great.

Edited:

I added,

```<code>log.Println(r)
</code>```

And I am getting this additional information:

```<code>2013/07/31 20:59:47 &{POST /api/auth.json HTTP/1.1 1 1 map[Accept-Encoding:[gzip, deflate] Content-Type:[application/x-www-form-urlencoded; charset=UTF-8] X-Requested-With:[XMLHttpRequest] Content-Length:[30] Connection:[keep-alive] Pragma:[no-cache] Cache-Control:[no-cache] User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:22.0) Gecko/20100101 Firefox/22.0] Accept:[*/*] Accept-Language:[en-US,en;q=0.5] Referer:[http://localhost:8080/]] 0x114adee0 30 [] false localhost:8080 map[] map[] <nil> map[] [::1]:58372 /api/auth.json <nil>}
</code>```

Here is b, _ := ioutil.ReadAll(r.Body);
    log.Println(b)

```<code>2013/08/01 07:48:40 [117 115 101 114 110 97 109 101 61 104 101 108 108 111 38 112 97 115 115 119 111 114 100 61 119 111 114 108 100]
</code>```

Full client side:

```<code><script type="text/x-handlebars" data-template-name="login">
 {{#if loggedIn}}
  <p>You are already logged in!</p>
  {{else}}
  <form class="form-inline" {{action login on="submit"}}>
    <h2>Log In</h2>
    {{input value=username type="text" placeholder="Username"}}
    {{input value=password type="password" placeholder="Password"}}
    {{input class="btn" type="submit" value="Log In"}}
  </form>
  {{#if errorMessage}}
    <div class="alert alert-error">{{errorMessage}}</div>
  {{/if}}
 {{/if}}
</script>

App.LoginController = Ember.Controller.extend({
  login: function() {

      var self = this, data = this.getProperties('username', 'password');

      // Clear out any error messages.
      this.set('errorMessage', null);

      $.post('/api/auth.json', data).then(function(response){

          // Check the response for the token
          self.set('errorMessage', response.message);
          if(response.success){
              self.set('token', response.token);
          }
      });
  }
});
</code>```

答: I faced the same issue when tried to make requests via POSTMAN. Change the body data type to raw and add data in json format, then it will work correctly also the headers must be application/json

Body:
My client side javascript posts this JSON to the server side:

{ username: 'hello', password: 'world' }

My Go server side code:

type AuthJSON struct {
  Username    string `json:"username"`
  Password  string `json:"password"`
}

func AuthenticationHandler(w http.ResponseWriter, r *http.Request) {

   // Parse the incoming user/pass from the request body
   var body AuthJSON
   err := json.NewDecoder(r.Body).Decode(&body)
   log.Println(body)
   log.Println(body.Username)
   if err != nil {
      log.Println(err)
      panic(err)
   }
   ...
}

My terminal looks like the following:

2013/07/31 20:26:53 { }
2013/07/31 20:26:53
2013/07/31 20:26:53 invalid character 'u' looking for beginning of value
2013/07/31 20:26:53 http: panic serving [::1]:58141: invalid character 'u' looking for beginning of value
goroutine 9 [running]:
net/http.func·007()
...

Obviously there is something wrong with the parsing of my JSON and I'm getting an error and panic(err) is being called.

The invalid character 'u' is coming from the username part in my JSON.

I've tested the client side with a Node server and it works great.
Very new to Go. Any help would be great.

Edited:

I added,

log.Println(r)

And I am getting this additional information:

2013/07/31 20:59:47 &{POST /api/auth.json HTTP/1.1 1 1 map[Accept-Encoding:[gzip, deflate] Content-Type:[application/x-www-form-urlencoded; charset=UTF-8] X-Requested-With:[XMLHttpRequest] Content-Length:[30] Connection:[keep-alive] Pragma:[no-cache] Cache-Control:[no-cache] User-Agent:[Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:22.0) Gecko/20100101 Firefox/22.0] Accept:[*/*] Accept-Language:[en-US,en;q=0.5] Referer:[http://localhost:8080/]] 0x114adee0 30 [] false localhost:8080 map[] map[] <nil> map[] [::1]:58372 /api/auth.json <nil>}

Here is b, _ := ioutil.ReadAll(r.Body);
    log.Println(b)

2013/08/01 07:48:40 [117 115 101 114 110 97 109 101 61 104 101 108 108 111 38 112 97 115 115 119 111 114 100 61 119 111 114 108 100]

Full client side:

App.LoginController = Ember.Controller.extend({
  login: function() {

      var self = this, data = this.getProperties('username', 'password');

      // Clear out any error messages.
      this.set('errorMessage', null);

      $.post('/api/auth.json', data).then(function(response){

          // Check the response for the token
          self.set('errorMessage', response.message);
          if(response.success){
              self.set('token', response.token);
          }
      });
  }
});


问:
How to communicate between child control and parent window with big hierarchy in wpf?
There is big hierarchy of controls: window , inside window there is control, inside one more...
All of them have view models. Before creating parent window , i generate some Field and pass as parameter of the window.
I need to display the field on child control, how i can pass this field from parent's window view model to child control's  view model not using the chain of properties/events/delegate commands  and using mvvm ?
What about ways to communicate between parent window and child control if there are many layers between?</p>

答: The number of layers in between should be irrelevant if you follow the MVVM pattern. If for example all can happen in a single view model then there should be no issue. If however you have a separate view models as context for the window and a specific control, then it would be a good idea that the relationship gets reflected on the view model side, having the top view model contain the bottom one for example.


问:
How can I run these macros together across every worksheet in the workbook?
I have made an excel book, where a data set is pasted into one tab, and macros are run to filter out the information into seperate worksheets, ready to batch PDF. Currently I have a button on each sheet to 'Update Table' and have to go through each sheet to click this button. I want this as one button on the first sheet. I also have a button to set the print area on all sheets - this one loops and works fine. I'd like to merge the codes, so one button will go through each sheet to update the tables, and then set the print area.

I have tried merging these codes together with no luck so far despite hours of googling, so thought I'd try here. I'm very new to VBA (just been teaching myself for a few weeks).

```<code>    Sub Auto_Table_Update()

        Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
            CriteriaRange:=Range("C2:C3"), CopyToRange:=Range("A5:K9999"), Unique:= _
            False
    '*Advance Filter Macro to update the table in the worksheet*

        Range("C4").Select
        ActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,3)"
        Range("C5").Select
    '*Sets the worksheet name as the first 3 letters in cell C4*

    End Sub

    Sub Workbook_Print_Area()
    Dim ws      As Worksheet

    Dim LR      As Long, _
        LC      As Long

    For Each ws In ActiveWorkbook.Worksheets
        With ws
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
            End With
    ' *sets the print area on every sheet*
    Next ws
    End Sub
</code>```

Like I said, I just want one button to run the above codes on every sheet. Or at least the 'Auto_Update_Table' to be run on every sheet rather than having a button to run it on each sheet like I currently do.

I appreciate some of it will be badly coded.. Any explanations of the changes would be much appreciated too. I appreciate your patience.. I am trying to get my head around all this :)

UPDATE

I have tried doing this:

```<code>    Sub One_Button()
    Dim ws      As Worksheet

    Dim LR      As Long, _
        LC      As Long

    For Each ws In ActiveWorkbook.Worksheets

        With ws
            Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
                CriteriaRange:=Range("C2:C3"), CopyToRange:=Range("A5:K9999"), Unique:= _
                False

            Range("C4").Select
            ActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,3)"
            Range("C5").Select
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
            End With
    Next ws
    End Sub
</code>```

This gives me the error 'The extract range has a missing or invalid field name.' Is this because it is trying to run on the first worksheet (with the main data set)? If so, how do I tell it to ignore the main data set sheet?
Thanks in advance :)

答:
Can you try this? You need to make sure your criteria range includes the correct headers and doesn't have any spaces.</p>

```<code>Sub One_Button()

Dim ws      As Worksheet
Dim LR      As Long, _
    LC      As Long

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "All Data" Then
        With ws
            Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
                     CriteriaRange:=ws.Range("C2:C3"), CopyToRange:=ws.Range("A5"), Unique:=False
            ws.Range("C4").FormulaR1C1 = "=LEFT(R[-1]C,3)"
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
        End With
    End If
Next ws

End Sub
</code>```

Body:
I have made an excel book, where a data set is pasted into one tab, and macros are run to filter out the information into seperate worksheets, ready to batch PDF. Currently I have a button on each sheet to 'Update Table' and have to go through each sheet to click this button. I want this as one button on the first sheet. I also have a button to set the print area on all sheets - this one loops and works fine. I'd like to merge the codes, so one button will go through each sheet to update the tables, and then set the print area.

I have tried merging these codes together with no luck so far despite hours of googling, so thought I'd try here. I'm very new to VBA (just been teaching myself for a few weeks).

    Sub Auto_Table_Update()

        Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
            CriteriaRange:=Range("C2:C3"), CopyToRange:=Range("A5:K9999"), Unique:= _
            False
    '*Advance Filter Macro to update the table in the worksheet*

        Range("C4").Select
        ActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,3)"
        Range("C5").Select
    '*Sets the worksheet name as the first 3 letters in cell C4*

    End Sub

    Sub Workbook_Print_Area()
    Dim ws      As Worksheet

    Dim LR      As Long, _
        LC      As Long

    For Each ws In ActiveWorkbook.Worksheets
        With ws
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
            End With
    ' *sets the print area on every sheet*
    Next ws
    End Sub

Like I said, I just want one button to run the above codes on every sheet. Or at least the 'Auto_Update_Table' to be run on every sheet rather than having a button to run it on each sheet like I currently do.

I appreciate some of it will be badly coded.. Any explanations of the changes would be much appreciated too. I appreciate your patience.. I am trying to get my head around all this :)

UPDATE

I have tried doing this:

    Sub One_Button()
    Dim ws      As Worksheet

    Dim LR      As Long, _
        LC      As Long

    For Each ws In ActiveWorkbook.Worksheets

        With ws
            Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
                CriteriaRange:=Range("C2:C3"), CopyToRange:=Range("A5:K9999"), Unique:= _
                False

            Range("C4").Select
            ActiveCell.FormulaR1C1 = "=LEFT(R[-1]C,3)"
            Range("C5").Select
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
            End With
    Next ws
    End Sub

This gives me the error 'The extract range has a missing or invalid field name.' Is this because it is trying to run on the first worksheet (with the main data set)? If so, how do I tell it to ignore the main data set sheet?
Thanks in advance :)

Body:
Can you try this? You need to make sure your criteria range includes the correct headers and doesn't have any spaces.

Sub One_Button()

Dim ws      As Worksheet
Dim LR      As Long, _
    LC      As Long

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "All Data" Then
        With ws
            Sheets("All Data").Range("A50:K9999").AdvancedFilter Action:=xlFilterCopy, _
                     CriteriaRange:=ws.Range("C2:C3"), CopyToRange:=ws.Range("A5"), Unique:=False
            ws.Range("C4").FormulaR1C1 = "=LEFT(R[-1]C,3)"
            LR = .Range("A" & Rows.Count).End(xlUp).Row
            LC = .Cells(1, Columns.Count).End(xlToLeft).Column
            .PageSetup.PrintArea = .Range(.Cells(1, 1), .Cells(LR, LC)).Address
        End With
    End If
Next ws

End Sub


问:
Why am I being displayed "TypeError: a float is required"?
My main issue is this error being displayed:

```<code>TypeError: a float is required
</code>```

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

```<code>from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)
</code>```

I want to be able to type in a number and it display the square root of it.

答:
This worked for me, had to fix syntax based on my version of python- </p>

```<code>from math import sqrt

n = input('Type number here: ')

n = float(n)

def square_root(n):

   #"""Returns the square root of a number."""

   square_rooted = sqrt(n)

   print("%d square rooted is %d." % (n, square_rooted))
   return square_rooted

square_root(n)
</code>```

Body:
My main issue is this error being displayed:

TypeError: a float is required

I haven't tried much as I don't really know what I'm doing, being very new to coding and all, so I would appreciate some patient advice on the matter.

from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

I want to be able to type in a number and it display the square root of it.

Body:
This worked for me, had to fix syntax based on my version of python-

from math import sqrt

n = input('Type number here: ')

n = float(n)

def square_root(n):

   #"""Returns the square root of a number."""

   square_rooted = sqrt(n)

   print("%d square rooted is %d." % (n, square_rooted))
   return square_rooted

square_root(n)


问:
How can I reduce the size of a 1GB MSI file using Orca?
I have written a C# WPF application. I have now created an MSI that will install the application. However, the file size is gigantic. The application contains many video and image files, which have combined to make the MSI a whopping 1GB in size.

I have tried to reduce the file size with Orca. I have used "Save As" to create a brand new MSI and have also exported the database tables and then imported them to another MSI. In both cases, the file size is reduced to less than 1MB, but then the installer doesn't work at all. Looks like it's not compressing the content, but rather removing it entirely.

How can I use Orca to reduce the MSI file size without stopping the installation from actually working? If there's another way to do it, I'm open to any suggestions.

答:
Online: Can you put some videos online? Youtube? Easier to manage and update over time as well. And easier access for people who do not have your product downloaded? Better for marketing? It depends if the content is help material or the actual product you are trying to sell. You can install low-res versions of the videos and images as a fallback mechanism if Internet is not available? Maybe see this older answer?

Compression: You are using WiX? No? On selecting an MSI tool. If you are using WiX, then you can try to use the highest compression level for the MSI? (MSI compression levels). This means you have to rebuild it with the new setting. There are alternative elements to do so:

Media Element (CompressionLevel)

MediaTemplate Element (CompressionLevel)

WiX: In WiX it is easy to set the compression level:

```<code><MediaTemplate EmbedCab="yes" CompressionLevel="high" />
</code>```

A little crash course in minimal WiX markup to compile an MSI can be found here: Transparent aluminum! The markup towards the bottom with inline comments is usually enough for people to get going. See other resources here: installdude.com (my own experimental site - expand help section in left navigation pane). Also check "WiX Samples" in quick search section towards top.

I forgot the WiX quick-start tips answer.

Links:

What is the compression method used by MSI files?

How to generate msi/exe installer file in visual studio 2017 for a project of over 24 GB files?

Body:
Online: Can you put some videos online? Youtube? Easier to manage and update over time as well. And easier access for people who do not have your product downloaded? Better for marketing? It depends if the content is help material or the actual product you are trying to sell. You can install low-res versions of the videos and images as a fallback mechanism if Internet is not available? Maybe see this older answer?

Compression: You are using WiX? No? On selecting an MSI tool. If you are using WiX, then you can try to use the highest compression level for the MSI? (MSI compression levels). This means you have to rebuild it with the new setting. There are alternative elements to do so:

Media Element (CompressionLevel)

MediaTemplate Element (CompressionLevel)

WiX: In WiX it is easy to set the compression level:

<MediaTemplate EmbedCab="yes" CompressionLevel="high" />

A little crash course in minimal WiX markup to compile an MSI can be found here: Transparent aluminum! The markup towards the bottom with inline comments is usually enough for people to get going. See other resources here: installdude.com (my own experimental site - expand help section in left navigation pane). Also check "WiX Samples" in quick search section towards top.

I forgot the WiX quick-start tips answer.

Links:

What is the compression method used by MSI files?

How to generate msi/exe installer file in visual studio 2017 for a project of over 24 GB files?


问:
How to extract numbers from a string and dumping them as a comma separated values?
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

```<code>MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut
</code>```

shows me the following

```<code>output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

my expected results would be a string variable

```<code>123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96
</code>```

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

```<code>numbers=$(echo $MyOut | grep -o -E '[0-9]+')
</code>```

gives me

```<code>192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96
</code>```

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

```<code>#!/bin/bash

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

</code>```

Thanks
Ash

Body:
I have a test_file in bash which outputs following on screen . I have no control on the upstream code to print them in a certain way. So, I need to do parse some values from the screen output.
Here is what I'm doing:

MyOut=$(./my_test_file.sh)    # this is my example script which echo's the
                                 #output
echo $MyOut

shows me the following

output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

my expected results would be a string variable

123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96

comma-separated 16 values getting stored in some variable which I can dump in a text file for further processing.

I tried playing with regular expressions and would like to only extract last 16 numbers in the following output

I did this

numbers=$(echo $MyOut | grep -o -E '[0-9]+')

gives me

192 168 0 12 0 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96

I need to extract the last 16 numbers. Since it is not a array format , Can I add something in regular expression which only spits out only last 16 numbers delimited by commma ???

btw If you need to look into my_test_file.sh , its just echoing the statements

#!/bin/bash

echo "output for different segments "
echo "IP address: 192.168.0.12 Segment :0xfff"
echo "Segment Data:"
echo "123"
echo "23"
echo "42"
echo "23"
echo "4"
echo "444"
echo "1121"
echo "8676"
echo "34"
echo "530"
echo "323"
echo "564"
echo "523"
echo "7878"
echo "7328"
echo "96"

Thanks
Ash

Body:
Other way:

echo "output for different segments IP address: 192.168.0.12 Segment :0xfff Segment Data: 123 23 42 23 4 444 1121 8676 34 530 323 564 523 7878 7328 96" | awk -F'Segment Data: ' '{print $2}' | sed 's/ /,/g'

gives you:

123,23,42,23,4,444,1121,8676,34,530,323,564,523,7878,7328,96


问:
Joining two DataFrames in Spark SQL and selecting columns of only one
I have two DataFrames in Spark SQL (D1 and D2).

I am trying  to inner join both of them D1.join(D2, "some column")
and get back data of only D1, not the complete data set.

Both D1 and D2 are having the same columns.

Could some one please help me on this?

I am using Spark 1.6.

答:
You could use left_semi:

```<code>d1.as("d1").join(d2.as("d2"), $"d1.id" === $"d2.id", "left_semi")
</code>```

Semi-join takes only rows from the left dataset where joining condition is met.

There's also another interesting join type: left_anti, which works similarily to left_semi but takes only those rows where the condition is not met.

Body:
You could use left_semi:

d1.as("d1").join(d2.as("d2"), $"d1.id" === $"d2.id", "left_semi")

Semi-join takes only rows from the left dataset where joining condition is met.

There's also another interesting join type: left_anti, which works similarily to left_semi but takes only those rows where the condition is not met.


问:
Exception on streaming the audio on android media player, on okhttp buffering
```<code>E/JavaBinder: *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.ArrayIndexOutOfBoundsException: length=8192; index=8192
     at com.android.okhttp.okio.Buffer.writeByte(Buffer.java:973)
     at com.android.okhttp.internal.Platform.concatLengthPrefixed(Platform.java:212)
     at com.android.okhttp.internal.Platform.configureTlsExtensions(Platform.java:116)
     at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:187)
     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:26)
     at android.media.MediaHTTPConnection.seekTo(MediaHTTPConnection.java:212)
     at android.media.MediaHTTPConnection.getSize(MediaHTTPConnection.java:374)
     at android.media.IMediaHTTPConnection$Stub.onTransact(IMediaHTTPConnection.java:81)
     at android.os.Binder.execTransact(Binder.java:731)
</code>```

This exception occurs on android media player streaming and buffering, the player got stuck on the same position for unusual period of time and sometimes forever.

答:
I don't think there's much you can do. It's been reported to the okhttp devs. But, as they point out, the error is with the internally packaged version of okhttp that is included with android. There's no bug with square's externally developed version, so they have rightfully closed the issue as a non-issue.

The bug has been reported to google, but it doesn't look like any action has been taken in the last almost 2 years.

Perhaps you could include the newer, upstream version of okhttp from square in your project and somehow tell MediaHTTPConnection to use the okhttp3 implementation of HttpURLConnection. There's the OkUrlFactory that could be used with java's URL.setURLStreamHandlerFactory. However that's deprecated and it might not be a good idea to override the built-in url stream handler logic.

In fact, it's been removed from recent versions of okhttp. The dev who removed it did make an ObsoleteUrlFactory.java that you can copy/paste yourself into your project and use as:

```<code>OkHttpClient okHttpClient = new OkHttpClient();
URL.setURLStreamHandlerFactory(new ObsoleteUrlFactory(okHttpClient));
</code>```

Body:
E/JavaBinder: *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.ArrayIndexOutOfBoundsException: length=8192; index=8192
     at com.android.okhttp.okio.Buffer.writeByte(Buffer.java:973)
     at com.android.okhttp.internal.Platform.concatLengthPrefixed(Platform.java:212)
     at com.android.okhttp.internal.Platform.configureTlsExtensions(Platform.java:116)
     at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:187)
     at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:149)
     at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:26)
     at android.media.MediaHTTPConnection.seekTo(MediaHTTPConnection.java:212)
     at android.media.MediaHTTPConnection.getSize(MediaHTTPConnection.java:374)
     at android.media.IMediaHTTPConnection$Stub.onTransact(IMediaHTTPConnection.java:81)
     at android.os.Binder.execTransact(Binder.java:731)

This exception occurs on android media player streaming and buffering, the player got stuck on the same position for unusual period of time and sometimes forever.

Body:
I don't think there's much you can do. It's been reported to the okhttp devs. But, as they point out, the error is with the internally packaged version of okhttp that is included with android. There's no bug with square's externally developed version, so they have rightfully closed the issue as a non-issue.

The bug has been reported to google, but it doesn't look like any action has been taken in the last almost 2 years.

Perhaps you could include the newer, upstream version of okhttp from square in your project and somehow tell MediaHTTPConnection to use the okhttp3 implementation of HttpURLConnection. There's the OkUrlFactory that could be used with java's URL.setURLStreamHandlerFactory. However that's deprecated and it might not be a good idea to override the built-in url stream handler logic.

In fact, it's been removed from recent versions of okhttp. The dev who removed it did make an ObsoleteUrlFactory.java that you can copy/paste yourself into your project and use as:

OkHttpClient okHttpClient = new OkHttpClient();
URL.setURLStreamHandlerFactory(new ObsoleteUrlFactory(okHttpClient));


问:
How can I change color of items on Toolbar
I have a Toolbar, I want to change background to Black but by default items color is black and I want to change their color to gray, how can I do that ? Thanks you so much:
My Image about Toolbar

And this is my toolbar.xml

```<code><android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2196F3"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
</code>```

My styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

答:
Change the tint attribute of the icon.

Via xml:

```<code><item android:id="@+id/slash_toolbar"
android:title=""
android:icon="@drawable/ic_voice"
app:showAsAction="always"
android:tint="@android:color/white"/>
</code>```

Via code:

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    for(int i = 0; i < menu.size(); i++){
        Drawable drawable = menu.getItem(i).getIcon();
        if(drawable != null) {
            drawable.mutate();
            drawable.setColorFilter(getResources().getColor(R.color.textColorPrimary), PorterDuff.Mode.SRC_ATOP);
        }
    }

    return true;
}
</code>```

To change the three dots color put it in your style.xml in AppTheme:

```<code><!-- android:textColorSecondary is the color of the menu overflow icon (three vertical dots) -->
<item name="android:textColorSecondary">@color/white</item>
</code>```

Body:
I have a Toolbar, I want to change background to Black but by default items color is black and I want to change their color to gray, how can I do that ? Thanks you so much:
My Image about Toolbar

And this is my toolbar.xml

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2196F3"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

My styles.xml

Body:
Change the tint attribute of the icon.

Via xml:

<item android:id="@+id/slash_toolbar"
android:title=""
android:icon="@drawable/ic_voice"
app:showAsAction="always"
android:tint="@android:color/white"/>

Via code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    for(int i = 0; i < menu.size(); i++){
        Drawable drawable = menu.getItem(i).getIcon();
        if(drawable != null) {
            drawable.mutate();
            drawable.setColorFilter(getResources().getColor(R.color.textColorPrimary), PorterDuff.Mode.SRC_ATOP);
        }
    }

    return true;
}

To change the three dots color put it in your style.xml in AppTheme:

<!-- android:textColorSecondary is the color of the menu overflow icon (three vertical dots) -->
<item name="android:textColorSecondary">@color/white</item>


问:
Converting List<string> to byte[]
How can I take a List and turn it into a byte array.

I thought there might be some clever LINQ options for it but am unsure eg/List.ForEach

答:
with a simple foreach loop:

(pseudocode)

```<code>    List<byte[]> bytes = new List<byte[]>();
    ForEach string el in somelist
        {
           byte[] arr;
           System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
           arr = encoding.GetBytes(el);
           bytes.add(arr);
        }
</code>```

Title: Converting List<string> to byte[]

Body:
with a simple foreach loop:

(pseudocode)

    List<byte[]> bytes = new List<byte[]>();
    ForEach string el in somelist
        {
           byte[] arr;
           System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
           arr = encoding.GetBytes(el);
           bytes.add(arr);
        }


问:
IOS: Difference between proposedCredentials and URLCredential for trust
In URLSession:task:didReceiveChallenge:completionHandler:, is there a difference between using .proposedCredential vs URLCredential(trust:) of the server trust object in the challenge protection space?

This is to pass back as the second parameter in the completion handler of the delegate method, along with .useCredentials.

答:
Answer received here: https://forums.developer.apple.com/message/361609

Realistically there’s no difference here.  For server trust authentication challenges, the system does not actually look at the trust object embedded in the credential you pass to the completion handler; all that matters is that you pass in something.

Having said that, I recommend that you stick on the well-trodden path and construct a new credential.  I’m actually quite surprised that proposedCredential is even populated in this case.


问:
why "ordering": false not working in another table
I have 3 data tables. I'd like to remove the order and show the data table style. I'm currently using "ordering": "false" this worked for 2 of the data tables, but one is still ordered.

Here is my code:

```<code> $(document).ready(function() {
            $('#example').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"
            });
            $('#example1').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"

            });
            $('#example2').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"

            });
</code>```

答:
I think it should be boolean value in ordering.

```<code>$('#example').dataTable({
  "ordering": false // boolean type value
});
</code>```

for more visit here.

Body:
I have 3 data tables. I'd like to remove the order and show the data table style. I'm currently using "ordering": "false" this worked for 2 of the data tables, but one is still ordered.

Here is my code:

 $(document).ready(function() {
            $('#example').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"
            });
            $('#example1').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"

            });
            $('#example2').DataTable( {
                "pagingType": "full_numbers",
                "ordering": "false"

            });

Body:
I think it should be boolean value in ordering.

$('#example').dataTable({
  "ordering": false // boolean type value
});

for more visit here.


问:
Are non-generic collections in .NET obsolete?
Put differently:

Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?

As far as I understand, generic collections not only are type-safe, but their performance is better.

Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.

答:
There might be instances where you need to store objects of unknown types, or objects of multiple different types, but if you do indeed know the type of the objects that you want to store then I cannot see a reason not to use the generic version.

Edit: As commented you can just use List<Object> - doh!

OwnerDisplayName: guillermooo

LastEditorDisplayName: guillermooo

OwnerDisplayName: samjudson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: samjudson


问:
c++ vectors and pointers
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}
</code>```

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

答:
Have a look at your initialization:

```<code>string test = "my-name";
vector<string*> names(20);
names.push_back(&test);
</code>```

You first create a std::vector with 20 elements.

Then you use push_back to append a 21st element, which points to a valid string. That's fine, but this element is never reached in the loop: the first iteration crashes already since the first 20 pointers stored in the vector don't point to valid strings.

Dereferencing an invalid pointer causes a crash. If you make sure that you have a valid pointers in your vector, **iterator is just fine to access an element.

Title: c++ vectors and pointers

Body:
As i understand if i dont store pointers, everything in c++ gets copied, which can lead to bad performance (ignore the simplicity of my example). So i thought i store my objects as pointers instead of string object inside my vector, thats better for performance right? (assumining i have very long strings and lots of them).

The problem when i try to iterate over my vector of string pointers is i cant extract the actual value from them

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

vector<string*>::iterator iterator = names.begin();
while (iterator != names.end())
{
    std::cout << (*iterator) << ":" << std::endl;
    // std::cout << *(*iterator); // fails

    iterator++;
}

See the commented line, i have no problem in receiving the string pointer. But when i try to get the string pointers value i get an error (i couldnt find what excatly the error is but the program just fails).

I also tried storing (iterator) in a new string variable and but it didnt help?

Body:
Have a look at your initialization:

string test = "my-name";
vector<string*> names(20);
names.push_back(&test);

You first create a std::vector with 20 elements.

Then you use push_back to append a 21st element, which points to a valid string. That's fine, but this element is never reached in the loop: the first iteration crashes already since the first 20 pointers stored in the vector don't point to valid strings.

Dereferencing an invalid pointer causes a crash. If you make sure that you have a valid pointers in your vector, **iterator is just fine to access an element.


问:
PostMessage between Iframe hierarchy
I'm trying to communicate between grandfather and grandson iframes.

In case of one level (parent - child), I can send:

Child => parent:

window.parent.postMessage("message", "*");

Parent => child:

iframe.contentWindow.postMessage(message, "*");

The problem is how to handle communication when the relations are grandfather and grandson.
I tried with window.parent.parent but it does not work.

I thought maybe to write some proxy code that will be added in the middle iframe and will pass the messages, but maybe there is another better solution for this?

答:
I ended up adding some proxy script.

And also added to each message "sender" key

```<code><script>

    var father = 'aaa';
    var child = 'bbb';
    var proxyIframe;

    document.addEventListener('DOMContentLoaded', function(event) {
        proxyIframe = document.getElementById('proxyIframe');
    });

    window.addEventListener("message", function(e) {
        if (e.data) {
            if (e.data.sender === father) {
                proxyIframe.contentWindow && proxyIframe.contentWindow.postMessage(e.data, "*");
            } else if (e.data.sender === child) {
                window.parent.postMessage(e.data, "*");
            }
        }
    }, false);

</script>

</code>```

Hope it can help anyone

Title: PostMessage between Iframe hierarchy

Body:
I ended up adding some proxy script.

And also added to each message "sender" key

<script>

    var father = 'aaa';
    var child = 'bbb';
    var proxyIframe;

    document.addEventListener('DOMContentLoaded', function(event) {
        proxyIframe = document.getElementById('proxyIframe');
    });

    window.addEventListener("message", function(e) {
        if (e.data) {
            if (e.data.sender === father) {
                proxyIframe.contentWindow && proxyIframe.contentWindow.postMessage(e.data, "*");
            } else if (e.data.sender === child) {
                window.parent.postMessage(e.data, "*");
            }
        }
    }, false);

</script>

Hope it can help anyone


问:
CMD batch file to delete a file if not found in list from text txt file
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

```<code>C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png
</code>```

and the in the same folder have this files:

```<code>Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt
</code>```

So i need to delete the next files because not exist in list.txt

```<code>Carlos.jpg
Sapo.png
</code>```

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

```<code>@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"
</code>```

any one can help me with this.

Thanks

答:
On cmd line this should do

```<code>for /f "delims=" %A in ('Dir /B /A-D ^|find /v /i "list.txt"') Do @findstr /IL "%~nxA" list.txt >Nul ||(echo del %A)
</code>```

I'd include the /E switch with findstr if the last line in list.txt has a trailing cr/lf,

otherwise the last entry wouldn't match reference.

If the output looks OK, remove the echo in front of del.

As a batch file:

```<code>@Echo off
set "folder=C:\S-ATLANTICO-1\MEDIA"
PushD "%folder%"
set "excludeFile=list.txt"
for /f "delims=" %%A in ('
    Dir /B /A-D ^|find /v /i "%excludefile%"'
) Do findstr /IL "%~nxA" "%excludefile%" >Nul ||(
    echo del %%A
)
Popd
</code>```

Body:
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png

and the in the same folder have this files:

Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt

So i need to delete the next files because not exist in list.txt

Carlos.jpg
Sapo.png

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"

any one can help me with this.

Thanks

Body:
On cmd line this should do

for /f "delims=" %A in ('Dir /B /A-D ^|find /v /i "list.txt"') Do @findstr /IL "%~nxA" list.txt >Nul ||(echo del %A)

I'd include the /E switch with findstr if the last line in list.txt has a trailing cr/lf,

otherwise the last entry wouldn't match reference.

If the output looks OK, remove the echo in front of del.

As a batch file:

@Echo off
set "folder=C:\S-ATLANTICO-1\MEDIA"
PushD "%folder%"
set "excludeFile=list.txt"
for /f "delims=" %%A in ('
    Dir /B /A-D ^|find /v /i "%excludefile%"'
) Do findstr /IL "%~nxA" "%excludefile%" >Nul ||(
    echo del %%A
)
Popd


问:
Rails ArgumentError on Job - wrong number of arguments - how to debug?
I’m trying to create a Job within my specs with the following, but keep getting an ArgumentError:-

MyJob.new.perform_now(user_id: @current_user.id, building_ids: [building.id])

```<code>module ActionPlan
class MyJob < ApplicationJob
queue_as :low

def perform(user_id:, building_ids:, **_args)
  @user = User.find(user_id)
  @buildings = ActionPlan::Reminder.where(user_id: user_id)
  @buildings.map(&method(:create_alerts))
end
</code>```

I keep getting wrong number of arguments (given 1, expected 0) (ArgumentError).  Where am I going wrong?  The perform method takes 2 arguments, right?  How would I debug this?

答:
Try this:

```<code>module ActionPlan
  class MyJob < ApplicationJob
    queue_as :low

    def initialize(user_id:, building_ids:, **_args)
      @buildings = ActionPlan::Reminder.where(user_id: user_id)
    end

    def perform
      buildings.map(&method(:create_alerts))
    end

    private

    attr_accessor :buildings
  end
end
</code>```

That should allow you to call:

MyJob.new(user_id: @current_user.id, building_ids: [building.id]).perform

Body:
I’m trying to create a Job within my specs with the following, but keep getting an ArgumentError:-

MyJob.new.perform_now(user_id: @current_user.id, building_ids: [building.id])

module ActionPlan
class MyJob < ApplicationJob
queue_as :low

def perform(user_id:, building_ids:, **_args)
  @user = User.find(user_id)
  @buildings = ActionPlan::Reminder.where(user_id: user_id)
  @buildings.map(&method(:create_alerts))
end

I keep getting wrong number of arguments (given 1, expected 0) (ArgumentError).  Where am I going wrong?  The perform method takes 2 arguments, right?  How would I debug this?

Body:
Try this:

module ActionPlan
  class MyJob < ApplicationJob
    queue_as :low

    def initialize(user_id:, building_ids:, **_args)
      @buildings = ActionPlan::Reminder.where(user_id: user_id)
    end

    def perform
      buildings.map(&method(:create_alerts))
    end

    private

    attr_accessor :buildings
  end
end

That should allow you to call:

MyJob.new(user_id: @current_user.id, building_ids: [building.id]).perform


问:
Difference between (eval '(+ 1 2)) and (eval (+ 1 2))?
In clisp, what is the difference?

```<code>(eval '(+ 1 2))

(eval (+ 1 2))
</code>```

答:
It seems
(eval (+ 1 2)) will first compute (+ 1 2), then use (eval 3)

(eval '(+ 1 2)) will transfer expression (+ 1 2) to eval, and let eval to interpret it.

OwnerDisplayName: KayKay

Body:
In clisp, what is the difference?

(eval '(+ 1 2))

(eval (+ 1 2))


问:
Adding hover effect when hovering on something else
I have a nav-bar with an  and inside the  I have I want to make the icon translate when I hover on the a text. Here is the code.

          Go back

```

<p>So far I tried this: </p>

<pre class="lang-css prettyprint-override"><code>.button:hover ~ i {
    transform: translateX(-3px);
}
</code>```

答:
The link is child of the .button div and the i is a child of that so:

```<code>.button:hover a i {
transform: translateX(-3px);
}
</code>```

.button:hover a i {
  transform: translateX(-10px);
  /* wildly exaggerated */
  display: inline-block;
  /* required to transform inline elements */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css" rel="stylesheet" />
<div class="nav-bar">
  <div class="button">
     <i class="fas fa-sign-out-alt icon"></i> Go back
  </div>
</div></code>```

Body:
I have a nav-bar with an  and inside the  I have I want to make the icon translate when I hover on the a text. Here is the code.

          Go back

So far I tried this:

.button:hover ~ i {
    transform: translateX(-3px);
}

Body:
The link is child of the .button div and the i is a child of that so:

.button:hover a i {
transform: translateX(-3px);
}

.button:hover a i {
  transform: translateX(-10px);
  /* wildly exaggerated */
  display: inline-block;
  /* required to transform inline elements */
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css" rel="stylesheet" />
<div class="nav-bar">
  <div class="button">
    <a href="index.html"> <i class="fas fa-sign-out-alt icon"></i> Go back</a>
  </div>
</div>


问:
Parse responseJSON to ObjectMapper
I'm currently making a migration from Android to iOS, better said Java to Swift, I got a generic response in JSON, but I'm not able to use it as an object and show it in the storyboard. I'm really new to Swift so I've been stuck for a while.

I've tried ObjectMapper and also JSON decode with no result at all.

I declared this response as I used in Java(Android)

```<code>class ResponseObjectMapper<T,R>: Mappable where T: Mappable,R:Mappable{

var data:T?
var message:String!
var error:R?

required init?(_ map: Map) {
    self.mapping(map: map)
}

func mapping(map: Map) {
    data          <- map["data"]
    message          <- map["message"]
    error          <- map["error"]
}
}

class UserMapper :Mappable{
var email:String?
var fullName:String?
var id:CLong?
var phoneNumber:String?
var token:CLong?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    email <- map["email"]
    fullName <- map["fullName"]
    id <- map["id"]
    phoneNumber <- map["phoneNumber"]
    token <- map["token"]
    phoneNumber <- map["phoneNumber"]
}
}
</code>```

In my Android project I use the Gson dependency and I was able to use my JSON as an object

```<code>class ErrorMapper:Mappable{

var message:String?
var code:Int?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    message          <- map["message"]
    code          <- map["code"]
}

}
</code>```

This is the Alamofire that gave me the JSON.

```<code>func login(params: [String:Any]){Alamofire.request
("http://192.168.0.192:8081/SpringBoot/user/login", method: .post,
parameters: params,encoding: JSONEncoding.default, headers:
headers).responseJSON {
            response in
            switch response.result {
            case .success:

                let response = Mapper<ResponseObjectMapper<UserMapper,ErrorMapper>>.map(JSONString: response.data)

                break
            case .failure(let error):

                print(error)
            }
        }
}
</code>```

If I print the response with print(response) I got

```<code>SUCCESS: {
data =     {
    email = "vpozo@montran.com";
    fullName = "Victor Pozo";
    id = 6;
    phoneNumber = 099963212;
    token = 6;
};
error = "<null>";
message = SUCCESS;
}
</code>```

and if I use this code I can got a result with key and value but I don't know how to use it as an object

```<code>if let result = response.result.value {
                    let responseDict = result as! [String : Any]
                    print(responseDict["data"])
                }
</code>```

console:

```<code>Optional({
email = "vpozo@gmail.com";
fullName = "Victor Pozo";
id = 6;
phoneNumber = 099963212;
token = 6;
})
</code>```

I would like to use it in an Object, like user.token in a View Controller, probably I'm really confused, trying to map with generic attributes.

```<code>Type 'ResponseObjectMapper<UserMapper, ErrorMapper>' does not conform to protocol 'BaseMappable'
</code>```

答:
First of all you will need a Network Manager which uses Alamofire to make all your requests. I have made generalized one that looks something like this. You can modify it as you want.

```<code>import Foundation
import Alamofire
import SwiftyJSON

class NetworkHandler: NSObject {

let publicURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json"
]

let privateURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json",
    "Authorization" : ""
]

enum RequestType {
    case publicURL
    case privateURL
}

func createNetworkRequestWithJSON(urlString : String , prametres : [String : Any], type : RequestType, completion:@escaping(JSON) -> Void) {

    let internetIsReachable = NetworkReachabilityManager()?.isReachable ?? false
    if !internetIsReachable {
        AlertViewManager.sharedInstance.showAlertFromWindow(title: "", message: "No internet connectivity.")
    } else {
        switch type {
        case .publicURL :
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: publicURLHeaders)
            break
        case .privateURL:
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: privateURLHeaders)
            break
        }
    }
}

func commonRequest(urlString : String, parameters : [String : Any], completion : @escaping (JSON) -> Void , headers : HTTPHeaders){

    print("urlString:"+urlString)
    print("headers:")
    print(headers)
    print("parameters:")
    print(parameters)

    let url = NSURL(string: urlString)
    var request = URLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.httpHeaders = headers
    request.timeoutInterval = 10
    let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    if let json = json {
        print("parameters:")
        print(json)
    }

    request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
    let alamoRequest = AF.request(request as URLRequestConvertible)
    alamoRequest.validate(statusCode: 200..<300)
    alamoRequest.responseJSON{ response in
        print(response.response?.statusCode as Any )
        if let status = response.response?.statusCode {
            switch(status){
            case 201:
                print("example success")
                SwiftLoader.hide()
            case 200 :
                if let json = response.value {
                    let jsonObject = JSON(json)
                    completion(jsonObject)
                }
            default:
                SwiftLoader.hide()
                print("error with response status: \(status)")
            }
        }else{
            let jsonObject = JSON()
            completion(jsonObject)
            SwiftLoader.hide()
        }
    }
}
}
</code>```

After this when ever you need to make a request you can use this function. This will take in parameters if any needed and once the request is complete it will execute a call back function in which you can handle the response. The response here will be of SWIFTYJSON format.

```<code>func makeNetworkRequest(){
    let networkHandler = NetworkHandler()
    var parameters : [String:String] = [:]
    parameters["email"] = usernameTextField.text
    parameters["pass"] = passwordTextField.text
    networkHandler.createNetworkRequestWithJSON(urlString: "http://192.168.0.192:8081/SpringBoot/user/login", prametres: parameters, type: .publicURL, completion: self.handleResponseForRequest)
}

func handleResponseForRequest(response: JSON){
    if let message = response["message"].string{
        if message == "SUCCESS"{

            if let email = response["data"]["email"].string{
                //Do something with email.
            }

            if let fullName = response["data"]["fullName"].string{
                //Do something with fullName.
            }

            if let id = response["data"]["id"].int{
                //Do something with id.
            }

            if let phoneNumber = response["data"]["phoneNumber"].int64{
                //Do something with phoneNumber.
            }

            if let token = response["data"]["token"].int{
                //Do something with token.
            }
        }else{
            //Error
        }
    }
}
</code>```

Hope this helps. Let me know if you get stuck anywhere.

Title: Parse responseJSON to ObjectMapper

Body:
I'm currently making a migration from Android to iOS, better said Java to Swift, I got a generic response in JSON, but I'm not able to use it as an object and show it in the storyboard. I'm really new to Swift so I've been stuck for a while.

I've tried ObjectMapper and also JSON decode with no result at all.

I declared this response as I used in Java(Android)

class ResponseObjectMapper<T,R>: Mappable where T: Mappable,R:Mappable{

var data:T?
var message:String!
var error:R?

required init?(_ map: Map) {
    self.mapping(map: map)
}

func mapping(map: Map) {
    data          <- map["data"]
    message          <- map["message"]
    error          <- map["error"]
}
}

class UserMapper :Mappable{
var email:String?
var fullName:String?
var id:CLong?
var phoneNumber:String?
var token:CLong?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    email <- map["email"]
    fullName <- map["fullName"]
    id <- map["id"]
    phoneNumber <- map["phoneNumber"]
    token <- map["token"]
    phoneNumber <- map["phoneNumber"]
}
}

In my Android project I use the Gson dependency and I was able to use my JSON as an object

class ErrorMapper:Mappable{

var message:String?
var code:Int?

required init?(_ map: Map) {
}

func mapping(map: Map) {
    message          <- map["message"]
    code          <- map["code"]
}

}

This is the Alamofire that gave me the JSON.

func login(params: [String:Any]){Alamofire.request
("http://192.168.0.192:8081/SpringBoot/user/login", method: .post,
parameters: params,encoding: JSONEncoding.default, headers:
headers).responseJSON {
            response in
            switch response.result {
            case .success:

                let response = Mapper<ResponseObjectMapper<UserMapper,ErrorMapper>>.map(JSONString: response.data)

                break
            case .failure(let error):

                print(error)
            }
        }
}

If I print the response with print(response) I got

SUCCESS: {
data =     {
    email = "vpozo@montran.com";
    fullName = "Victor Pozo";
    id = 6;
    phoneNumber = 099963212;
    token = 6;
};
error = "<null>";
message = SUCCESS;
}

and if I use this code I can got a result with key and value but I don't know how to use it as an object

if let result = response.result.value {
                    let responseDict = result as! [String : Any]
                    print(responseDict["data"])
                }

console:

Optional({
email = "vpozo@gmail.com";
fullName = "Victor Pozo";
id = 6;
phoneNumber = 099963212;
token = 6;
})

I would like to use it in an Object, like user.token in a View Controller, probably I'm really confused, trying to map with generic attributes.

Type 'ResponseObjectMapper<UserMapper, ErrorMapper>' does not conform to protocol 'BaseMappable'

Body:
First of all you will need a Network Manager which uses Alamofire to make all your requests. I have made generalized one that looks something like this. You can modify it as you want.

import Foundation
import Alamofire
import SwiftyJSON

class NetworkHandler: NSObject {

let publicURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json"
]

let privateURLHeaders : HTTPHeaders = [
    "Content-type" : "application/json",
    "Authorization" : ""
]

enum RequestType {
    case publicURL
    case privateURL
}

func createNetworkRequestWithJSON(urlString : String , prametres : [String : Any], type : RequestType, completion:@escaping(JSON) -> Void) {

    let internetIsReachable = NetworkReachabilityManager()?.isReachable ?? false
    if !internetIsReachable {
        AlertViewManager.sharedInstance.showAlertFromWindow(title: "", message: "No internet connectivity.")
    } else {
        switch type {
        case .publicURL :
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: publicURLHeaders)
            break
        case .privateURL:
            commonRequest(urlString: baseURL+urlString, parameters: prametres, completion: completion, headers: privateURLHeaders)
            break
        }
    }
}

func commonRequest(urlString : String, parameters : [String : Any], completion : @escaping (JSON) -> Void , headers : HTTPHeaders){

    print("urlString:"+urlString)
    print("headers:")
    print(headers)
    print("parameters:")
    print(parameters)

    let url = NSURL(string: urlString)
    var request = URLRequest(url: url! as URL)
    request.httpMethod = "POST"
    request.httpHeaders = headers
    request.timeoutInterval = 10
    let data = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)

    let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
    if let json = json {
        print("parameters:")
        print(json)
    }

    request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
    let alamoRequest = AF.request(request as URLRequestConvertible)
    alamoRequest.validate(statusCode: 200..<300)
    alamoRequest.responseJSON{ response in
        print(response.response?.statusCode as Any )
        if let status = response.response?.statusCode {
            switch(status){
            case 201:
                print("example success")
                SwiftLoader.hide()
            case 200 :
                if let json = response.value {
                    let jsonObject = JSON(json)
                    completion(jsonObject)
                }
            default:
                SwiftLoader.hide()
                print("error with response status: \(status)")
            }
        }else{
            let jsonObject = JSON()
            completion(jsonObject)
            SwiftLoader.hide()
        }
    }
}
}

After this when ever you need to make a request you can use this function. This will take in parameters if any needed and once the request is complete it will execute a call back function in which you can handle the response. The response here will be of SWIFTYJSON format.

func makeNetworkRequest(){
    let networkHandler = NetworkHandler()
    var parameters : [String:String] = [:]
    parameters["email"] = usernameTextField.text
    parameters["pass"] = passwordTextField.text
    networkHandler.createNetworkRequestWithJSON(urlString: "http://192.168.0.192:8081/SpringBoot/user/login", prametres: parameters, type: .publicURL, completion: self.handleResponseForRequest)
}

func handleResponseForRequest(response: JSON){
    if let message = response["message"].string{
        if message == "SUCCESS"{

            if let email = response["data"]["email"].string{
                //Do something with email.
            }

            if let fullName = response["data"]["fullName"].string{
                //Do something with fullName.
            }

            if let id = response["data"]["id"].int{
                //Do something with id.
            }

            if let phoneNumber = response["data"]["phoneNumber"].int64{
                //Do something with phoneNumber.
            }

            if let token = response["data"]["token"].int{
                //Do something with token.
            }
        }else{
            //Error
        }
    }
}

Hope this helps. Let me know if you get stuck anywhere.


问:
How to install a Notepad++ plugin offline?
I am trying to install a Notepad++ plugin from Plugins -> Plugin Manager, but my office firewall is restricting its download.
Is there any alternate way to install the plugin offline?

答: I couldn't import the .dll if it was already in the plugins folder. I put it in a temp folder on the C:\ drive, and it worked perfectly.</p>


问:
Do I need to opt-in to Ivy to use dynamic imports when lazy loading routes (Angular 8)?
I've recently upgraded to Angular 8 and want to make use of the new dynamic imports feature.

I want to convert this:

```<code> { path: 'payments', loadChildren: './components/payments/payments.module#PaymentsModule' }
</code>```

To this:

```<code> { path: 'payments', loadChildren: () => import('./components/payments/payments.module').then(m => m.PaymentsModule)}
</code>```

However my code editor (VSCode) throws a Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext' error, which I'm unsure how to fix.

On the Angular update guide (https://update.angular.io/), when talking about using the new import syntax, it says:

For lazy loaded modules via the router, importing via string is
  deprecated. ng update will take care of this automatically. The new
  syntax leverages the ecosystem wide support for import rather than our
  custom rewrites.

ng update did not do this automatically and throws the aforementioned error when manually changing the syntax.

I read an article by one of the maintainers of this new feature and he mentions that I will need to opt-in to Ivy.

I'm not sure if this is an Angular 8 bug, or if I will need to opt-in to Ivy (in which case, the docs need to be clearer)

My package.json:

```<code>  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.1.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/pwa": "^0.800.0",
    "@angular/router": "^8.0.0",
    "@angular/service-worker": "^8.0.0",
    "basic-keyboard-event-polyfill": "^1.0.1",
    "classlist.js": "^1.1.20150312",
    "concurrently": "^4.1.0",
    "core-js": "^3.1.3",
    "hammerjs": "^2.0.8",
    "moment": "^2.22.2",
    "ng-click-outside": "^4.0.0",
    "ng2-pdf-viewer": "^5.2.1",
    "ngx-device-detector": "^1.3.3",
    "ngx-logger": "^3.3.11",
    "phantomjs": "^2.1.7",
    "rxjs": "^6.2.1",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.9.1"
   },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular-devkit/build-ng-packagr": "~0.800.0",
    "@angular-devkit/build-optimizer": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@compodoc/compodoc": "^1.1.3",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.3",
    "@types/karma-viewport": "^0.4.0",
    "@types/node": "12.0.3",
    "codelyzer": "~5.0.1",
    "gulp": "^4.0.2",
    "gulp-sass": "^4.0.1",
    "gzipper": "^2.5.1",
    "http-server": "^0.11.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-viewport": "^1.0.4",
    "ng-packagr": "^5.2.0",
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "rimraf": "^2.6.2",
    "ts-node": "~8.2.0",
    "tsickle": "^0.35.0",
    "tslib": "^1.9.3",
    "tslint": "~5.16.0",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^3.3.2"
   }
</code>```

答:
Like Tony said in this other question, you need to add "module": "esnext" to the tsconfig.json file. Also make sure you change the same line in the tsconfig.app.json if you have a different value there.

After that I got no error in the VSCode, but got another error when compilating, but I think is a different issue (Module parse failed: Unexpected token) and this may solve it for you.

Body:
I've recently upgraded to Angular 8 and want to make use of the new dynamic imports feature.

I want to convert this:

 { path: 'payments', loadChildren: './components/payments/payments.module#PaymentsModule' }

To this:

 { path: 'payments', loadChildren: () => import('./components/payments/payments.module').then(m => m.PaymentsModule)}

However my code editor (VSCode) throws a Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext' error, which I'm unsure how to fix.

On the Angular update guide (https://update.angular.io/), when talking about using the new import syntax, it says:

For lazy loaded modules via the router, importing via string is
  deprecated. ng update will take care of this automatically. The new
  syntax leverages the ecosystem wide support for import rather than our
  custom rewrites.

ng update did not do this automatically and throws the aforementioned error when manually changing the syntax.

I read an article by one of the maintainers of this new feature and he mentions that I will need to opt-in to Ivy.

I'm not sure if this is an Angular 8 bug, or if I will need to opt-in to Ivy (in which case, the docs need to be clearer)

My package.json:

  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.1.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/pwa": "^0.800.0",
    "@angular/router": "^8.0.0",
    "@angular/service-worker": "^8.0.0",
    "basic-keyboard-event-polyfill": "^1.0.1",
    "classlist.js": "^1.1.20150312",
    "concurrently": "^4.1.0",
    "core-js": "^3.1.3",
    "hammerjs": "^2.0.8",
    "moment": "^2.22.2",
    "ng-click-outside": "^4.0.0",
    "ng2-pdf-viewer": "^5.2.1",
    "ngx-device-detector": "^1.3.3",
    "ngx-logger": "^3.3.11",
    "phantomjs": "^2.1.7",
    "rxjs": "^6.2.1",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.9.1"
   },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular-devkit/build-ng-packagr": "~0.800.0",
    "@angular-devkit/build-optimizer": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@compodoc/compodoc": "^1.1.3",
    "@types/jasmine": "~3.3.13",
    "@types/jasminewd2": "~2.0.3",
    "@types/karma-viewport": "^0.4.0",
    "@types/node": "12.0.3",
    "codelyzer": "~5.0.1",
    "gulp": "^4.0.2",
    "gulp-sass": "^4.0.1",
    "gzipper": "^2.5.1",
    "http-server": "^0.11.1",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-ie-launcher": "^1.0.0",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-viewport": "^1.0.4",
    "ng-packagr": "^5.2.0",
    "node-sass": "^4.12.0",
    "protractor": "~5.4.2",
    "rimraf": "^2.6.2",
    "ts-node": "~8.2.0",
    "tsickle": "^0.35.0",
    "tslib": "^1.9.3",
    "tslint": "~5.16.0",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^3.3.2"
   }


问:
Custom PHP Errors for AJAX calls
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

```<code>//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery
</code>```

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.

答: I'd just use a JSON object and an HTTP header of 200. There was nothing wrong with the request itself, and your server behaved as it was supposed to - the error was on a different layer of the abstraction.</p>

Title: Custom PHP Errors for AJAX calls

Body:
I'm building a web application, and am wondering how to handle errors with my AJAX calls.  For instance, if the user enters some sort of data that is invalid (bad email address, user already exists) I want to be able to throw an error from PHP.

I've seen here http://php4every1.com/tutorials/jquery-ajax-tutorial/ that you could just use a JSON object and handle the error report from JQuery's Success function, but that doesn't seem like the right way to do it. It would make sense to me that jQuery's error function should be utilized when there is an error. I guess I'm a stickler for that kind of thing.

Here's how I'm doing it right now.

//In my PHP file called from JQuery
function error($msg) {
    header("HTTP/1.0 555 ".$msg);
    die();
}
//Then that error is handled accordingly from JQuery

So I'm creating an error code of 555—which is not defined as anything—and tacking on my own custom error message. Is that the right way to do this? Should I just use JSON? There's gotta be a standard way to send out error messages like this, right?

If you need to see more of my code to get a better idea, the whole project is up on github: https://github.com/josephwegner/fileDrop. The file in question is config/phpFuncts.php.


问:
Git create release on commit reading a variable in file
I have a PHP project,
with a file called release.php, that's just containing some info about the version of the project and a variable $create_release:

```<code><?php
$release = '1.0.4';
$release_date = '2019/05/30';
$create_release = TRUE;
</code>```

I would on git push to GitHub, create a release if the variable inside PHP file is set TRUE.

How can I trigger GitHub release creation automatically on git push?

Is it possible?

答:
You can use Tomtit task manager as well for that type of tasks. Just create this helper inside PWD:

.tomtit/push.pl6

```<code>#!perl6

task-run "push my changes", "git-push";

if slurp "release.php" ~~ / '$' create_release \s+ '=' \s+ TRUE / {
  bash "./fire-release.sh" # or whatever command you need
}

</code>```

Then just:

```<code>tom push
</code>```

Body:
I have a PHP project,
with a file called release.php, that's just containing some info about the version of the project and a variable $create_release:

<?php
$release = '1.0.4';
$release_date = '2019/05/30';
$create_release = TRUE;

I would on git push to GitHub, create a release if the variable inside PHP file is set TRUE.

How can I trigger GitHub release creation automatically on git push?

Is it possible?

Body:
You can use Tomtit task manager as well for that type of tasks. Just create this helper inside PWD:

.tomtit/push.pl6

#!perl6

task-run "push my changes", "git-push";

if slurp "release.php" ~~ / '$' create_release \s+ '=' \s+ TRUE / {
  bash "./fire-release.sh" # or whatever command you need
}

Then just:

tom push


问:
How do I read a custom error message returned when HttpWebRequest.GetResponse throws a WebException?
I've a NET.Core API with simple test method:

```<code>public async Task<IActionResult> TestApi()
{
    try
    {
        throw new UnauthorizedAccessException("My custom error");

        return Ok();
    }
    catch (UnauthorizedAccessException ex)
    {
        return StatusCode(401,ex.Message);
    }
    catch (Exception ex)
    {
        throw;
    }

}
</code>```

I need to retrieve the message from a client like this:

```<code>var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;

if (parameters != null)
{
    request.ContentLength = serializedObject.Length;
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(serializedObject);
    }
}

var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);

using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
    var result = sr.ReadToEnd();
    return JsonConvert.DeserializeObject<T>(result);
}
</code>```

Now request.GetResponse() as HttpWebResponse returns me:

```<code>The remote server returned an error: (401) Unauthorized.
</code>```

instead of My custom error. Can someone point me in the right direction?

答:
Here's a pared-down example which reads your custom message. Your message is returned in the response stream.</p>

```<code>try
{
    var response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex) // this exception is thrown because of the 401.
{
    var responseStream = ex.Response.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        var message = reader.ReadToEnd();
    }
}
</code>```

Body:
I've a NET.Core API with simple test method:

public async Task<IActionResult> TestApi()
{
    try
    {
        throw new UnauthorizedAccessException("My custom error");

        return Ok();
    }
    catch (UnauthorizedAccessException ex)
    {
        return StatusCode(401,ex.Message);
    }
    catch (Exception ex)
    {
        throw;
    }

}

I need to retrieve the message from a client like this:

var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;

if (parameters != null)
{
    request.ContentLength = serializedObject.Length;
    using (var writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write(serializedObject);
    }
}

var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);

using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
    var result = sr.ReadToEnd();
    return JsonConvert.DeserializeObject<T>(result);
}

Now request.GetResponse() as HttpWebResponse returns me:

The remote server returned an error: (401) Unauthorized.

instead of My custom error. Can someone point me in the right direction?

Body:
Here's a pared-down example which reads your custom message. Your message is returned in the response stream.

try
{
    var response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex) // this exception is thrown because of the 401.
{
    var responseStream = ex.Response.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        var message = reader.ReadToEnd();
    }
}