问:
Emacs lisp. Split custom-set-variables in multiple custom-set-variables
I have read this: Multiple custom-set-faces and custom-set-variables in emacs

An answer is:

If you are manually adding custom faces, keep it in custom-set-faces.

As for having multiple (custom-set-faces ... ) or (custom-set-variables ... ) lists, I have just tested this (in Emacs 23.1). They do work - Emacs will process all lists - however, if you then use M-x customize-face to add a new custom face (similarly for a variable) and save it for future sessions, Emacs will combine all the lists into one. So, you should probably only keep the one.

I would like to know if there is any way to split a custom-set-variables call into smaller calls. Example: I would line to split this

```<code>(custom-set-variables
 '(custom-enabled-themes (quote (solarized-dark)))
 '(custom-safe-themes
   (quote
    ("8aebf25556399b58091e533e455dd50a6a9cba958cc4ebb0aab175863c25b9a4" default)))
 '(package-archives
   (quote
    (("gnu" . "http://elpa.gnu.org/packages/")
     ("melpa" . "https://stable.melpa.org/packages/"))))
 '(package-selected-packages (quote (solarized-theme)))
)
</code>```

into

```<code>(custom-set-variables
 '(custom-enabled-themes (quote (solarized-dark)))
 '(custom-safe-themes
   (quote
    ("8aebf25556399b58091e533e455dd50a6a9cba958cc4ebb0aab175863c25b9a4" default))))

(custom-set-variables
 '(package-archives
   (quote
    (("gnu" . "http://elpa.gnu.org/packages/")
     ("melpa" . "https://stable.melpa.org/packages/"))))
 '(package-selected-packages (quote (solarized-theme)))
)
</code>```

答:
Not sure what you are really asking.

You can use custom-set-variables anywhere and as many times as you want.

However, if you also expect/want Customize to write to your custom-file (or your init file, if you do not have a custom-file) then what the other SO post told you holds true. When Customize writes to your file it coalesces the calls to custom-set-variables.

It is a bad idea to mix your own calls to custom-set-variables with Customize's writing of such code.

Keep your code separate from what Customize writes. That's the whole point of using a separate custom-file: to give Customize a separate place to play, so it doesn't mess with your code.

Body:
I have read this: Multiple custom-set-faces and custom-set-variables in emacs

An answer is:

If you are manually adding custom faces, keep it in custom-set-faces.

As for having multiple (custom-set-faces ... ) or (custom-set-variables ... ) lists, I have just tested this (in Emacs 23.1). They do work - Emacs will process all lists - however, if you then use M-x customize-face to add a new custom face (similarly for a variable) and save it for future sessions, Emacs will combine all the lists into one. So, you should probably only keep the one.

I would like to know if there is any way to split a custom-set-variables call into smaller calls. Example: I would line to split this

(custom-set-variables
 '(custom-enabled-themes (quote (solarized-dark)))
 '(custom-safe-themes
   (quote
    ("8aebf25556399b58091e533e455dd50a6a9cba958cc4ebb0aab175863c25b9a4" default)))
 '(package-archives
   (quote
    (("gnu" . "http://elpa.gnu.org/packages/")
     ("melpa" . "https://stable.melpa.org/packages/"))))
 '(package-selected-packages (quote (solarized-theme)))
)

into

(custom-set-variables
 '(custom-enabled-themes (quote (solarized-dark)))
 '(custom-safe-themes
   (quote
    ("8aebf25556399b58091e533e455dd50a6a9cba958cc4ebb0aab175863c25b9a4" default))))

(custom-set-variables
 '(package-archives
   (quote
    (("gnu" . "http://elpa.gnu.org/packages/")
     ("melpa" . "https://stable.melpa.org/packages/"))))
 '(package-selected-packages (quote (solarized-theme)))
)


来源: stackexchange

问:
change image of input type="range" thumb javascript
I am trying to change the image of the thumb for the slide range when the value is changing.

The problem is I don't know how to select the thumb with javascript as a selector. Can you please help?

```<code>      <div class="slider-bar">
              <input type="range" id="myRange" min="0" max="10" value="0" />
        </div>

            input[type=range]::-webkit-slider-thumb {
                        -webkit-appearance: none;
                        border: none;
                        height: 50px;
                        width: 50px;
                        border-radius: 50%;
                        background:url(images/image.jpg) center no-repeat;
                        margin-top: -24px;
                        }
            input[type=range]:focus {
                        outline: none;
                        }
            input[type=range]::-moz-range-thumb {
                        border: none;
                        height: 50px;
                        width: 50px;
                        border-radius: 50%;
                        background:url(images/image.jpg) center no-repeat;
                        margin-top: -24px;}

var slider = document.getElementById("myRange");
    function xvalue () {
        var x = document.getElementById("myRange").value;
        console.log(x);
        if(x==1 && x==2 && x==3) {
            thumb.style.backgroundImage = "url('images/image1.jpg')";
        } else if (x==4 && x==5 && x==6) {
            thumb.style.backgroundImage = "url('images/images/image2.jpg')";
        } else if (x==7 && x==8 && x==9 && x==10) {
            thumb.style.backgroundImage = "url('images/images/image3.jpg')";
        }
    }
   slider.addEventListener("change", xvalue);
</code>```

答:
You can't modify CSS pseudo-selectors with JavaScript.

What you need to do instead is simply toggle a class name.

Here's an example:

HTML

```<code><div class="slider-bar">
  <input type="range" id="myRange" min="0" max="10" value="0" />
</div>
</code>```

CSS

```<code>input[type=range] {
  -webkit-appearance: none;
}

 input[type=range]::-webkit-slider-thumb {
   background-image: :url(images/default.jpg);
 }

 input[type=range].MyClass-1::-webkit-slider-thumb {
   background-image: :url(images/thumb-1.jpg);
 }

 input[type=range].MyClass-2::-webkit-slider-thumb {
   background-image: :url(images/thumb-2.jpg);
 }
</code>```

JavaScript

```<code>var slider = document.getElementById('myRange')

function onChange(event) {
  var x = event.target.value

  if (x <= 3) {
    slider.className = ''
  } else if (x > 3 && x <= 6) {
    slider.className = 'MyClass-1'
  } else if (x > 6) {
    slider.className = 'MyClass-2'
  }
}

slider.addEventListener('input', onChange)
</code>```

JSFiddle Demo: https://jsfiddle.net/vbsmkfus/1/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to change the image of the thumb for the slide range when the value is changing.

The problem is I don't know how to select the thumb with javascript as a selector. Can you please help?

              <input type="range" id="myRange" min="0" max="10" value="0" />

            input[type=range]::-webkit-slider-thumb {
                        -webkit-appearance: none;
                        border: none;
                        height: 50px;
                        width: 50px;
                        border-radius: 50%;
                        background:url(images/image.jpg) center no-repeat;
                        margin-top: -24px;
                        }
            input[type=range]:focus {
                        outline: none;
                        }
            input[type=range]::-moz-range-thumb {
                        border: none;
                        height: 50px;
                        width: 50px;
                        border-radius: 50%;
                        background:url(images/image.jpg) center no-repeat;
                        margin-top: -24px;}

var slider = document.getElementById("myRange");
    function xvalue () {
        var x = document.getElementById("myRange").value;
        console.log(x);
        if(x==1 && x==2 && x==3) {
            thumb.style.backgroundImage = "url('images/image1.jpg')";
        } else if (x==4 && x==5 && x==6) {
            thumb.style.backgroundImage = "url('images/images/image2.jpg')";
        } else if (x==7 && x==8 && x==9 && x==10) {
            thumb.style.backgroundImage = "url('images/images/image3.jpg')";
        }
    }
   slider.addEventListener("change", xvalue);

Body:
You can't modify CSS pseudo-selectors with JavaScript.

What you need to do instead is simply toggle a class name.

Here's an example:

HTML

<div class="slider-bar">
  <input type="range" id="myRange" min="0" max="10" value="0" />
</div>

CSS

input[type=range] {
  -webkit-appearance: none;
}

 input[type=range]::-webkit-slider-thumb {
   background-image: :url(images/default.jpg);
 }

 input[type=range].MyClass-1::-webkit-slider-thumb {
   background-image: :url(images/thumb-1.jpg);
 }

 input[type=range].MyClass-2::-webkit-slider-thumb {
   background-image: :url(images/thumb-2.jpg);
 }

JavaScript

var slider = document.getElementById('myRange')

function onChange(event) {
  var x = event.target.value

  if (x <= 3) {
    slider.className = ''
  } else if (x > 3 && x <= 6) {
    slider.className = 'MyClass-1'
  } else if (x > 6) {
    slider.className = 'MyClass-2'
  }
}

slider.addEventListener('input', onChange)

JSFiddle Demo: https://jsfiddle.net/vbsmkfus/1/


问:
Plot arcs in leaflet using R
I'm trying to plot frequency arcs in R using leaflet

This is what my dataset looks like

