问:
CocoaPods - A custom dynamic framework - cannot get the latest version of frameworks
My project in Xcode consist of static frameworks and one custom dynamic framework. This dynamic framework includes some other static frameworks.
When I try to compile the custom dynamic framework itself, everything is fine. I was able to force to install latest version of frameworks (Alamofire, Realm, etc..) by forcing the pod definition file

```<code>platform :ios, '9.0'
</code>```

But when I compile my project even when I use the above line, I am getting the old frameworks.
When I try to force the pods for a explicit version,

```<code>pod 'Alamofire', '~> 4.4.0'
</code>```

getting the version 3.5.1.
Is there any other explicit setting to force CocoaPods to be more accurate in versions?
Originally the project for the dynamic framework was made for the Swift  version 2.3, which is actually requiring the version of Alamofire 3.5.1.

Any help will be appreciated.

答:
The solution is kinda tricky. I haven't realise in the beginning that the pods under a dynamic framework cannot actually be executed directly from top project and there is a configuration JSON file, which actually is managing the pods under the dynamic framework.
So the pod versions were actually hardcoded there.</p>

Body:
My project in Xcode consist of static frameworks and one custom dynamic framework. This dynamic framework includes some other static frameworks.
When I try to compile the custom dynamic framework itself, everything is fine. I was able to force to install latest version of frameworks (Alamofire, Realm, etc..) by forcing the pod definition file

platform :ios, '9.0'

But when I compile my project even when I use the above line, I am getting the old frameworks.
When I try to force the pods for a explicit version,

pod 'Alamofire', '~> 4.4.0'

getting the version 3.5.1.
Is there any other explicit setting to force CocoaPods to be more accurate in versions?
Originally the project for the dynamic framework was made for the Swift  version 2.3, which is actually requiring the version of Alamofire 3.5.1.

Any help will be appreciated.


来源: stackexchange

问:
Process n objects each time by condition
I have next object struct:

```<code>{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}
</code>```

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

```<code>chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;
</code>```

}

答:
Here is a skeleton of what you will need. I tried to name the functions and variables in a way that it could be self explaining.

'use strict';

let toProcess = {
 '1698452536': { url: "1", isProcessed: false },
 '1701673991': { url: "2", isProcessed: false },
 '1717724454': { url: "3", isProcessed: false },
 '1756233961': { url: "4", isProcessed: false },
 '1797093325': { url: "5", isProcessed: false },
 '1857721095': { url: "6", isProcessed: false },
 '2095153396': { url: "7", isProcessed: false },
 '2098466246': { url: "8", isProcessed: false },
 '2131427779': { url: "9", isProcessed: false },
 '89975': { url: "10", isProcessed: false },
 '21591836': { url: "11", isProcessed: false },
 '80794211': { url: "12", isProcessed: false },
 '116460496': { url: "13", isProcessed: false },
 '159798435': { url: "14", isProcessed: false },
 '223366448': { url: "15", isProcessed: false },
 '361352239': { url: "16", isProcessed: false },
 '498790092': { url: "17", isProcessed: false },
 '508072650': { url: "18", isProcessed: false },
 '514973525': { url: "19", isProcessed: false },
 '560440401': { url: "20", isProcessed: false }
};

let howManyItemsInConcurrency = 5;
stackProcessing(toProcess, howManyItemsInConcurrency);

function stackProcessing(stack, concurrency){
 let objsToProcess = Object.keys(stack).filter(objKey => !stack[objKey].isProcessed).slice(0, concurrency);
 if(!objsToProcess.length){
  return console.log('Finish!');
 }

 let objsBeingProcessed = objsToProcess.map(objKey => objProcessing(stack[objKey]));
 Promise.all(objsBeingProcessed)
  .then(result => {
   console.log('result', result);
   stackProcessing(stack, concurrency);
  });
}

function objProcessing(obj){
 console.log(`Processing URL: ${obj.url}`);
 return new Promise((resolve, reject) => {
  // Simulating some async processing happening
  setTimeout(() => {
   obj.isProcessed = true;
   resolve(obj);
  }, 1000);
 });
}```

ContentLicense: CC BY-SA 3.0

Body:
I have next object struct:

{
1698452536:Object {url: "1", isProcessed: false}
1701673991:Object {url: "2", isProcessed: false}
1717724454:Object {url: "3", isProcessed: false}
1756233961:Object {url: "4", isProcessed: false}
1797093325:Object {url: "5", isProcessed: false}
1857721095:Object {url: "6", isProcessed: false}
2095153396:Object {url: "7", isProcessed: false}
2098466246:Object {url: "8", isProcessed: false}
2131427779:Object {url: "9", isProcessed: false}
89975:Object {url: "10", isProcessed: false}
21591836:Object {url: "11", isProcessed: false}
80794211:Object {url: "12", isProcessed: false}
116460496:Object {url: "13", isProcessed: false}
159798435:Object {url: "14", isProcessed: false}
223366448:Object {url: "15", isProcessed: false}
361352239:Object {url: "16", isProcessed: false}
498790092:Object {url: "17", isProcessed: false}
508072650:Object {url: "18", isProcessed: false}
514973525:Object {url: "19", isProcessed: false}
560440401:Object {url: "20", isProcessed: false}
}

I need to process five inner objects each time and only after first five is completed take another five.
Is there is a way to do such implementation?

UPDATE:

I`d tried next code in order to transform object to chunked array, but how to call bulk by bulk async and only after full bulk is succeed take another?

chunkArray(Object.values(images),5).forEach((array)=>{});
function chunkArray(array, groupsize) {
var sets = [],
    chunks, i = 0;
chunks = array.length / groupsize;

while (i < chunks) {
    sets[i] = array.splice(0, groupsize);
    i++;
}
return sets;

}


问:
Plot two histograms from DataFrame on the same graph, specifieng axises
I have a DataFrame  df

```<code>    A           B
H
8   0.899160    1
9   41.659693   7
10  336.414450  20
11  8.442857    3
12  0.848837    1
13  3.298130    2
14  3.447251    2
15  7.667236    3
17  0.831579    1
16  0.000000    0
</code>```

I want to plot 2 histograms on one plot, so H - is the x axis and A with B - y axis.
Whatever i try, e.g.:

```<code>x = delivered['A']
y = delivered['B']
fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='hist', ax=ax)
y.plot(kind='hist', ax=ax, color='red')
</code>```

or

```<code>p = df.plot(kind='hist', x=['H'])
</code>```

plots histograms with B as an x-axis. But i need my H{8,9,10,11,12,13,14,15,16,17} to be the x axis!

答: As @jrjc said, the problem was in that i've chosen the wrong type of graph!. As i had already counted the charecteristics for each observation, "bar" graph is needed. "hist" graph is suitable for cases, when i have plenty of rows for each observation. </p>

Body:
I have a DataFrame  df

    A           B
H
8   0.899160    1
9   41.659693   7
10  336.414450  20
11  8.442857    3
12  0.848837    1
13  3.298130    2
14  3.447251    2
15  7.667236    3
17  0.831579    1
16  0.000000    0

I want to plot 2 histograms on one plot, so H - is the x axis and A with B - y axis.
Whatever i try, e.g.:

x = delivered['A']
y = delivered['B']
fig = plt.figure()
ax = fig.add_subplot(111)
x.plot(kind='hist', ax=ax)
y.plot(kind='hist', ax=ax, color='red')

or

p = df.plot(kind='hist', x=['H'])

plots histograms with B as an x-axis. But i need my H{8,9,10,11,12,13,14,15,16,17} to be the x axis!


问:
How to remove common objects from two lists with linq

Both lists have Objects with ID and Name properties.

List1({1, apple}, {2, orange}, {3, banana}, {4, potato}, {5, tomato})

List2({1, apple}, {2, orange}, {3, banana})

Final output List3({4, potato}, {5, tomato})

答:
```<code>IEnumerable<T> list3 = list1.Except(list2);
</code>```

This works if your objects in the two lists are the same (the same object reference). If they are only equal, but not the same, consider overriding the Equals operator of the type of the objects in your sets, or use an alternative LINQ expression, such as

```<code>IEnumerable<TypeWithId> set3 = set1.Where((item) => !set2.Any((item2) => item.id==item2.id));
</code>```

Body:
IEnumerable<T> list3 = list1.Except(list2);

This works if your objects in the two lists are the same (the same object reference). If they are only equal, but not the same, consider overriding the Equals operator of the type of the objects in your sets, or use an alternative LINQ expression, such as

IEnumerable<TypeWithId> set3 = set1.Where((item) => !set2.Any((item2) => item.id==item2.id));


问:
Behaviour of Table.getNumberOfRows()
The iText Table.getNumberofRows() fn returns the number of rows in a table, and generally works as expected. If the last row only contains a partial number of Cells it still counts as a row, which makes sense. However if it doesn't contain any cells, I don't think that's a row, so it shouldn't count. Unfortunately it does. For example, when a Table is first created, getNumRows() returns 1 rather than 0. (This is because in its constructor it (sensibly) calls an init fn which prepares an empty row.)

