问:
confusion about git rev-list
I want to know the related commit-id with the 100 submit in branch  dev. (for example: git rev-list --reverse --branches=dev --date-order --count <commit-id> == 100):

And got the 100 commit is 1f345e80fba518c72dec7f2e02da5da12be5810f:

```<code>$ git rev-list --reverse --branches=dev --date-order HEAD | head -100 | tail -1
1f345e80fba518c72dec7f2e02da5da12be5810f

$ git rev-list --reverse --branches=dev --date-order HEAD | nl | grep 100
   100  1f345e80fba518c72dec7f2e02da5da12be5810f

$ git rev-list --reverse --branches=dev --date-order HEAD | awk '{print NR"\t"$0}' | grep -E ^100
100     1f345e80fba518c72dec7f2e02da5da12be5810f
</code>```

However, when I try to verify the rev-number about this commit-id (1f345e80fba518c72dec7f2e02da5da12be5810f), the result shows: rev number is 98!!!

```<code>$ git rev-list --reverse --branches=dev --date-order --count 1f345e80fba518c72dec7f2e02da5da12be5810f
98

$ git rev-list --reverse --branches=dev --date-order 1f345e80fba518c72dec7f2e02da5da12be5810f | nl | tail -1
    98  1f345e80fba518c72dec7f2e02da5da12be5810f
</code>```

So I try to find out which 2 commit is missing:

```<code>$ git rev-list --reverse --branches=dev --date-order HEAD | head -100 | nl > commit-100.log
$ git rev-list --reverse --branches=dev --date-order 1f345e80fba518c72dec7f2e02da5da12be5810f | head -100 | nl > commit-98.log
$ diff -y commit-100.log commit-98.log
 90  63546ce0207cdd6ade353ea05c466d0210af1d29              |     90  75a8fd85043908049e11595aaa2c988282fa1a0c
 91  75a8fd85043908049e11595aaa2c988282fa1a0c              |     91  c1bbb33cd0241c16dde2579696c08ed2eb146cdf
 92  c1bbb33cd0241c16dde2579696c08ed2eb146cdf              |     92  28e9bbc06cb3036bce4cce71f5acf4b27835e9a0
 93  28e9bbc06cb3036bce4cce71f5acf4b27835e9a0              |     93  7b1d0caddc6218eb982d27c1df27c885bc84204c
 94  7b1d0caddc6218eb982d27c1df27c885bc84204c              |     94  945fd63a256391e72e55e8ac98c449c1473c1e5e
 95  945fd63a256391e72e55e8ac98c449c1473c1e5e              |     95  0ff3f47eb8dc40815ac7effdb2172e5d69dd0e10
 96  0ff3f47eb8dc40815ac7effdb2172e5d69dd0e10              |     96  ac90a7b2a371ff7a0fad0475d94691663aceaa1b
 97  ac90a7b2a371ff7a0fad0475d94691663aceaa1b              |     97  1a0e26b517f88870fed0cf5f346495b67c29463a
 98  937807239dd706f3bf124dd4d3266c71fd8071f4              |     98  1f345e80fba518c72dec7f2e02da5da12be5810f
 99  1a0e26b517f88870fed0cf5f346495b67c29463a              <
100  1f345e80fba518c72dec7f2e02da5da12be5810f              <
</code>```

Apparent, the 2 missing commit-id is:

```<code>90  63546ce0207cdd6ade353ea05c466d0210af1d29
98  937807239dd706f3bf124dd4d3266c71fd8071f4
</code>```

According to git show <commit-id>, and nothing strange. These two commits was submitted by the same guy. But this person committed 10 times in the first 100 commits.

Does it a git rev-list issue?

答:
I don't know quite what you are trying to do, but git rev-list does not do that, whatever it is.

What git rev-list does is to list reachable commits, by walking the commit graph, starting from particular set of starting-points, while applying some set of constraints.  The walk itself may be done in a particular order, some commits may be optionally simplified away, you can stop the walk early with --max-count or skip some initial commits with --skip, and after the set of commits is found it can be reversed and/or counted.

You set no constraints on the graph itself (no path arguments) and did not enable any simplification modes or skips or max counts, but you did ask to reverse the set in the end.