```<code>lng lat Freq    Country
67.709953   33.93911    26  Afghanistan
104.990963  12.565679   9   Cambodia
12.354722   7.369722    15  Cameroon
-23.6051868 15.120142   312 Cape Verde
-71.542969  -35.675147  2   Chile
104.195397  35.86166    639 China
-74.297333  4.570868    92  Colombia
21.758664   -4.038333   8   Congo
-77.781167  21.521757   1   Cuba
42.590275   11.825138   1   Djibouti
-70.162651  18.735693   350 Dominican Republic
20.168331   41.153332   34  Albania
-78.183406  -1.831239   16  Ecuador
30.802498   26.820553   4   Egypt
-88.89653   13.794185   207 El Salvador
40.489673   9.145   129 Ethiopia
2.213749    46.227638   12  France
</code>```

I'm trying to plot all these countries on a leaflet and the condition is that the starting arc or starting point for each country would be from Boston, MA

The code that I used is as under

```<code>library(leaflet)
library(geosphere)

rg1<-read.csv("rg.csv")
bos=geocode(as.character("Boston"))

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200, breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles()%>%
  addCircleMarkers(data=rg1, radius = 8, color = 'red', fill = TRUE, label = ~as.character(Freq), labelOptions=c(noHide=TRUE)) %>%
  addPolylines(data=rg1, lng = ~lng, lat = ~lat)
</code>```

I referred to instructions specified in

Adding Curved Flight path using R's Leaflet Package

but I'm getting a vague output

this is the output of the leaflet

Please let me know what am I doing wrong thats causing the arcs to be as a straight line and not originate from Boston, MA

Thanks

Updated Code:
Added Quantiles based on the frequency and then tried changing colors based on the Quantiles, but it throws this error "Don't know how to get location data from object of class SpatialLines"

```<code>rg1$q<-ifelse(rg1$Freq<=100,"1st Quantile(1-100 occurances)",ifelse(rg1$Freq>=101 & rg1$Freq<=250,"2nd Quantile(101-250 occurances)","3rd Quantile(250+ occurances)"))
rg1$q <- as.ordered(rg1$q)

pal <- colorFactor(c("navy", "red","green"), domain = c("1st Quantile(1-100 occurances)","2nd Quantile(101-250 occurances)","3rd Quantile(250+ occurances)"))

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200,
               breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles() %>%
  addCircleMarkers(
    color = ~pal(q),
    stroke = FALSE, fillOpacity = 0.5)  %>%
  addPolylines()
</code>```

答:
gcIntermediate computes the arcs but you are plotting lines with rg1:

```<code>gcIntermediate(bos, rg1[,c('lng', 'lat')], 200, breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles()%>%
  addCircleMarkers(data=rg1, radius = 8, color = 'red', fill = TRUE, label = ~as.character(Freq), labelOptions=c(noHide=TRUE)) %>%
  addPolylines(data=rg1, lng = ~lng, lat = ~lat)
</code>```

Try:

```<code>gcIntermediate(bos, rg1[,c('lng', 'lat')], 200,
  breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles() %>% addPolylines()
</code>```

for starters - note the empty addPolylines() means it gets the coordinates from the data piped into leaflet() - your interpolated great circle curves.

Title: Plot arcs in leaflet using R

Body:
I'm trying to plot frequency arcs in R using leaflet

This is what my dataset looks like

lng lat Freq    Country
67.709953   33.93911    26  Afghanistan
104.990963  12.565679   9   Cambodia
12.354722   7.369722    15  Cameroon
-23.6051868 15.120142   312 Cape Verde
-71.542969  -35.675147  2   Chile
104.195397  35.86166    639 China
-74.297333  4.570868    92  Colombia
21.758664   -4.038333   8   Congo
-77.781167  21.521757   1   Cuba
42.590275   11.825138   1   Djibouti
-70.162651  18.735693   350 Dominican Republic
20.168331   41.153332   34  Albania
-78.183406  -1.831239   16  Ecuador
30.802498   26.820553   4   Egypt
-88.89653   13.794185   207 El Salvador
40.489673   9.145   129 Ethiopia
2.213749    46.227638   12  France

I'm trying to plot all these countries on a leaflet and the condition is that the starting arc or starting point for each country would be from Boston, MA

The code that I used is as under

library(leaflet)
library(geosphere)

rg1<-read.csv("rg.csv")
bos=geocode(as.character("Boston"))

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200, breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles()%>%
  addCircleMarkers(data=rg1, radius = 8, color = 'red', fill = TRUE, label = ~as.character(Freq), labelOptions=c(noHide=TRUE)) %>%
  addPolylines(data=rg1, lng = ~lng, lat = ~lat)

I referred to instructions specified in

Adding Curved Flight path using R's Leaflet Package

but I'm getting a vague output

this is the output of the leaflet

Please let me know what am I doing wrong thats causing the arcs to be as a straight line and not originate from Boston, MA

Thanks

Updated Code:
Added Quantiles based on the frequency and then tried changing colors based on the Quantiles, but it throws this error "Don't know how to get location data from object of class SpatialLines"

rg1$q<-ifelse(rg1$Freq<=100,"1st Quantile(1-100 occurances)",ifelse(rg1$Freq>=101 & rg1$Freq<=250,"2nd Quantile(101-250 occurances)","3rd Quantile(250+ occurances)"))
rg1$q <- as.ordered(rg1$q)

pal <- colorFactor(c("navy", "red","green"), domain = c("1st Quantile(1-100 occurances)","2nd Quantile(101-250 occurances)","3rd Quantile(250+ occurances)"))

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200,
               breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles() %>%
  addCircleMarkers(
    color = ~pal(q),
    stroke = FALSE, fillOpacity = 0.5)  %>%
  addPolylines()

Body:
gcIntermediate computes the arcs but you are plotting lines with rg1:

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200, breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles()%>%
  addCircleMarkers(data=rg1, radius = 8, color = 'red', fill = TRUE, label = ~as.character(Freq), labelOptions=c(noHide=TRUE)) %>%
  addPolylines(data=rg1, lng = ~lng, lat = ~lat)

Try:

gcIntermediate(bos, rg1[,c('lng', 'lat')], 200,
  breakAtDateLine=FALSE, addStartEnd=TRUE, sp=TRUE) %>%
  leaflet()  %>% addTiles() %>% addPolylines()

for starters - note the empty addPolylines() means it gets the coordinates from the data piped into leaflet() - your interpolated great circle curves.


问:
how to sum variables with NA values using withColumn
I have a data frame with 4 numeric variables, and i need to create another variable with the sum from the other 4 variables.
This function works, sure:

df4.withColumn( "sumVariables", sum(df4[x] for x in df4.columns[1:5])).show()

the problem is the sum with Null values, because the result in a row with

0|   null|      1|      0 is Null

how can i solve it?

答:
Replace Null with 0's</p>

```<code>df4 = df4.fillna(0)
df4.withColumn( "sumVariables", when(sum(df4[x] for x in df4.columns) > 0, sum(df4[x] for x in df4.columns)).otherwise(None)).show()
</code>```

Body:
Replace Null with 0's

df4 = df4.fillna(0)
df4.withColumn( "sumVariables", when(sum(df4[x] for x in df4.columns) > 0, sum(df4[x] for x in df4.columns)).otherwise(None)).show()


问:
Issue defining traefik labelselector in traefik.toml vs. container arg
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

```<code>[kubernetes]
  labelselector = "expose=internal"
</code>```

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

```<code>- --kubernetes.labelselector=expose=internal
</code>```

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.

答: Indeed, flags take precedence over toml config. It's documented here http://docs.traefik.io/basics/#static-trfik-configuration :)</p>

Body:
I have a traefik.toml file defined as part of my traefik configmap. The snippet below is the kubernetes endpoint configuration with a labelselector defined:

[kubernetes]
  labelselector = "expose=internal"

When I check the traefik status page in this configuration, I see all ingresses listed, not just those with the label "expose: internal" defined.

If I set the kubernetes.labelselector as a container argument to my deployment, however, only the ingresses with the matching label are displayed on the traefik status page as expected:

- --kubernetes.labelselector=expose=internal

According to the Kubernetes Ingress Backend documentation, any label selector format valid in the label selector section of the Labels and Selectors should be valid in the traefik.toml file. I have experimented with both the equality baed (as shown above) and the set-based (to determine if the "expose" label is present, only), neither of which have worked in the toml. The set-based does not seem to work in the container args, but the equality statements do.

I'm assuming there is some issue related to how I've formatted the kubernetes endpoint within the traefik.toml file. Before reporting this issue to github I was hoping someone could clarify the documentation and/or correct any mistakes I've made in the toml file format.


问:
What exactly is the '%' sign used for in python?
This is a code for a simple encryption method. </p>

```<code>if character in alphabet:
    position=alphabet.find(character)
    newPosition=(position-key)%26  # here
    newCharacter=alphabet[newPosition]
    print("The encrypted character is: " + newCharacter)
    newMessage += newCharacter
    print(newMessage)
</code>```

答:
The % sign in your code is a modulo operator - the remainder after integer division. E. g.

```<code>    13 % 5
</code>```

gives the result 3