Now, if you add a full line of cells to the table, getNumRows() still returns 1, so you can't tell an empty table from a valid one-liner. A workaround is to call startNewRow() after each line of cells is added, and handle the consequence that getNumRows() will be one too big. On 7.0.2, though, this workaround has started generating a warning message about Last row is not completed. Table bottom border may collapse as you do not expect it. It's not wrong, but it looks bad.

Could you update iText to treat a row with no cells as no row at all?

答:
Vernon.

I believe you can use table.isEmpty() to check whether Table has some children (cells) or not. If the result is true, the row exists indeed.

But fortunately (thanks for your suggestions) we've fixed the problem (see 7.0.3-SNAPSHOT). Now Table will have empty row list until one adds a cell. So the result of table.getNumberOfRows() will be correct.

Title: Behaviour of Table.getNumberOfRows()


问:
machine learning - svm feature fusion techique
for my final thesis i am trying to build up an 3d face recognition system by combining color and depth information. the first step i did, is to realign the data-head to an given model-head using the iterative closest point algorithm. for the detection step i was thinking about using the libsvm. but i dont understand how to combine the depth and the color information to one feature vector? they are dependent information (each point consist of color (RGB), depth information and also scan quality).. what do you suggest to do? something like weighting?

edit:
last night i read an article about SURF/SIFT features i would like to use them! could it work? the concept would be the following: extracting this features out of the color image and the depth image (range image), using each feature as a single feature vector for the svm?

答:
As mentioned by others, the easiest approach is to simply combine the two sets of features into one.

SVM is characterized by the normal to the maximum-margin hyperplane, where its components specify the weights/importance of the features, such that higher absolute values have a larger impact on the decision function. Thus SVM assigns weights to each feature all on its own.

In order for this to work, obviously you would have to normalize all the attributes to have the same scale (say transform all features to be in the range [-1,1] or [0,1])

ContentLicense: CC BY-SA 2.5


问:
JAXRS Asynchronous Services
Here's a sample code from Jersey docs for Asynchronous Services:

```<code>@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}
</code>```

Considering that container is already in charge of releasing the connection handling thread back to the pool and handing the request processing to a worker thread, I'm wondering why we still need to spawn a new thread programmatically? Shouldn't this be just a matter of container configuration (setting number of worker threads)?

答:
There is no need to spwan a new thread like this. If you are in an JavaEE environment you can simply place an @Asynchronous annotation to your method:

```<code>@GET
@Asynchronous
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
        String result = veryExpensiveOperation();
        asyncResponse.resume(result);
}
</code>```

I you need extended thread pooling you can also have a look at ManagedExecutorService.

Title: JAXRS Asynchronous Services

Body:
Here's a sample code from Jersey docs for Asynchronous Services:

@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}

Considering that container is already in charge of releasing the connection handling thread back to the pool and handing the request processing to a worker thread, I'm wondering why we still need to spawn a new thread programmatically? Shouldn't this be just a matter of container configuration (setting number of worker threads)?

Body:
There is no need to spwan a new thread like this. If you are in an JavaEE environment you can simply place an @Asynchronous annotation to your method:

@GET
@Asynchronous
public void asyncGet(@Suspended final AsyncResponse asyncResponse) {
        String result = veryExpensiveOperation();
        asyncResponse.resume(result);
}

I you need extended thread pooling you can also have a look at ManagedExecutorService.


问:
How to prevent a CheckBox from being checked?
I would like to be able to prevent a CheckBox from being selected (or to set it back to unselected), when the CheckBox is clicked

How can I achieve this?

I do not want to simply disable the checkbox. I want the user to think it is checkable, but when the user tries to check it... then I will (possibly) prevent the checkbox from being checked and display a message.

答:
Just set it to never being clicked</p>

```<code>cb.setClickable(false);
</code>```

Body:
Just set it to never being clicked

cb.setClickable(false);


问:
Save "object without data" pointer in Parse Cloud Code
Is it possible to save "empty" objects in an object to save the reference without having to fetch the full objects before ?

I'm doing this :

```<code>var myObject = new MyObject();
myObject.id = "id I retrieved somewhere on my client device"

// later
var user = request.user;
user.set("key", myObject);
</code>```

But it's not working, it's saying "Cannot create a pointer to an unsaved ParseObject"

答:
I think createWithoutData method is what you're looking for. So in your case it'll be something like:

```<code> var ClassOfMyObject = Parse.Object.extend("ClassOfMyObject");
 var myObject = ClassOfMyObject.createWithoutData("myObjectId");

 // later
 var user = request.user;
 user.set("key", myObject);
</code>```

Hope this answer your question.

Body:
Is it possible to save "empty" objects in an object to save the reference without having to fetch the full objects before ?

I'm doing this :

var myObject = new MyObject();
myObject.id = "id I retrieved somewhere on my client device"

// later
var user = request.user;
user.set("key", myObject);

But it's not working, it's saying "Cannot create a pointer to an unsaved ParseObject"

Body:
I think createWithoutData method is what you're looking for. So in your case it'll be something like:

 var ClassOfMyObject = Parse.Object.extend("ClassOfMyObject");
 var myObject = ClassOfMyObject.createWithoutData("myObjectId");

 // later
 var user = request.user;
 user.set("key", myObject);

Hope this answer your question.

ContentLicense: CC BY-SA 4.0


问:
difference # and {} or nohing in item on SASS
```<code>$list: (orange, purple, teal);

//Add your each-loop here
@each $item in $list {
  .{$item} {
    background: $item;
  }
}
</code>```

$list: (orange, purple, teal);

```<code>//Add your each-loop here
@each $item in $list {
  .$item {
    background: $item;
  }
}
</code>```

$list: (orange, purple, teal);

```<code>//Add your each-loop here
@each $item in $list {
  .#{$item} {
    background: $item;
  }
}
</code>```

I am new to SASS,when I practising this all gave me same result.What is difference between them?# {} or nothing why we just use nothing

答: Only $item when you don't want to add anything more. SASS use #{} to separate  its code from CSS. So if you want to select a class you need .#{$item}.

Body:
$list: (orange, purple, teal);

//Add your each-loop here
@each $item in $list {
  .{$item} {
    background: $item;
  }
}

$list: (orange, purple, teal);

//Add your each-loop here
@each $item in $list {
  .$item {
    background: $item;
  }
}

$list: (orange, purple, teal);

//Add your each-loop here
@each $item in $list {
  .#{$item} {
    background: $item;
  }
}

I am new to SASS,when I practising this all gave me same result.What is difference between them?# {} or nothing why we just use nothing


问:
How to count how many times delete_if has acted?
I have a code block like this:

```<code>hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo')}
</code>```

There is a simple way to count how many times the delete_if has actually acted ?

答:
counter

Since every integer is truthy, you could write :

```<code>count = 0
hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo') && count += 1}
</code>```

cell will be deleted every time count is incremented, and count is incremented every time cell["id"]["name"] == ('foo').

As an example :

```<code>count = 0
true  && count += 1
false && count += 1
true  && count += 1
false && count += 1
true  && count += 1

count
# 3
</code>```

difference

Since delete_if is destructive, you can simply compare the size difference before and after the method call.

```<code>original_size = hash["value"].size
hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo') && count += 1}
original_size - hash["value"].size
</code>```

partition

If you need not only the number of times delete_if has acted, but for which elements, you could use partition :

```<code>deleted, hash["value"] = hash["value"].partition{|cell| cell["id"]["name"] == ('foo')}
deleted.size
# deleted contains the deleted cells from `hash['value']`
</code>```

Body:
I have a code block like this:

hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo')}

There is a simple way to count how many times the delete_if has actually acted ?

Body:
counter

Since every integer is truthy, you could write :

count = 0
hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo') && count += 1}

cell will be deleted every time count is incremented, and count is incremented every time cell["id"]["name"] == ('foo').

As an example :

count = 0
true  && count += 1
false && count += 1
true  && count += 1
false && count += 1
true  && count += 1

count
# 3

difference

Since delete_if is destructive, you can simply compare the size difference before and after the method call.

original_size = hash["value"].size
hash["value"].delete_if{|cell| cell["id"]["name"] == ('foo') && count += 1}
original_size - hash["value"].size

partition

If you need not only the number of times delete_if has acted, but for which elements, you could use partition :

deleted, hash["value"] = hash["value"].partition{|cell| cell["id"]["name"] == ('foo')}
deleted.size
# deleted contains the deleted cells from `hash['value']`


问:
strcat segmentation fault
The second call to strcat here is generating a segmentation fault, why?

```<code>#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}
</code>```

答:
strcat is generally unsafe because it can happily overrun buffers, like it does in your case.