Your starting points are --branches=dev (which means --branches=dev/*) and HEAD in one case, and --branches=dev and commit 1f345e80fba518c72dec7f2e02da5da12be5810f in another.

You asked for the walk to be done in --date-order, which means that whenever Git has two commits it could walk right now, it should select the one with the later commit time stamp, as long as it is not selecting the parent of a child commit that it has not yet selected.

The set of commits reachable from HEAD may include commits not reachable from from the set of commits selected by refs/heads/dev/* (all dev branches).  The set of commits reachable from 1f345e80fba518c72dec7f2e02da5da12be5810f may also differ, if 1f345e80fba518c72dec7f2e02da5da12be5810f is not itself reachable from one of the dev branches.  It's not surprising that the 100th such commit (after reversing the list) differs.

Title: confusion about git rev-list

Body:
I want to know the related commit-id with the 100 submit in branch  dev. (for example: git rev-list --reverse --branches=dev --date-order --count <commit-id> == 100):

And got the 100 commit is 1f345e80fba518c72dec7f2e02da5da12be5810f:

$ git rev-list --reverse --branches=dev --date-order HEAD | head -100 | tail -1
1f345e80fba518c72dec7f2e02da5da12be5810f

$ git rev-list --reverse --branches=dev --date-order HEAD | nl | grep 100
   100  1f345e80fba518c72dec7f2e02da5da12be5810f

$ git rev-list --reverse --branches=dev --date-order HEAD | awk '{print NR"\t"$0}' | grep -E ^100
100     1f345e80fba518c72dec7f2e02da5da12be5810f

However, when I try to verify the rev-number about this commit-id (1f345e80fba518c72dec7f2e02da5da12be5810f), the result shows: rev number is 98!!!

$ git rev-list --reverse --branches=dev --date-order --count 1f345e80fba518c72dec7f2e02da5da12be5810f
98

$ git rev-list --reverse --branches=dev --date-order 1f345e80fba518c72dec7f2e02da5da12be5810f | nl | tail -1
    98  1f345e80fba518c72dec7f2e02da5da12be5810f

So I try to find out which 2 commit is missing:

$ git rev-list --reverse --branches=dev --date-order HEAD | head -100 | nl > commit-100.log
$ git rev-list --reverse --branches=dev --date-order 1f345e80fba518c72dec7f2e02da5da12be5810f | head -100 | nl > commit-98.log
$ diff -y commit-100.log commit-98.log
 90  63546ce0207cdd6ade353ea05c466d0210af1d29              |     90  75a8fd85043908049e11595aaa2c988282fa1a0c
 91  75a8fd85043908049e11595aaa2c988282fa1a0c              |     91  c1bbb33cd0241c16dde2579696c08ed2eb146cdf
 92  c1bbb33cd0241c16dde2579696c08ed2eb146cdf              |     92  28e9bbc06cb3036bce4cce71f5acf4b27835e9a0
 93  28e9bbc06cb3036bce4cce71f5acf4b27835e9a0              |     93  7b1d0caddc6218eb982d27c1df27c885bc84204c
 94  7b1d0caddc6218eb982d27c1df27c885bc84204c              |     94  945fd63a256391e72e55e8ac98c449c1473c1e5e
 95  945fd63a256391e72e55e8ac98c449c1473c1e5e              |     95  0ff3f47eb8dc40815ac7effdb2172e5d69dd0e10
 96  0ff3f47eb8dc40815ac7effdb2172e5d69dd0e10              |     96  ac90a7b2a371ff7a0fad0475d94691663aceaa1b
 97  ac90a7b2a371ff7a0fad0475d94691663aceaa1b              |     97  1a0e26b517f88870fed0cf5f346495b67c29463a
 98  937807239dd706f3bf124dd4d3266c71fd8071f4              |     98  1f345e80fba518c72dec7f2e02da5da12be5810f
 99  1a0e26b517f88870fed0cf5f346495b67c29463a              <
100  1f345e80fba518c72dec7f2e02da5da12be5810f              <

Apparent, the 2 missing commit-id is:

90  63546ce0207cdd6ade353ea05c466d0210af1d29
98  937807239dd706f3bf124dd4d3266c71fd8071f4

According to git show <commit-id>, and nothing strange. These two commits was submitted by the same guy. But this person committed 10 times in the first 100 commits.

Does it a git rev-list issue?


来源: stackexchange

问:
Unable to output or save API response from custom function in Google sheet
I have the following Google App Script that ultimately returns a matrix but I am able to alter rows and use the appendRow method because I am trying to call it from a custom function.

Consulting other related questions on stackoverflow and the GAS documentation whatever a custom function returns should be displayed in the cell it was called from.

I'm able to see the return using the GAS Logger inside the Google script editor but that's it. How can I output to the sheet instead or otherwise save and export this response?

The sample response looks like:

```<code>[[diy_move, forward_mail, update_account, renters_insurance, recommended_provider, utility, home_service, offer, share],
 [forward_mail, update_account, utility, home_service, offer, share]]
</code>```

// Get current row
function getActiveRow() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var activeRow = sheet.getActiveCell().getRow();

  return activeRow;
}

// call updater api
function getSteps() {
  var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  var userIds = [];

  var sheet = SpreadsheetApp.getActiveSheet();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sss = ss.getSheets()[0];
  var range = sheet.getRange(getActiveRow(), 1, 1, 1);
  var id = range.getValues();

  function first(list) {
    return list[0];
  }

  function getProperty(property) {
    return function (item) {
      return item[property];
    }
  }

  var getCode = getProperty('code');

  var userIds = values.map(first);

  var headers = {
    // auth
    "Content-Type": "application/json",
    "app": "company",
    "uid": "phong@updater.com",
    "client": "*****",
    "access-token": "*****"
  };

  var options = {
    "method": "GET",
    "headers": headers
    //"muteHttpExceptions": true
  };

  function callApi(id) {
    var url = "http://api.updater.com/v2/item_definitions?user_id=" + id;
    var response = UrlFetchApp.fetch(url, options)
    var json = response.getContentText();
    var data = JSON.parse(json);

    return data.map(getCode);
  }

  function createSupersteps(ids) {
     return ids.map(callApi);
  }
  Logger.log(createSupersteps(userIds));
  sss.appendRow(createSupersteps(userIds));
  //createSupersteps(userIds)
}```

答:
Try adding [] to sss.appendRow(createSupersteps(userIds)); making it to sss.appendRow([createSupersteps(userIds)]);.

Based on the documentation sample code appendRow(rowContents)

Appends a row to the spreadsheet. This operation is atomic; it prevents issues where a user asks for the last row, and then writes to that row, and an intervening mutation occurs between getting the last row and writing to it.

```<code> var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 // Appends a new row with 3 columns to the bottom of the
 // spreadsheet containing the values in the array
 sheet.appendRow(["a man", "a plan", "panama"]);
</code>```

Here is my sample code:

```<code>function insert(){
 var ss = SpreadsheetApp.openById('FILE_ID');
 var sheet = ss.getSheets()[0];
 var sample = "sample";
 // Appends a new row with 3 columns to the bottom of the
 // spreadsheet containing the values in the array
 sheet.appendRow([sample]);
}
</code>```

Trying to add using sheet.appendRow(sample); gives an error

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have the following Google App Script that ultimately returns a matrix but I am able to alter rows and use the appendRow method because I am trying to call it from a custom function.

Consulting other related questions on stackoverflow and the GAS documentation whatever a custom function returns should be displayed in the cell it was called from.

I'm able to see the return using the GAS Logger inside the Google script editor but that's it. How can I output to the sheet instead or otherwise save and export this response?

The sample response looks like:

[[diy_move, forward_mail, update_account, renters_insurance, recommended_provider, utility, home_service, offer, share],
 [forward_mail, update_account, utility, home_service, offer, share]]

// Get current row
function getActiveRow() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var activeRow = sheet.getActiveCell().getRow();

  return activeRow;
}

// call updater api
function getSteps() {
  var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  var userIds = [];

  var sheet = SpreadsheetApp.getActiveSheet();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sss = ss.getSheets()[0];
  var range = sheet.getRange(getActiveRow(), 1, 1, 1);
  var id = range.getValues();

  function first(list) {
    return list[0];
  }

  function getProperty(property) {
    return function (item) {
      return item[property];
    }
  }

  var getCode = getProperty('code');

  var userIds = values.map(first);

  var headers = {
    // auth
    "Content-Type": "application/json",
    "app": "company",
    "uid": "phong@updater.com",
    "client": "*****",
    "access-token": "*****"
  };

  var options = {
    "method": "GET",
    "headers": headers
    //"muteHttpExceptions": true
  };

  function callApi(id) {
    var url = "http://api.updater.com/v2/item_definitions?user_id=" + id;
    var response = UrlFetchApp.fetch(url, options)
    var json = response.getContentText();
    var data = JSON.parse(json);

    return data.map(getCode);
  }

  function createSupersteps(ids) {
     return ids.map(callApi);
  }
  Logger.log(createSupersteps(userIds));
  sss.appendRow(createSupersteps(userIds));
  //createSupersteps(userIds)
}

Body:
Try adding [] to sss.appendRow(createSupersteps(userIds)); making it to sss.appendRow([createSupersteps(userIds)]);.

Based on the documentation sample code appendRow(rowContents)

Appends a row to the spreadsheet. This operation is atomic; it prevents issues where a user asks for the last row, and then writes to that row, and an intervening mutation occurs between getting the last row and writing to it.

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

 // Appends a new row with 3 columns to the bottom of the
 // spreadsheet containing the values in the array
 sheet.appendRow(["a man", "a plan", "panama"]);

Here is my sample code:

function insert(){
 var ss = SpreadsheetApp.openById('FILE_ID');
 var sheet = ss.getSheets()[0];
 var sample = "sample";
 // Appends a new row with 3 columns to the bottom of the
 // spreadsheet containing the values in the array
 sheet.appendRow([sample]);
}

Trying to add using sheet.appendRow(sample); gives an error

Hope this helps.


问:
PHP Authentication
Currently my authentication looks like this:

User enters username/password combination
 Sent to the server, the username and password are salted and hashed (md5) and checked against the database.

If correct, and the user has specified, a month long cookie is set.

If the user does not specify to set a cookie, they are automatically signed out after five minutes of inactivity.

My question is simply if I need to, and how to, make this more secure. I'm pretty fluent in PHP, but I'm not as well off in security. Any help, pointers, leads, and general assistance would be appreciated.

Thanks. :)

答: Just make sure you are stripping slashes from the username and password to avoid SQL Injection with mysql_escape_real_string and that should be all the security you need.</p>

ContentLicense: CC BY-SA 2.5

Title: PHP Authentication


问:
Why string to hex give me same result
I want to convert string 00 to hex value 3030

```<code>'00'.toString('hex')
</code>```

give me 00.

What is the right method?

答:
Shamelessly stolen from this web site:</p>

```<code>function ascii_to_hexa(str)
{
    var arr1 = [];
    for (var n = 0, l = str.length; n < l; n ++)
    {
        var hex = Number(str.charCodeAt(n)).toString(16);
        arr1.push(hex);
    }
    return arr1.join('');
}
</code>```

Title: Why string to hex give me same result

Body:
I want to convert string 00 to hex value 3030

'00'.toString('hex')

give me 00.

What is the right method?

Body:
Shamelessly stolen from this web site:

function ascii_to_hexa(str)
{
    var arr1 = [];
    for (var n = 0, l = str.length; n < l; n ++)
    {
        var hex = Number(str.charCodeAt(n)).toString(16);
        arr1.push(hex);
    }
    return arr1.join('');
}


问:
Leaflet Draw 0.4.9 control not working with Leaflet 1.1.0?
I created a very minimal codepen, but I am getting an error when trying to create the draw control.

See: https://codepen.io/DrYSG/pen/QgmVZg

I assume it is something simple that I doing wrong. But I looked at the CDN I am using , and I see nothing obvious:

https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.9/leaflet.draw-src.js

These are the errors I am seeing in the console:

```<code>Util.js:15 Uncaught TypeError: Cannot add property segmentsIntersect, object is not extensible
    at Object.extend (Util.js:15)
    at LineUtil.Intersect.js:6
    at EditToolbar.Delete.js:145 extend @ Util.js:15 (anonymous) @ LineUtil.Intersect.js:6 (anonymous) @ EditToolbar.Delete.js:145 pen.js:11 Uncaught TypeError: L.Control.Draw is not a constructor
    at pen.js:11
</code>```

```<code>var map = L.map("root").setView([42, -71], 7);

L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy <a href="http://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a> contributors'
}).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);
</code>```

答:
Apparently I can't comment until I have more reputation.

Leaflet.Draw 0.4.10 has been released that limits the ceiling version of Leaflet to 1.0.x rather than 1.1.x. Leaflet 1.1.x introduced ES6 and Rollup which Leaflet.Draw was not prepared for, and that is being actively pursued to be resolved.

Body:
I created a very minimal codepen, but I am getting an error when trying to create the draw control.

See: https://codepen.io/DrYSG/pen/QgmVZg

I assume it is something simple that I doing wrong. But I looked at the CDN I am using , and I see nothing obvious:

https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.4.9/leaflet.draw-src.js

These are the errors I am seeing in the console:

Util.js:15 Uncaught TypeError: Cannot add property segmentsIntersect, object is not extensible
    at Object.extend (Util.js:15)
    at LineUtil.Intersect.js:6
    at EditToolbar.Delete.js:145 extend @ Util.js:15 (anonymous) @ LineUtil.Intersect.js:6 (anonymous) @ EditToolbar.Delete.js:145 pen.js:11 Uncaught TypeError: L.Control.Draw is not a constructor
    at pen.js:11

var map = L.map("root").setView([42, -71], 7);

L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '&copy OpenStreetMap contributors'
}).addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
  edit: {
    featureGroup: drawnItems
  }
});
map.addControl(drawControl);


问:
Run python interpreter using python code, with local variables
Many a times we get an error in some user defined function and want to debug it. If the error had happened in the main program, we can use the -i flag to preserve variables after the error. But if the error happens in a user defined function, there is no way we can access the local variables of the function. Is there a way where we can open python interpreter through python code, accept code from stdin and print output to stdout. Something like this:-

```<code>def foo():
  x = 'Inside foo()'
  run_interpreter() # Pauses for input

foo()
</code>```

We should be able to give following input through stdin:-

```<code>print(x) # prints 'Inside foo()'
exit()   # exits interpreter and resumes other code
</code>```

答:
You can't use a local variable of a function outside the function.

If you can to use a variable outside the function you need to declare it as a global Variable by Using GLOBAL.

Body:
Many a times we get an error in some user defined function and want to debug it. If the error had happened in the main program, we can use the -i flag to preserve variables after the error. But if the error happens in a user defined function, there is no way we can access the local variables of the function. Is there a way where we can open python interpreter through python code, accept code from stdin and print output to stdout. Something like this:-

def foo():
  x = 'Inside foo()'
  run_interpreter() # Pauses for input

foo()

We should be able to give following input through stdin:-

print(x) # prints 'Inside foo()'
exit()   # exits interpreter and resumes other code


问:
Create vector of data frame names from a list of data frames
I have a list of data frames, and I want to create a character vector that contains the data frame names that meet a certain criteria.  In this case, I want the names of the data frames that contain at least 1 observation.  I need these names in a vector for use in another function later on.

The list of data frames is created automatically by the split function.  For reproducibility, here's a list of data frames:

```<code>df1 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df2 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df3 <- data.frame(replicate(0,sample(0:1,5,rep=TRUE))) #empty

mylist <- list(df1, df2,df3) #create list of data frames

mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0] #subset list so that df's with no observations are dropped
</code>```

Now, what I need is a character vector with the names of the data frames in mylist2.  (In this example, "df1" and "df2".)

Thanks!

答:
You need to have a named list. Here is how you could do it:</p>

```<code>library(dplyr)
library(purrr)

mylist <- list(df1 = df1, df2 = df2, df3 = df3)

test <- mylist %>%
  map_int(nrow)

test[test > 0] %>% names()
#[1] "df1" "df2"
</code>```

Body:
I have a list of data frames, and I want to create a character vector that contains the data frame names that meet a certain criteria.  In this case, I want the names of the data frames that contain at least 1 observation.  I need these names in a vector for use in another function later on.

The list of data frames is created automatically by the split function.  For reproducibility, here's a list of data frames:

df1 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df2 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df3 <- data.frame(replicate(0,sample(0:1,5,rep=TRUE))) #empty

mylist <- list(df1, df2,df3) #create list of data frames

mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0] #subset list so that df's with no observations are dropped

Now, what I need is a character vector with the names of the data frames in mylist2.  (In this example, "df1" and "df2".)

Thanks!

Body:
You need to have a named list. Here is how you could do it:

library(dplyr)
library(purrr)

mylist <- list(df1 = df1, df2 = df2, df3 = df3)

test <- mylist %>%
  map_int(nrow)

test[test > 0] %>% names()
#[1] "df1" "df2"


问:
how to initialize all the base class objects from derived class using base keyword
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

```<code>    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }
</code>```

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

```<code>class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }
</code>```

then from class C how to initialize both the base classes using base keyword.

答:
Inheriting from multiple classes is not allowed in .Net. (Cause that would lead to Diamond problem). But implementing from multiple interface and multi level inheritance is allowed.

In first snippet first A's constructor is called followed by B's constructor.

In second snippet first A's constructor will be called, then B's followed by C's constructor.

Body:
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }

then from class C how to initialize both the base classes using base keyword.


问:
Skip an iteration if time limit exceeds PYTHON
I'm working with proxies on request library for my project.Depending on the proxy used, each request takes different (unpredictable) time.

```<code>for proxy in proxyList:
    r=requests.post(url, proxies=proxy, data=payload)
</code>```

If a certain request takes more than certain time,I want to skip it and move on to the next.How can this be done?

EDIT : Using timeout parameter raises an exception.Of course,I can get my work done by Exception handling.But I wanted it in a more general sense..like what if I'm not talking about requests ..suppose there is statement whose time can't be pre-defined?! Is there any way to move on to next iteration?

答:
On Mac/UNIX systems, you can raise a custom exception after a certain period of time like this:

```<code>import signal

class TimeoutException(Exception):   # custom exception
    pass

def timeout_handler(signum, frame):   # raises exception when signal sent
    raise TimeoutException

# Makes it so that when SIGALRM signal sent, it calls the function timeout_handler, which raises your exception
signal.signal(signal.SIGALRM, timeout_handler)

# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
for proxy in proxyList:
    signal.alarm(5)
    try:
        r=requests.post(url, proxies=proxy, data=payload)
    except TimeoutException:
        pass
</code>```

Basically, you're creating a custom exception that's raised when the after the time limit is up (i.e., the SIGALRM is sent). You can of course tweak the time limit.

More simply in your case, you can use the timeout parameter, as far as I can tell. As the documentation says:

You can tell Requests to stop waiting for a response after a given number of seconds with the timeout parameter. Nearly all production code should use this parameter in nearly all requests. Failure to do so can cause your program to hang indefinitely [...]

so your code would end up looking like

```<code>for proxy in proxyList:
    r=requests.post(url, proxies=proxy, data=payload, timeout=1)
</code>```

(Timeout parameter is in seconds.)

Body:
I'm working with proxies on request library for my project.Depending on the proxy used, each request takes different (unpredictable) time.

for proxy in proxyList:
    r=requests.post(url, proxies=proxy, data=payload)

If a certain request takes more than certain time,I want to skip it and move on to the next.How can this be done?

EDIT : Using timeout parameter raises an exception.Of course,I can get my work done by Exception handling.But I wanted it in a more general sense..like what if I'm not talking about requests ..suppose there is statement whose time can't be pre-defined?! Is there any way to move on to next iteration?

Body:
On Mac/UNIX systems, you can raise a custom exception after a certain period of time like this:

import signal

class TimeoutException(Exception):   # custom exception
    pass

def timeout_handler(signum, frame):   # raises exception when signal sent
    raise TimeoutException

# Makes it so that when SIGALRM signal sent, it calls the function timeout_handler, which raises your exception
signal.signal(signal.SIGALRM, timeout_handler)

# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
for proxy in proxyList:
    signal.alarm(5)
    try:
        r=requests.post(url, proxies=proxy, data=payload)
    except TimeoutException:
        pass

Basically, you're creating a custom exception that's raised when the after the time limit is up (i.e., the SIGALRM is sent). You can of course tweak the time limit.

More simply in your case, you can use the timeout parameter, as far as I can tell. As the documentation says:

You can tell Requests to stop waiting for a response after a given number of seconds with the timeout parameter. Nearly all production code should use this parameter in nearly all requests. Failure to do so can cause your program to hang indefinitely [...]

so your code would end up looking like

for proxy in proxyList:
    r=requests.post(url, proxies=proxy, data=payload, timeout=1)

(Timeout parameter is in seconds.)


问:
how to put text data in lightbox instead of images
it's possible to put text content into a frame, and show in lightbox, instead show images?
How can I do it?

i tried

```<code><a class="iframe" href="/folder/file.txt"><img height="80" width="120" src="img/txtFile.png"</a>
</code>```

and in jquery

```<code>    <script type="text/javascript">
    $("a.iframe").fancybox({

'width': 640, // or whatever you want
'height': 480, // or whatever you want
'type': 'iframe'
});
  </script>
</code>```

答:
Fancybox is able to display multiple types of content. See their documentation for more information. This includes inline content (ie displaying a hidden element, like a div), loading an iframe, or displaying an ajax response. The examples section can help clarify a lot of this for you.

If you want to read from a txt file, it may be more appropriate to load the data via ajax, as opposed to loading it into an iframe.

I've copied the relevant documentation from the documentation link listed above, for posterity (you can view the example in this codepen demo that the fancyapps team setup):

Ajax

To load content via AJAX, you need to add a data-type="ajax"
  attribute to your link:

```<code><a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" href="javascript:;">
  AJAX content
</a>
</code>```

Additionally it is possible to define a selector with the data-filter
  attribute to show only a part of the response. The selector can be any
  string, that is a valid jQuery selector:

```<code><a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" data-filter="#two" href="javascript:;">
  AJAX content
</a>
</code>```

Body:
it's possible to put text content into a frame, and show in lightbox, instead show images?
How can I do it?

i tried

<img height="80" width="120" src="img/txtFile.png"

and in jquery

Body:
Fancybox is able to display multiple types of content. See their documentation for more information. This includes inline content (ie displaying a hidden element, like a div), loading an iframe, or displaying an ajax response. The examples section can help clarify a lot of this for you.

If you want to read from a txt file, it may be more appropriate to load the data via ajax, as opposed to loading it into an iframe.

I've copied the relevant documentation from the documentation link listed above, for posterity (you can view the example in this codepen demo that the fancyapps team setup):

Ajax

To load content via AJAX, you need to add a data-type="ajax"
  attribute to your link:

<a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" href="javascript:;">
  AJAX content
</a>

Additionally it is possible to define a selector with the data-filter
  attribute to show only a part of the response. The selector can be any
  string, that is a valid jQuery selector:

<a data-fancybox data-type="ajax" data-src="my_page.com/path/to/ajax/" data-filter="#two" href="javascript:;">
  AJAX content
</a>


问:
Dynamically Add UserControl to Form
I would like to dynamically add a usercontrol to a form in VB.Net. I will be pulling the UserControl name (String) from a database and if that UserControl exists in the project I would like it to be added to the form.
I know how to programmatically add usercontrols to a form, but I am not sure how when using a string for the name.

```<code>Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name")
Panel1.Controls.Add(userContName)
</code>```

I attempted this soultion

```<code>Public Sub LoadGroups()
dtModules = Tbl_GroupModulesTableAdapter1.GetDataBy_spGetModuleByGroup(grp.Name)
For k = 0 To dtModules.Rows.Count - 1
   If grp.Name = dtModules.Rows(k).Item("Module_Group") Then
        Dim fullyQualifiedClassName As String = dtModules.Rows(k).Item("Module_Name")
        If fullyQualifiedClassName = Nothing Then
        Else
            Dim o = fetchInstance(fullyQualifiedClassName)
            Dim b = CType(o, Control)
            grp.Controls.Add(b)
        End If
   End If
Next
End Sub

Public Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
    Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
    Dim o As Object = Nothing
    Try
        For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
            If (ay.Name = nspc) Then
                o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
                Exit For
            End If
        Next
    Catch
    End Try
    Return o
End Function
</code>```

答:
Ok got it to work with this;

```<code>Dim ucName As String = Projectname.UserControlName
Dim newType As Type = Type.[GetType](ucName, True, True)
Dim o As Object = Activator.CreateInstance(newType)
Form.Controls.Add(o)
</code>```

Once I got this it was pretty simple! thanks for the feedback!

Title: Dynamically Add UserControl to Form

Body:
I would like to dynamically add a usercontrol to a form in VB.Net. I will be pulling the UserControl name (String) from a database and if that UserControl exists in the project I would like it to be added to the form.
I know how to programmatically add usercontrols to a form, but I am not sure how when using a string for the name.

Dim userContName As UserControl = dtModules.Rows(k).Item("uc_Name")
Panel1.Controls.Add(userContName)

I attempted this soultion

Public Sub LoadGroups()
dtModules = Tbl_GroupModulesTableAdapter1.GetDataBy_spGetModuleByGroup(grp.Name)
For k = 0 To dtModules.Rows.Count - 1
   If grp.Name = dtModules.Rows(k).Item("Module_Group") Then
        Dim fullyQualifiedClassName As String = dtModules.Rows(k).Item("Module_Name")
        If fullyQualifiedClassName = Nothing Then
        Else
            Dim o = fetchInstance(fullyQualifiedClassName)
            Dim b = CType(o, Control)
            grp.Controls.Add(b)
        End If
   End If
Next
End Sub

Public Function fetchInstance(ByVal fullyQualifiedClassName As String) As Object
    Dim nspc As String = fullyQualifiedClassName.Substring(0, fullyQualifiedClassName.LastIndexOf("."c))
    Dim o As Object = Nothing
    Try
        For Each ay In Assembly.GetExecutingAssembly().GetReferencedAssemblies()
            If (ay.Name = nspc) Then
                o = Assembly.Load(ay).CreateInstance(fullyQualifiedClassName)
                Exit For
            End If
        Next
    Catch
    End Try
    Return o
End Function

Body:
Ok got it to work with this;

Dim ucName As String = Projectname.UserControlName
Dim newType As Type = Type.[GetType](ucName, True, True)
Dim o As Object = Activator.CreateInstance(newType)
Form.Controls.Add(o)

Once I got this it was pretty simple! thanks for the feedback!


问:
Change height of element on resize
Hello guys I'm trying to change height of my element dynamically.
These are my variables.

```<code>var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();
</code>```

Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.

```<code>$( window ).bind("resize", function(){
    if((windowWidth - currentWidth)<6) {
        $("#line4").css('height', elementHeight-14);
    }
});
</code>```

It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.

答:
You need to get windowWidth each time resize event called
And you should add debounce into resize event for better performance.
I often do like this, maybe you can search any better way:

```<code>var resizeTimer;
$(window).on('resize', function(e) {

  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {

  // Run code here, resizing has "stopped"
  currentWidth = $(window).width()
  if((windowWidth - currentWidth)<6) {
    $("#line4").css('height', elementHeight-14);
  }

  }, 250);
});
</code>```

and I created this to test, you can try it. Btw i increase from 6 to 600 to check easier :D
https://codepen.io/huytran0605/pen/NgBEVO

Title: Change height of element on resize

Body:
Hello guys I'm trying to change height of my element dynamically.
These are my variables.

var windowWidth = 1440;
var currentWidth = $(window).width();
var elementHeight = $('#line4').height();

Now what I want is when difference between window width and current width is lower then 6 I want to change height of my element. I want to do this every time when (windowWidth - currentWidth)<6. So every time when window resizes and it's lower then 6 I want to change height of element by minus 14px. This is what I've tried.

$( window ).bind("resize", function(){
    if((windowWidth - currentWidth)<6) {
        $("#line4").css('height', elementHeight-14);
    }
});

It does not work and I don't know what I'm missing. Also follow up question can I change other CSS properties this way. For this particular problem I will also need to change css top property in the same way, because I have some div with absolute position.

Body:
You need to get windowWidth each time resize event called
And you should add debounce into resize event for better performance.
I often do like this, maybe you can search any better way:

var resizeTimer;
$(window).on('resize', function(e) {

  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(function() {

  // Run code here, resizing has "stopped"
  currentWidth = $(window).width()
  if((windowWidth - currentWidth)<6) {
    $("#line4").css('height', elementHeight-14);
  }

  }, 250);
});

and I created this to test, you can try it. Btw i increase from 6 to 600 to check easier :D
https://codepen.io/huytran0605/pen/NgBEVO


答:
A class can only inherit from one base class.

If your base class inherits from some other base class, your base class will initialize its base class, just like any other class.

Title: how to initialize all the base class objects from derived class using base keyword


问:
How to fill entity by uploading json file in symfony easyadmin bundle
i have an entity called User, and instead of filling the entity manually in easyadmin, i want to upload json file to fill the form automatically with available data,</p>

答:
Have you looked at the Serializer Component? This can serialize and deserialize entities to and from JSON amongst other formats.

https://symfony.com/doc/current/components/serializer.html


问:
Python 2 - Trying to reduce string by eliminating identical letters
Let's say given string is "aabcc". After this input is run thru my function, it should be reduced to "b", because aa and cc get eliminated. If given string is "aaabbccc", this would be reduced to "ac".

So here is my code

```<code>def super_reduced_string(s):
    for i in range(len(s)-1):
        if s[i] == s[i+1]:
            s = s.replace(s[i],'')
    return s
</code>```

It keeps throwing string index out of range error whenever I attempt to update string s each iteration s = s.replace(s[i],''). This also happens when I assign s to placeholder at the beginning.

Error

```<code>Traceback (most recent call last):
  File "solution.py", line 12, in <module>
    result = super_reduced_string(s)
  File "solution.py", line 7, in super_reduced_string
    if s[i] == s[i+1]:
IndexError: string index out of range
</code>```

Would appreciate an explanation and a fix.

Cheers

答:
The first big issue is that s.replace(s[i], '') will replace every instance of s[i] in the string with ''.Using either s = s.replace(s[i], '', 2) or s = s[:i] + s[i + 2:] which will remove the identicals. Also fredtantini is right you still go to 5 even after shortening your string and that's why using a for loop is dangerous in this case. It is safer if you want to iterate through a string and remove elements to use a while loop. </p>

```<code>def super_reduced_string(s):
  i = 0
  while i < len(s) - 1:
    if s[i] == s[i+1]:
      s = s.replace(s[i], '', 2)
    else:
      i += 1
  return s
</code>```

Body:
Let's say given string is "aabcc". After this input is run thru my function, it should be reduced to "b", because aa and cc get eliminated. If given string is "aaabbccc", this would be reduced to "ac".

So here is my code

def super_reduced_string(s):
    for i in range(len(s)-1):
        if s[i] == s[i+1]:
            s = s.replace(s[i],'')
    return s

It keeps throwing string index out of range error whenever I attempt to update string s each iteration s = s.replace(s[i],''). This also happens when I assign s to placeholder at the beginning.

Error

Traceback (most recent call last):
  File "solution.py", line 12, in <module>
    result = super_reduced_string(s)
  File "solution.py", line 7, in super_reduced_string
    if s[i] == s[i+1]:
IndexError: string index out of range

Would appreciate an explanation and a fix.

Cheers

Body:
The first big issue is that s.replace(s[i], '') will replace every instance of s[i] in the string with ''.Using either s = s.replace(s[i], '', 2) or s = s[:i] + s[i + 2:] which will remove the identicals. Also fredtantini is right you still go to 5 even after shortening your string and that's why using a for loop is dangerous in this case. It is safer if you want to iterate through a string and remove elements to use a while loop.

def super_reduced_string(s):
  i = 0
  while i < len(s) - 1:
    if s[i] == s[i+1]:
      s = s.replace(s[i], '', 2)
    else:
      i += 1
  return s


问:
Q: Rails Best Practices for database calls
Quick question. I am building out a portfolio application for an artist, currently have 9 tables of different types of projects (exhibitions, press, news, texts, photography, etc). As a visual artist, he wants his site to represent his vision.

Background:

edit: The information is loaded from the controller originally, not from an API call. I later changed it to an API call because I was worried 9 calls from the controller was too much.

This means the site is graphic and information heavy. Loading all the information just for the navigation was 15 mb (and this was after shrinking the images when needed and running them through tinypng). I put all the information off to different layout views to be rendered only when needed to keep loading times down and offset it, which helped speed everything. But this setup no matter which way resulted in 9 different database calls on each page load.

I rebuilt the back end to API endpoints, so the information is only pulled from the database when needed. This has slightly increased the load time for the information though, only like a second more if that. I'm not bothered by it, but the artist might be.

Actual Question

So I've been wondering for the past few days, is 9 database calls too much at once and how will it affect scalability? Postgres database for reference. Normal load, I cant imagine too many users will view the site on any given time, so I wouldnt be worried about it. But when he has an exhibition and there are 100-500 people using the site at once, thats 900-4500 database calls each page load. Or with the API route, people may only do 1 or 2 calls before finding what they want. I just want to follow the industry best practice for handling this situation and this seemed like a good time to ask this question.

Also, this will be hosted on heroku currently, and wondering which way (all at once or API routes) will be better for handling postgres connections since the free tier (which will be enough 95% of the time) has a limit of 20 connections. Though for months where he has a show we could bump it up to the next tier for 60 connections.

答:
What you describe doesn't sound like a dynamic website. Unless it has an admin section to modify the content, there is really little reason to keep the data in a DB or use a web "application" like Rails.

I would suggest to use a Ruby static site generator. Jekyll is the most popular one, but I recommend Middleman because it makes it very easy to migrate from Rails view templates and helpers.

If you really want to use Rails, then yours is a textbook use case for view caching. If the content is static there is no reason to load it over and over again with each page view.

Also, nine DB queries per page views doesn't mean much. It could be little or it could be a lot, it really depends on the queries.


问:
jq filter to remove duplicates by comparing objects inside
I am trying to convert JSON lines to JSON and in the process trying to find and remove duplicates by comparing values from objects.

For example:

```<code>{"headline": "sample headline 1", "title": "sample title 1", "href": "sample link 1", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag1"}
{"headline": "sample headline 2", "title": "sample title 2", "href": "sample link 2", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag2"}
{"headline": "sample headline 3", "title": "sample title 3", "href": "sample link ", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag3"}
{"headline": "sample headline 4", "title": "sample title 1", "href": "sample link 4", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag4"}
</code>```

Now I want to compare title from the first JSON line and the fourth JSON line, and if the  title is the same I want to omit one of the entries.

I have only been able to convert it to JSON and remove duplicates by comparing all objects:

```<code>jq --slurp [.[]] | unique
</code>```

but this compares all objects inside whereas I want to compare only one object and remove the entire line. How can I do that?

答:
In words:

.. to compare title from the first JSON line and the fourth JSON line, and if the title is the same I want to omit one of the entries.

In jq:

```<code>jq -s 'if .[0].title == .[3].title then del(.[0]) else . end'
</code>```

In words:

find and remove duplicates [based on .title]

In jq:

```<code>INDEX(.title) | [.[]]
</code>```

Apart from brevity, the big advantage of using INDEX/1 here (e.g. vs unique or group_by) is that it does NOT incur the cost of sorting.

(If your jq does not have INDEX then simply copy its definition from https://github.com/stedolan/jq/blob/master/src/builtin.jq )

Using the -f option

Assuming you have jq 1.5 and that the file named program.jq contains the following text:

```<code>def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);
def INDEX(idx_expr): INDEX(.[]; idx_expr);

INDEX(.title) | [.[]]
</code>```

you can invoke jq as follows:

```<code>jq -s -f program.jq input
</code>```

where "input" is the name of the file containing the JSON lines (or JSON stream).

jq 1.4

If you only have access to jq 1.4, then you could use this variant:

```<code>def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);

INDEX(.[]; .title) | [.[]]
</code>```

jq 1.3

jq 1.3 is very out-of-date but if you cannot upgrade, then for present purposes, it will suffice to use the version immediately above, replacing tojson with tostring. Or even just:

```<code>def INDEX(f): map( {(f|tostring): . } ) | add;
</code>```

Body:
I am trying to convert JSON lines to JSON and in the process trying to find and remove duplicates by comparing values from objects.

For example:

{"headline": "sample headline 1", "title": "sample title 1", "href": "sample link 1", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag1"}
{"headline": "sample headline 2", "title": "sample title 2", "href": "sample link 2", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag2"}
{"headline": "sample headline 3", "title": "sample title 3", "href": "sample link ", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag3"}
{"headline": "sample headline 4", "title": "sample title 1", "href": "sample link 4", "day": " Fri, 7 Jul 2017 , 8:30PM ", "tags": "tag4"}

Now I want to compare title from the first JSON line and the fourth JSON line, and if the  title is the same I want to omit one of the entries.

I have only been able to convert it to JSON and remove duplicates by comparing all objects:

jq --slurp [.[]] | unique

but this compares all objects inside whereas I want to compare only one object and remove the entire line. How can I do that?

Body:
In words:

.. to compare title from the first JSON line and the fourth JSON line, and if the title is the same I want to omit one of the entries.

In jq:

jq -s 'if .[0].title == .[3].title then del(.[0]) else . end'

In words:

find and remove duplicates [based on .title]

In jq:

INDEX(.title) | [.[]]

Apart from brevity, the big advantage of using INDEX/1 here (e.g. vs unique or group_by) is that it does NOT incur the cost of sorting.

(If your jq does not have INDEX then simply copy its definition from https://github.com/stedolan/jq/blob/master/src/builtin.jq )

Using the -f option

Assuming you have jq 1.5 and that the file named program.jq contains the following text:

def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);
def INDEX(idx_expr): INDEX(.[]; idx_expr);

INDEX(.title) | [.[]]

you can invoke jq as follows:

jq -s -f program.jq input

where "input" is the name of the file containing the JSON lines (or JSON stream).

jq 1.4

If you only have access to jq 1.4, then you could use this variant:

def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);

INDEX(.[]; .title) | [.[]]

jq 1.3

jq 1.3 is very out-of-date but if you cannot upgrade, then for present purposes, it will suffice to use the version immediately above, replacing tojson with tostring. Or even just:

def INDEX(f): map( {(f|tostring): . } ) | add;


问:
SharePoint error: "Cannot import Web Part"
I have a web part that I've developed, and if I manually install the web part it is fine.

However when I have packaged the web part following the instructions on this web site as a guide:
http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html

I get this error in the log files:

```<code>09/23/2008 14:13:03.67  w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       8l4d    Monitorable Error importing WebPart. Cannot import Project Filter.
09/23/2008 14:13:03.67  w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       89ku    High        Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.  Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.     at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)     at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)     at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)     at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(...
09/23/2008 14:13:03.67* w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       89ku    High        ...String eventArgument)
</code>```

The pertinent bit is:

```<code>http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.
Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.
at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
</code>```

And that's accompanied by a rather terse error message: "Cannot import web part".

I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.

Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.

Any help finding a solution is appreciated.

答:
Now I get a answer for similar problem as below:

When I try to added a new wep part to the page, then sharepoint show me a error message, tell me--Can not import my web part, this error message define in .webpart file.

So i tried to add some ohter web parts in the page , A strange quesiton appearance, some of them can be added , some of them can not be added.

After I traced the code of my web part and anaylsis them, I found the reason:

Old Code for web part ProjectInfo(my web part name) is:

```<code>namespace ProjectInfo
....
 public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part
 {
        .....
        private SPWeb _spWeb;
        private SPList _spList;
        private string _listName = "ProjectDocs";
        ......
 }
public ProjectInfo()
 {
        .....
            _spWeb = SPContext.Current.Web;
            //It show me a error here when i trace the code
            _spList = _spWeb.Lists[_listName];
        .....
 }
</code>```

Stop now, I thought that it maybe the web page init order problem. AS web page load web part control, constructrue function ProjectInfo() will be running at first. Actually, the web page havn't finish its init. by the time.

so i did a test. firstly, I put a good web in the page, it's ok . then, I try to put the web part in the page which can not be added just now. ~~ OK!! It's working ...because the page already init. finished.

Ok! I corrected my code:

```<code>   namespace ProjectInfo
    ....
     public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part
     {
            .....
            private SPWeb _spWeb;
            private SPList _spList;
            private string _listName = "ProjectDocs";
            ......
     }
    public ProjectInfo()
     {
            .....
                //Remove code in constructure function.
                //_spWeb = SPContext.Current.Web;
                //It show me a error here when i trace the code
                //_spList = _spWeb.Lists[_listName];
            .....
     }

   protected override void CreateChildControls()
        {
         ....
           base.CreateChildControls();

            _spWeb = SPContext.Current.Web;
            _spList = _spWeb.Lists[_listName];
          ....
         }
</code>```

After I test, the error message did't happed again..
  LoL ~~

Hope this explain will help you .

OwnerDisplayName: anonymous

Body:
I have a web part that I've developed, and if I manually install the web part it is fine.

However when I have packaged the web part following the instructions on this web site as a guide:
http://www.theartofsharepoint.com/2007/05/how-to-build-solution-pack-wsp.html

I get this error in the log files:

09/23/2008 14:13:03.67  w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       8l4d    Monitorable Error importing WebPart. Cannot import Project Filter.
09/23/2008 14:13:03.67  w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       89ku    High        Failed to add webpart http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.  Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.     at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)     at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)     at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)     at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(...
09/23/2008 14:13:03.67* w3wp.exe (0x1B5C)                           0x1534  Windows SharePoint Services     Web Parts                       89ku    High        ...String eventArgument)

The pertinent bit is:

http%253A%252F%252Fuk64p12%252FPWA%252F%255Fcatalogs%252Fwp%252FProjectFilter%252Ewebpart;Project%2520Filter.
Exception Microsoft.SharePoint.WebPartPages.WebPartPageUserException: Cannot import Project Filter.
at Microsoft.SharePoint.WebPartPages.WebPartImporter.CreateWebPart(Boolean clearConnections)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, Uri webPartPageUri, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartImporter.Import(SPWebPartManager manager, XmlReader reader, Boolean clearConnections, SPWeb spWeb)
at Microsoft.SharePoint.WebPartPages.WebPartQuickAdd.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)

And that's accompanied by a rather terse error message: "Cannot import web part".

I have checked and my .dll is registered as safe, it is in the GAC, the feature is activated, and the web parts appear in the web part library with all of the correct properties showing that the webpart files were read successfully.

Everything appears to be in place, yet I get that error and little explanation from SharePoint of how to resolve it.

Any help finding a solution is appreciated.

Body:
Now I get a answer for similar problem as below:

When I try to added a new wep part to the page, then sharepoint show me a error message, tell me--Can not import my web part, this error message define in .webpart file.

So i tried to add some ohter web parts in the page , A strange quesiton appearance, some of them can be added , some of them can not be added.

After I traced the code of my web part and anaylsis them, I found the reason:

Old Code for web part ProjectInfo(my web part name) is:

namespace ProjectInfo
....
 public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part
 {
        .....
        private SPWeb _spWeb;
        private SPList _spList;
        private string _listName = "ProjectDocs";
        ......
 }
public ProjectInfo()
 {
        .....
            _spWeb = SPContext.Current.Web;
            //It show me a error here when i trace the code
            _spList = _spWeb.Lists[_listName];
        .....
 }

Stop now, I thought that it maybe the web page init order problem. AS web page load web part control, constructrue function ProjectInfo() will be running at first. Actually, the web page havn't finish its init. by the time.

so i did a test. firstly, I put a good web in the page, it's ok . then, I try to put the web part in the page which can not be added just now. ~~ OK!! It's working ...because the page already init. finished.

Ok! I corrected my code:

   namespace ProjectInfo
    ....
     public class ProjectInfo:System.Web.UI.WebControls.WebParts.Web.part
     {
            .....
            private SPWeb _spWeb;
            private SPList _spList;
            private string _listName = "ProjectDocs";
            ......
     }
    public ProjectInfo()
     {
            .....
                //Remove code in constructure function.
                //_spWeb = SPContext.Current.Web;
                //It show me a error here when i trace the code
                //_spList = _spWeb.Lists[_listName];
            .....
     }

   protected override void CreateChildControls()
        {
         ....
           base.CreateChildControls();

            _spWeb = SPContext.Current.Web;
            _spList = _spWeb.Lists[_listName];
          ....
         }

After I test, the error message did't happed again..
  LoL ~~

Hope this explain will help you .


问:
Two dictionaries in python with different results
I dont understand why the same approach works for the one function and dictionary and it doesn´t for the second one, even though I just "copied" it.

```<code>allGuests = {"Alice": {"apples": 5, "pretzels": 12}, "Bob": {"ham sandwiches": 3, "apples": 2}, "Carol": {"cups": 3, "apple pies": 1}}
allCalories = {"apples": {"Calories": 100, "fat": 10}, "pretzels": {"Calories": 200, "fat": 20}, "ham sandwiches": {"Calories": 300, "fat": 30}, "cups": {"Calories": 0, "fat": 0}, "apple pies": {"Calories": 500, "fat": 50}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():

        numBrought = numBrought + v.get(item, 0)
    return numBrought

def totalCalories(dish, calories):
    cal = 0
    for k, v in dish.items():
        cal = cal + v.get(calories, 0)
    return cal

print(" Number of Things being brought: ")
print(" - Apples " + str(totalBrought(allGuests, "apples")))
print(" Calories of apples " + str(totalCalories(allCalories, "apples")))
print(" - Cups " + str(totalBrought(allGuests, "cups")))
print(" - Cakes " + str(totalBrought(allGuests, "cakes")))
print(" - Ham Sandwiches " + str(totalBrought(allGuests, "ham sandwiches")))
print(" - Apple Pies " + str(totalBrought(allGuests, "apple pies")))
</code>```

The (wrong) outcome is:

```<code>Number of Things being brought:
- Apples 7
Calories of apples 0
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1
</code>```

Can anyone explain to me why it doesn´t work? Seems like a simple logical gap by a python beginner....
Thanks in advance!

答:
Thanks for the help. I changed the namings for a better understanding (see below).
There might be more sophisticated solutions but I like to stick to the "initial" approach since I am still a beginner and dont want to skip topics and just adapt the more sophisticated ways.

```<code>allCalories = {"apples": {"Calories apples": 80, "Fat apples": 2}, "pretzels":
              {"Calories pretzels": 200, "Fat pretzels": 20},"ham sandwiches":
              {"Calories ham sandwiches": 300, "Fat ham sandwiches":30}"cups":
              {"Calories cups": 0, "Fat Cups": 0},"apple pies":
              {"Calories apple pies": 500, "Fat apple pies": 50}}
</code>```

And then for example:

```<code>print(" -> Total Calories of Apples " +
str(totalCalories(allCalories,"Calories apples")*
(totalBrought(allGuests,"apples"))))
</code>```

I also added a few other lines so the outcome now looks like this:

```<code>Number, Calories and Fat of Things being brought:
- Apples 7
-> Total Calories of Apples 560
-> Total Fat of Apples 14 Gramm
- Pretzels 12
-> Total Calories of Pretzels 2400
-> Total Fat of Pretzels 240 Gramm
- Cups 3
-> Total Calories of Cups 0
-> Total Fat of Cups 0 Gramm
- Cakes 0
-> Total Calories of Cakes 0
-> Total Fat of Cakes 0 Gramm
- Ham Sandwiches 3
-> Total Calories of Ham Sandwiches 900
-> Total Fat of Ham Sandwiches 90 Gramm
- Apple Pies 3
-> Total Calories of Apple Pies 1500
-> Total Fat of Apple Pies 150 Gramm
==>> Total Calories of Things being brought: 5360
==>> Total Fat of Things being brought: 494
</code>```

Body:
I dont understand why the same approach works for the one function and dictionary and it doesn´t for the second one, even though I just "copied" it.

allGuests = {"Alice": {"apples": 5, "pretzels": 12}, "Bob": {"ham sandwiches": 3, "apples": 2}, "Carol": {"cups": 3, "apple pies": 1}}
allCalories = {"apples": {"Calories": 100, "fat": 10}, "pretzels": {"Calories": 200, "fat": 20}, "ham sandwiches": {"Calories": 300, "fat": 30}, "cups": {"Calories": 0, "fat": 0}, "apple pies": {"Calories": 500, "fat": 50}}

def totalBrought(guests, item):
    numBrought = 0
    for k, v in guests.items():

        numBrought = numBrought + v.get(item, 0)
    return numBrought

def totalCalories(dish, calories):
    cal = 0
    for k, v in dish.items():
        cal = cal + v.get(calories, 0)
    return cal

print(" Number of Things being brought: ")
print(" - Apples " + str(totalBrought(allGuests, "apples")))
print(" Calories of apples " + str(totalCalories(allCalories, "apples")))
print(" - Cups " + str(totalBrought(allGuests, "cups")))
print(" - Cakes " + str(totalBrought(allGuests, "cakes")))
print(" - Ham Sandwiches " + str(totalBrought(allGuests, "ham sandwiches")))
print(" - Apple Pies " + str(totalBrought(allGuests, "apple pies")))

The (wrong) outcome is:

Number of Things being brought:
- Apples 7
Calories of apples 0
- Cups 3
- Cakes 0
- Ham Sandwiches 3
- Apple Pies 1

Can anyone explain to me why it doesn´t work? Seems like a simple logical gap by a python beginner....
Thanks in advance!

Body:
Thanks for the help. I changed the namings for a better understanding (see below).
There might be more sophisticated solutions but I like to stick to the "initial" approach since I am still a beginner and dont want to skip topics and just adapt the more sophisticated ways.

allCalories = {"apples": {"Calories apples": 80, "Fat apples": 2}, "pretzels":
              {"Calories pretzels": 200, "Fat pretzels": 20},"ham sandwiches":
              {"Calories ham sandwiches": 300, "Fat ham sandwiches":30}"cups":
              {"Calories cups": 0, "Fat Cups": 0},"apple pies":
              {"Calories apple pies": 500, "Fat apple pies": 50}}

And then for example:

print(" -> Total Calories of Apples " +
str(totalCalories(allCalories,"Calories apples")*
(totalBrought(allGuests,"apples"))))

I also added a few other lines so the outcome now looks like this:

Number, Calories and Fat of Things being brought:
- Apples 7
-> Total Calories of Apples 560
-> Total Fat of Apples 14 Gramm
- Pretzels 12
-> Total Calories of Pretzels 2400
-> Total Fat of Pretzels 240 Gramm
- Cups 3
-> Total Calories of Cups 0
-> Total Fat of Cups 0 Gramm
- Cakes 0
-> Total Calories of Cakes 0
-> Total Fat of Cakes 0 Gramm
- Ham Sandwiches 3
-> Total Calories of Ham Sandwiches 900
-> Total Fat of Ham Sandwiches 90 Gramm
- Apple Pies 3
-> Total Calories of Apple Pies 1500
-> Total Fat of Apple Pies 150 Gramm
==>> Total Calories of Things being brought: 5360
==>> Total Fat of Things being brought: 494


问:
javascript counting duplicates in array
Please consider this JS function

I have seen this similar question but couldn't understand.

```<code>function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)
</code>```

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.

答:
I guess the main confusion comes from this line:

```<code>counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
</code>```

The || operator returns what is on the left side if it is "truthy" (anything other than the "falsy" values false, 0, '', null, undefined, and NaN), otherwise it returns what is on the right hand side.

If ResultArray[p] is not inside of counts, then counts[ResultArray[p]] will be undefined. Since undefined + 1 is NaN, the left hand side of || is "falsy", so it will return the right hand side 1.

Otherwise, counts[ResultArray[p]] will be the amount of times we've already seen ResultArray[p], and we'll add 1 to it. In this case the left hand side will be "truthy" and it will return the new count.

Title: javascript counting duplicates in array

Body:
Please consider this JS function

I have seen this similar question but couldn't understand.

function a (ResultArray){
    var counts={};
    for ( p = 0; p < ResultArray.length; p++){
        counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;
    }
    return counts;
}

var arr = ["a","b","c","d","a","b","e"];
var res = new a(arr);
console.log(res)

Its working fine and giving the count. I need to understand  how is it giving the count, specially (counts[ResultArray[p]] + 1) || 1; part. what is +1 and || doing.

Body:
I guess the main confusion comes from this line:

counts[ResultArray[p]] = (counts[ResultArray[p]] + 1) || 1;

The || operator returns what is on the left side if it is "truthy" (anything other than the "falsy" values false, 0, '', null, undefined, and NaN), otherwise it returns what is on the right hand side.

If ResultArray[p] is not inside of counts, then counts[ResultArray[p]] will be undefined. Since undefined + 1 is NaN, the left hand side of || is "falsy", so it will return the right hand side 1.

Otherwise, counts[ResultArray[p]] will be the amount of times we've already seen ResultArray[p], and we'll add 1 to it. In this case the left hand side will be "truthy" and it will return the new count.


问:
Update nested field in BigQuery table
I am trying to perform what, you would think, is a trivial operation in BigQuery; I am trying to update a nested field in a BigQuery table that is the result of a 360 export.

Here is my query:

```<code>#standardSQL
UPDATE `dataset_name`.`ga_sessions_20170705`
SET hits.eventInfo.eventLabel = 'some string'
WHERE TRUE
</code>```

But I get this error message:

Error: Cannot access field eventInfo on a value with type ARRAY<STRUCT<item STRUCT<transactionId INT64, currencyCode STRING>, isEntrance BOOL, minute INT64, ...>> at [3:10]

How can I update this nested field?

答:
hits is an array, so you need to use an array subquery to assign to it. It would look something like this:

```<code>#standardSQL
UPDATE `dataset_name`.`ga_sessions_20170705`
SET hits =
  ARRAY(
    SELECT AS STRUCT * REPLACE(
      (SELECT AS STRUCT eventInfo.* REPLACE('some string' AS eventLabel)) AS eventInfo)
    FROM UNNEST(hits)
  )
WHERE TRUE;
</code>```

Title: Update nested field in BigQuery table

Body:
I am trying to perform what, you would think, is a trivial operation in BigQuery; I am trying to update a nested field in a BigQuery table that is the result of a 360 export.

Here is my query:

#standardSQL
UPDATE `dataset_name`.`ga_sessions_20170705`
SET hits.eventInfo.eventLabel = 'some string'
WHERE TRUE

But I get this error message:

Error: Cannot access field eventInfo on a value with type ARRAY<STRUCT<item STRUCT<transactionId INT64, currencyCode STRING>, isEntrance BOOL, minute INT64, ...>> at [3:10]

How can I update this nested field?

Body:
hits is an array, so you need to use an array subquery to assign to it. It would look something like this:

#standardSQL
UPDATE `dataset_name`.`ga_sessions_20170705`
SET hits =
  ARRAY(
    SELECT AS STRUCT * REPLACE(
      (SELECT AS STRUCT eventInfo.* REPLACE('some string' AS eventLabel)) AS eventInfo)
    FROM UNNEST(hits)
  )
WHERE TRUE;


答:
Add timeout=10 (for example) to your post call.

```<code>r = requests.post(url, proxies=proxy, data=payload, timeout=10)
</code>```

You could have answered the question yourself with e.g. help(requests.post) or by looking at the documentation.

Title: Skip an iteration if time limit exceeds PYTHON

Body:
I'm working with proxies on request library for my project.Depending on the proxy used, each request takes different (unpredictable) time.

for proxy in proxyList:
    r=requests.post(url, proxies=proxy, data=payload)

If a certain request takes more than certain time,I want to skip it and move on to the next.How can this be done?

EDIT : Using timeout parameter raises an exception.Of course,I can get my work done by Exception handling.But I wanted it in a more general sense..like what if I'm not talking about requests ..suppose there is statement whose time can't be pre-defined?! Is there any way to move on to next iteration?

Body:
Add timeout=10 (for example) to your post call.

r = requests.post(url, proxies=proxy, data=payload, timeout=10)

You could have answered the question yourself with e.g. help(requests.post) or by looking at the documentation.


问:
Convert formatted lines of delimited text into an associative array
I have a string of key->value pairs in the following colon-separated format:

```<code>MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!
</code>```

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

答:
```<code>$temp = explode("\r\n", $string);
$sets = array();
foreach ($temp as $value) {
    $array = explode(': ', $value);
    $array[1] = trim($array[1], '"');
    $sets[$array[0]] = $array[1];
}
</code>```

$string is the value you're getting from the database.

ContentLicense: CC BY-SA 4.0

Body:
I have a string of key->value pairs in the following colon-separated format:

MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

Body:
$temp = explode("\r\n", $string);
$sets = array();
foreach ($temp as $value) {
    $array = explode(': ', $value);
    $array[1] = trim($array[1], '"');
    $sets[$array[0]] = $array[1];
}

$string is the value you're getting from the database.


问:
How to tell if Spring Integration Inbound email adapter has started successfully other than assuming if no error was thrown
We're using SI for email integration and there is a requirement to set the Status of the started Adapter(s). I don't see any direct way of telling if the adapter such as Imap with poller has started without any issue other than assuming it did if no error event was thrown to the error-channel.

We've max tries in case of connection exception and then we don't know if & when it has recovered from that connection failure.

This is causing some difficulty in updating the real status of the started adapter.

thanks.

答:
You can use the Smart Poller feature.

Create a subclass of the AbstractMessageSourceAdvice. If the afterReceive() method is called, it means the operation was successful (regardless of whether or not the poll actually resulted in a message).


问:
c++ XOR between bitsets
```<code>std::bitset <1> a1;
std::bitset <1> a2;

a1 = std::bitset<1> (0);
a2 = std::bitset<1> (1);

std::bitset<1> b = (a1 ^= a2)
</code>```

This results in

```<code>b = 1
</code>```

which is fine but modifies also a1, which after the XOR operation becomes:

```<code>a1 = 1
</code>```

Why is this happening?
How can I avoid this without creating temp variables?

答:
in line : std::bitset<1> b = (a1 ^= a2) , you are using nested equation.

if u will simplyfy the rhs you will get -> a1 = a1^a2, so you are first assigning a1 = 0 xor 1 i.e. 1 and then you are assigning b with a1 that's why you are getting a1 = 1 also, along with b.

for more explanation you can refer to https://www.tutorialspoint.com/cplusplus/cpp_operators.htm (directly go to the assignment operators section.)

Title: c++ XOR between bitsets

Body:
std::bitset <1> a1;
std::bitset <1> a2;

a1 = std::bitset<1> (0);
a2 = std::bitset<1> (1);

std::bitset<1> b = (a1 ^= a2)

This results in

b = 1

which is fine but modifies also a1, which after the XOR operation becomes:

a1 = 1

Why is this happening?
How can I avoid this without creating temp variables?


问:
How to solve TS2349 in a protractor test model
I've got the following test setup, but the transpiler is giving me the following error:

Error:(108, 9) TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((opt_callback?: (value: Model1[]) => R | IThenable, opt_errback?: (error: any...' has no compatible call signatures.

// action class

```<code>export class SearchResultsActions {
    // setup and other stuff

    // Model1 and Model2 are both interfaces
    getJSON(): promise.Promise<Array<Model1>> | promise.Promise<Array<Model2>> {
        return option.getText().then((selected: string) => {
            let searchType: "model1" | "model2"  = "model1";
            if (selected === "Model 2") {
                searchType = "model2";
            }

            // getResultsEl returns an ElementArrayFinder
            return ResultsPage.getResultsEl().map((el, index) => {
                let pageObject: Model1PageObject | Model2PageObject = SearchPage.getResult(searchType, index);
                let actionObject: Model1Actions | Model2Actions;

                if (searchType === "model1") {
                    actionObject = new Model1Actions(<Model1PageObject> pageObject);
                } else {
                    actionObject = new Model2Actions(<Model2PageObject> pageObject)
                }

                // both Model1Actions and Model2Actions have a getJSON() method
                return actionObject.getJSON(); // returns a JSON object
            });
        });
    }
}
</code>```

In the search spec where the error is:

```<code>SearchResultsActions.getJSON()
    .then((res: Array<Model1> | Array<Model2>) => {
        // use lodash to perform equality
        expect(_.isEqual(res, expected)).toBeTruthy();
    });
</code>```

The curious thing is, despite the error, the transpile works anyway and the tests pass.  But I would like to not have the error blaring at me.

I'm using typescript 2.3.3, protractor 5.1.2

Any thoughts?  Anywhere I can clarify?

答:
The answer is to change the return type to

```<code>promise.Promise<Array<Model1> | Array<Model2>>
</code>```

which is different from

```<code>promise.Promise<Array<Model1>> | promise.Promise<Array<Model2>>
</code>```

which doesn't work.

Apparently this is true for Observables as well.

Body:
I've got the following test setup, but the transpiler is giving me the following error:

Error:(108, 9) TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((opt_callback?: (value: Model1[]) => R | IThenable, opt_errback?: (error: any...' has no compatible call signatures.

// action class

export class SearchResultsActions {
    // setup and other stuff

    // Model1 and Model2 are both interfaces
    getJSON(): promise.Promise<Array<Model1>> | promise.Promise<Array<Model2>> {
        return option.getText().then((selected: string) => {
            let searchType: "model1" | "model2"  = "model1";
            if (selected === "Model 2") {
                searchType = "model2";
            }

            // getResultsEl returns an ElementArrayFinder
            return ResultsPage.getResultsEl().map((el, index) => {
                let pageObject: Model1PageObject | Model2PageObject = SearchPage.getResult(searchType, index);
                let actionObject: Model1Actions | Model2Actions;

                if (searchType === "model1") {
                    actionObject = new Model1Actions(<Model1PageObject> pageObject);
                } else {
                    actionObject = new Model2Actions(<Model2PageObject> pageObject)
                }

                // both Model1Actions and Model2Actions have a getJSON() method
                return actionObject.getJSON(); // returns a JSON object
            });
        });
    }
}

In the search spec where the error is:

SearchResultsActions.getJSON()
    .then((res: Array<Model1> | Array<Model2>) => {
        // use lodash to perform equality
        expect(_.isEqual(res, expected)).toBeTruthy();
    });

The curious thing is, despite the error, the transpile works anyway and the tests pass.  But I would like to not have the error blaring at me.

I'm using typescript 2.3.3, protractor 5.1.2

Any thoughts?  Anywhere I can clarify?

Body:
The answer is to change the return type to

promise.Promise<Array<Model1> | Array<Model2>>

which is different from

promise.Promise<Array<Model1>> | promise.Promise<Array<Model2>>

which doesn't work.

Apparently this is true for Observables as well.


问:
How to interpret vector angles for the 'shape' package?
I'm trying to figure out whether some vector angles I'm using are correctly calculated.

I have a simulated particle track with data like this:

```<code>   track_id       track_length frame          x         y         dx           dy steplength   direction
     <fctr>             <fctr> <dbl>      <dbl>     <dbl>      <dbl>        <dbl>      <dbl>       <dbl>
 1  Track 1 Track length:  464     0 -0.2779444 0.6532534  0.0000000  0.000000000  0.0000000   0.0000000
 2  Track 1 Track length:  464     1  0.9527568 1.6890017  1.2307012  1.035748375  1.6085398  40.0836991
 3  Track 1 Track length:  464     2  3.1617740 1.5406508  2.2090172 -0.148350899  2.2139930  -3.8420418
 4  Track 1 Track length:  464     3  3.4791213 1.1602548  0.3173472 -0.380396044  0.4953892 -50.1632825
 5  Track 1 Track length:  464     4  3.0130556 1.7207842 -0.4660657  0.560529394  0.7289790 129.7426481
 6  Track 1 Track length:  464     5  4.1270750 1.7163850  1.1140194 -0.004399235  1.1140281  -0.2262584
 7  Track 1 Track length:  464     6  3.5344773 2.2045875 -0.5925977  0.488202537  0.7677980 140.5171189
 8  Track 1 Track length:  464     7  1.8244100 2.3753219 -1.7100673  0.170734431  1.7185693 174.2984400
 9  Track 1 Track length:  464     8  3.2462738 1.7072696  1.4218637 -0.668052374  1.5709839 -25.1661450
10  Track 1 Track length:  464     9  2.0981822 2.1773816 -1.1480916  0.470112097  1.2406126 157.7322425
</code>```

The direction column is calculated like so:

direction  = (180/pi)*(atan2(dy, dx)))

And this gives me an angle for the vector of every point in a [-180, 180] degree format. I checked with ggplot's arrow feature and the angles appear to be correct. So far so good.

Now, I want to plot the vector directions for every xy-bin using a combination of raster and shape packages. In particular, I'm having trouble with interpretation of the Arrowhead() function's documentation, which says:

angle: angle of arrowhead (anti-clockwise, relative to x-axis), in degrees [0,360]; either one value or a vector.

It takes my "unconverted" values though. Does that mean they're correct? Or do they need to be formatted? How do I go from [-180, 180] to [0, 360]?

答:
Just change angle domain like this:</p>

```<code>if (angle < 0)
    angle = angle + 360
</code>```

Body:
I'm trying to figure out whether some vector angles I'm using are correctly calculated.

I have a simulated particle track with data like this:

   track_id       track_length frame          x         y         dx           dy steplength   direction
     <fctr>             <fctr> <dbl>      <dbl>     <dbl>      <dbl>        <dbl>      <dbl>       <dbl>
 1  Track 1 Track length:  464     0 -0.2779444 0.6532534  0.0000000  0.000000000  0.0000000   0.0000000
 2  Track 1 Track length:  464     1  0.9527568 1.6890017  1.2307012  1.035748375  1.6085398  40.0836991
 3  Track 1 Track length:  464     2  3.1617740 1.5406508  2.2090172 -0.148350899  2.2139930  -3.8420418
 4  Track 1 Track length:  464     3  3.4791213 1.1602548  0.3173472 -0.380396044  0.4953892 -50.1632825
 5  Track 1 Track length:  464     4  3.0130556 1.7207842 -0.4660657  0.560529394  0.7289790 129.7426481
 6  Track 1 Track length:  464     5  4.1270750 1.7163850  1.1140194 -0.004399235  1.1140281  -0.2262584
 7  Track 1 Track length:  464     6  3.5344773 2.2045875 -0.5925977  0.488202537  0.7677980 140.5171189
 8  Track 1 Track length:  464     7  1.8244100 2.3753219 -1.7100673  0.170734431  1.7185693 174.2984400
 9  Track 1 Track length:  464     8  3.2462738 1.7072696  1.4218637 -0.668052374  1.5709839 -25.1661450
10  Track 1 Track length:  464     9  2.0981822 2.1773816 -1.1480916  0.470112097  1.2406126 157.7322425

The direction column is calculated like so:

direction  = (180/pi)*(atan2(dy, dx)))

And this gives me an angle for the vector of every point in a [-180, 180] degree format. I checked with ggplot's arrow feature and the angles appear to be correct. So far so good.

Now, I want to plot the vector directions for every xy-bin using a combination of raster and shape packages. In particular, I'm having trouble with interpretation of the Arrowhead() function's documentation, which says:

angle: angle of arrowhead (anti-clockwise, relative to x-axis), in degrees [0,360]; either one value or a vector.

It takes my "unconverted" values though. Does that mean they're correct? Or do they need to be formatted? How do I go from [-180, 180] to [0, 360]?

Body:
Just change angle domain like this:

if (angle < 0)
    angle = angle + 360


问:
excel, VBA, duplicate values
I have a large spreadsheet I was asked to edit. Basically wherever the data was pulled from, it created several duplicates of individuals names, country, start dates, and end dates. Would it be possible to get the start and stop dates in adjacent cells and remove the duplicate data?

I have provided a screen shot. Manually copying, pasting, and deleting would take a very long time since this spreadsheet has over 2300 rows with approximately 50% being duplicates that will need edited.

thanks

答:
Using SQL is suitable.</p>

```<code>Sub myQuery()
    Dim strSQL  As String
    Dim strTable As String
    Dim Ws As Worksheet

    strTable = "[" & ActiveSheet.Name & "$]"

    strSQL = "SELECT NAME, COUNTRY, MIN([Start Date]) as [Start Date] , max([End Date]) as [End Date] "
    strSQL = strSQL & " FROM " & strTable & " "
    strSQL = strSQL & " Where not isnull(NAME) "
    strSQL = strSQL & " Group by NAME, COUNTRY "

    Set Ws = Sheets.Add

    exeSQL strSQL, Ws

End Sub

Sub exeSQL(strSQL As String, Ws As Worksheet)

    Dim Rs As Object
    Dim strConn As String
    Dim i As Integer

    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & ThisWorkbook.FullName & ";" & _
            "Extended Properties=Excel 12.0;"

    Set Rs = CreateObject("ADODB.Recordset")
    Rs.Open strSQL, strConn

    If Not Rs.EOF Then
         With Ws
            .Range("a1").CurrentRegion.ClearContents
            For i = 0 To Rs.Fields.Count - 1
               .Cells(1, i + 1).Value = Rs.Fields(i).Name
            Next
            .Range("a" & 2).CopyFromRecordset Rs
            .Columns.AutoFit
        End With
    End If
    Rs.Close
    Set Rs = Nothing
End Sub
</code>```

Title: excel, VBA, duplicate values

Body:
Using SQL is suitable.

Sub myQuery()
    Dim strSQL  As String
    Dim strTable As String
    Dim Ws As Worksheet

    strTable = "[" & ActiveSheet.Name & "$]"

    strSQL = "SELECT NAME, COUNTRY, MIN([Start Date]) as [Start Date] , max([End Date]) as [End Date] "
    strSQL = strSQL & " FROM " & strTable & " "
    strSQL = strSQL & " Where not isnull(NAME) "
    strSQL = strSQL & " Group by NAME, COUNTRY "

    Set Ws = Sheets.Add

    exeSQL strSQL, Ws

End Sub

Sub exeSQL(strSQL As String, Ws As Worksheet)

    Dim Rs As Object
    Dim strConn As String
    Dim i As Integer

    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & ThisWorkbook.FullName & ";" & _
            "Extended Properties=Excel 12.0;"

    Set Rs = CreateObject("ADODB.Recordset")
    Rs.Open strSQL, strConn

    If Not Rs.EOF Then
         With Ws
            .Range("a1").CurrentRegion.ClearContents
            For i = 0 To Rs.Fields.Count - 1
               .Cells(1, i + 1).Value = Rs.Fields(i).Name
            Next
            .Range("a" & 2).CopyFromRecordset Rs
            .Columns.AutoFit
        End With
    End If
    Rs.Close
    Set Rs = Nothing
End Sub


问:
How do I transform appsettings.json in a .NET Core MVC project?
I've added additional json config files to my project

```<code>appsettings.DEV.json
appsettings.QA.json
</code>```

and loaded them in the Startup function based on the environment:

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    ...
</code>```

And I understand how to change the environment: modify the value of the ASPNETCORE_ENVIRONMENT environment variable in project properties. However, there does not appear to be the ability to specify different environment variables depending on the configuration, the dropdownlist is labeled "N/A" and disabled.

The only option I see is to manually change the environment variable value, to change which appsettings are used. I'm sure there is a way to do it automatically, or else how would you ever use CI? (other than using a script to change the environment variable, there has to be an easier way).

The goal here is to setup automated builds and continuous integration  for three environments: DEV, QA, and PROD. DEV and QA are on the same machine, so setting the environment variable that specifies the environment manually is not an option.

答:
Determine EnvironmentName from Build Type

For anybody that would like to set the EnvironmentName based on the build type, there is the handy .UseEnvironment(environmentName) on WebHostBuilder (found in Program Main).

As long as the appropriate compilation symbols are set against the build configurations in your project, you can do something like this to determine the EnvironmentName:

```<code>public static void Main(string[] args)
{
    string environmentName;
#if DEBUG
    environmentName = "Development";
#elif STAGING
    environmentName = "Staging";
#elif RELEASE
    environmentName = "Production";
#endif

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseEnvironment(environmentName)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}
</code>```

Body:
I've added additional json config files to my project

appsettings.DEV.json
appsettings.QA.json

and loaded them in the Startup function based on the environment:

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    ...

And I understand how to change the environment: modify the value of the ASPNETCORE_ENVIRONMENT environment variable in project properties. However, there does not appear to be the ability to specify different environment variables depending on the configuration, the dropdownlist is labeled "N/A" and disabled.

The only option I see is to manually change the environment variable value, to change which appsettings are used. I'm sure there is a way to do it automatically, or else how would you ever use CI? (other than using a script to change the environment variable, there has to be an easier way).

The goal here is to setup automated builds and continuous integration  for three environments: DEV, QA, and PROD. DEV and QA are on the same machine, so setting the environment variable that specifies the environment manually is not an option.

Body:
Determine EnvironmentName from Build Type

For anybody that would like to set the EnvironmentName based on the build type, there is the handy .UseEnvironment(environmentName) on WebHostBuilder (found in Program Main).

As long as the appropriate compilation symbols are set against the build configurations in your project, you can do something like this to determine the EnvironmentName:

public static void Main(string[] args)
{
    string environmentName;
#if DEBUG
    environmentName = "Development";
#elif STAGING
    environmentName = "Staging";
#elif RELEASE
    environmentName = "Production";
#endif

    var host = new WebHostBuilder()
        .UseKestrel()
        .UseEnvironment(environmentName)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}