(as 13 divided by 5 is 2, and the remainder is 3.

Body:
This is a code for a simple encryption method.

if character in alphabet:
    position=alphabet.find(character)
    newPosition=(position-key)%26  # here
    newCharacter=alphabet[newPosition]
    print("The encrypted character is: " + newCharacter)
    newMessage += newCharacter
    print(newMessage)

Body:
The % sign in your code is a modulo operator - the remainder after integer division. E. g.

    13 % 5

gives the result 3

(as 13 divided by 5 is 2, and the remainder is 3.


问:
how to compare word letters using if statements?
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

```<code>  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }
</code>```

答:
String has an endsWith method.

```<code>if (word.endsWith("y") || word.endsWith("Y")) {
    System.out.println(word + " ends with y");
}
</code>```

You can get a character from the string using charAt, as long as the string is not empty. You can convert a character to upper case using Character.toUpperCase so that you can compare characters without worrying about what case they are in.

```<code>if (word.length() > 0 && Character.toUpperCase(word.charAt(0))==Character.toUpperCase(word.charAt(word.length()-1))) {
    System.out.println(word + " starts and ends with the same letter.");
}
</code>```

Body:
I'm trying to write a program that reads a word and prints if:

it ends with the letter y.

has the same first and last character, ignoring case.

This is what I have so far, but I'm having trouble thinking of a line of code that will check individual letters or compare the first and last letters.

  if (. . .)
  {
     System.out.println(word + " ends in a y");
  }

  if (. . .)
  {
     System.out.println(word + " starts and ends with the same letter");
  }

Body:
String has an endsWith method.

if (word.endsWith("y") || word.endsWith("Y")) {
    System.out.println(word + " ends with y");
}

You can get a character from the string using charAt, as long as the string is not empty. You can convert a character to upper case using Character.toUpperCase so that you can compare characters without worrying about what case they are in.

if (word.length() > 0 && Character.toUpperCase(word.charAt(0))==Character.toUpperCase(word.charAt(word.length()-1))) {
    System.out.println(word + " starts and ends with the same letter.");
}


问:
angular 2 and socket.io
I recently started programming with angular2 (or it is the 4 version now) anyways, I grasp all the fundementals. The problem I ran into recently is implementing sockets with socket.io.

So basically I have a simple nodejs express server listening for socket connections, thats easy.

I create a simple application using angulars-cli terminal ng. Simply ng new application-name. It creates a minimal working angular application. Now the problem is, how do I add socket.io-client into application. I have followed many tutorials, but they all differ in one or the other way. Many of the tutorials are using systemjs module loader, but when I create boilerplate with the ng no such file with a name systemjs.

So my question is how do i tell angular to load socket.io into the app. Ofcourse import * as io from 'socket.io-client' into the client isn't enough, as I expierenced. I tried creating @Injectable(), then adding it into the approot module as provider, but that seems not to work.

can someone elaborate?

Much appreciated

答:
It would be helpful to have more details here. What did you make @Injectable()? One of your own services, or one of theirs? And give us details about the failure you are referring to in the following statement:

Of course import * as io from 'socket.io' into the client isn't enough, as I experienced.

If you want to just include a script on the page with Angular CLI, you can use the apps -> scripts array in .angular-cli.json (documentation).

However, you'll most likely have better luck with a module like this: https://www.npmjs.com/package/ng2-socket-io. The source for that package can be used as an example of how to import socket.io on its own, too. Simply import the package and use it within your application and the Angular/webpack compilation steps will include the library in your final bundle.

If you are continuing to see issues, then you will need to provide more details.

Title: angular 2 and socket.io


问:
HTML href links does not work after i added javascript to navigation component
I have a simple main navigation menu created with html and css. When I added some javascript to handle the collapsing and toggling for the button for the mobile menu, every link on the page stops working.

I based the navigation off of this pen: https://codepen.io/anon/pen/YQjzzq

(function() {

  // Definition of caller element
  var getTriggerElement = function(el) {
    var isCollapse = el.getAttribute('data-collapse');
    if (isCollapse !== null) {
      return el;
    } else {
      var isParentCollapse = el.parentNode.getAttribute('data-collapse');
      return (isParentCollapse !== null) ? el.parentNode : undefined;
    }
  };

  // A handler for click on toggle button
  var collapseClickHandler = function(event) {
    var triggerEl = getTriggerElement(event.target);
    // If trigger element does not exist
    if (triggerEl === undefined) {
      event.preventDefault();
      return false;
    }

    // If the target element exists
    var targetEl = document.querySelector(triggerEl.getAttribute('data-target'));
    if (targetEl) {
      triggerEl.classList.toggle('-active');
      targetEl.classList.toggle('-on');
    }
  };

  // Delegated event
  document.addEventListener('click', collapseClickHandler, false);

})(document, window);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav role="navigation" id="navigation" class="list">
          Hem
          Vårt Boende
          Om Kvinnovåld
          Länkar
          Engagera Dig
          English
          Kontakt
        </nav>

        <!-- Button to toggle the display menu  -->
        <button data-collapse data-target="#navigation" class="toggle">
          <!-- Hamburger icon -->
          <span class="icon"></span>
        </button></code>```

答:
Currently, the links are not working because they are having their default behavior prevented on line 19 on the JavaScript. If I'm understanding the situation correctly, you only want the event listener to apply to the collapsible menu, so I'd suggest altering the code to something like this:</p>

```<code> // Delegated event
document.getElementsByClassName('toggle')[0].addEventListener('click', collapseClickHandler, false);
</code>```

Body:
I have a simple main navigation menu created with html and css. When I added some javascript to handle the collapsing and toggling for the button for the mobile menu, every link on the page stops working.

I based the navigation off of this pen: https://codepen.io/anon/pen/YQjzzq

(function() {

  // Definition of caller element
  var getTriggerElement = function(el) {
    var isCollapse = el.getAttribute('data-collapse');
    if (isCollapse !== null) {
      return el;
    } else {
      var isParentCollapse = el.parentNode.getAttribute('data-collapse');
      return (isParentCollapse !== null) ? el.parentNode : undefined;
    }
  };

  // A handler for click on toggle button
  var collapseClickHandler = function(event) {
    var triggerEl = getTriggerElement(event.target);
    // If trigger element does not exist
    if (triggerEl === undefined) {
      event.preventDefault();
      return false;
    }

    // If the target element exists
    var targetEl = document.querySelector(triggerEl.getAttribute('data-target'));
    if (targetEl) {
      triggerEl.classList.toggle('-active');
      targetEl.classList.toggle('-on');
    }
  };

  // Delegated event
  document.addEventListener('click', collapseClickHandler, false);

})(document, window);

          Hem
          Vårt Boende
          Om Kvinnovåld
          Länkar
          Engagera Dig
          English
          Kontakt

        <button data-collapse data-target="#navigation" class="toggle">

        </button>

Body:
Currently, the links are not working because they are having their default behavior prevented on line 19 on the JavaScript. If I'm understanding the situation correctly, you only want the event listener to apply to the collapsible menu, so I'd suggest altering the code to something like this:

 // Delegated event
document.getElementsByClassName('toggle')[0].addEventListener('click', collapseClickHandler, false);


问:
Add raw serialized value to a repeated field in protocol buffers (protobuf-net, protobuf-csharp)
I am looking for a way to add a serialized value of an object (byte[]) to a repeated field in a protocol buffers message.

I have an application that keeps data items in serialized form in memcached and needs to deliver them to remote clients. The client requests data items by providing a list of keys and the server sends back the list of data items. The content of data items is not important for the server; it does not need to know what is contained in them, it only needs to know their key.

The current approach is to fetch items from memcached, deserialize them, add them to the list of data items in a response, serialize the response into a byte array and send it over a socket. This is not optimal, because we deserialize data items only to have them serialized again in the next step. Both serializations (for memcached and for output) are done with protocol buffers. Ideally, we could skip the deserialization after fetching the data from memcached and add the serialized values to the response. I looked into both protobuf-net and protobuf-csharp and did not find a way to accomplish this. Is it possible? Did I overlook something?

Here are proto definitions (simplified):

```<code>message Request {
    required int32 messageId;
    repeated string keys;
}

message DataItem {

    required string key = 1;
    required ValueType type = 2;      // the type of the value, enumeration

    optional int32 intValue = 3;
    optional int64 longValue = 4;
    optional double doubleValue = 5;
    optional float floatValue = 6;
    optional bool boolValue = 7;
    optional string stringValue = 8;
}

message Response {
    required int32 messageId;
    repeated DataItem dataItems;
}
</code>```

答:
You can add one more message to your protobuf:

```<code>message RawResponse {
    required int32 messageId;
    repeated bytes dataItems;
}
</code>```

Then, do following:

Fetch memcached items directly into RawResponse

Send RawResponse back

On the client deserialize into Response

This approach will work, because both RawResponse and Response would have same binary representation. [1]

ContentLicense: CC BY-SA 2.5

Body:
I am looking for a way to add a serialized value of an object (byte[]) to a repeated field in a protocol buffers message.

I have an application that keeps data items in serialized form in memcached and needs to deliver them to remote clients. The client requests data items by providing a list of keys and the server sends back the list of data items. The content of data items is not important for the server; it does not need to know what is contained in them, it only needs to know their key.

The current approach is to fetch items from memcached, deserialize them, add them to the list of data items in a response, serialize the response into a byte array and send it over a socket. This is not optimal, because we deserialize data items only to have them serialized again in the next step. Both serializations (for memcached and for output) are done with protocol buffers. Ideally, we could skip the deserialization after fetching the data from memcached and add the serialized values to the response. I looked into both protobuf-net and protobuf-csharp and did not find a way to accomplish this. Is it possible? Did I overlook something?

Here are proto definitions (simplified):

message Request {
    required int32 messageId;
    repeated string keys;
}

message DataItem {

    required string key = 1;
    required ValueType type = 2;      // the type of the value, enumeration

    optional int32 intValue = 3;
    optional int64 longValue = 4;
    optional double doubleValue = 5;
    optional float floatValue = 6;
    optional bool boolValue = 7;
    optional string stringValue = 8;
}

message Response {
    required int32 messageId;
    repeated DataItem dataItems;
}

Body:
You can add one more message to your protobuf:

message RawResponse {
    required int32 messageId;
    repeated bytes dataItems;
}

Then, do following:

Fetch memcached items directly into RawResponse

Send RawResponse back

On the client deserialize into Response

This approach will work, because both RawResponse and Response would have same binary representation. [1]


问:
Sort file by key with awk or perl like a join without presorting
I want to join two tab separated files, but they are in a different order. I know that it is doable with awk, but I don't know how. Here is the equivalent toy python code (python is too memory inefficient for this task without crazy workarounds):

```<code>import pandas as pd
from random import shuffle

a = ['bar','qux','baz','foo','spam']
df = pd.DataFrame({'nam':a,'asc':[1,2,3,4,5],'desc':[5,4,3,2,1]})

shuffle(a)
print(a)

dex = pd.DataFrame({'dex' : a})
df_b = pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})