First of all, whitespaceseparator is only two bytes large? Are you sure that's what you want? And you concatenate pidstring to it? I think you got the arguments mixed up.

In general though, strcat will cause hard-to-debug crashes if you're not very careful with your buffer sizes. There are safer alternatives.

Title: strcat segmentation fault

Body:
The second call to strcat here is generating a segmentation fault, why?

#include <unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int main (int argc, char * argv[])
{
         char command[250];

         //if(scanf("%199s", command) == 1)

            gets(command);
            puts(command);

         int pipeIntId;

         char whitespaceseparator[2]=" ";

         char pidstring [30];

         int pid= getpid();

         sprintf(pidstring,"%d", pid);

         char * whitespace_and_pid;

         whitespace_and_pid = strcat(whitespaceseparator,pidstring);

         char * command_and_pid;

         command_and_pid=strcat(command,whitespace_and_pid); // here's the problem, I guess

          if((mkfifo("pipe"/*pipeName*/,0666))==-1)
          {
              perror("error creating pipe 1");
          exit(1);
          }

         if((pipeIntId=open("pipe",/*pipeName*/O_WRONLY))==-1)
         {
          perror("error creating pipe 2");
          exit(1);
         }

         int written;

         written=write(pipeIntId,command_and_pid,250); // send the command + the pid

         close(pipeIntId);

    return 0;
}


问:
d3 line does not draw
I've a problem here. The d3.line() is not showing any lines based on the data provided.

I've tried to print out the values via console.log and it fits the scale. I've checked this link about the scaling issue.

I followed this page but modified it to suit the data given to me. I was wondering if the modifications made broke the code.

Thank you!

Here is my code:

```<code>var svg = d3.select("#line-graph"),
margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleLinear().rangeRound([0, width]);
var y = d3.scaleLinear().rangeRound([height, 0]);

var line = d3.line()
   .x(function(d, i) { console.log(i); return i; })
   .y(function(d) { console.log(d); return d; });

d3.json("Data2.json", function(data) {
    x.domain([0, data.length]);
    y.domain(d3.extent(data, function(d1) { return d1.week; }));

    var arrWeek = function(data1) {
    var arr = [];
    for (var i = 0; i < data1.length; i++)
        arr.push(data1[i].week);
    return arr;
    }

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .select(".domain");

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("No. of commits");

    g.append("path")
        .datum(arrWeek(data))
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line);
    });
</code>```

EDIT: The graph just displays the values scale without any line drawn for the data.

EDIT 2: My apologies. I'm using d3.v4.min.js. As for Data2.json, here are 2 elements as it is quite long:

```<code>[
 {
"days": [
  0,
  0,
  0,
  0,
  0,
  1,
  0
],
"total": 1,
"week": 1457827200
},
{
"days": [
  0,
  0,
  0,
  1,
  0,
  3,
  1
],
"total": 5,
"week": 1458432000
}
]
</code>```

EDIT 3: I'm drawing only the "week" variable, hence the scale would be [0, Data2.length] for x-axis. Hope it clears some doubt.

答:
You have to use your scales in the line generator:

```<code>var line = d3.line()
    .x(function(d, i) {
        return x(i);
    //scale ---^
    })
    .y(function(d) {
        return y(d);
    //scale ---^
    });
</code>```

It may not be your case, but this error normally occurs because people mistake the x and y in the line generator for the x and y in the scales names. That's why it's always a good practice to give meaningful names for your variables and objects: xScale, yScale, xAxis, yAxis etc...

Besides that, when you say...

I've tried to print out the values via console.log and it fits the scale

... this is not accurate. Those are simply the data values, not related to the SVG coordinates system (unless you use your scales).

Here is your working code:

var svg = d3.select("svg"),
margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = [
 {
"days": [
  0,
  0,
  0,
  0,
  0,
  1,
  0
],
"total": 1,
"week": 1457827200
},
{
"days": [
  0,
  0,
  0,
  1,
  0,
  3,
  1
],
"total": 5,
"week": 1458432000
}
];

var x = d3.scaleLinear().rangeRound([0, width]);
var y = d3.scaleLinear().rangeRound([height, 0]);

var line = d3.line()
   .x(function(d, i) {  return x(i); })
   .y(function(d) { return y(d); });

    x.domain([0, data.length]);
    y.domain(d3.extent(data, function(d1) { return d1.week; }));

    var arrWeek = function(data1) {
    var arr = [];
    for (var i = 0; i < data1.length; i++)
        arr.push(data1[i].week);
    return arr;
    }

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .select(".domain");

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("No. of commits");

    g.append("path")
        .datum(arrWeek(data))
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="500"></svg></code>```

Title: d3 line does not draw

Body:
I've a problem here. The d3.line() is not showing any lines based on the data provided.

I've tried to print out the values via console.log and it fits the scale. I've checked this link about the scaling issue.

I followed this page but modified it to suit the data given to me. I was wondering if the modifications made broke the code.

Thank you!

Here is my code:

var svg = d3.select("#line-graph"),
margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleLinear().rangeRound([0, width]);
var y = d3.scaleLinear().rangeRound([height, 0]);

var line = d3.line()
   .x(function(d, i) { console.log(i); return i; })
   .y(function(d) { console.log(d); return d; });

d3.json("Data2.json", function(data) {
    x.domain([0, data.length]);
    y.domain(d3.extent(data, function(d1) { return d1.week; }));

    var arrWeek = function(data1) {
    var arr = [];
    for (var i = 0; i < data1.length; i++)
        arr.push(data1[i].week);
    return arr;
    }

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .select(".domain");

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("No. of commits");

    g.append("path")
        .datum(arrWeek(data))
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line);
    });

EDIT: The graph just displays the values scale without any line drawn for the data.

EDIT 2: My apologies. I'm using d3.v4.min.js. As for Data2.json, here are 2 elements as it is quite long:

[
 {
"days": [
  0,
  0,
  0,
  0,
  0,
  1,
  0
],
"total": 1,
"week": 1457827200
},
{
"days": [
  0,
  0,
  0,
  1,
  0,
  3,
  1
],
"total": 5,
"week": 1458432000
}
]

EDIT 3: I'm drawing only the "week" variable, hence the scale would be [0, Data2.length] for x-axis. Hope it clears some doubt.

Body:
You have to use your scales in the line generator:

var line = d3.line()
    .x(function(d, i) {
        return x(i);
    //scale ---^
    })
    .y(function(d) {
        return y(d);
    //scale ---^
    });

It may not be your case, but this error normally occurs because people mistake the x and y in the line generator for the x and y in the scales names. That's why it's always a good practice to give meaningful names for your variables and objects: xScale, yScale, xAxis, yAxis etc...

Besides that, when you say...

I've tried to print out the values via console.log and it fits the scale

... this is not accurate. Those are simply the data values, not related to the SVG coordinates system (unless you use your scales).

Here is your working code:

var svg = d3.select("svg"),
margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = [
 {
"days": [
  0,
  0,
  0,
  0,
  0,
  1,
  0
],
"total": 1,
"week": 1457827200
},
{
"days": [
  0,
  0,
  0,
  1,
  0,
  3,
  1
],
"total": 5,
"week": 1458432000
}
];

var x = d3.scaleLinear().rangeRound([0, width]);
var y = d3.scaleLinear().rangeRound([height, 0]);

var line = d3.line()
   .x(function(d, i) {  return x(i); })
   .y(function(d) { return y(d); });

    x.domain([0, data.length]);
    y.domain(d3.extent(data, function(d1) { return d1.week; }));

    var arrWeek = function(data1) {
    var arr = [];
    for (var i = 0; i < data1.length; i++)
        arr.push(data1[i].week);
    return arr;
    }

    g.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x))
        .select(".domain");

    g.append("g")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("fill", "#000")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("text-anchor", "end")
        .text("No. of commits");

    g.append("path")
        .datum(arrWeek(data))
        .attr("fill", "none")
        .attr("stroke", "steelblue")
        .attr("stroke-linejoin", "round")
        .attr("stroke-linecap", "round")
        .attr("stroke-width", 1.5)
        .attr("d", line);

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="600" height="500"></svg>


问:
Xcode comment shortcut on spanish keyboard?
Using a Spanish keyboard: how can I comment out multiple lines of text?

The keyboard shorcut ⌘+/ works fine on the English keyboard.

答:
Search for comment in Xcode help menu (i.e., the top bar above all windows). There should be a shortcut besides the menu item.

Otherwise, go to Xcode→Preferences→Key Bindings and add the desired shortcut yourself.


问:
Error when my selenium script is launching Internet Explorer
When my test script try to open Internet Explorer, I have an error.

Here is my test script :

```<code>package selenium;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class RegistrationTest{

public  int a = 1;

@Test //This is JUnit annotation

public void testRegister(){

        WebDriver driver ;
        System.setProperty("webdriver.ie.driver","IEDriverServer.exe");

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

        driver = new InternetExplorerDriver(capabilities);

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.navigate().to("http://newtours.demoaut.com/");

        driver.findElement(By.linkText("REGISTER")).click();
        driver.findElement(By.name("firstName")).sendKeys("User1");
        driver.findElement(By.name("lastName")).sendKeys("Surname1");
        driver.findElement(By.name("phone")).sendKeys("123456789");
        driver.findElement(By.name("userName")).sendKeys("user1@test.com");
        driver.findElement(By.name("address1")).sendKeys("Test Address");
        driver.findElement(By.name("city")).sendKeys("Test City");
        Select select = new Select(driver.findElement(By.name("country")));
        select.selectByVisibleText("ANGOLA");
        driver.findElement(By.name("email")).sendKeys("user1@test.com");
        driver.findElement(By.name("password")).sendKeys("user1");
        driver.findElement(By.name("confirmPassword")).sendKeys("user1");
        driver.findElement(By.name("register")).click();

        driver.quit();

}

 }