pd.merge(dex, df,left_on='dex',right_on='nam')[['asc','desc','nam']]
</code>```

I have two files:
For file one, column 2 holds the identifier for each row, there 5 columns I don't need, and then there are about 3 million columns of data.

For file two, There are 12 columns, with the second column containing the same identifiers in a different order, along with additional ids.

I want to sort file one to have the same identifiers and order as file two, with the other columns appropriately rearranged.

File one is potentially multiple gigabytes.

Is this easier with awk and/or other GNU tools, or should I use perl?

答:
3 million columns of data, eh?  It sounds like you're doing some NLP work.

Assuming this is true, and your matrix is sparse, python can handle it just fine (just not with pandas).  Look at scipy.sparse.  Example:

```<code>from scipy.sparse import dok_matrix

A = dok_matrix((10,10))
A[1,1] = 1

B = dok_matrix((10,10))
B[2,2] = 2

print A+B
</code>```

DOK stands for "dictionary of keys", which is typically used to build the sparse matrix, then it's usually converted to CSR, etc. depending on use.  See available sparse matrix types.

Body:
I want to join two tab separated files, but they are in a different order. I know that it is doable with awk, but I don't know how. Here is the equivalent toy python code (python is too memory inefficient for this task without crazy workarounds):

import pandas as pd
from random import shuffle

a = ['bar','qux','baz','foo','spam']
df = pd.DataFrame({'nam':a,'asc':[1,2,3,4,5],'desc':[5,4,3,2,1]})

shuffle(a)
print(a)

dex = pd.DataFrame({'dex' : a})
df_b = pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})

pd.merge(dex, df,left_on='dex',right_on='nam')[['asc','desc','nam']]

I have two files:
For file one, column 2 holds the identifier for each row, there 5 columns I don't need, and then there are about 3 million columns of data.

For file two, There are 12 columns, with the second column containing the same identifiers in a different order, along with additional ids.

I want to sort file one to have the same identifiers and order as file two, with the other columns appropriately rearranged.

File one is potentially multiple gigabytes.

Is this easier with awk and/or other GNU tools, or should I use perl?

Body:
3 million columns of data, eh?  It sounds like you're doing some NLP work.

Assuming this is true, and your matrix is sparse, python can handle it just fine (just not with pandas).  Look at scipy.sparse.  Example:

from scipy.sparse import dok_matrix

A = dok_matrix((10,10))
A[1,1] = 1

B = dok_matrix((10,10))
B[2,2] = 2

print A+B

DOK stands for "dictionary of keys", which is typically used to build the sparse matrix, then it's usually converted to CSR, etc. depending on use.  See available sparse matrix types.


问:
Java 8 Stream read file for every 100 lines
Let's say I have a huge file and I would like to read 100 every lines and do one operation. (I want to combine 100 lines and send a rest request)

In Java 7, I would do something like below.

```<code>try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Is there something we can leverage Java 8 Stream here?
I know we can do something like this but it operates on each line instead of 100 lines. So I think foreach is not the option here.

```<code>try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
you can split the stream by using Stream#skip and Stream#limit, and then send a rest request per 100 lines in parallel. for example:

```<code>split(Paths.get("file"), 100).parallel().forEach(this::sendRequest);
</code>```

```<code>Stream<Stream<String>> split(Path path, int limit) throws IOException {
    return LongStream.of(0, lines(path) / limit).parallel()
            .map(it -> it * limit)
            .mapToObj(offset -> {
                try {
                    return Files.lines(path).skip(offset).limit(limit);
                } catch (IOException e) {
                    throw new RejectedExecutionException(e);
                }
            });
}

long lines(Path path) throws IOException {
    try (LineNumberReader in = open(path)) {
        return in.getLineNumber();
    }
}

LineNumberReader open(Path path) throws IOException {
    return new LineNumberReader(newBufferedReader(path));
}

void sendRequest(Stream<String> each) {
    try (BufferedWriter out = null) {// todo: create the output writer
        each.forEach(line -> {
            try {
                out.write(line);
            } catch (IOException e) {
                // todo: handle error
            }
        });
    } catch (IOException ex) {
        //todo: handle error
    }
}
</code>```

IF you want higher performance, you must implements your own algorithm in split & lines method. and Note LineNumberReader#getLineNumber is an int rather than an long. for calculate lines I think there are many opensource projects that can be calculates the total lines number in parallel.

AND this just an skeleton, if you want the highest performance. first, you need indexing the line information, e.g:(totalLines and offset) in parallel (the algorithm like as merge sort)  into memory or disk if needed. then you can using RandomeAccessFile to jump to the offset quickly.

The Indexed Line Information File Format like as below

```<code>total_lines|ofsset1|offset2|...|offsetN
</code>```

Note: there is no separator | in the Line Information File. and each value you must using DataOutputStream#writeLong to write as a long, because write the Line Information File in this format you can calculate the position of offsetN by bytes, e.g: 8*M; M=(1..N), then you can obtain the offsetN by read 8 bytes from the offsetN.

Indeed, the index file should be created when the huge file (if the file is too huge, it need to split too) was created, then it can saving lost of your time for using as further.

Body:
Let's say I have a huge file and I would like to read 100 every lines and do one operation. (I want to combine 100 lines and send a rest request)

In Java 7, I would do something like below.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Is there something we can leverage Java 8 Stream here?
I know we can do something like this but it operates on each line instead of 100 lines. So I think foreach is not the option here.

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

Body:
you can split the stream by using Stream#skip and Stream#limit, and then send a rest request per 100 lines in parallel. for example:

split(Paths.get("file"), 100).parallel().forEach(this::sendRequest);

Stream<Stream<String>> split(Path path, int limit) throws IOException {
    return LongStream.of(0, lines(path) / limit).parallel()
            .map(it -> it * limit)
            .mapToObj(offset -> {
                try {
                    return Files.lines(path).skip(offset).limit(limit);
                } catch (IOException e) {
                    throw new RejectedExecutionException(e);
                }
            });
}

long lines(Path path) throws IOException {
    try (LineNumberReader in = open(path)) {
        return in.getLineNumber();
    }
}

LineNumberReader open(Path path) throws IOException {
    return new LineNumberReader(newBufferedReader(path));
}

void sendRequest(Stream<String> each) {
    try (BufferedWriter out = null) {// todo: create the output writer
        each.forEach(line -> {
            try {
                out.write(line);
            } catch (IOException e) {
                // todo: handle error
            }
        });
    } catch (IOException ex) {
        //todo: handle error
    }
}

IF you want higher performance, you must implements your own algorithm in split & lines method. and Note LineNumberReader#getLineNumber is an int rather than an long. for calculate lines I think there are many opensource projects that can be calculates the total lines number in parallel.

AND this just an skeleton, if you want the highest performance. first, you need indexing the line information, e.g:(totalLines and offset) in parallel (the algorithm like as merge sort)  into memory or disk if needed. then you can using RandomeAccessFile to jump to the offset quickly.

The Indexed Line Information File Format like as below

total_lines|ofsset1|offset2|...|offsetN

Note: there is no separator | in the Line Information File. and each value you must using DataOutputStream#writeLong to write as a long, because write the Line Information File in this format you can calculate the position of offsetN by bytes, e.g: 8*M; M=(1..N), then you can obtain the offsetN by read 8 bytes from the offsetN.

Indeed, the index file should be created when the huge file (if the file is too huge, it need to split too) was created, then it can saving lost of your time for using as further.


问:
Change View Background color for clicked recyclerview items
I am trying to change the background color of my recyclerview row when it is clicked. When one row is clicked, its background color is changed. If another row is clicked, then the previous row changes back to its old state and the newly clicked one changes color.

I've tried achieving this using selectors, but when i release the touch, the color just goes back to normal and none of my rows are highlighted.

Would anyone have an idea how to approach this? Thanks in advance

Here is my selector code - Desired goal (Selected row STAYS charcoal until another row is selected)

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@color/charcoal_dark" />
    <item android:state_enabled="true"
        android:state_focused="false" android:drawable="@color/charcoal_dark" />
    <item android:drawable="@color/black"/>
</selector>
</code>```

答:
There are several ways this is a question I posted about multiselection. But your rows shall have a boolean property, for me this is the most simple way to do it of all I have found. In my question @cool alien showed a different aproach. Here is another one, the only difference from your question is that you are looking for single-select.
For Single select in your OnBindViewHolder, you should have a variable tracking previous selections and adjust, when there is a click. I have at the end of my question my code.</p>

Body:
I am trying to change the background color of my recyclerview row when it is clicked. When one row is clicked, its background color is changed. If another row is clicked, then the previous row changes back to its old state and the newly clicked one changes color.

I've tried achieving this using selectors, but when i release the touch, the color just goes back to normal and none of my rows are highlighted.

Would anyone have an idea how to approach this? Thanks in advance

Here is my selector code - Desired goal (Selected row STAYS charcoal until another row is selected)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true"
        android:state_pressed="true" android:drawable="@color/charcoal_dark" />
    <item android:state_enabled="true"
        android:state_focused="false" android:drawable="@color/charcoal_dark" />
    <item android:drawable="@color/black"/>
</selector>


问:
Can't Connect to BigTable using Connection Factory
I am using a custom code to load HFiles directly into BigTable using the following API's
LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);
loader.doBulkLoad(new Path(inputPath), admin, table, regionLocator);
while using ConnectionFactory I am using the following function in the statement

```<code>Connection connection = ConnectionFactory.createConnection(conf, null, null);
</code>```

which always returns the parameter managed as false but I am getting the following error while running it.

```<code>java.io.IOException: java.lang.reflect.InvocationTargetException
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:431)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
        at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:302)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:235)
        at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles.initialize(LoadIncrementalHFiles.java:154)
        at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles.<init>(LoadIncrementalHFiles.java:144)
        at com.example.bigtable.sample.BigtableLoader.main(BigtableLoader.java:122)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
        at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
        at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:152)
        at com.example.bigtable.sample.BigtableDriver.main(BigtableDriver.java:18)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
        at com.google.cloud.hadoop.services.agent.job.shim.HadoopRunJarShim.main(HadoopRunJarShim.java:12)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
        ... 22 more
Caused by: java.lang.IllegalArgumentException: Bigtable does not support managed connections.
        at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:130)
        at com.google.cloud.bigtable.hbase1_2.BigtableConnection.<init>(BigtableConnection.java:55)
        ... 27 more
</code>```

答: Cloud Bigtable does not support LoadIncrementalHFiles.  If you want to load data, your best bet is to use these instructions.</p>

Body:
I am using a custom code to load HFiles directly into BigTable using the following API's
LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);
loader.doBulkLoad(new Path(inputPath), admin, table, regionLocator);
while using ConnectionFactory I am using the following function in the statement

Connection connection = ConnectionFactory.createConnection(conf, null, null);

which always returns the parameter managed as false but I am getting the following error while running it.

java.io.IOException: java.lang.reflect.InvocationTargetException
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:240)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:431)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
        at org.apache.hadoop.hbase.client.ConnectionManager.getConnectionInternal(ConnectionManager.java:302)
        at org.apache.hadoop.hbase.client.HBaseAdmin.<init>(HBaseAdmin.java:235)
        at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles.initialize(LoadIncrementalHFiles.java:154)
        at org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles.<init>(LoadIncrementalHFiles.java:144)
        at com.example.bigtable.sample.BigtableLoader.main(BigtableLoader.java:122)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.ProgramDriver$ProgramDescription.invoke(ProgramDriver.java:71)
        at org.apache.hadoop.util.ProgramDriver.run(ProgramDriver.java:144)
        at org.apache.hadoop.util.ProgramDriver.driver(ProgramDriver.java:152)
        at com.example.bigtable.sample.BigtableDriver.main(BigtableDriver.java:18)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at org.apache.hadoop.hbase.client.ConnectionManager.createConnection(ConnectionManager.java:424)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
        at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
        at com.google.cloud.hadoop.services.agent.job.shim.HadoopRunJarShim.main(HadoopRunJarShim.java:12)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:238)
        ... 22 more
Caused by: java.lang.IllegalArgumentException: Bigtable does not support managed connections.
        at org.apache.hadoop.hbase.client.AbstractBigtableConnection.<init>(AbstractBigtableConnection.java:130)
        at com.google.cloud.bigtable.hbase1_2.BigtableConnection.<init>(BigtableConnection.java:55)
        ... 27 more


问:
check if a number is present in a list, app engine templates
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

```<code>{% for number in list }
  <td {% if number in another_list %}class="special"{% endif %}>{{number}}</td>
{% endfor }
</code>```

答: At this point you might be better off writing your own templatetag, or using something like smartif, which should let you do {% if foo in bar %}.

Body:
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

{% for number in list }
  {{number}}
{% endfor }


问:
Can't get state to update array inside of an object correctly in REACT/REDUX
I am going to break this down step by step for what I want to happen so hopefully people can understand what I am wanting.

Using React/Redux, Lodash

I have many post that are sent from a back end api as an array. Each post has an _id. When I call on the action getAllPost() it gives me back that array with all the post. This is working just fine.

I then dispatch type GET_ALL_POSTS and it triggers the reducer reducer_posts to change/update the state.

reducer:

```<code>export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
    const postsState =  _.mapKeys(action.payload.data, '_id');
    //const newPostsState = _.map(postsState, post => {
      //const newComments = _.mapKeys(post.comments, '_id');
    //});
      return postsState;
    break;
    default:
      return state;
    break;
  }
}
</code>```

As you can see I change the array into one giant object that contains many post as objects with keys that are equal to their '_id'. This works just fine and returning this part of the state also works fine.

As I mentioned each of these posts has a comments value that is an array. I would like to change the comments array into one large object that holds each comment as an object with a key that is equal to their '_id' just like I did in the post.

Now I need to do this all at once and return the newly created state with One large object that contains all the post as objects and on each of those post there should be a comments object that contains all the comments as objects. I will try to write some example code to show what I am trying to do.

Example:

```<code>BigPostsObject {
1: SinglePostObject{},
2: SinglePostObject{},
3: SinglePostObject {
  _id: '3',
  author: 'Mike',
  comments: BigCommentObject{1: SingleCommentObject{}, 2: SingleCommentObject{}}
 }
}
</code>```

I hope that the example kind of clears up what I am trying to do. If it still is confusing as to what I am doing then please ask and also please do not say things like use an array instead. I know I can use an array, but that is not helpful to this post as if others want to do it this way that is not helpful information.

答:
Write a function that processes all the comments from the comments array for each post you have in the posts array:

```<code>function processComment(post) {
   post.bigCommentsObject = _.mapKeys(post.comments, '_id');
   // now the comments array is no longer needed
   return _.omit(post, ['comments']);

}
</code>```

Now use that function to turn each comments array into a big object with all the comments WHILE it still is in the array. Then afterwards turn the array itself in a big object:

```<code>const commentsProcessed =  _.map(action.payload.data, procesComment);
const postsState =  _.mapKeys(commentsProcessed, '_id');
</code>```

Body:
I am going to break this down step by step for what I want to happen so hopefully people can understand what I am wanting.

Using React/Redux, Lodash

I have many post that are sent from a back end api as an array. Each post has an _id. When I call on the action getAllPost() it gives me back that array with all the post. This is working just fine.

I then dispatch type GET_ALL_POSTS and it triggers the reducer reducer_posts to change/update the state.

reducer:

export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
    const postsState =  _.mapKeys(action.payload.data, '_id');
    //const newPostsState = _.map(postsState, post => {
      //const newComments = _.mapKeys(post.comments, '_id');
    //});
      return postsState;
    break;
    default:
      return state;
    break;
  }
}

As you can see I change the array into one giant object that contains many post as objects with keys that are equal to their '_id'. This works just fine and returning this part of the state also works fine.

As I mentioned each of these posts has a comments value that is an array. I would like to change the comments array into one large object that holds each comment as an object with a key that is equal to their '_id' just like I did in the post.