</code>```

My POM.xml is :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cgi.nouguierc</groupId>
<artifactId>WD-Automation</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>selenium.MainJar</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
               <execution>
                     <id>copy-dependencies</id>
                     <phase>prepare-package</phase>
                     <goals>
                        <goal>copy-dependencies</goal>
                     </goals>
                     <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                     </configuration>
               </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>
</project>
</code>```

When I launch RegistrationTest, Internet is opening, going to the adress "http://newtours.demoaut.com/" and then doing nothing.

And in the console I have some errors :

```<code>Started InternetExplorerDriver server (64-bit)
3.0.0.0
Listening on port 44920
Only local connections are allowed
mars 29, 2017 3:16:07 PM org.openqa.selenium.remote.ProtocolHandshake    createSession
INFOS: Detected dialect: OSS
</code>```

Point is that I can't check or uncheck the box "Enable protected..." (see the screenshot below) because I am on a work network so I can't do what I want.

Screenshot of the checkbox

Maybe someone can help me :)

答:
Try to give complete path to IEDriverServer.exe

```<code>System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\IEDriverServer.exe");
</code>```

and the console ouput you have mentioned is absolutely fine , that is not an error. If you have noticed you will see the similar thing in both Chrome and firefox

```<code>Started InternetExplorerDriver server (32-bit)
3.3.0.0
Listening on port 17384
Only local connections are allowed
Mar 29, 2017 7:33:32 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
</code>```

Your actual problem is , in case of Intenet Explorer, Selenium is not able to locate REGISTER Webelement, which is working fine in both Chrome and Firefox.

On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, "Enhanced Protected Mode" must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog.
The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates.
For IE 11 only, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. For 64-bit Windows installations, the key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present. Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.

My guess is that your issue is with Protected Mode.

Body:
When my test script try to open Internet Explorer, I have an error.

Here is my test script :

package selenium;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class RegistrationTest{

public  int a = 1;

@Test //This is JUnit annotation

public void testRegister(){

        WebDriver driver ;
        System.setProperty("webdriver.ie.driver","IEDriverServer.exe");

        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

        driver = new InternetExplorerDriver(capabilities);

        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

        driver.navigate().to("http://newtours.demoaut.com/");

        driver.findElement(By.linkText("REGISTER")).click();
        driver.findElement(By.name("firstName")).sendKeys("User1");
        driver.findElement(By.name("lastName")).sendKeys("Surname1");
        driver.findElement(By.name("phone")).sendKeys("123456789");
        driver.findElement(By.name("userName")).sendKeys("user1@test.com");
        driver.findElement(By.name("address1")).sendKeys("Test Address");
        driver.findElement(By.name("city")).sendKeys("Test City");
        Select select = new Select(driver.findElement(By.name("country")));
        select.selectByVisibleText("ANGOLA");
        driver.findElement(By.name("email")).sendKeys("user1@test.com");
        driver.findElement(By.name("password")).sendKeys("user1");
        driver.findElement(By.name("confirmPassword")).sendKeys("user1");
        driver.findElement(By.name("register")).click();

        driver.quit();

}

 }

My POM.xml is :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.cgi.nouguierc</groupId>
<artifactId>WD-Automation</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>

            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.0.2</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>selenium.MainJar</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
               <execution>
                     <id>copy-dependencies</id>
                     <phase>prepare-package</phase>
                     <goals>
                        <goal>copy-dependencies</goal>
                     </goals>
                     <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        <overWriteReleases>false</overWriteReleases>
                        <overWriteSnapshots>false</overWriteSnapshots>
                        <overWriteIfNewer>true</overWriteIfNewer>
                     </configuration>
               </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.3.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>
</project>

When I launch RegistrationTest, Internet is opening, going to the adress "http://newtours.demoaut.com/" and then doing nothing.

And in the console I have some errors :

Started InternetExplorerDriver server (64-bit)
3.0.0.0
Listening on port 44920
Only local connections are allowed
mars 29, 2017 3:16:07 PM org.openqa.selenium.remote.ProtocolHandshake    createSession
INFOS: Detected dialect: OSS

Point is that I can't check or uncheck the box "Enable protected..." (see the screenshot below) because I am on a work network so I can't do what I want.

Screenshot of the checkbox

Maybe someone can help me :)

Body:
Try to give complete path to IEDriverServer.exe

System.setProperty("webdriver.ie.driver", System.getProperty("user.dir")+"\\IEDriverServer.exe");

and the console ouput you have mentioned is absolutely fine , that is not an error. If you have noticed you will see the similar thing in both Chrome and firefox

Started InternetExplorerDriver server (32-bit)
3.3.0.0
Listening on port 17384
Only local connections are allowed
Mar 29, 2017 7:33:32 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS

Your actual problem is , in case of Intenet Explorer, Selenium is not able to locate REGISTER Webelement, which is working fine in both Chrome and Firefox.

On IE 7 or higher on Windows Vista or Windows 7, you must set the Protected Mode settings for each zone to be the same value. The value can be on or off, as long as it is the same for every zone. To set the Protected Mode settings, choose "Internet Options..." from the Tools menu, and click on the Security tab. For each zone, there will be a check box at the bottom of the tab labeled "Enable Protected Mode". Additionally, "Enhanced Protected Mode" must be disabled for IE 10 and higher. This option is found in the Advanced tab of the Internet Options dialog.
The browser zoom level must be set to 100% so that the native mouse events can be set to the correct coordinates.
For IE 11 only, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. For 64-bit Windows installations, the key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present. Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.

My guess is that your issue is with Protected Mode.


问:
Save regular expression result in variable
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:

Direct user input with BC1 = input("BC1: ") in the following format: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'

Now I want each number - and just the number in a single variable:

```<code>a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000
</code>```

How to realise that in python 3?

Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!

答:
If I understand you correctly, this should do the trick

```<code>BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]
</code>```

And now your desired numbers are

```<code>numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000
</code>```

The split function creates an array of your numbers, but includes the spaces and the quotes.

["'17899792270101010000000000'", " '17899792270102010000000000'", " '17899792270103010000000000'"]

The strip function gets rid of the spaces and the quotes

['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']

The int function parses the strings into an integer (number)

[17899792270101010000000000, 17899792270102010000000000, 17899792270103010000000000]

However, this requires the user to follow the format you specified. Foryah's answer is more robust to different input formats.

Body:
I would like to split a string into separated, single strings and save each in a new variable. That's the use case:

Direct user input with BC1 = input("BC1: ") in the following format: '17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000'

Now I want each number - and just the number in a single variable:

a = 17899792270101010000000000
b = 17899792270102010000000000
c = 17899792270103010000000000

How to realise that in python 3?

Sadly I'm not able to create a suitable regular expression for it and neither a way to save string parts in separate variables. I hope someone of you could help me.
Thanks already in advance!

Body:
If I understand you correctly, this should do the trick

BC1 = input("BC1: ")
numbers = [int(x.strip(' \'')) for x in BC1.split(',')]

And now your desired numbers are

numbers[0] == a # 17899792270101010000000000
numbers[1] == b # 17899792270102010000000000
numbers[2] == c # 17899792270103010000000000

The split function creates an array of your numbers, but includes the spaces and the quotes.

["'17899792270101010000000000'", " '17899792270102010000000000'", " '17899792270103010000000000'"]

The strip function gets rid of the spaces and the quotes

['17899792270101010000000000', '17899792270102010000000000', '17899792270103010000000000']

The int function parses the strings into an integer (number)

[17899792270101010000000000, 17899792270102010000000000, 17899792270103010000000000]

However, this requires the user to follow the format you specified. Foryah's answer is more robust to different input formats.


问:
OWIN - clear invalid WSFederation cookies
I implemented an ASP.Net Web API 2 project with ADFS cookie authentication and hosted it on IIS. All works fine.

However, some clients have got old cookies which became invalid because of configuration changes. Such cookies cause following error when calling my API:

```<code>[CryptographicException: Key not valid for use in specified state.
]
   System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +447
   System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +49

[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
   System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +329
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +167
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +826
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +92
   System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +569
   System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +306
   System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +159
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92
</code>```

The obvious workaround is to clear the cookies. However, it's likely that I'll change the cookies configuration again in future, so I'd like to clear all invalid cookies automatically from the API.

I've tried adding a custom OWIN middleware and overriding IExceptionHandler.

Here's my WIF config:

```<code><system.identityModel>
  <identityConfiguration>
    <audienceUris>
      <add value="https://my.web-api.com" />
    </audienceUris>
    <issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
      <authority name="ADFS">
        <keys>
          <add thumbprint="--a thumbprint--" />
        </keys>
        <validIssuers>
          <add name="http://my.adfs.com/adfs/services/trust" />
        </validIssuers>
      </authority>
    </issuerNameRegistry>
  </identityConfiguration>
</system.identityModel>
<system.identityModel.services>
  <federationConfiguration>
    <wsFederation issuer="https://my.adfs.com/adfs/ls" realm="https://my.web-api.com" requireHttps="true" passiveRedirectEnabled="false"
                  persistentCookiesOnPassiveRedirects="true" />
    <cookieHandler name="my.cookie" path="/" persistentSessionLifetime="7.0:0:0" />
    <serviceCertificate>
      <certificateReference x509FindType="FindBySubjectName" findValue="my.web-api.com" storeLocation="LocalMachine" storeName="My" />
    </serviceCertificate>
  </federationConfiguration>
</system.identityModel.services>
</code>```

Here's my Startup class:

```<code>public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        config.Services.Replace(typeof(IExceptionHandler), new CryptographicExceptionHandler());
        WebApiConfig.Register(config);
        appBuilder.UseWebApi(config);
        appBuilder.Use<ClearInvalidCookiesMiddleware>();
    }
}
</code>```

No matter what's inside CryptographicExceptionHandler and ClearInvalidCookiesMiddleware, their code is not called and I'm getting 500 error. I also tried to move ClearInvalidCookiesMiddleware before UseWebApi.

My aim is to add Set-Cookie response header to clear invalid cookies and return 401 or a redirect.

How can I make OWIN to customize the response in this case?

答:
The solution appeared to override SessionAuthenticationModule.OnAuthenticateRequest and call SignOut() in case of exceptions:

```<code>class ClearInvalidCookiesSessionAuthenticationModule : SessionAuthenticationModule
{
    protected override void OnAuthenticateRequest(object sender, EventArgs eventArgs)
    {
        try
        {
            base.OnAuthenticateRequest(sender, eventArgs);
        }
        catch(InvalidOperationException ex) when (ex.InnerException is CryptographicException) // Invalid cookie signing key
        {
            SignOut();
        }
        catch(System.Xml.XmlException) // Invalid cookie structure
        {
            SignOut();
        }
    }
}
</code>```

To use the inherited class instead of default one, one should insert following line inside Web.config:

```<code><system.webServer>
  <modules ...>
    <!-- Insert the line below or replace existing SessionAuthenticationModule -->
    <add name="SessionAuthenticationModule" preCondition="managedHandler"
         type="MyNamespace.ClearInvalidCookiesSessionAuthenticationModule, MyAssembly" />
    ...
  </modules>
...
</system.webServer>
</code>```

Body:
I implemented an ASP.Net Web API 2 project with ADFS cookie authentication and hosted it on IIS. All works fine.

However, some clients have got old cookies which became invalid because of configuration changes. Such cookies cause following error when calling my API:

[CryptographicException: Key not valid for use in specified state.
]
   System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +447
   System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +49

[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
   System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +329
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +167
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +826
   System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +92
   System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +569
   System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +306
   System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +159
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92

The obvious workaround is to clear the cookies. However, it's likely that I'll change the cookies configuration again in future, so I'd like to clear all invalid cookies automatically from the API.

I've tried adding a custom OWIN middleware and overriding IExceptionHandler.

Here's my WIF config:

<system.identityModel>
  <identityConfiguration>
    <audienceUris>
      <add value="https://my.web-api.com" />
    </audienceUris>
    <issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
      <authority name="ADFS">
        <keys>
          <add thumbprint="--a thumbprint--" />
        </keys>
        <validIssuers>
          <add name="http://my.adfs.com/adfs/services/trust" />
        </validIssuers>
      </authority>
    </issuerNameRegistry>
  </identityConfiguration>
</system.identityModel>
<system.identityModel.services>
  <federationConfiguration>
    <wsFederation issuer="https://my.adfs.com/adfs/ls" realm="https://my.web-api.com" requireHttps="true" passiveRedirectEnabled="false"
                  persistentCookiesOnPassiveRedirects="true" />
    <cookieHandler name="my.cookie" path="/" persistentSessionLifetime="7.0:0:0" />
    <serviceCertificate>
      <certificateReference x509FindType="FindBySubjectName" findValue="my.web-api.com" storeLocation="LocalMachine" storeName="My" />
    </serviceCertificate>
  </federationConfiguration>
</system.identityModel.services>

Here's my Startup class:

public class Startup
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();

        config.Services.Replace(typeof(IExceptionHandler), new CryptographicExceptionHandler());
        WebApiConfig.Register(config);
        appBuilder.UseWebApi(config);
        appBuilder.Use<ClearInvalidCookiesMiddleware>();
    }
}

No matter what's inside CryptographicExceptionHandler and ClearInvalidCookiesMiddleware, their code is not called and I'm getting 500 error. I also tried to move ClearInvalidCookiesMiddleware before UseWebApi.

My aim is to add Set-Cookie response header to clear invalid cookies and return 401 or a redirect.

How can I make OWIN to customize the response in this case?

Body:
The solution appeared to override SessionAuthenticationModule.OnAuthenticateRequest and call SignOut() in case of exceptions:

class ClearInvalidCookiesSessionAuthenticationModule : SessionAuthenticationModule
{
    protected override void OnAuthenticateRequest(object sender, EventArgs eventArgs)
    {
        try
        {
            base.OnAuthenticateRequest(sender, eventArgs);
        }
        catch(InvalidOperationException ex) when (ex.InnerException is CryptographicException) // Invalid cookie signing key
        {
            SignOut();
        }
        catch(System.Xml.XmlException) // Invalid cookie structure
        {
            SignOut();
        }
    }
}

To use the inherited class instead of default one, one should insert following line inside Web.config:

<system.webServer>
  <modules ...>
    <!-- Insert the line below or replace existing SessionAuthenticationModule -->
    <add name="SessionAuthenticationModule" preCondition="managedHandler"
         type="MyNamespace.ClearInvalidCookiesSessionAuthenticationModule, MyAssembly" />
    ...
  </modules>
...
</system.webServer>


问:
Point Feature Histograms in PCL library output interpretation
I am using library called Point Cloud Library (PCL). In particular I am trying to compute point feature histograms. I followed this code from the website:

```<code>#include <pcl/point_types.h>
#include <pcl/features/pfh.h>

{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal> ());

  ... read, pass in or create a point cloud with normals ...
  ... (note: you can create a single PointCloud<PointNormal> if you want) ...

  // Create the PFH estimation class, and pass the input dataset+normals to it
  pcl::PFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::PFHSignature125> pfh;
  pfh.setInputCloud (cloud);
  pfh.setInputNormals (normals);
  // alternatively, if cloud is of tpe PointNormal, do pfh.setInputNormals (cloud);

  // Create an empty kdtree representation, and pass it to the PFH estimation object.
  // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
  //pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZ> ()); -- older call for PCL 1.5-
  pfh.setSearchMethod (tree);

  // Output datasets
  pcl::PointCloud<pcl::PFHSignature125>::Ptr pfhs (new pcl::PointCloud<pcl::PFHSignature125> ());

  // Use all neighbors in a sphere of radius 5cm
  // IMPORTANT: the radius used here has to be larger than the radius used to estimate the surface normals!!!
  pfh.setRadiusSearch (0.05);

  // Compute the features
  pfh.compute (*pfhs);

  // pfhs->points.size () should have the same size as the input cloud->points.size ()*
}
</code>```

The output I get is an array of 125 values per point from the original point cloud. For example if I have a point cloud with 1000 points, where each point contains XYZ, then there will be 1000 * 125 values. I was able to understand why I have 125 entries where each corresponds to a bin. (assuming 3 features and 5 divisions 5^3 = 125)

This post helped some: PCL Point Feature Histograms - binning

Unfortunately I still have a few questions:

1) Why do I have a 125 histograms per point? Is it because it measures what is the percentage of points that are in K-nearest neighborhood to current point have similar features and then each point has its own neighborhood?

2) I see for some points all 125 entries are zeros. Why?

3) Graphing point feature histograms values as shown in the paper and website:

Website:
http://pointclouds.org/documentation/tutorials/pfh_estimation.php#pfh-estimation

Paper:
https://pdfs.semanticscholar.org/5aee/411f0b4228ba63c85df0e8ed64cab5844aed.pdf

The graphs shown have their X axis as number of bins (in my case 125 bins) so the natural question how do we consolidate 125 values per point into one graph?
I tried a simple summation of appropriate columns and scaling them by a constant but I do not think it is right. By summation I mean add all bin[0] for every point, next sum all bin[1] for every point and so on until bin[124].

I would really appreciate any help to clarify this.
Thank you.

答:
The PFH descriptor is a local descriptor, so the histogram is computed for each point it is given. You likely will want to use only a keypoint or a set of kepypoints.

The histogram will have entries of 0 if it has no nearest neighbors within the radius search.

As for graphing, try viewing the histogram for one point at a time. I don't think it makes sense to consolidate it into one graph.

If you are interested in global descriptors that take into account all points, take a look at the CVFH descriptor (Clustered Viewpoint Feature Histogram) or other global ones.

Body:
I am using library called Point Cloud Library (PCL). In particular I am trying to compute point feature histograms. I followed this code from the website:

#include <pcl/point_types.h>
#include <pcl/features/pfh.h>

{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
  pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal> ());

  ... read, pass in or create a point cloud with normals ...
  ... (note: you can create a single PointCloud<PointNormal> if you want) ...

  // Create the PFH estimation class, and pass the input dataset+normals to it
  pcl::PFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::PFHSignature125> pfh;
  pfh.setInputCloud (cloud);
  pfh.setInputNormals (normals);
  // alternatively, if cloud is of tpe PointNormal, do pfh.setInputNormals (cloud);

  // Create an empty kdtree representation, and pass it to the PFH estimation object.
  // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given).
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
  //pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZ> ()); -- older call for PCL 1.5-
  pfh.setSearchMethod (tree);

  // Output datasets
  pcl::PointCloud<pcl::PFHSignature125>::Ptr pfhs (new pcl::PointCloud<pcl::PFHSignature125> ());

  // Use all neighbors in a sphere of radius 5cm
  // IMPORTANT: the radius used here has to be larger than the radius used to estimate the surface normals!!!
  pfh.setRadiusSearch (0.05);

  // Compute the features
  pfh.compute (*pfhs);

  // pfhs->points.size () should have the same size as the input cloud->points.size ()*
}

The output I get is an array of 125 values per point from the original point cloud. For example if I have a point cloud with 1000 points, where each point contains XYZ, then there will be 1000 * 125 values. I was able to understand why I have 125 entries where each corresponds to a bin. (assuming 3 features and 5 divisions 5^3 = 125)

This post helped some: PCL Point Feature Histograms - binning

Unfortunately I still have a few questions:

1) Why do I have a 125 histograms per point? Is it because it measures what is the percentage of points that are in K-nearest neighborhood to current point have similar features and then each point has its own neighborhood?

2) I see for some points all 125 entries are zeros. Why?

3) Graphing point feature histograms values as shown in the paper and website:

Website:
http://pointclouds.org/documentation/tutorials/pfh_estimation.php#pfh-estimation

Paper:
https://pdfs.semanticscholar.org/5aee/411f0b4228ba63c85df0e8ed64cab5844aed.pdf

The graphs shown have their X axis as number of bins (in my case 125 bins) so the natural question how do we consolidate 125 values per point into one graph?
I tried a simple summation of appropriate columns and scaling them by a constant but I do not think it is right. By summation I mean add all bin[0] for every point, next sum all bin[1] for every point and so on until bin[124].

I would really appreciate any help to clarify this.
Thank you.


问:
Launch of activity shows white blank windows
When I open my app for debugging on my device it shows white blank page for around 1-2 sec then my splash screen is shown. I read about this problem on android developer website that says it may be causes due to heavy app initalization in application subclass.

My application extended class code is here :

```<code>public class MyApplication extends Application{

private static ApplicationComponent mApplicationComponent;

@Override
public void onCreate() {
    super.onCreate();

    FacebookSdk.sdkInitialize(getApplicationContext());

    if (mApplicationComponent == null){
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this)).build();
    }
}

public static ApplicationComponent providesApplicationComponent(){return Preconditions.checkNotNull(mApplicationComponent);}

}
</code>```

My splash Screen Code : -

```<code>public class SplashActivity extends AppCompatActivity {

@BindView(R.id.splash_screen)
ImageView mSplashScreen;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    ButterKnife.bind(this);
    Picasso.with(this).load(R.drawable.bg_splash_screen).fit().centerCrop().into(mSplashScreen);
    SharedPreferences mSharedPreferences = getSharedPreferences(Constants.PREFERENCE,MODE_PRIVATE);
    if (mSharedPreferences.getBoolean(Constants.LOGGEDIN,false)){
        Intent homeIntent = new Intent(this, HomeActivity.class);
        openPage(homeIntent);
    } else {
        Intent signupIntent = new Intent(this, SignUpActivity.class);
        openPage(signupIntent);
    }
}

private void openPage(final Intent intent){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(intent);
            finish();
        }
    },1200);
}

}
</code>```

I'm doing only this two initialization in my application class. Is this is the problem ? If or If not How to solve this problems.

答:
When i had the same issue, after a lot of research i added the below code in the styles.xml

```<code><item name="android:windowDisablePreview">true</item>
</code>```

Disable preview removes instant application launching but since you have splash screen then this should work.

Hope it helps you as well.

Body:
When I open my app for debugging on my device it shows white blank page for around 1-2 sec then my splash screen is shown. I read about this problem on android developer website that says it may be causes due to heavy app initalization in application subclass.

My application extended class code is here :

public class MyApplication extends Application{

private static ApplicationComponent mApplicationComponent;

@Override
public void onCreate() {
    super.onCreate();

    FacebookSdk.sdkInitialize(getApplicationContext());

    if (mApplicationComponent == null){
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this)).build();
    }
}

public static ApplicationComponent providesApplicationComponent(){return Preconditions.checkNotNull(mApplicationComponent);}

}

My splash Screen Code : -

public class SplashActivity extends AppCompatActivity {

@BindView(R.id.splash_screen)
ImageView mSplashScreen;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    ButterKnife.bind(this);
    Picasso.with(this).load(R.drawable.bg_splash_screen).fit().centerCrop().into(mSplashScreen);
    SharedPreferences mSharedPreferences = getSharedPreferences(Constants.PREFERENCE,MODE_PRIVATE);
    if (mSharedPreferences.getBoolean(Constants.LOGGEDIN,false)){
        Intent homeIntent = new Intent(this, HomeActivity.class);
        openPage(homeIntent);
    } else {
        Intent signupIntent = new Intent(this, SignUpActivity.class);
        openPage(signupIntent);
    }
}

private void openPage(final Intent intent){

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            startActivity(intent);
            finish();
        }
    },1200);
}

}

I'm doing only this two initialization in my application class. Is this is the problem ? If or If not How to solve this problems.

Body:
When i had the same issue, after a lot of research i added the below code in the styles.xml

<item name="android:windowDisablePreview">true</item>

Disable preview removes instant application launching but since you have splash screen then this should work.

Hope it helps you as well.


问:
Protect frontend form odoo 9
What is the best solution for protection frontend form of spam, before insert data in database, random  addition two number or any captcha?

Any simple solution?

答:
I am not sure how you are setting up your form however you should be able to do client side validation and server side validation. If the client side validation is not passed then Do not let the user submit.

Client side validation should always be followed by server side validation. In your controller or whatever process you are using to handle your form submission you can validate the data again. Use regular expression to validate phone numbers, email addresses, names whatever you wish to validate. Check that all required fields in fact contain data etc.

HTML5 FORM VALIDATION

Regular expression phone validation

Title: Protect frontend form odoo 9