Now I need to do this all at once and return the newly created state with One large object that contains all the post as objects and on each of those post there should be a comments object that contains all the comments as objects. I will try to write some example code to show what I am trying to do.

Example:

BigPostsObject {
1: SinglePostObject{},
2: SinglePostObject{},
3: SinglePostObject {
  _id: '3',
  author: 'Mike',
  comments: BigCommentObject{1: SingleCommentObject{}, 2: SingleCommentObject{}}
 }
}

I hope that the example kind of clears up what I am trying to do. If it still is confusing as to what I am doing then please ask and also please do not say things like use an array instead. I know I can use an array, but that is not helpful to this post as if others want to do it this way that is not helpful information.

Body:
Write a function that processes all the comments from the comments array for each post you have in the posts array:

function processComment(post) {
   post.bigCommentsObject = _.mapKeys(post.comments, '_id');
   // now the comments array is no longer needed
   return _.omit(post, ['comments']);

}

Now use that function to turn each comments array into a big object with all the comments WHILE it still is in the array. Then afterwards turn the array itself in a big object:

const commentsProcessed =  _.map(action.payload.data, procesComment);
const postsState =  _.mapKeys(commentsProcessed, '_id');


问:
Remove duplicate values of specific key in multidimensional array in PHP but remove the last?
I have an array like this

```<code> Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)
</code>```

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

```<code>foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}
</code>```

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

```<code>Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)
</code>```

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

答:
Try this:

It begins with an array. The first time an duplicate is encountered, it's value is added to the array. The second, third, etc. time it's encountered, it's removed.

$dup = array();

foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            if ( in_array( $value['clave'], $dup) ) {
                unset($my_array[$k]);
            } else {
              $dup[] = $value['clave'];
            }
        }
    }
}
```

Body:
I have an array like this

 Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.


问:
Custom grouping for legend in ggplot
In R, I am trying to create a custom line chart where all the lines are shown on the chart, but the legend for chart is customized to only show two things.

Right now my code:

```<code>x = data.frame(runif(20),runif(20)*2,runif(20)*3)
names(x) = c("Run 1", "Run 2", "Run 3")
x$Avg = apply(x, 1, mean)
x$Step = row.names(x)
df = melt(x, id=c("Step"))
ggplot(df, aes(x=Step, y=value, group=variable, color=variable)) +
  geom_line()
</code>```

Result:

I would like to have the chart show all 4 lines (runs 1,2,3  and avg), but for the legend, I want it to read "Avg" and "Individual Runs", where "Avg" is any color I choose, and each of the "Individual Runs" is in gray or some neutral color. This way when I have lots of runs, I see visually see the data but the legend doesnt go off the screen. How do I accomplish this?

答:
You could make a grouping variable to map to color that has only two levels.  This is pretty straightforward using the fct_other function from package forcats.

This keeps the "Avg" group but lump all other runs together into a single level, which can be set via other_level.

```<code>library(forcats)
df$variable2 = fct_other(df$variable, keep = "Avg", other_level = "Individual Runs")
</code>```

Use the new variable for color, keeping the original variable variable for group. Set colors with scale_color_manual.

```<code>ggplot(df, aes(x = Step, y = value, group = variable, color = variable2)) +
     geom_line() +
     scale_color_manual(values = c("red", "grey") )
</code>```

Title: Custom grouping for legend in ggplot

Body:
In R, I am trying to create a custom line chart where all the lines are shown on the chart, but the legend for chart is customized to only show two things.

Right now my code:

x = data.frame(runif(20),runif(20)*2,runif(20)*3)
names(x) = c("Run 1", "Run 2", "Run 3")
x$Avg = apply(x, 1, mean)
x$Step = row.names(x)
df = melt(x, id=c("Step"))
ggplot(df, aes(x=Step, y=value, group=variable, color=variable)) +
  geom_line()

Result:

I would like to have the chart show all 4 lines (runs 1,2,3  and avg), but for the legend, I want it to read "Avg" and "Individual Runs", where "Avg" is any color I choose, and each of the "Individual Runs" is in gray or some neutral color. This way when I have lots of runs, I see visually see the data but the legend doesnt go off the screen. How do I accomplish this?

Body:
You could make a grouping variable to map to color that has only two levels.  This is pretty straightforward using the fct_other function from package forcats.

This keeps the "Avg" group but lump all other runs together into a single level, which can be set via other_level.

library(forcats)
df$variable2 = fct_other(df$variable, keep = "Avg", other_level = "Individual Runs")

Use the new variable for color, keeping the original variable variable for group. Set colors with scale_color_manual.

ggplot(df, aes(x = Step, y = value, group = variable, color = variable2)) +
     geom_line() +
     scale_color_manual(values = c("red", "grey") )


问:
swift stop loop and continue it with a button
is it possible to stop an for in loop and continue it and the stopped position with a button.

i mean something like this:

```<code>for x in 0..<5 {

   if x == 3 {
      // show a button
      // this button have to be pressed
      // which do some tasks
      // when all tasks are finished >
      // continue this loop at the stopped point
   }
}
</code>```

is this possible? if yes, how?

答:
Short answer: use a semaphore

Longer answer:

Your situation is an example of the more general case of how to pause some computation, saving its current state (local variables, call stack, etc.), and later to resume it from the same point, with all state restored.

Some languages/systems provide coroutines to support this, others the more esoteric call with current continuation, neither are available to you (currently) Swift...

What you do have is Grand Central Dispatch (GCD), provided in Swift through Dispatch, which provides support for executing concurrent asynchronous tasks and synchronisation between them. Other concurrency mechanisms such as pthread are also available, but GCD tends to be recommended.

Using GCD an outline of a solution is:

Execute you loop as an asynchronous concurrent task. It must not be executing on the main thread or you will deadlock...

When you wish to pause:

Create a semaphore

Start another async task to display the button, run the other jobs etc. This new task must signal the semaphore when it is finished. The new task may call the main thread to perform UI operations.

Your loop task waits on the semaphore, this will block the loop task until the button task signals it.

This may sound complicated but with Swift block syntax and Dispatch it is quite simple. However you do need to read up on GCD first!

Alternatively you can ask whether you can restructure your solution into multiple parts so saving/restoring the current state is not required. You might find designs such as continuation passing style useful, which again is quite easy using Swift's blocks.

HTH

Body:
is it possible to stop an for in loop and continue it and the stopped position with a button.

i mean something like this:

for x in 0..<5 {

   if x == 3 {
      // show a button
      // this button have to be pressed
      // which do some tasks
      // when all tasks are finished >
      // continue this loop at the stopped point
   }
}

is this possible? if yes, how?


问:
LAMP vhost still points to www/html
I've created the following virtual host file in /etc/apache2/sites-available/lion.dev:

```<code><VirtualHost *:80>
    ServerAdmin webmaster@lion.dev
    ServerName lion.dev

    DocumentRoot /var/www/lion.dev
    <Directory />
    Options FollowSymLinks
    AllowOverride None
    </Directory>
    <Directory /var/www/lion.dev/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>

    CustomLog /var/log/apache2/lion.dev/access.log combined
    ErrorLog /var/log/apache2/lion.dev/error.log
</VirtualHost>
</code>```

The problem is that it is actually pointing to the /www/html folder when I visit lion.dev in my browser.

What am I missing and why isn't this working?

答:
Did you uncomment load virtual host in httpd.conf file?
That is usally commented and the module wont be loaded, just remove //before virtual host part.
My apologies I saw late that you resolved the issue.</p>

Title: LAMP vhost still points to www/html

Body:
I've created the following virtual host file in /etc/apache2/sites-available/lion.dev:

<VirtualHost *:80>
    ServerAdmin webmaster@lion.dev
    ServerName lion.dev

    DocumentRoot /var/www/lion.dev
    <Directory />
    Options FollowSymLinks
    AllowOverride None
    </Directory>
    <Directory /var/www/lion.dev/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>

    CustomLog /var/log/apache2/lion.dev/access.log combined
    ErrorLog /var/log/apache2/lion.dev/error.log
</VirtualHost>

The problem is that it is actually pointing to the /www/html folder when I visit lion.dev in my browser.

What am I missing and why isn't this working?


问:
Custom metric based on tensorflow's streaming metrics returns NaN
I'm trying to define the F1-score as a custom metric in TensorFlow for a DNNClassifier. To do that, I wrote a function

```<code>def metric_fn(predictions=[], labels=[], weights=[]):
    P, _ = tf.contrib.metrics.streaming_precision(predictions, labels)
    R, _ = tf.contrib.metrics.streaming_recall(predictions, labels)
    if P + R == 0:
        return 0
    return 2*(P*R)/(P+R)
</code>```

that uses streaming_precision and streaming_recall from TensorFlow to calulate the F1 score. After that I made a new entry to the validation_metrics:

```<code>validation_metrics = {
    "accuracy":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_accuracy,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "precision":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_precision,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "recall":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_recall,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "f1score":
        tf.contrib.learn.MetricSpec(
            metric_fn=metric_fn,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES)
}
</code>```

However, although I get correct precision and recall values, f1score is always nan:

INFO:tensorflow:Saving dict for global step 151: accuracy = 0.982456, accuracy/baseline_label_mean = 0.397661, accuracy/threshold_0.500000_mean = 0.982456, auc = 0.982867, f1score = nan, global_step = 151, labels/actual_label_mean = 0.397661, labels/prediction_mean = 0.406118, loss = 0.310612, precision = 0.971014, precision/positive_threshold_0.500000_mean = 0.971014, recall = 0.985294, recall/positive_threshold_0.500000_mean = 0.985294
```