问:
Android Gradle compiling commons-io creates duplicate in library tree
I'm trying to build and maintain an old application for work but I can't get past the build phase.  In my app/build.gradle file I have

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.apache.commons:commons-io:1.3.2'
    //some more libraries compiled as well
}
</code>```

but get the following error when trying to execute:

Error:Execution failed for task ':myApp'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class

This is almost certainly because when I compile that jar, at the top of my External Libraries tree, this is generated:

Why is this happening, and how can I get it to stop so I can complete the build?

答:
I know that this thread is old enough, but if someone faces this issue, the reason may be in the artifact itself.

com.apache.commons:commons-io:XXX has been moved to commons-io:commons-io:XXX and fetching of the old artifact may produce unexpected behavior.

Body:
I'm trying to build and maintain an old application for work but I can't get past the build phase.  In my app/build.gradle file I have

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.apache.commons:commons-io:1.3.2'
    //some more libraries compiled as well
}

but get the following error when trying to execute:

Error:Execution failed for task ':myApp'.
  com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: org/apache/commons/io/CopyUtils.class

This is almost certainly because when I compile that jar, at the top of my External Libraries tree, this is generated:

Why is this happening, and how can I get it to stop so I can complete the build?


问:
How to install english.pickle for nltk on an off line Linux machine
I am trying to run nltk on a SUSE Linux box which cannot be connected to the internet.

I have successfully installed nltk and it runs but when I submit

```<code>>>> tagged = nltk.pos_tag(tokens)
</code>```

I get this error:

LookupError:

       **********************************************************************

  Resource 'tokenizers/punkt/english.pickle' not
  found. Please use the NLTK
  Downloader to obtain the resource:

I cannot use the downloader since I can't connect the box to the internet.

Does anyone how I can install the necessary packages?

答:
For reference purposes (as of 2017), punkt tokenizers are found at this link in GitHub:

https://github.com/nltk/nltk_data/blob/gh-pages/packages/tokenizers/punkt.zip

You should be able to download from a non-airgapped machine, and move it over on a flash drive.

Body:
I am trying to run nltk on a SUSE Linux box which cannot be connected to the internet.

I have successfully installed nltk and it runs but when I submit

>>> tagged = nltk.pos_tag(tokens)

I get this error:

LookupError:

       **********************************************************************

  Resource 'tokenizers/punkt/english.pickle' not
  found. Please use the NLTK
  Downloader to obtain the resource:

I cannot use the downloader since I can't connect the box to the internet.

Does anyone how I can install the necessary packages?


问:
How Do I Import CSS With Safari and Opera When Using CSS Hacks?
I have a tough one here, but I think the benefit will be great...

I'm using the following CSS hack with PHP. The U variable in the file below is a constant, previously defined (before I include this file) as the URL such as http://example.com/. The P constant variable is defined as the physical file path like /var/www/example.com/. (The reason I have to use U and P for absolute pathing is because I use pretty URLs via Apache RewriteRule and it messes up the relative pathing.)

As you can see, I'm using the "link rel" technique to load a default style sheet, and for one for IE, and then another one for IE6. But for Safari and Opera, I tried the linkrel CSS hack technique and it failed -- FF was loading and interpreting the Opera and Safari stylesheets when I thought it might fail on the linkrel tag. So, I had to switch it to an inline CSS and use an @import url() call, but that failed because Opera and Safari wouldn't interpret the @import url() call. So, I had no choice but to switch context back to PHP and load it inline with a require() statement.

Well, the current arrangement in the file below works, but it means that the stylesheet for Opera and Safari is loading with all browsers (it's just not interpreted except by Opera and Safari).

I'd like to know how to get the linkrel or the @import working for Opera and Safari, instead.

```<code><?php ?>
<? /*
***************************************************
  DEFAULT STYLING (AND FIREFOX)
***************************************************
*/ ?>
<link rel="stylesheet" media="all" href="<?= U ?>css/default.css"/>
<style type='text/css'>

<? /*
***************************************************
  SAFARI & GOOGLE CHROME STYLING (WEBKIT STYLING)
***************************************************

NOTE A LINKREL WILL GET INTERPRETED BY FF IF YOU DO IT LIKE THIS...

<link rel="stylesheet" media="screen and (-webkit-min-device-pixel-ratio:0)"
href="<?= U ?>css/safari.css"/>

...SO THAT CAN'T WORK. ALSO, IF YOU USE AN @import url('<?= U ?>css/safari.css'); TO
REPLACE WHERE I HAVE THE require() BELOW, THAT WON'T WORK EITHER BECAUSE
OPERA AND SAFARI DON'T SEEM TO UNDERSTAND THE @import DIRECTIVE IN CSS.

*/ ?>
@media screen and (-webkit-min-device-pixel-ratio:0){
<? require(P . 'css/safari.css'); ?>
}

<? /*
***************************************************
  OPERA STYLING
***************************************************
*/ ?>
@media all and (-webkit-min-device-pixel-ratio:10000), not all and (-webkit-min-device-pixel-ratio:0){
<? require(P . 'css/opera.css'); ?>
}
</style>

<? /*
***************************************************
  IE (ALL) STYLING
***************************************************
*/ ?>
<!--[if IE]>
<link rel="stylesheet" media="all" href="<?= U ?>css/ie.css"/>
<![endif]-->