Something is wrong with my metric_fn, but I can't figure it out.
The values P and R obtained by metric_fn are of the form
Tensor("precision/value:0", shape=(), dtype=float32). I find this a bit strange. I was expecting a scalar tensor.

Any help is appreciated.

答:
I think the problem may come from the fact that the streaming metrics you use within your metric_fn do not get any update.

Try the following (I also included minor modifications to my taste):

```<code>def metric_fn(predictions=None, labels=None, weights=None):
    P, update_op1 = tf.contrib.metrics.streaming_precision(predictions, labels)
    R, update_op2 = tf.contrib.metrics.streaming_recall(predictions, labels)
    eps = 1e-5;
    return (2*(P*R)/(P+R+eps), tf.group(update_op1, update_op2))
</code>```

Body:
I'm trying to define the F1-score as a custom metric in TensorFlow for a DNNClassifier. To do that, I wrote a function

def metric_fn(predictions=[], labels=[], weights=[]):
    P, _ = tf.contrib.metrics.streaming_precision(predictions, labels)
    R, _ = tf.contrib.metrics.streaming_recall(predictions, labels)
    if P + R == 0:
        return 0
    return 2*(P*R)/(P+R)

that uses streaming_precision and streaming_recall from TensorFlow to calulate the F1 score. After that I made a new entry to the validation_metrics:

validation_metrics = {
    "accuracy":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_accuracy,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "precision":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_precision,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "recall":
        tf.contrib.learn.MetricSpec(
            metric_fn=tf.contrib.metrics.streaming_recall,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES),
    "f1score":
        tf.contrib.learn.MetricSpec(
            metric_fn=metric_fn,
            prediction_key=tf.contrib.learn.PredictionKey.CLASSES)
}

However, although I get correct precision and recall values, f1score is always nan:

INFO:tensorflow:Saving dict for global step 151: accuracy = 0.982456, accuracy/baseline_label_mean = 0.397661, accuracy/threshold_0.500000_mean = 0.982456, auc = 0.982867, f1score = nan, global_step = 151, labels/actual_label_mean = 0.397661, labels/prediction_mean = 0.406118, loss = 0.310612, precision = 0.971014, precision/positive_threshold_0.500000_mean = 0.971014, recall = 0.985294, recall/positive_threshold_0.500000_mean = 0.985294

Something is wrong with my metric_fn, but I can't figure it out.
The values P and R obtained by metric_fn are of the form
Tensor("precision/value:0", shape=(), dtype=float32). I find this a bit strange. I was expecting a scalar tensor.

Any help is appreciated.

Body:
I think the problem may come from the fact that the streaming metrics you use within your metric_fn do not get any update.

Try the following (I also included minor modifications to my taste):

def metric_fn(predictions=None, labels=None, weights=None):
    P, update_op1 = tf.contrib.metrics.streaming_precision(predictions, labels)
    R, update_op2 = tf.contrib.metrics.streaming_recall(predictions, labels)
    eps = 1e-5;
    return (2*(P*R)/(P+R+eps), tf.group(update_op1, update_op2))


问:
bash - How to find the index of the maximum value of a row in a matrix
Here's my input :

```<code>chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907
</code>```

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

```<code>data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)
</code>```

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

```<code>maxindex= 1  1  1  1
</code>```

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

答:
Use the following awk solution, it will go faster than perl approach (on "big" files):

```<code>awk '{ m=$3; p=1; for(i=4;i<=NF;i++) {
           if ($i>m) { m=$i; p=i-2 } } printf "%d ",p }' file > max_indices
</code>```

m=$3 - initial maximum value (the 3rd field value)

for(i=4;i<=NF;i++) - iterating through remaining fields

if ($i>m) { m=$i; p=i-2 } - capturing maximal value

Body:
Here's my input :

chr1 58962 -0.042053 -22.525086 -20.817409 -19.525688
chr1 58989 -0.014479 -14.459352 -12.824315 -11.744024
chr1 59155 -0.062963 -13.810858 -12.749009 -12.102778
chr1 59256 -0.014105 -7.371202  -9.117587  -11.525907

I'm looking for a way, in bash, to get the index of the maximum value of the row for each row. I don't want to take into account the first two columns.

I could do it very simply in R :

data=fread(myfile)
maxindex=apply(data[,3:6],1,which.max)

So that the output is an array containing the index. This is the kind of output I want in the end. In this case :

maxindex= 1  1  1  1

Unfortunately the whole file is 32 Gb (big table containing 300000 rows and 8183 columns) so that R can't take it even after I subsidized the original file. I've read that bash isn't made to work by row but is there still a way to do what I want to do?

Body:
Use the following awk solution, it will go faster than perl approach (on "big" files):

awk '{ m=$3; p=1; for(i=4;i<=NF;i++) {
           if ($i>m) { m=$i; p=i-2 } } printf "%d ",p }' file > max_indices

m=$3 - initial maximum value (the 3rd field value)

for(i=4;i<=NF;i++) - iterating through remaining fields

if ($i>m) { m=$i; p=i-2 } - capturing maximal value


问:
WordPress wp-admin in Linux Shared Host is out of reach
These days I am facing a weird problem with my wordpress websites on a linux shared host.
I had 6 WordPress websites on my Linux shared host service. As two of them were moved to a new server, I tried to cleanup some mess by deleting some of the cached, temp and log files from different folders such as .trash, .cache, tmp and so on. (I don't remember what files are deleted from which folders exactly).

After this cleaning, I can see the main page of the websites but all /wp-admin's are out of reach even if I install a fresh WP.
When I try to access wp-admin I'll get the following error,

and after that I can't see the main pages for a few hours! It seems that cPanel is blocking my IP for a while, because my domain.com/cpanel is also not working after I tried domain/wp-admin.

Unfortunately, the Mesrahosting host provider has a terrible service support and they are not replying my tickets nor Whatsapp messages.

Any idea to solve this problem would be appreciated.

答:
First of all the tmp folder should exist in your cPanel account. If you deleted it you have to create it in /home/cpaneluserame/tmp and it needs to have cpaneluser:cpaneluser ownership and also 755 permissions. That would be a 1st step. Since you are unable to access cPanel then most probably your ip got blocked by the server's firewall or cPhulkd. In most cases the block is just temporary. If you keep trying then depending on the server's firewall configuration and the settings of cPhulkd (that comes with WHM) your blocking time might be increased gradually. Try accessing cPanel from another ip address (use a proxy or VPN service) and see if that works. When you are able to access cPanel be sure to create /tmp folder and then try again and see if that works. If your ip address is permanently blocked then your only chance to unblock it is to request that to your hoster's tech support team.

So if I were you, I would try accessing cPanel from another ip address.


问:
How to have a dynamic DataTemplateSelector
I have an observable collection that I am displaying in a Xamarin Forms ListView.  I have defined a detail and a summary template that I use to view each list item.  I want to be able to dynamically change between summary and detail template based on a Boolean property in each item.

Here is the item.

```<code>public class MyItem : INotifyPropertyChanged
{
    bool _switch = false;
    public bool Switch
    {
        get
        {
            return _switch;
        }
        set
        {
            if (_switch != value)
            {
                _switch = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Switch"));
            }
        }

    }
    public int Addend1 { get; set; }
    public int Addend2 { get; set; }
    public int Result
    {
        get
        {
            return Addend1 + Addend2;
        }
    }
    public string Summary
    {
        get
        {
            return Addend1 + " + " + Addend2 + " = " + Result;
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

Here is the observable collection.  Note that whenever the switch value changes I remove the item and reinsert.  The reason this is done is to force the ListView to reselect the DataTemplate.

```<code>public class MyItems : ObservableCollection<MyItem>
{
    protected override void InsertItem(int index, MyItem item)
    {
        item.PropertyChanged += MyItems_PropertyChanged;
        base.InsertItem(index, item);
    }
    protected override void RemoveItem(int index)
    {
        this[index].PropertyChanged -= MyItems_PropertyChanged;
        base.RemoveItem(index);
    }
    private void MyItems_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        int index = IndexOf(sender as MyItem);
        if(index >= 0)
        {
            RemoveAt(index);
            Insert(index, sender as MyItem);
        }
    }
}
</code>```

Here is my data template selector...

```<code>public class MyItemTemplateSelector : DataTemplateSelector
{
    DataTemplate Detail { get; set; }
    DataTemplate Summary { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if(item is MyItem)
        {
            return (item as MyItem).Switch ? Detail : Summary;
        }
        return null;
    }
}
</code>```

Here are my resource definitions...

```<code>        <DataTemplate x:Key="MyDetail">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Entry Text="{Binding Addend1}"/>
                    <Entry Text="{Binding Addend2}"/>
                    <Label Text="{Binding Result}"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <DataTemplate x:Key="MySummary">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Label Text="{Binding Summary}" VerticalOptions="Center"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <local:MyItemTemplateSelector x:Key="MySelector" Detail="{StaticResource MyDetail}" Summary="{StaticResource MySummary}"/>
</code>```

Here is my collection initialization...

```<code>        MyItems = new MyItems();
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 2, Addend2 = 3 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 2, Addend2 = 3 });
</code>```

And this is what it looks like...

Right.  So everything works fine. If the switch is toggled the view of the item changes from summary to detail.  The problem is that this cannot be the right way of doing this!  It is a complete kluge to remove a list item and put it back in the same place in order to get the data template to reselect.  But I cannot figure out another way of doing it.  In WPF I used a data trigger in an item container style to set the content template based on the switch value, but there seems to be no way to do the equivalent thing in Xamarin.

答:
The way to do this is not through switching templates, but defining a content view as the template and changing the visibility of controls within the template.  There is apparently no way to get the ListView to re-evaluate the item template on an item short of removing it and re-adding it.

Here is my content view...

```<code><ContentView xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XamarinFormsBench"
         x:Class="XamarinFormsBench.SummaryDetailView">
<ContentView.Content>
  <StackLayout x:Name="stackLayout" Orientation="Horizontal">
        <Switch x:Name="toggle" IsToggled="{Binding Switch}"/>
        <Entry x:Name="addend1" Text="{Binding Addend1}"/>
        <Entry x:Name="addend2" Text="{Binding Addend2}"/>
        <Label x:Name="result" Text="{Binding Result}"/>
        <Label x:Name="summary" Text="{Binding Summary}" VerticalOptions="Center"/>
    </StackLayout>
</ContentView.Content>
</code>```

This is the code behind...

```<code>namespace XamarinFormsBench
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SummaryDetailView : ContentView
{
    public SummaryDetailView()
    {
        InitializeComponent();
        toggle.PropertyChanged += Toggle_PropertyChanged;
        UpdateVisibility();
    }

    private void Toggle_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if(e.PropertyName == "IsToggled")
        {
            UpdateVisibility();
        }
    }

    private void UpdateVisibility()
    {
        bool isDetail = toggle.IsToggled;
        addend1.IsVisible = isDetail;
        addend2.IsVisible = isDetail;
        result.IsVisible = isDetail;
        summary.IsVisible = !isDetail;
        InvalidateLayout();  // this is key!
    }
}
}
</code>```

Now the main page contains this...

```<code>    <ListView ItemsSource="{Binding MyItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <local:SummaryDetailView/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

The key to making this work properly is to invalidate the layout of the ContentView when switching between summary and detail.  This forces the ListView to layout the cell again.  Without this the controls that are made invisible disappear the controls made visible never show.  You do not need this if the ContentView is used outside of the ListView.  This seems to me to be a bug in the ListView.  You could get the item template switching to work if you could invalidate the layout of the ViewCell, but there is no public method (only a protected one) to do this.

Body:
I have an observable collection that I am displaying in a Xamarin Forms ListView.  I have defined a detail and a summary template that I use to view each list item.  I want to be able to dynamically change between summary and detail template based on a Boolean property in each item.

Here is the item.

public class MyItem : INotifyPropertyChanged
{
    bool _switch = false;
    public bool Switch
    {
        get
        {
            return _switch;
        }
        set
        {
            if (_switch != value)
            {
                _switch = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Switch"));
            }
        }

    }
    public int Addend1 { get; set; }
    public int Addend2 { get; set; }
    public int Result
    {
        get
        {
            return Addend1 + Addend2;
        }
    }
    public string Summary
    {
        get
        {
            return Addend1 + " + " + Addend2 + " = " + Result;
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Here is the observable collection.  Note that whenever the switch value changes I remove the item and reinsert.  The reason this is done is to force the ListView to reselect the DataTemplate.

public class MyItems : ObservableCollection<MyItem>
{
    protected override void InsertItem(int index, MyItem item)
    {
        item.PropertyChanged += MyItems_PropertyChanged;
        base.InsertItem(index, item);
    }
    protected override void RemoveItem(int index)
    {
        this[index].PropertyChanged -= MyItems_PropertyChanged;
        base.RemoveItem(index);
    }
    private void MyItems_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        int index = IndexOf(sender as MyItem);
        if(index >= 0)
        {
            RemoveAt(index);
            Insert(index, sender as MyItem);
        }
    }
}

Here is my data template selector...

public class MyItemTemplateSelector : DataTemplateSelector
{
    DataTemplate Detail { get; set; }
    DataTemplate Summary { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if(item is MyItem)
        {
            return (item as MyItem).Switch ? Detail : Summary;
        }
        return null;
    }
}

Here are my resource definitions...

        <DataTemplate x:Key="MyDetail">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Entry Text="{Binding Addend1}"/>
                    <Entry Text="{Binding Addend2}"/>

                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <DataTemplate x:Key="MySummary">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>

                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <local:MyItemTemplateSelector x:Key="MySelector" Detail="{StaticResource MyDetail}" Summary="{StaticResource MySummary}"/>

Here is my collection initialization...

        MyItems = new MyItems();
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 2, Addend2 = 3 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 2, Addend2 = 3 });

And this is what it looks like...

Right.  So everything works fine. If the switch is toggled the view of the item changes from summary to detail.  The problem is that this cannot be the right way of doing this!  It is a complete kluge to remove a list item and put it back in the same place in order to get the data template to reselect.  But I cannot figure out another way of doing it.  In WPF I used a data trigger in an item container style to set the content template based on the switch value, but there seems to be no way to do the equivalent thing in Xamarin.

Body:
The way to do this is not through switching templates, but defining a content view as the template and changing the visibility of controls within the template.  There is apparently no way to get the ListView to re-evaluate the item template on an item short of removing it and re-adding it.

Here is my content view...

<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:XamarinFormsBench"
         x:Class="XamarinFormsBench.SummaryDetailView">
<ContentView.Content>
  <StackLayout x:Name="stackLayout" Orientation="Horizontal">
        <Switch x:Name="toggle" IsToggled="{Binding Switch}"/>
        <Entry x:Name="addend1" Text="{Binding Addend1}"/>
        <Entry x:Name="addend2" Text="{Binding Addend2}"/>
        <Label x:Name="result" Text="{Binding Result}"/>
        <Label x:Name="summary" Text="{Binding Summary}" VerticalOptions="Center"/>
    </StackLayout>
</ContentView.Content>

This is the code behind...

namespace XamarinFormsBench
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SummaryDetailView : ContentView
{
    public SummaryDetailView()
    {
        InitializeComponent();
        toggle.PropertyChanged += Toggle_PropertyChanged;
        UpdateVisibility();
    }

    private void Toggle_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if(e.PropertyName == "IsToggled")
        {
            UpdateVisibility();
        }
    }

    private void UpdateVisibility()
    {
        bool isDetail = toggle.IsToggled;
        addend1.IsVisible = isDetail;
        addend2.IsVisible = isDetail;
        result.IsVisible = isDetail;
        summary.IsVisible = !isDetail;
        InvalidateLayout();  // this is key!
    }
}
}

Now the main page contains this...

    <ListView ItemsSource="{Binding MyItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <local:SummaryDetailView/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

The key to making this work properly is to invalidate the layout of the ContentView when switching between summary and detail.  This forces the ListView to layout the cell again.  Without this the controls that are made invisible disappear the controls made visible never show.  You do not need this if the ContentView is used outside of the ListView.  This seems to me to be a bug in the ListView.  You could get the item template switching to work if you could invalidate the layout of the ViewCell, but there is no public method (only a protected one) to do this.


问:
Sed move a line
I just need to move a line up in sed. I can select the line with

```<code>sed -i '7s///'
</code>```

I need to move line 7 up 2 lines so it will be line 5.

I can't find anything on the internet to do this without complicated scripts, I can't find a simple solution of moving a specific line a specific number of times.

答:
ed is better at this, since it has a "move" command that does exactly what you want.  To move line 7 to be the line after line 4, just do 7m4.  ed doesn't write the data back by default, so you need to explicitly issue a w command to write the data:

```<code>printf '7m4\nw\n' | ed input
</code>```

Although it is perhaps better to use a more modern tool:

```<code>ex -s -c 7m4 -c w -c q input
</code>```

Title: Sed move a line

Body:
I just need to move a line up in sed. I can select the line with

sed -i '7s///'

I need to move line 7 up 2 lines so it will be line 5.

I can't find anything on the internet to do this without complicated scripts, I can't find a simple solution of moving a specific line a specific number of times.

Body:
ed is better at this, since it has a "move" command that does exactly what you want.  To move line 7 to be the line after line 4, just do 7m4.  ed doesn't write the data back by default, so you need to explicitly issue a w command to write the data:

printf '7m4\nw\n' | ed input

Although it is perhaps better to use a more modern tool:

ex -s -c 7m4 -c w -c q input