<? /*
***************************************************
  IE6 STYLING
***************************************************
*/ ?>
<!--[if lte IE 6]>
<link rel="stylesheet" media="all" href="<?= U ?>css/ie6.css"/>
<![endif]-->
</code>```

答:
I'm going to assume you've tried using the same stylesheets for webkit/ff/opera allready, and that this is the last resort because you're doing something strange?

Anyway, Opera does indeed support @import. (It has to, @import is used in 6.79% of all stylesheets.)

In addition, the media query that precedes the Opera CSS will never run in Opera because you're using (-webkit-min-device-pixel-ratio:10000) in the rule. According to the Media query specs error handling rules: "User agents are to ignore a media query when one of the specified media features is unknown.". I doubt Opera honours -webkit vendor media features.

For a full list of what Opera does and doesn't support, look at the Opera feature chart

OwnerDisplayName: Volomike

LastEditorDisplayName: KevDog

Body:
I have a tough one here, but I think the benefit will be great...

I'm using the following CSS hack with PHP. The U variable in the file below is a constant, previously defined (before I include this file) as the URL such as http://example.com/. The P constant variable is defined as the physical file path like /var/www/example.com/. (The reason I have to use U and P for absolute pathing is because I use pretty URLs via Apache RewriteRule and it messes up the relative pathing.)

As you can see, I'm using the "link rel" technique to load a default style sheet, and for one for IE, and then another one for IE6. But for Safari and Opera, I tried the linkrel CSS hack technique and it failed -- FF was loading and interpreting the Opera and Safari stylesheets when I thought it might fail on the linkrel tag. So, I had to switch it to an inline CSS and use an @import url() call, but that failed because Opera and Safari wouldn't interpret the @import url() call. So, I had no choice but to switch context back to PHP and load it inline with a require() statement.

Well, the current arrangement in the file below works, but it means that the stylesheet for Opera and Safari is loading with all browsers (it's just not interpreted except by Opera and Safari).

I'd like to know how to get the linkrel or the @import working for Opera and Safari, instead.

<?php ?>
<? /*
***************************************************
  DEFAULT STYLING (AND FIREFOX)
***************************************************
*/ ?>
<link rel="stylesheet" media="all" href="<?= U ?>css/default.css"/>

<? /*
***************************************************
  IE (ALL) STYLING
***************************************************
*/ ?>

<? /*
***************************************************
  IE6 STYLING
***************************************************
*/ ?>

OwnerDisplayName: runeh


答: To avoid buffer overflow errors, but use strcat you should to use strncat function.

Title: strcat segmentation fault


问:
How to setup structure with SpringBoot and Angular2?
I'm trying to use Angular2 with Springboot, but I can't set them together.

I first started a springboot project, and then tried to follow the Angular 2 Tour of Heroes by johnpapa and run npm install.

The structure looks like below:

I have the /app folder, and the .js are compiled to resources/static/app/js.

Problems:

1) The folder resources/static/node_modules/ has lots of files. So when running bootRun, it gets really slow and sometimes can't even refresh the files. I believe I shouldn't put the node_modules there, but not sure..

2) npm install puts the files in ./node_modules so currently I copied them to static folder. Should I just build the node_modules to static?

3) My structure looks hacky.. what is the best way to do it ?

How to set this structure? Also, please let me know if I should start using grunt/gulp or some other tool to make this easier.

Ps.: In case anyone is interested in the johnpapa's guide: johnpapa's angular2 guide

答: I shared on github a project that integrates Angular 2 with springboot. you can check here Angular 2 with spring boot</p>


问:
Algorithm which adapt (solve) the complex equations ( implicit function f(x,y) )
I'm trying to adapt some equations (implicit f(x,y)) in order to be able list the Y for corresponding X-Value.

The equations could be e.g. as follows:

```<code>y^2 = x^3 + 2x - 3xy
(X^2+y^2-1)^3-x^2y^3=0
X^3+y^3=3xy^2-x-1
X^3+y^2=6xy/sqrt(y/x)
cos(PI*Y) = cos(PI.X)
</code>```

Below you can see the plotted equations:

Hint, I don't know, but maybe this can be helpful, the following applies:

```<code>Y^2 + X^2 =1  ==>  Y= sqrt(1-X^2)
</code>```

The equations are to be adapt (substitution), so that they are expressed by X (not Y).

 For y^2=x^3+2x-3xy by means of substitution results:

y1 = (-(-3x) - sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

y2 = (-(-3x) + sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

By means of adapted equations I will be able to vary X and get the corresponding Y.

See here the solution of Arkadiusz Raszeja-Solution for the equation y^2=x^3+2x-3xy

The solution of "Arkadiusz Raszeja" is for Quadratic equation, but I need an algorithm, so that e.g. all above equations can be solved.

```<code>var x,y;
for(var n=0; n<=10; n++) {
    x=n;
    y = (-(-3*x)-Math.sqrt(((-3*x)*(-3*x)) - 4*(-1)*((x*x*x)+2*x)))/(2*(-1));
    alert(y);
}
</code>```

The above alert(y); will show for Y something like below list:

```<code>X= 1 ; Y=0.79
X=2 ; Y=1.58
X=3 ; Y=2.79
X=4 ; Y=4.39
X=5 ; Y=6.33
X=6 ; Y=8.57
X=7 ; Y=11.12
X=8 ; Y=13.92
X=9 ; Y=16.98
X=10 ; Y= 20.29
</code>```

My question is how can I program an algorithm, which will adapt (solve) the equations like in above example?

(You can also use a JS library like math.js, but not a plot or graph library.  The solution should be in javascript)

Thanks in advance.

答:
I'd like to point out that this problem cannot be solved exactly in general. The cited solution for the quadratic case (y^2) can be extended to the cubic case and quartic case (there are a general complicated solutions). But there is a math theorem (from Galois theory) that states that there is no general solution for the quintic equation (and so on). In your case, maximum degree is 3, so you can use the cubic equation from wikipedia. For the heart graphic write: x^2*y^3 - y^2 -(x^2-1) = 0  and treat x as constant. For the sqrt case, get rid of it. Square both sides of equation, isolate y and you end up with a quartic equation on y, that you can solve using wikipedia's quartic equation knowledge.

Anyway, if you don't have a very strong reason to do this, don't do it, as the computer can solve this numerically for you. Standard approach is to calculate this implicitly, as in the plots you made.

I hope this helps.

Body:
I'm trying to adapt some equations (implicit f(x,y)) in order to be able list the Y for corresponding X-Value.

The equations could be e.g. as follows:

y^2 = x^3 + 2x - 3xy
(X^2+y^2-1)^3-x^2y^3=0
X^3+y^3=3xy^2-x-1
X^3+y^2=6xy/sqrt(y/x)
cos(PI*Y) = cos(PI.X)

Below you can see the plotted equations:

Hint, I don't know, but maybe this can be helpful, the following applies:

Y^2 + X^2 =1  ==>  Y= sqrt(1-X^2)

The equations are to be adapt (substitution), so that they are expressed by X (not Y).

 For y^2=x^3+2x-3xy by means of substitution results:

y1 = (-(-3x) - sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

y2 = (-(-3x) + sqr((-3x)^2 - 4(-1)(x^3+2x)))/2*(-1)

By means of adapted equations I will be able to vary X and get the corresponding Y.

See here the solution of Arkadiusz Raszeja-Solution for the equation y^2=x^3+2x-3xy

The solution of "Arkadiusz Raszeja" is for Quadratic equation, but I need an algorithm, so that e.g. all above equations can be solved.

var x,y;
for(var n=0; n<=10; n++) {
    x=n;
    y = (-(-3*x)-Math.sqrt(((-3*x)*(-3*x)) - 4*(-1)*((x*x*x)+2*x)))/(2*(-1));
    alert(y);
}

The above alert(y); will show for Y something like below list:

X= 1 ; Y=0.79
X=2 ; Y=1.58
X=3 ; Y=2.79
X=4 ; Y=4.39
X=5 ; Y=6.33
X=6 ; Y=8.57
X=7 ; Y=11.12
X=8 ; Y=13.92
X=9 ; Y=16.98
X=10 ; Y= 20.29

My question is how can I program an algorithm, which will adapt (solve) the equations like in above example?

(You can also use a JS library like math.js, but not a plot or graph library.  The solution should be in javascript)

Thanks in advance.


问:
Two AND/OR in one bash if statement
I have a special condition to test in a bash script.
I thought about something like:

```<code>if [[ $categorie = "DG" || $categorie = "DI" ]] && [[ $client != "host1" || $client != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi
</code>```

In words: If categorie is DG OR DI AND client is NOT host1 OR host2 then do stuff.

Is this correct?
For me it looks like it just cares about the categorie and if the categorie condition is met it's ok and prints "requirements are met" and doesn't care about the condition for the client at all.

答:
English and logic ascribe different meanings to negated OR — it is very easy to get confused.

Think about possible values for $client; they are 'host1', 'host2', and 'other'.  If the value is 'host1' the second term in the || is true; if it is 'host2', the first term in the || is true; if it is 'other' both terms in the || are true; which means the condition is always true.

Replace that || with && — if the client is not equal to host1 and is not equal to host2.

```<code>if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
   [[ "$client" != "host1" && "$client" != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi
</code>```

Or use !(client == host1 || client == host2) which can be translated to:

```<code>if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
   [[ ! ( "$client" = "host1" || "$client" = "host2" ) ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi
</code>```

Putting it into a test script:

```<code>for categorie in DG DI XX
do
    for client in host1 host2 other
    do
        if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
           [[ "$client" != "host1" && "$client" != "host2" ]]; then
            echo "(categorie $categorie; client $client): requirements are met"
        else
            echo "(categorie $categorie; client $client): requirements not met"
        fi
        if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
           [[ ! ( "$client" = "host1" || "$client" = "host2" ) ]]; then
            echo "(categorie $categorie; client $client): requirements are met"
        else
            echo "(categorie $categorie; client $client): requirements not met"
        fi
    done
done
</code>```

Output:

```<code>(categorie DG; client host1): requirements not met
(categorie DG; client host1): requirements not met
(categorie DG; client host2): requirements not met
(categorie DG; client host2): requirements not met
(categorie DG; client other): requirements are met
(categorie DG; client other): requirements are met
(categorie DI; client host1): requirements not met
(categorie DI; client host1): requirements not met
(categorie DI; client host2): requirements not met
(categorie DI; client host2): requirements not met
(categorie DI; client other): requirements are met
(categorie DI; client other): requirements are met
(categorie XX; client host1): requirements not met
(categorie XX; client host1): requirements not met
(categorie XX; client host2): requirements not met
(categorie XX; client host2): requirements not met
(categorie XX; client other): requirements not met
(categorie XX; client other): requirements not met
</code>```

The pairs of lines are always the same — the expressions are equivalent.  And the results are, I believe, what you want.

Title: Two AND/OR in one bash if statement

Body:
I have a special condition to test in a bash script.
I thought about something like:

if [[ $categorie = "DG" || $categorie = "DI" ]] && [[ $client != "host1" || $client != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi

In words: If categorie is DG OR DI AND client is NOT host1 OR host2 then do stuff.

Is this correct?
For me it looks like it just cares about the categorie and if the categorie condition is met it's ok and prints "requirements are met" and doesn't care about the condition for the client at all.

Body:
English and logic ascribe different meanings to negated OR — it is very easy to get confused.

Think about possible values for $client; they are 'host1', 'host2', and 'other'.  If the value is 'host1' the second term in the || is true; if it is 'host2', the first term in the || is true; if it is 'other' both terms in the || are true; which means the condition is always true.

Replace that || with && — if the client is not equal to host1 and is not equal to host2.

if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
   [[ "$client" != "host1" && "$client" != "host2" ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi

Or use !(client == host1 || client == host2) which can be translated to:

if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
   [[ ! ( "$client" = "host1" || "$client" = "host2" ) ]]; then
    echo "requirements are met"
else
    echo "requirements not met"
fi

Putting it into a test script:

for categorie in DG DI XX
do
    for client in host1 host2 other
    do
        if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
           [[ "$client" != "host1" && "$client" != "host2" ]]; then
            echo "(categorie $categorie; client $client): requirements are met"
        else
            echo "(categorie $categorie; client $client): requirements not met"
        fi
        if [[ "$categorie" = "DG" || "$categorie" = "DI" ]] &&
           [[ ! ( "$client" = "host1" || "$client" = "host2" ) ]]; then
            echo "(categorie $categorie; client $client): requirements are met"
        else
            echo "(categorie $categorie; client $client): requirements not met"
        fi
    done
done

Output:

(categorie DG; client host1): requirements not met
(categorie DG; client host1): requirements not met
(categorie DG; client host2): requirements not met
(categorie DG; client host2): requirements not met
(categorie DG; client other): requirements are met
(categorie DG; client other): requirements are met
(categorie DI; client host1): requirements not met
(categorie DI; client host1): requirements not met
(categorie DI; client host2): requirements not met
(categorie DI; client host2): requirements not met
(categorie DI; client other): requirements are met
(categorie DI; client other): requirements are met
(categorie XX; client host1): requirements not met
(categorie XX; client host1): requirements not met
(categorie XX; client host2): requirements not met
(categorie XX; client host2): requirements not met
(categorie XX; client other): requirements not met
(categorie XX; client other): requirements not met

The pairs of lines are always the same — the expressions are equivalent.  And the results are, I believe, what you want.