问:
why i can't parse xml in javascript?
hello i have problem to parse xml..
i have xml like this :

```<code><tejemahan>
  <kategori> komputer </kategori>
  <hasil> aplikasi komputer </hasil>
</terjemahan>
</code>```

Edited:

xml above I get in that way :

```<code>   var url="http://localhost:8080/inlinetrans/api/translate/"+userSelection+"/"+hasilStemSel+"/"+hasilStem;
   var client = new XMLHttpRequest();
   client.open("GET", url, false);
   client.setRequestHeader("Content-Type", "text/plain");
   client.send(null);

   if(client.status == 200)
       alert("the request success"+client.responseText);
   else
       alert("the request isn't success"+client.status+""+client.statusText)

  }
</code>```

and this is my code to parse an xml file above :

```<code>this.loadXML = function (){
   var url = http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem
   xmlDoc=document.implementation.createDocument("","",null);
   xmlDoc.load("url");
   xmlDoc.onload= this.readXML;
  }

  this.readXML = function() {
        alert(xmlDoc.documentElement.tagName);
 alert(xmlDoc.documentElement.childNodes[0].tagName);
 alert(xmlDoc.documentElement.childNodes[1].tagName);
 alert(xmlDoc.documentElement.childNodes[0].textContent);
 alert(xmlDoc.documentElement.childNodes[1].textContent);

     }
</code>```

i can execute this code

```<code>xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("url");
</code>```

but why i can't execute this code
 xmlDoc.load = this.readXML ???

答:
Firstly, I second David Dorward's suggestion: use XMLHttpRequest instead, which will work in all major browsers. Code is below.

Secondly, your readXML function is flawed, since most browsers will include whitespace text nodes within the childNodes collection, so xmlDoc.documentElement.childNodes[0] will actually be a text node and have no tagName property. I would suggest using getElementsByTagName() or checking the nodeType property of each node as you iterate over childNodes.

Thirdly, your XML is not valid: the <tejemahan> and </terjemahan> do not match, although this may be a typo in your question.

```<code>var url = "http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem;

var readXML = function(xmlDoc) {
    alert(xmlDoc.documentElement.tagName);
    var kategori = xmlDoc.getElementsByTagName("kategori")[0];
    alert(kategori.tagName);
};

var createXmlHttpRequest = (function() {
    var factories = [
        function() { return new XMLHttpRequest(); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
        function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
    ];

    for (var i = 0, len = factories.length; i < len; ++i) {
        try {
            if ( factories[i]() ) {
                return factories[i];
            }
        }
        catch (e) {}
    }
})();

var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        readXML(xmlHttp.responseXML);
    }
};

xmlHttp.open("GET", url, true);
xmlHttp.send(null);
</code>```

Title: why i can't parse xml in javascript?

Body:
hello i have problem to parse xml..
i have xml like this :

<tejemahan>
  <kategori> komputer </kategori>
  <hasil> aplikasi komputer </hasil>
</terjemahan>

Edited:

xml above I get in that way :

   var url="http://localhost:8080/inlinetrans/api/translate/"+userSelection+"/"+hasilStemSel+"/"+hasilStem;
   var client = new XMLHttpRequest();
   client.open("GET", url, false);
   client.setRequestHeader("Content-Type", "text/plain");
   client.send(null);

   if(client.status == 200)
       alert("the request success"+client.responseText);
   else
       alert("the request isn't success"+client.status+""+client.statusText)

  }

and this is my code to parse an xml file above :

this.loadXML = function (){
   var url = http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem
   xmlDoc=document.implementation.createDocument("","",null);
   xmlDoc.load("url");
   xmlDoc.onload= this.readXML;
  }

  this.readXML = function() {
        alert(xmlDoc.documentElement.tagName);
 alert(xmlDoc.documentElement.childNodes[0].tagName);
 alert(xmlDoc.documentElement.childNodes[1].tagName);
 alert(xmlDoc.documentElement.childNodes[0].textContent);
 alert(xmlDoc.documentElement.childNodes[1].textContent);

     }

i can execute this code

xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("url");

but why i can't execute this code
 xmlDoc.load = this.readXML ???

Body:
Firstly, I second David Dorward's suggestion: use XMLHttpRequest instead, which will work in all major browsers. Code is below.

Secondly, your readXML function is flawed, since most browsers will include whitespace text nodes within the childNodes collection, so xmlDoc.documentElement.childNodes[0] will actually be a text node and have no tagName property. I would suggest using getElementsByTagName() or checking the nodeType property of each node as you iterate over childNodes.

Thirdly, your XML is not valid: the <tejemahan> and </terjemahan> do not match, although this may be a typo in your question.

var url = "http://localhost:8080/coba/api/artikan/"+sel+"/"+hasilStemSel+"/"+hasilStem;

var readXML = function(xmlDoc) {
    alert(xmlDoc.documentElement.tagName);
    var kategori = xmlDoc.getElementsByTagName("kategori")[0];
    alert(kategori.tagName);
};

var createXmlHttpRequest = (function() {
    var factories = [
        function() { return new XMLHttpRequest(); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); },
        function() { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); },
        function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
    ];

    for (var i = 0, len = factories.length; i < len; ++i) {
        try {
            if ( factories[i]() ) {
                return factories[i];
            }
        }
        catch (e) {}
    }
})();

var xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        readXML(xmlHttp.responseXML);
    }
};

xmlHttp.open("GET", url, true);
xmlHttp.send(null);


来源: stackexchange

问:
Bokeh: Upon callback, the new plot is overlaid on top of the old plot
I am trying to embed my plots. I have Select widgets for x-axis and y-axis selection. The plot gets updated as expected when I change the y-axis (fig 1); however, changing x-axis is giving me problems.
Upon changing the x-axis option, the new line graph gets overlaid on top of the old graph (fig 2). Only when I refresh the page, the graph is rendered as expected (fig 3). How can I refresh my plot without having to refresh the entire page?

This is the working example of what I am trying:

```<code>import io
import pandas as pd

from bokeh.plotting import figure
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Range1d
from bokeh.models.widgets import Select
from bokeh.client import push_session
from bokeh.document import Document
from bokeh.embed import server_session

document = Document()
session = push_session(document)

trip_data = [{"trip": '1', "totalDistanceTravelled": "4.66", "totalTimeTaken": "765083", "time": "1504189219256",
              "carRegNo": "ABC123", "driverName": "Anne"},
             {"trip": '2', "totalDistanceTravelled": "14.63", "totalTimeTaken": "1282369", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '3', "totalDistanceTravelled": "3.66", "totalTimeTaken": "602713", "time": "1504189219256",
              "carRegNo": "XYZ890", "driverName": "Ron"},
             {"trip": '4', "totalDistanceTravelled": "7.11", "totalTimeTaken": "2234282", "time": "1504189219256",
              "carRegNo": "ABC123", "driverName": "Anne"},
             {"trip": '5', "totalDistanceTravelled": "14.14", "totalTimeTaken": "1282369", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '6', "totalDistanceTravelled": "4.33", "totalTimeTaken": "748446", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '7', "totalDistanceTravelled": "10.66", "totalTimeTaken": "960362", "time": "1504189219256",
              "carRegNo": "XYZ890", "driverName": "Ron"}]

df = pd.DataFrame(trip_data)
drivers = df['driverName'].str.strip()
vehicles = df['carRegNo'].str.strip()
time_stamp = df['time'].astype(float)
total_distance_travelled = df['totalDistanceTravelled'].astype(float)
df['totalTimeTaken'] = df['totalTimeTaken'].astype(float)
df['totalTimeTaken'] /= 1000 * 3600

# Create Input controls
x_axis = Select(title="X Axis", options=sorted(["Drivers", "Vehicle Reg. Number"]), value="Drivers")
y_axis = Select(title="Y Axis", options=sorted(["Distance Travelled (kms)", "Time Taken (hours)"]),
                value="Time Taken (hours)")
source = ColumnDataSource(data=dict(x=[], y=[]))
p = figure(x_range=[], y_range=Range1d(), plot_height=600, plot_width=700, title="")

def update():
    print "UPDATE"
    col_key_values = {
        "Time Taken (hours)": 'totalTimeTaken',
        "Distance Travelled (kms)": 'totalDistanceTravelled'
    }

    x_map = {
        "Drivers": drivers,
        "Vehicle Reg. Number": vehicles
    }

    x_name = x_map[x_axis.value]
    x_y_values = {}
    for x in x_name.unique():
        x_y_values[x] = round(df.loc[x_name == x, col_key_values[y_axis.value]].astype(float).sum(), 2)
    source.data = dict(
        x=list(x_y_values.keys()),
        y=list(x_y_values.values())
    )
    p.y_range.start = min(x_y_values.values())-1
    p.y_range.end = max(x_y_values.values())+1
    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.x_range.factors = list(x_y_values.keys())
    p.line(x="x", y="y", source=source)
    print source.data
    return p

def on_x_change(attr, old, new):
    global x_axis
    x_axis.value = new
    update()

def on_y_change(attr, old, new):
    global y_axis
    y_axis.value = new
    update()

def create_layout():
    print 'CREATE LAYOUT'
    x_axis.on_change('value', on_x_change)
    y_axis.on_change('value', on_y_change)
    controls = column(children=[x_axis, y_axis])
    layout = column(children=[controls, update()])
    return layout

layout = create_layout()

html = u"""
<html>
    <head></head>
    <body>
        %s
    </body>
</html>
""" % server_session(layout, session_id=session.id, relative_urls=False)

with io.open("sample.html", mode='w+', encoding='utf-8') as f:
    f.write(html)

print(__doc__)

document.add_root(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()
</code>```

Attachments:

答:
Instead of redrawing the line with p.line() you should just update the source of the line with source.data.update(dict). Just have an empty source to draw the line at the beginning with no data.

Also update the source after you update the figure range

```<code>p = figure(x_range=[], y_range=Range1d(), plot_height=600, plot_width=700, title="")
source = ColumnDataSource(data={'x':[],'y':[]})
p.line(x="x", y="y", source=source)

def update():
    print "UPDATE"
    col_key_values = {
        "Time Taken (hours)": 'totalTimeTaken',
        "Distance Travelled (kms)": 'totalDistanceTravelled'
    }

    x_map = {
        "Drivers": drivers,
        "Vehicle Reg. Number": vehicles
    }

    x_name = x_map[x_axis.value]
    x_y_values = {}
    for x in x_name.unique():
        x_y_values[x] = round(df.loc[x_name == x, col_key_values[y_axis.value]].astype(float).sum(), 2)
    p.y_range.start = min(x_y_values.values())-1
    p.y_range.end = max(x_y_values.values())+1
    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.x_range.factors = list(x_y_values.keys())
    source.data.update( dict(
        x=list(x_y_values.keys()),
        y=list(x_y_values.values())
    ))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to embed my plots. I have Select widgets for x-axis and y-axis selection. The plot gets updated as expected when I change the y-axis (fig 1); however, changing x-axis is giving me problems.
Upon changing the x-axis option, the new line graph gets overlaid on top of the old graph (fig 2). Only when I refresh the page, the graph is rendered as expected (fig 3). How can I refresh my plot without having to refresh the entire page?

This is the working example of what I am trying:

import io
import pandas as pd

from bokeh.plotting import figure
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource, Range1d
from bokeh.models.widgets import Select
from bokeh.client import push_session
from bokeh.document import Document
from bokeh.embed import server_session

document = Document()
session = push_session(document)

trip_data = [{"trip": '1', "totalDistanceTravelled": "4.66", "totalTimeTaken": "765083", "time": "1504189219256",
              "carRegNo": "ABC123", "driverName": "Anne"},
             {"trip": '2', "totalDistanceTravelled": "14.63", "totalTimeTaken": "1282369", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '3', "totalDistanceTravelled": "3.66", "totalTimeTaken": "602713", "time": "1504189219256",
              "carRegNo": "XYZ890", "driverName": "Ron"},
             {"trip": '4', "totalDistanceTravelled": "7.11", "totalTimeTaken": "2234282", "time": "1504189219256",
              "carRegNo": "ABC123", "driverName": "Anne"},
             {"trip": '5', "totalDistanceTravelled": "14.14", "totalTimeTaken": "1282369", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '6', "totalDistanceTravelled": "4.33", "totalTimeTaken": "748446", "time": "1504189219256",
              "carRegNo": "DEF345", "driverName": "Harry"},
             {"trip": '7', "totalDistanceTravelled": "10.66", "totalTimeTaken": "960362", "time": "1504189219256",
              "carRegNo": "XYZ890", "driverName": "Ron"}]

df = pd.DataFrame(trip_data)
drivers = df['driverName'].str.strip()
vehicles = df['carRegNo'].str.strip()
time_stamp = df['time'].astype(float)
total_distance_travelled = df['totalDistanceTravelled'].astype(float)
df['totalTimeTaken'] = df['totalTimeTaken'].astype(float)
df['totalTimeTaken'] /= 1000 * 3600

# Create Input controls
x_axis = Select(title="X Axis", options=sorted(["Drivers", "Vehicle Reg. Number"]), value="Drivers")
y_axis = Select(title="Y Axis", options=sorted(["Distance Travelled (kms)", "Time Taken (hours)"]),
                value="Time Taken (hours)")
source = ColumnDataSource(data=dict(x=[], y=[]))
p = figure(x_range=[], y_range=Range1d(), plot_height=600, plot_width=700, title="")

def update():
    print "UPDATE"
    col_key_values = {
        "Time Taken (hours)": 'totalTimeTaken',
        "Distance Travelled (kms)": 'totalDistanceTravelled'
    }

    x_map = {
        "Drivers": drivers,
        "Vehicle Reg. Number": vehicles
    }

    x_name = x_map[x_axis.value]
    x_y_values = {}
    for x in x_name.unique():
        x_y_values[x] = round(df.loc[x_name == x, col_key_values[y_axis.value]].astype(float).sum(), 2)
    source.data = dict(
        x=list(x_y_values.keys()),
        y=list(x_y_values.values())
    )
    p.y_range.start = min(x_y_values.values())-1
    p.y_range.end = max(x_y_values.values())+1
    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.x_range.factors = list(x_y_values.keys())
    p.line(x="x", y="y", source=source)
    print source.data
    return p

def on_x_change(attr, old, new):
    global x_axis
    x_axis.value = new
    update()

def on_y_change(attr, old, new):
    global y_axis
    y_axis.value = new
    update()

def create_layout():
    print 'CREATE LAYOUT'
    x_axis.on_change('value', on_x_change)
    y_axis.on_change('value', on_y_change)
    controls = column(children=[x_axis, y_axis])
    layout = column(children=[controls, update()])
    return layout

layout = create_layout()

html = u"""

        %s

""" % server_session(layout, session_id=session.id, relative_urls=False)

with io.open("sample.html", mode='w+', encoding='utf-8') as f:
    f.write(html)

print(__doc__)

document.add_root(layout)

if __name__ == "__main__":
    print("\npress ctrl-C to exit")
    session.loop_until_closed()

Attachments:

Body:
Instead of redrawing the line with p.line() you should just update the source of the line with source.data.update(dict). Just have an empty source to draw the line at the beginning with no data.

Also update the source after you update the figure range

p = figure(x_range=[], y_range=Range1d(), plot_height=600, plot_width=700, title="")
source = ColumnDataSource(data={'x':[],'y':[]})
p.line(x="x", y="y", source=source)

def update():
    print "UPDATE"
    col_key_values = {
        "Time Taken (hours)": 'totalTimeTaken',
        "Distance Travelled (kms)": 'totalDistanceTravelled'
    }

    x_map = {
        "Drivers": drivers,
        "Vehicle Reg. Number": vehicles
    }

    x_name = x_map[x_axis.value]
    x_y_values = {}
    for x in x_name.unique():
        x_y_values[x] = round(df.loc[x_name == x, col_key_values[y_axis.value]].astype(float).sum(), 2)
    p.y_range.start = min(x_y_values.values())-1
    p.y_range.end = max(x_y_values.values())+1
    p.xaxis.axis_label = x_axis.value
    p.yaxis.axis_label = y_axis.value
    p.x_range.factors = list(x_y_values.keys())
    source.data.update( dict(
        x=list(x_y_values.keys()),
        y=list(x_y_values.values())
    ))


问:
From file to ldif script, attributes separated by comma
I have a file like this:

h3fah055,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah058,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah065,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah066,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah082,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal029,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal030,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG

I would like to generate an ldif from this file, so for each rows I need to generate:

```<code> dn: cn=h3fah055,ou=hosts,dc=example,dc=com
 objectClass: host
 objectClass: ipHost
 objectClass: top
 ipHostNumber: 1.1.1.1
 cn: h3fah055
 Allowednetgroup: NG_SYS_UX
 Allowednetgroup: NG_SYS_FO
 Allowednetgroup: NG_SYS_STG
 Allowednetgroup: NG_APP_DWH
</code>```

How can I read each rows in this file and save, if existing, each netgroup in a variable in order to print in a file my desired output?

I tryed with

```<code>while read p; do
  echo $p |  awk -F , '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com"}'
done <hosts_list.txt
</code>```

But I'm not sure how to add as many Allowednetgroup as defined in the file.

答:
awk has a variable NF which is the number of fields on the line.
So you can loop through them with a for statement like this.

```<code>awk -F',' '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com\nobjectClass:host\nobjectclass: ipHost\nobjectClass: top\nipHostNumber 1.1.1.1\ncn:" $1;
    for(i=2;i<=NF;i++) print "Allowednetgroup: " $i  }' hosts_list.txt
</code>```

Notice that awk will read each line itself so you don't need pass one line at a time like your MVCE. Just pass the filename as a second argument.
i.e. awk '

Body:
I have a file like this:

h3fah055,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah058,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_DWH
  h3fah065,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah066,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG,NG_APP_ERP
  h3fah082,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal029,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG
  h3fal030,NG_SYS_UX,NG_SYS_FO,NG_SYS_STG

I would like to generate an ldif from this file, so for each rows I need to generate:

 dn: cn=h3fah055,ou=hosts,dc=example,dc=com
 objectClass: host
 objectClass: ipHost
 objectClass: top
 ipHostNumber: 1.1.1.1
 cn: h3fah055
 Allowednetgroup: NG_SYS_UX
 Allowednetgroup: NG_SYS_FO
 Allowednetgroup: NG_SYS_STG
 Allowednetgroup: NG_APP_DWH

How can I read each rows in this file and save, if existing, each netgroup in a variable in order to print in a file my desired output?

I tryed with

while read p; do
  echo $p |  awk -F , '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com"}'
done <hosts_list.txt

But I'm not sure how to add as many Allowednetgroup as defined in the file.

Body:
awk has a variable NF which is the number of fields on the line.
So you can loop through them with a for statement like this.

awk -F',' '{print "dn: cn=" $1 ",ou=hosts,dc=example,dc=com\nobjectClass:host\nobjectclass: ipHost\nobjectClass: top\nipHostNumber 1.1.1.1\ncn:" $1;
    for(i=2;i<=NF;i++) print "Allowednetgroup: " $i  }' hosts_list.txt

Notice that awk will read each line itself so you don't need pass one line at a time like your MVCE. Just pass the filename as a second argument.
i.e. awk '<script>' filename

The above script will produce output like:

dn: cn=h3fah055,ou=hosts,dc=example,dc=com
objectClass:host
objectclass: ipHost
objectClass: top
ipHostNumber 1.1.1.1
cn:h3fah055
Allowednetgroup: NG_SYS_UX
Allowednetgroup: NG_SYS_FO
Allowednetgroup: NG_SYS_STG
Allowednetgroup: NG_APP_DWH
etc...


问:
Why do I have to wrap an Async<T> into another async workflow and let! it?
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

```<code>let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

```<code>let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

```<code>let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)
</code>```

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

```<code>>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream
</code>```

Result of not working code in FSI:

```<code>>
</code>```

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192

答:
I can't tell you why the second example doesn't work without knowing what Stream and partition are and how they work.

However, I want to take this opportunity to point out that the two examples are not strictly equivalent.

F# async is kind of like a "recipe" for what to do. When you write async { ... }, the resulting computation is just sitting there, not actually doing anything. It's more like declaring a function than like issuing a command. Only when you "start" it by calling something like Async.RunSynchronously or Async.Start does it actually run. A corollary is that you can start the same async workflow multiple times, and it's going to be a new workflow every time. Very similar to how IEnumerable works.

C# Task, on the other hand, is more like a "reference" to an async computation that is already running. The computation starts as soon as you call Stream.TryOpenAsync(partition), and it's impossible to obtain a Task instance before the task actually starts. You can await the resulting Task multiple times, but each await will not result in a fresh attempt to open a stream. Only the first await will actually wait for the task's completion, and every subsequent one will just return you the same remembered result.

In the async/reactive lingo, F# async is what you call "cold", while C# Task is referred to as "hot".

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to understand async workflows in F# but I found one part that I really don't understand.

The following code works fine:

let asynWorkflow = async{
    let! result = Stream.TryOpenAsync(partition) |> Async.AwaitTask
    return result
    }

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I define a async workflow where TryOpenAsync returns a Task<StreamOpenResult> type. I convert it to Async<StreamOpenResult> with Async.AwaitTask. (Side quest: "Await"Task? It doesn't await it just convert it, does it? I think it has nothing to do with Task.Wait or the await keyword). I "await" it with let! and return it.
To start the workflow I use RunSynchronously which should start the workflow and return the result (bind it). On the result I check if the Stream is Found or not.

But now to my first question. Why do I have to wrap the TryOpenAsync call in another async computation and let! ("await") it?
E.g. the following code does not work:

let asynWorkflow =  Stream.TryOpenAsync(partition) |> Async.AwaitTask

let stream = Async.RunSynchronously asynWorkflow
             |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I thought the AwaitTask makes it an Async<T> and RunSynchronously should start it. Then use the result. What do I miss?

My second question is why is there any "Async.Let!" function available? Maybe because it does not work or better why doesn't it work with the following code?

let ``let!`` task = async{
    let! result = task |> Async.AwaitTask
   return result
   }

let stream = Async.RunSynchronously ( ``let!`` (Stream.TryOpenAsync(partition))  )
         |> fun openResult -> if openResult.Found then openResult.Stream else Stream(partition)

I just insert the TryOpenAsync as a parameter but it does not work. By saying does not work I mean the whole FSI will hang. So it has something to do with my async/"await".

--- Update:

Result of working code in FSI:

>

Real: 00:00:00.051, CPU: 00:00:00.031, GC gen0: 0, gen1: 0, gen2: 0
val asynWorkflow : Async<StreamOpenResult>
val stream : Stream

Result of not working code in FSI:

>

And you cannot execute anything in the FSI anymore

--- Update 2

I'm using Streamstone. Here the C# example: https://github.com/yevhen/Streamstone/blob/master/Source/Example/Scenarios/S04_Write_to_stream.cs

and here the Stream.TryOpenAsync: https://github.com/yevhen/Streamstone/blob/master/Source/Streamstone/Stream.Api.cs#L192


问:
Encrypting App.Config Section and deploying to multiple machines
I've done a lot of reading around and am trying to encrypt a section in a WPF App.Config file. I am not using the  default section, but rather a custom one . I have an app where the user specifices a .config file and the app reads this file in order to update keys.

In order to decrypt and encrypt my file section I am using the following code:

```<code>var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (!configSection.SectionInformation.IsProtected)
   if (!configSection.ElementInformation.IsLocked)
     {
          configSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
          configSection.SectionInformation.ForceSave = true;
          config.Save(ConfigurationSaveMode.Full);
     }
</code>```

and to Decrypt:

```<code>var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (configSection.SectionInformation.IsProtected)
{
    configSection.SectionInformation.UnprotectSection();
    configSection.SectionInformation.ForceSave = true;
    config.Save(ConfigurationSaveMode.Full);
}
</code>```

The problem I am facing is that if I have a file that is encrypted on Machine A and I place the file on Machine B, I cannot decrypt the .config file because the encryption was done on Machine A.

I've tried to follow the steps in several articles that recommend using aspnet_regiis to create and export key containers (link) and (link) but maybe i'm doing something wrong. My guess is that because i'm not using aspnet_regiis in order to encrypt the file or to decrypt the file I get stuck. Is there a way to do this without using the aspnet_regiis tool and the command line?

A lot of the information around is more for web.config vs app.config. Again, this is for a C#/WPF application using MVVM.

I was also looking at custom encryption (custom data provider), but all the examples i've seen are for web.config (link).

答:
Looking for answers myself. However, in your case, if I'm not mistaken, you have to do step #2 -- export the RSA key.

https://magenic.com/thinking/encrypting-configuration-sections-in-net

Body:
I've done a lot of reading around and am trying to encrypt a section in a WPF App.Config file. I am not using the  default section, but rather a custom one . I have an app where the user specifices a .config file and the app reads this file in order to update keys.

In order to decrypt and encrypt my file section I am using the following code:

var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (!configSection.SectionInformation.IsProtected)
   if (!configSection.ElementInformation.IsLocked)
     {
          configSection.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
          configSection.SectionInformation.ForceSave = true;
          config.Save(ConfigurationSaveMode.Full);
     }

and to Decrypt:

var configMap = new ExeConfigurationFileMap { ExeConfigFilename = this.FileName };
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
var configSection = config.GetSection(Section);

if (configSection.SectionInformation.IsProtected)
{
    configSection.SectionInformation.UnprotectSection();
    configSection.SectionInformation.ForceSave = true;
    config.Save(ConfigurationSaveMode.Full);
}

The problem I am facing is that if I have a file that is encrypted on Machine A and I place the file on Machine B, I cannot decrypt the .config file because the encryption was done on Machine A.

I've tried to follow the steps in several articles that recommend using aspnet_regiis to create and export key containers (link) and (link) but maybe i'm doing something wrong. My guess is that because i'm not using aspnet_regiis in order to encrypt the file or to decrypt the file I get stuck. Is there a way to do this without using the aspnet_regiis tool and the command line?

A lot of the information around is more for web.config vs app.config. Again, this is for a C#/WPF application using MVVM.

I was also looking at custom encryption (custom data provider), but all the examples i've seen are for web.config (link).


问:
Sort a string of comma-separated items alphabetically
I have a data frame, and one of the columns in the data frame contains a string of items separated by commas like this;

```<code>[1] "A, D, B, C"
[2] "D, A, B, C"
[3] "B, A, C, D"
etc...
</code>```

Is there a way to sort these strings within themselves, so that I can get something like this?:

```<code>"A, B, C, D"
"A, B, C, D"
"A, B, C, D"
</code>```

I am close with the following:

```<code>library(gtools)
df$col <- sapply(df$col , function (x)
    mixedsort(strsplit(paste(x, collapse = ','), ',')[[1]]))
</code>```

But this outputs the results as a list, so I can't do any manipulations in dplyr on the output (like group_by)

答:
```<code>x = c("a, b, c, d", "d, a, b, c", "b, a, c, d")
y = unname(sapply(x, function(x) {
    paste(sort(trimws(strsplit(x[1], ',')[[1]])), collapse=',')} ))
y
</code>```

[1] "a,b,c,d" "a,b,c,d" "a,b,c,d"

trimws() removes whitespace so sort works correctly on the splitted string. sort() sorts alphabetically. paste(..., collapse = ',') concatenates the sorted vector of strings into a single string.

Body:
I have a data frame, and one of the columns in the data frame contains a string of items separated by commas like this;

[1] "A, D, B, C"
[2] "D, A, B, C"
[3] "B, A, C, D"
etc...

Is there a way to sort these strings within themselves, so that I can get something like this?:

"A, B, C, D"
"A, B, C, D"
"A, B, C, D"

I am close with the following:

library(gtools)
df$col <- sapply(df$col , function (x)
    mixedsort(strsplit(paste(x, collapse = ','), ',')[[1]]))

But this outputs the results as a list, so I can't do any manipulations in dplyr on the output (like group_by)

Body:
x = c("a, b, c, d", "d, a, b, c", "b, a, c, d")
y = unname(sapply(x, function(x) {
    paste(sort(trimws(strsplit(x[1], ',')[[1]])), collapse=',')} ))
y

[1] "a,b,c,d" "a,b,c,d" "a,b,c,d"

trimws() removes whitespace so sort works correctly on the splitted string. sort() sorts alphabetically. paste(..., collapse = ',') concatenates the sorted vector of strings into a single string.


问:
Android EditText focus issue, wrong EditText
EditText is driving us crazy! really!

We have an issue in the login screen for our app. It contains two EditTexts but only the first (Username) gets focussed, by means of the SoftKeyboard does only show up if the username EditText is touched/clicked.
Once the username EditText has been clicked, and therefore the SoftKeyboard is visible, when then touching/clicking the password EditText it shows focussed (the cursor is blinking in the password EditText) but input from the Keyboard will be inserted in the username EditText.

Now the funny part. We have tried to turn it off and on again, by means of the screen (by pressing the power button), and then, surprise, everything works as expected.

Are we missing something?

We tried quite everything:

flattened the view hierarchy

layout with only one linear layout containing views

focusable, focusable in touch mode

remove fill viewport from parent ScrollView

converted Fragments to Activities

We are using Android Design Support Library v23.1.1 and AppCompat Library v23.1.1

Screenshot of the login screen

LoginFragment.java

```<code>public class LoginFragment extends Fragment {

private LoginButton fbLoginButton;
private EditText etxUsername;
private EditText etxPassword;
private Button btnLogin;
private Button btnRegister;
private Button btnRequestPassword;
private ImageView backgroundImage;
private View content;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup   container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_login, container, false);
        fbLoginButton = (LoginButton) root.findViewById(R.id.fb_login);
        fbLoginButton.setFragment(this);
        content = root.findViewById(R.id.content);
        etxUsername = (EditText) root.findViewById(R.id.etx_username);
        etxPassword = (EditText) root.findViewById(R.id.etx_password);
        btnLogin = (Button) root.findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(v -> login());
        btnRegister = (Button) root.findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(v -> showRegister());
        btnRequestPassword = (Button) root.findViewById(R.id.btn_request_password);
        btnRequestPassword.setOnClickListener(v -> requestPassword());
        backgroundImage = (ImageView) root.findViewById(R.id.backgroundImage);
        return root;
    }
}
</code>```

fragment_login.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:id="@+id/backgroundImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:scaleType="centerCrop"/>

    <ScrollView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:layout_centerInParent="true"
        android:background="@color/transparent_black">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <LinearLayout
                android:id="@+id/login_form"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="150dp"
                    android:layout_height="150dp"
                    android:layout_gravity="center"
                    android:layout_marginBottom="@dimen/activity_vertical_margin"
                    android:padding="@dimen/activity_horizontal_margin"
                    android:src="@drawable/login_logo"/>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:minHeight="48dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="24dp"
                        android:layout_height="24dp"
                        android:layout_marginRight="32dp"
                        android:src="@drawable/ic_w_user_24"/>

                    <EditText
                        android:id="@+id/etx_username"
                        style="@style/AccountManagerEditText.Light"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/username_or_email"
                        android:focusable="true"
                        android:nextFocusDown="@+id/etx_password"
                        android:inputType="text"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:minHeight="48dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="24dp"
                        android:layout_height="24dp"
                        android:layout_marginRight="32dp"
                        android:src="@drawable/ic_w_password_24"/>

                    <EditText
                        android:id="@+id/etx_password"
                        style="@style/AccountManagerEditText.Light"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:focusable="true"
                        android:hint="@string/password"
                        android:inputType="textPassword"/>
                </LinearLayout>
            </LinearLayout>

            <Button
                android:id="@+id/btn_request_password"
                style="@style/VLButtonFlat.Light"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="@dimen/spacing"
                android:text="@string/forgot_password"
                android:textAllCaps="false"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption"
                android:textColor="@color/white"/>

            <Button
                android:id="@+id/btn_login"
                style="@style/VLButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/login"/>

            <TextView
                style="@style/TextAppearance.AppCompat.Body1"
                android:layout_width="wrap_content"
                android:layout_height="38dp"
                android:autoLink="all"
                android:clickable="true"
                android:layout_gravity="center"
                android:gravity="center"
                android:text="or"
                android:textColor="@color/white"/>

            <com.facebook.login.widget.LoginButton
                android:id="@+id/fb_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:layout_marginTop="@dimen/activity_vertical_margin"/>

            <Button
                android:id="@+id/btn_register"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:text="@string/create_new_account"
                android:textAllCaps="false"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption"/>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>
</code>```

EDIT:
Added styles

```<code><resources
xmlns:tools=" http://schemas.android.com/tools"
tools:ignore="MissingPrefix">

<style name="AccountManagerTheme.Dark" parent="Theme.AppCompat">
    <item name="colorPrimary">@color/black</item>
    <item name="colorPrimaryDark">@color/black</item>
    <item name="colorAccent">@color/dirty_white</item>
    <item name="android:textColorPrimary">@color/black</item>
    <item name="android:textColorSecondary">@color/dirty_white</item>
</style>

<style name="AccountManagerEditText.Light" parent="Base.Widget.AppCompat.EditText">
    <item name="android:theme">@style/AccountManagerTheme</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:minHeight">48dp</item>
    <item name="android:textColorHint">@color/dirty_white</item>
</style>

<style name="AccountManagerEditText.Dark" parent="Base.Widget.AppCompat.EditText">
    <item name="android:theme">@style/AccountManagerTheme.Dark</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat.Body1</item>
    <item name="android:textColorHint">@color/dirty_white</item>
    <item name="android:minHeight">48dp</item>
</style>
</code>```

答:
Try combining these two in your layout that is the child of ScrollView:
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"</p>

Body:
EditText is driving us crazy! really!

We have an issue in the login screen for our app. It contains two EditTexts but only the first (Username) gets focussed, by means of the SoftKeyboard does only show up if the username EditText is touched/clicked.
Once the username EditText has been clicked, and therefore the SoftKeyboard is visible, when then touching/clicking the password EditText it shows focussed (the cursor is blinking in the password EditText) but input from the Keyboard will be inserted in the username EditText.

Now the funny part. We have tried to turn it off and on again, by means of the screen (by pressing the power button), and then, surprise, everything works as expected.

Are we missing something?

We tried quite everything:

flattened the view hierarchy

layout with only one linear layout containing views

focusable, focusable in touch mode

remove fill viewport from parent ScrollView

converted Fragments to Activities

We are using Android Design Support Library v23.1.1 and AppCompat Library v23.1.1

Screenshot of the login screen

LoginFragment.java

public class LoginFragment extends Fragment {

private LoginButton fbLoginButton;
private EditText etxUsername;
private EditText etxPassword;
private Button btnLogin;
private Button btnRegister;
private Button btnRequestPassword;
private ImageView backgroundImage;
private View content;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup   container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_login, container, false);
        fbLoginButton = (LoginButton) root.findViewById(R.id.fb_login);
        fbLoginButton.setFragment(this);
        content = root.findViewById(R.id.content);
        etxUsername = (EditText) root.findViewById(R.id.etx_username);
        etxPassword = (EditText) root.findViewById(R.id.etx_password);
        btnLogin = (Button) root.findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(v -> login());
        btnRegister = (Button) root.findViewById(R.id.btn_register);
        btnRegister.setOnClickListener(v -> showRegister());
        btnRequestPassword = (Button) root.findViewById(R.id.btn_request_password);
        btnRequestPassword.setOnClickListener(v -> requestPassword());
        backgroundImage = (ImageView) root.findViewById(R.id.backgroundImage);
        return root;
    }
}

fragment_login.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ImageView
        android:id="@+id/backgroundImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:scaleType="centerCrop"/>

    <ScrollView
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:layout_centerInParent="true"
        android:background="@color/transparent_black">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="16dp">

            <LinearLayout
                android:id="@+id/login_form"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <ImageView
                    android:layout_width="150dp"
                    android:layout_height="150dp"
                    android:layout_gravity="center"
                    android:layout_marginBottom="@dimen/activity_vertical_margin"
                    android:padding="@dimen/activity_horizontal_margin"
                    android:src="@drawable/login_logo"/>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:minHeight="48dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="24dp"
                        android:layout_height="24dp"
                        android:layout_marginRight="32dp"
                        android:src="@drawable/ic_w_user_24"/>

                    <EditText
                        android:id="@+id/etx_username"
                        style="@style/AccountManagerEditText.Light"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/username_or_email"
                        android:focusable="true"
                        android:nextFocusDown="@+id/etx_password"
                        android:inputType="text"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:minHeight="48dp"
                    android:orientation="horizontal">

                    <ImageView
                        android:layout_width="24dp"
                        android:layout_height="24dp"
                        android:layout_marginRight="32dp"
                        android:src="@drawable/ic_w_password_24"/>

                    <EditText
                        android:id="@+id/etx_password"
                        style="@style/AccountManagerEditText.Light"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:focusable="true"
                        android:hint="@string/password"
                        android:inputType="textPassword"/>
                </LinearLayout>
            </LinearLayout>

            <Button
                android:id="@+id/btn_request_password"
                style="@style/VLButtonFlat.Light"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginTop="@dimen/spacing"
                android:text="@string/forgot_password"
                android:textAllCaps="false"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption"
                android:textColor="@color/white"/>

            <Button
                android:id="@+id/btn_login"
                style="@style/VLButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/login"/>

            <TextView
                style="@style/TextAppearance.AppCompat.Body1"
                android:layout_width="wrap_content"
                android:layout_height="38dp"
                android:autoLink="all"
                android:clickable="true"
                android:layout_gravity="center"
                android:gravity="center"
                android:text="or"
                android:textColor="@color/white"/>

            <com.facebook.login.widget.LoginButton
                android:id="@+id/fb_login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:layout_marginTop="@dimen/activity_vertical_margin"/>

            <Button
                android:id="@+id/btn_register"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:text="@string/create_new_account"
                android:textAllCaps="false"
                android:textAppearance="@style/TextAppearance.AppCompat.Caption"/>

        </LinearLayout>
    </ScrollView>

</RelativeLayout>

EDIT:
Added styles

<resources
xmlns:tools=" http://schemas.android.com/tools"
tools:ignore="MissingPrefix">


问:
Getting hit after invicibility when standing on trap
I am working on a simple 2D platformer game in which i have made an knockback effect. When the player gets hit by an obstacle, which currently is just a spike, he has a knockback and temporary invicibility, so when standing on spike during the invicibility he dosen't get hit. However, once the invicibility ends, i want to have player get hit by a spike like in the following GIF.

https://media.giphy.com/media/26FeVTRop5PhBrJQs/giphy.gif

The player gets hit because the invicibility is gone and it is standing on the spike. The problem I have is, if the invicibility ends and the player is still standing on the spike, it dosen't get hit and it cannot be hurt untill it gets off the spikes. Can you suggest how i solve this problem? Here is my code for hiting the player.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitThePlayer : MonoBehaviour
{
    public int damage;

    GameObject player;
    PlayerController playerController;
    PlayerMovement playerMovement;

    void Start ()
    {
        player = GameObject.FindGameObjectWithTag ("Player");
        playerController = GameObject.FindGameObjectWithTag  ("GameController").GetComponent<PlayerController>();
        playerMovement = player.GetComponent<PlayerMovement> ();
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (!playerController.isInvicible)
        {
            if (other.gameObject.CompareTag ("Player"))
            {
                playerController.AddPlayerHealth (-damage);
                playerMovement.isKnockedBacked = true;
                if (other.transform.position.x < transform.position.x)
                {
                    playerMovement.knockFromRight = true;
                }
                else
                {
                    playerMovement.knockFromRight = false;
                }
                StartCoroutine ("KnockBackEffectsDuration");
            }
        }
    }

    IEnumerator KnockBackEffectsDuration ()
    {
        player.GetComponent<Animator> ().SetTrigger ("GotHurt");
        StartCoroutine (playerController.Invicibility (3.0f));
        yield return new WaitForSeconds (0.2f);
        playerMovement.isKnockedBacked = false;
        playerMovement.enabled = false;
        yield return new WaitForSeconds (0.2f);
        playerMovement.enabled = true;
    }
}
</code>```

Also, here is the Invicibility IEnumerator that is in another script.

```<code>public IEnumerator Invicibility (float duration)
{
    isInvicible = true;
    yield return new WaitForSeconds (duration);
    isInvicible = false;
    player.GetComponent<Animator> ().SetTrigger ("GoIdle");
}
</code>```

HitThePlayer script references other scripts, so if you need me to bring up those scripts aswell, let me know.

答: It looks like you probably aren't checking for a collision with the spikes when invincibility ends, though there isn't enough code posted to be sure. Make sure you are calling the OnTriggerEnter2D function when invincibility ends.</p>

Body:
I am working on a simple 2D platformer game in which i have made an knockback effect. When the player gets hit by an obstacle, which currently is just a spike, he has a knockback and temporary invicibility, so when standing on spike during the invicibility he dosen't get hit. However, once the invicibility ends, i want to have player get hit by a spike like in the following GIF.

https://media.giphy.com/media/26FeVTRop5PhBrJQs/giphy.gif

The player gets hit because the invicibility is gone and it is standing on the spike. The problem I have is, if the invicibility ends and the player is still standing on the spike, it dosen't get hit and it cannot be hurt untill it gets off the spikes. Can you suggest how i solve this problem? Here is my code for hiting the player.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HitThePlayer : MonoBehaviour
{
    public int damage;

    GameObject player;
    PlayerController playerController;
    PlayerMovement playerMovement;

    void Start ()
    {
        player = GameObject.FindGameObjectWithTag ("Player");
        playerController = GameObject.FindGameObjectWithTag  ("GameController").GetComponent<PlayerController>();
        playerMovement = player.GetComponent<PlayerMovement> ();
    }

    void OnTriggerEnter2D (Collider2D other)
    {
        if (!playerController.isInvicible)
        {
            if (other.gameObject.CompareTag ("Player"))
            {
                playerController.AddPlayerHealth (-damage);
                playerMovement.isKnockedBacked = true;
                if (other.transform.position.x < transform.position.x)
                {
                    playerMovement.knockFromRight = true;
                }
                else
                {
                    playerMovement.knockFromRight = false;
                }
                StartCoroutine ("KnockBackEffectsDuration");
            }
        }
    }

    IEnumerator KnockBackEffectsDuration ()
    {
        player.GetComponent<Animator> ().SetTrigger ("GotHurt");
        StartCoroutine (playerController.Invicibility (3.0f));
        yield return new WaitForSeconds (0.2f);
        playerMovement.isKnockedBacked = false;
        playerMovement.enabled = false;
        yield return new WaitForSeconds (0.2f);
        playerMovement.enabled = true;
    }
}

Also, here is the Invicibility IEnumerator that is in another script.

public IEnumerator Invicibility (float duration)
{
    isInvicible = true;
    yield return new WaitForSeconds (duration);
    isInvicible = false;
    player.GetComponent<Animator> ().SetTrigger ("GoIdle");
}

HitThePlayer script references other scripts, so if you need me to bring up those scripts aswell, let me know.


问:
Pandas: append row to DataFrame with multiindex in columns
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

```<code>index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])
</code>```

Then I'm creating a dataframe:

```<code>dataframe = pd.DataFrame(index=["city"], columns = index)
</code>```

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

```<code>my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city
</code>```

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

答:
I don't think you even need to initialise an empty dataframe. With your d, I can get your desired output with unstack and a transpose:

```<code>pd.DataFrame(d).unstack().to_frame().T

   far     near
  bike car bike car
0    0   1    1   0
</code>```

Body:
I have a DataFrame with a multiindex in the columns and would like to use dictionaries to append new rows.

Let's say that each row in the DataFrame is a city. The columns contains "distance" and "vehicle". And each cell would be the percentage of the population that chooses this vehicle for this distance.

I'm constructing an index like this:

index_tuples=[]

for distance in ["near", "far"]:
    for vehicle in ["bike", "car"]:
        index_tuples.append([distance, vehicle])

index = pd.MultiIndex.from_tuples(index_tuples, names=["distance", "vehicle"])

Then I'm creating a dataframe:

dataframe = pd.DataFrame(index=["city"], columns = index)

The structure of the dataframe looks good. Although pandas has added Nans as default values ?

Now I would like to set up a dictionary for the new city and add it:

my_home_city = {"near":{"bike":1, "car":0},"far":{"bike":0, "car":1}}
dataframe["my_home_city"] = my_home_city

But this fails:

ValueError: Length of values does not match length of index

Here is the complete error message (pastebin)

UPDATE:

Thank you for all the good answers. I'm afraid I've oversimplified the problem in my example. Actually my index is nested with 3 levels (and it could become more).

So I've accepted the universal answer of converting my dictionary into a list of tuples. This might not be as clean as the other approaches but works for any multiindex setup.

Body:
I don't think you even need to initialise an empty dataframe. With your d, I can get your desired output with unstack and a transpose:

pd.DataFrame(d).unstack().to_frame().T

   far     near
  bike car bike car
0    0   1    1   0


问:
Blueprints plugin for Cytoscape, Gephi etc
I'm building UI to visualize and edit graph which is present in a gremlin store.
Which framework is better Cytoscape.js vs Gephi.js Vs other?
Do these frameworks have Blueprints plugin available? I want to avoid writing  module to convert the gremlin output to the framework compatible format.

Please advice. Thanks.

答:
Answer from the Cytoscape development team...

Well, there are a number of ways you can use Cytoscape with TinkerPop, but I would think that the best way would be to use the REST interface to Cytoscape and inject your graph directly into it.  You could save your graph as a Neo4j database and use the Neo4j app to pull it into Cytoscape or save your graph as a GraphML or some other common graph format and read it in that way.  Neither Cytoscape or Gephi are UI frameworks, though -- both are standalone applications that are designed to import, visualize, analyze and manipulate very large graphs.

A good place to start is on the Cytoscape Automation topic in the Cytoscape manual: http://manual.cytoscape.org/en/stable/Programmatic_Access_to_Cytoscape_Features_Scripting.html


问:
How to clear cookies from single site in Google Chrome version 62
The instructions given for clearing individual cookies at the Google help page at https://support.google.com/chrome/answer/95647?co=GENIE.Platform%3DDesktop&hl=en is incorrect for version 62, it seems.

Under Advanced settings, Privacy and Security, Clear Browsing Data one can only clear ALL cookies back for a period of time specified in the drop down menu.  I can't seem to find any way of clearing ALL cookies from a specific site the way it was possible in the past (and the way specified in the help page).

Has this been moved to another place in the Settings interface, or has Google deleted the ability to manage cookies site by site?

答: Click the "i" next to the domain. There should be the word "Cookies" and under that the text " used". Click that. Now select the first one and spam-click "Remove" until the list is empty.</p>


问:
R regular expression for p#q#c#
What would the regular expression be to encompass variable names such as p3q10000c150 and p29q2990c98? I want to add all variables in the format of p-any number-q-any number-c-any number to a list in R.

Thanks!

答:
I think you are looking for something like matches function in dplyr::select:

```<code>df = data.frame(1:10, 1:10, 1:10, 1:10)
names(df) = c("p3q10000c150", "V1", "p29q2990c98", "V2")

library(dplyr)

df %>%
  select(matches("^p\\d+q\\d+c\\d+$"))
</code>```

Result:

```<code>   p3q10000c150 p29q2990c98
1             1           1
2             2           2
3             3           3
4             4           4
5             5           5
6             6           6
7             7           7
8             8           8
9             9           9
10           10          10
</code>```

matches in select allows you to use regex to extract variables.

Title: R regular expression for p#q#c#

Body:
I think you are looking for something like matches function in dplyr::select:

df = data.frame(1:10, 1:10, 1:10, 1:10)
names(df) = c("p3q10000c150", "V1", "p29q2990c98", "V2")

library(dplyr)

df %>%
  select(matches("^p\\d+q\\d+c\\d+$"))

Result:

   p3q10000c150 p29q2990c98
1             1           1
2             2           2
3             3           3
4             4           4
5             5           5
6             6           6
7             7           7
8             8           8
9             9           9
10           10          10

matches in select allows you to use regex to extract variables.


问:
how to combine data from 2 list of lists to form a single JSON in python
I have 2 csv files(semicolon delimited) with following structure and sample data:

File 1:

```<code>qid;question
1.0;How can I find specific content
2.0;How do I modify content
2.0;How can I edit items
2.0;I need to change some answers
3.0;How do I troubleshoot and fix problems
</code>```

File 2:

```<code>qid;answer
1.0;Use the Filter feature to filter the items
2.0;Use the test tool to find your existing documents and edit them
3.0;Use the test tool to test a document
</code>```

Now what I want to do is form  a JSON structure which contains data from both documents to form following sample structure:

```<code>{
   "qna": [
      {
         "qid": "1.0",
         "q": [
            "How can I find specific content"
         ],
         "a": "Use the Filter feature to filter the items."

      },
      {
         "qid": "2.0",
         "q": [
            "How do I modify content","How do I edit items","I need to change some answers"
         ],
         "a": "Use the test tool to find your existing documents and edit them."
      },
      {
         "qid": "3.0",
         "q": [
            "How do I troubleshoot and fix problems"
         ],
         "a": "Use the test tool to test a document"

      }
]
}
</code>```

As you can see what this JSON contains a list of list within qna field. Each of the items in this list of list contains the qid, list of questions matching same qid, and answer matching the qid.

I wrote this code where I am reading these 2 csv files and forming 2 list of lists:

```<code>qid_question_list = {}
qid_answer_list = {}

reader1 = csv.reader(csv_file1, delimiter=';')

next(reader1)

reader2 = csv.reader(csv_file2, delimiter=';')

next(reader2)

for qid,question in reader1:
    if qid not in qid_question_list:
        qid_question_list[qid] = list()
    qid_question_list[qid].append(question)

for qid,answer in reader2:
    if qid not in qid_answer_list:
        qid_answer_list[qid] = list()
    qid_answer_list[qid].append(answer)
</code>```

When I execute above I get following 2 lists:

qid_question_list

```<code>{'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}
</code>```

qid_answer_list

```<code>{'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}
</code>```

Now I am not able to determine how can I club these 2 list of lists to form the desired JSON structure shown above?

答:
Assuming you've the two dicts handy

```<code>l1={'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}

l2={'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}

l = [ {"qid": k, "q": v, "a": l2[k]} for k,v in l1.items() ]

q={'qna': l }

print(q)
</code>```

Output

```<code>{'qna': [{'qid': '1.0', 'q': ['How can I find specific content'], 'a': ['Use the Filter feature to filter the items']}, {'qid': '2.0', 'q': ['How do I modify content', 'How do I edit items', 'I need to change some answers'], 'a': ['Use the test tool to find your existing documents and edit them']}, {'qid': '3.0', 'q': ['How do I troubleshoot and fix problems'], 'a': ['Use the test tool to test a document']}]}
</code>```

Body:
I have 2 csv files(semicolon delimited) with following structure and sample data:

File 1:

qid;question
1.0;How can I find specific content
2.0;How do I modify content
2.0;How can I edit items
2.0;I need to change some answers
3.0;How do I troubleshoot and fix problems

File 2:

qid;answer
1.0;Use the Filter feature to filter the items
2.0;Use the test tool to find your existing documents and edit them
3.0;Use the test tool to test a document

Now what I want to do is form  a JSON structure which contains data from both documents to form following sample structure:

{
   "qna": [
      {
         "qid": "1.0",
         "q": [
            "How can I find specific content"
         ],
         "a": "Use the Filter feature to filter the items."

      },
      {
         "qid": "2.0",
         "q": [
            "How do I modify content","How do I edit items","I need to change some answers"
         ],
         "a": "Use the test tool to find your existing documents and edit them."
      },
      {
         "qid": "3.0",
         "q": [
            "How do I troubleshoot and fix problems"
         ],
         "a": "Use the test tool to test a document"

      }
]
}

As you can see what this JSON contains a list of list within qna field. Each of the items in this list of list contains the qid, list of questions matching same qid, and answer matching the qid.

I wrote this code where I am reading these 2 csv files and forming 2 list of lists:

qid_question_list = {}
qid_answer_list = {}

reader1 = csv.reader(csv_file1, delimiter=';')

next(reader1)

reader2 = csv.reader(csv_file2, delimiter=';')

next(reader2)

for qid,question in reader1:
    if qid not in qid_question_list:
        qid_question_list[qid] = list()
    qid_question_list[qid].append(question)

for qid,answer in reader2:
    if qid not in qid_answer_list:
        qid_answer_list[qid] = list()
    qid_answer_list[qid].append(answer)

When I execute above I get following 2 lists:

qid_question_list

{'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}

qid_answer_list

{'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}

Now I am not able to determine how can I club these 2 list of lists to form the desired JSON structure shown above?

Body:
Assuming you've the two dicts handy

l1={'1.0': ['How can I find specific content'], '2.0': ['How do I modify content','How do I edit items','I need to change some answers'], '3.0': ['How do I troubleshoot and fix problems']}

l2={'1.0': ['Use the Filter feature to filter the items'], '2.0': ['Use the test tool to find your existing documents and edit them'], '3.0': ['Use the test tool to test a document']}

l = [ {"qid": k, "q": v, "a": l2[k]} for k,v in l1.items() ]

q={'qna': l }

print(q)

Output

{'qna': [{'qid': '1.0', 'q': ['How can I find specific content'], 'a': ['Use the Filter feature to filter the items']}, {'qid': '2.0', 'q': ['How do I modify content', 'How do I edit items', 'I need to change some answers'], 'a': ['Use the test tool to find your existing documents and edit them']}, {'qid': '3.0', 'q': ['How do I troubleshoot and fix problems'], 'a': ['Use the test tool to test a document']}]}


问:
Freeing memory which has been allocated to an array of char pointers (strings). Do I have to free each string or just the "main" pointer?
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

```<code>char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */
</code>```

How would I go about freeing the memory after I've used the strings? If I call

```<code>free(list_of_strings);
</code>```

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

Just for clarity the function looks something like this:

```<code>fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}
</code>```

答: Basically, there's a rule of thumb to allocating and freeing: You need to call as many free() as you called malloc(). It's as simple as that. In every other case you got yourself a memory leak.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a function that takes a pointer to a char ** and fills it with strings (an array of strings I guess). *list_of_strings* is allocated memory inside the function.

char * *list_of_strings = NULL;

/* list_of_strings malloc'd inside function */
fill_strings_with_stuff(&list_of strings);

use_list_for_something(list_of_strings);

/* Now how do I free it all? */

How would I go about freeing the memory after I've used the strings? If I call

free(list_of_strings);

won't that just free the actual pointers and not the memory each string itself was using? How do I completely free the memory

Just for clarity the function looks something like this:

fill_strings_with_stuff(char *** list)
{
    *list = malloc(AMOUNT);

    for (i = 0; i < SOMETHING; i++) {
        *(list + i) = malloc(LINE_LEN);
        *(list + i) = some_string_from_somewhere
    }

    /* ... */

}


问:
Correct gulp-destination
I have gulp configured the first time on my project with the global and local version 3.9.1 and set up a gulp-watch-task like that:

```<code>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');

// vars
var SCSS_PATH ='styles/**/*.scss';
var DIST_CSS_PATH ='css/';

// Styles for SCSS
gulp.task('styles', function () {
    return gulp.src(SCSS_PATH)
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(autoprefixer())
    .pipe(gulp.dest(DIST_CSS_PATH));
});

// Watch-Task
gulp.task('watch', function() {
    gulp.watch(SCSS_PATH, ['styles'])
});
</code>```

Now my watch task runs successfully and creates a css-file minified and prefixed. BUT it does created in css/local.css/sw.css which is obviously not correct. What I want it to be created is css/sw.css What do I do wrong there and why is that?

答:
When you use globs (**) it will keep the original folder structure. You can also choose the base for gulp.src and gulp.dest, as explained here.

What you want, however, is to flatten the folder structure. You can do that with gulp-flatten.

It would be end up as something like this:

```<code>var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var flatten = require('gulp-flatten');

// vars
var SCSS_PATH ='styles/**/*.scss';
var DIST_CSS_PATH ='css/';

// Styles for SCSS
gulp.task('styles', function () {
    return gulp.src(SCSS_PATH)
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(autoprefixer())
    .pipe(flatten())
    .pipe(gulp.dest(DIST_CSS_PATH));
});

// Watch-Task
gulp.task('watch', function() {
    gulp.watch(SCSS_PATH, ['styles'])
});
</code>```

I didn't really check with your code, but it worked in one of my build systems.

Title: Correct gulp-destination

Body:
I have gulp configured the first time on my project with the global and local version 3.9.1 and set up a gulp-watch-task like that:

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');

// vars
var SCSS_PATH ='styles/**/*.scss';
var DIST_CSS_PATH ='css/';

// Styles for SCSS
gulp.task('styles', function () {
    return gulp.src(SCSS_PATH)
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(autoprefixer())
    .pipe(gulp.dest(DIST_CSS_PATH));
});

// Watch-Task
gulp.task('watch', function() {
    gulp.watch(SCSS_PATH, ['styles'])
});

Now my watch task runs successfully and creates a css-file minified and prefixed. BUT it does created in css/local.css/sw.css which is obviously not correct. What I want it to be created is css/sw.css What do I do wrong there and why is that?

Body:
When you use globs (**) it will keep the original folder structure. You can also choose the base for gulp.src and gulp.dest, as explained here.

What you want, however, is to flatten the folder structure. You can do that with gulp-flatten.

It would be end up as something like this:

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-sass');
var flatten = require('gulp-flatten');

// vars
var SCSS_PATH ='styles/**/*.scss';
var DIST_CSS_PATH ='css/';

// Styles for SCSS
gulp.task('styles', function () {
    return gulp.src(SCSS_PATH)
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(autoprefixer())
    .pipe(flatten())
    .pipe(gulp.dest(DIST_CSS_PATH));
});

// Watch-Task
gulp.task('watch', function() {
    gulp.watch(SCSS_PATH, ['styles'])
});

I didn't really check with your code, but it worked in one of my build systems.


问:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)
I'm attempting to use fog-google to upload images to my google cloud storage.
My code looks like this:

```<code>config.paperclip_defaults = {
  storage: :fog,
  fog_host: "https://#{ENV.fetch('GOOGLE_STORAGE_BUCKET')}.storage.googleapis.com",
  fog_credentials: {
      google_storage_access_key_id: ENV.fetch('GOOGLE_STORAGE_ID'),
      google_storage_secret_access_key: ENV.fetch('GOOGLE_STORAGE_SECRET'),
      provider: 'Google' },
  fog_directory: ENV.fetch('GOOGLE_STORAGE_BUCKET') }
</code>```

However, I always get this error:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)

Seems like the connection is not established successfully.

Here is the error log:

```<code>C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `connect_nonblock'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `initialize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `new'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `socket'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:101:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/mock.rb:48:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/instrumentor.rb:26:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:250:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-core-1.45.0/lib/fog/core/connection.rb:81:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-xml-0.1.3/lib/fog/xml/connection.rb:9:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/real.rb:103:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/requests/head_object.rb:36:in `head_object'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/models/files.rb:81:in `head'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/paperclip-5.1.0/lib/paperclip/storage/fog.rb:65:in `exists?'
</code>```

答:
It's because you are trying to reach a url https and is failing to verify ssl in your case.

Try adding    OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

Edit - For Your concern about Man In The Middle Attack

Also You can verify your application by adding an ssl certificate with the following steps

Download https://curl.haxx.se/ca/cacert.pem into a path_to_file\cacert.pem. Make sure you save it as a .pem file, rather than a text file.

Set Environment Variable: SSL_CERT_FILE = path_to_file\cacert.pem

Restart all your ruby / rails applications and the retry accessing it now.

Body:
I'm attempting to use fog-google to upload images to my google cloud storage.
My code looks like this:

config.paperclip_defaults = {
  storage: :fog,
  fog_host: "https://#{ENV.fetch('GOOGLE_STORAGE_BUCKET')}.storage.googleapis.com",
  fog_credentials: {
      google_storage_access_key_id: ENV.fetch('GOOGLE_STORAGE_ID'),
      google_storage_secret_access_key: ENV.fetch('GOOGLE_STORAGE_SECRET'),
      provider: 'Google' },
  fog_directory: ENV.fetch('GOOGLE_STORAGE_BUCKET') }

However, I always get this error:
Excon::Error::Socket: SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError)

Seems like the connection is not established successfully.

Here is the error log:

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `connect_nonblock'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/ssl_socket.rb:117:in `initialize'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `new'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:404:in `socket'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:101:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/mock.rb:48:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/instrumentor.rb:26:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/middlewares/base.rb:16:in `request_call'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/excon-0.59.0/lib/excon/connection.rb:250:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-core-1.45.0/lib/fog/core/connection.rb:81:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-xml-0.1.3/lib/fog/xml/connection.rb:9:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/real.rb:103:in `request'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/requests/head_object.rb:36:in `head_object'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/fog-google-0.6.0/lib/fog/storage/google_xml/models/files.rb:81:in `head'
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/paperclip-5.1.0/lib/paperclip/storage/fog.rb:65:in `exists?'


问:
Dynamic center div bootstrap
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

```

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

答:
To test, try removing a column.

For All Resolutions:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

```
</div>
</div>
</p>

<p>For Mobile Resolution Only:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">

      <img src="https://dummyimage.com/250x250/000/fff">

  </div>
</div>
<style>
@media (max-width:767px) {
  .col-xs-6:first-child:nth-last-child(3),
  .col-xs-6:first-child:nth-last-child(3) ~ .col-xs-6 {
      width: 33.3%;
  }
}
</style></code>```

Explanation:

```<code>`.col-xs-6:first-child:nth-last-child(3)`
</code>```

For The column that is the first column, and also the 3rd from the last column

```<code>, .col-xs-6:first-child:nth-last-child(3) ~ .col-xs-6
</code>```

and for all adjacent siblings of said column (every column that comes after)

```<code>width: 33.3%;
</code>```

take up 1/3 of the width.

If there are 4 or more columns, or less than 3 columns, the first child can't be 3rd from the last, so we only change the width when it's 3. No flexbox needed (although I love flexbox), no polyfills needed, no bs.

Title: Dynamic center div bootstrap

Body:
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

Body:
To test, try removing a column.

For All Resolutions:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
</div>
<style>
 .col-xs-6:first-child:nth-last-child(3),
 .col-xs-6:first-child:nth-last-child(3) ~ .col-xs-6 {
     width: 33.3%;
 }
</style>

For Mobile Resolution Only:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
</div>
<style>
@media (max-width:767px) {
  .col-xs-6:first-child:nth-last-child(3),
  .col-xs-6:first-child:nth-last-child(3) ~ .col-xs-6 {
      width: 33.3%;
  }
}
</style>

Explanation:

`.col-xs-6:first-child:nth-last-child(3)`

For The column that is the first column, and also the 3rd from the last column

, .col-xs-6:first-child:nth-last-child(3) ~ .col-xs-6

and for all adjacent siblings of said column (every column that comes after)

width: 33.3%;

take up 1/3 of the width.

If there are 4 or more columns, or less than 3 columns, the first child can't be 3rd from the last, so we only change the width when it's 3. No flexbox needed (although I love flexbox), no polyfills needed, no bs.


问:
Missing Android NDK toolchains directory '\toolchains' when building Xamarin.Android with hosted tfs build server
I am trying to set up a TFS Build agent to build my Xamarin.Android project automatically on every check in.

I have followed the steps outlined here: https://msdn.microsoft.com/library/vs/alm/build/apps/xamarin for setting up a Hosted build agent.

TFS Build templates also have a Xamarin.Android  template, which you would expect means they are ready to go. This is also backed up from the above link which states you can build a Xamarin.Android solution on a Hosted pool

But I keep getting the following error on building the project:

Missing Android NDK toolchains directory '\toolchains'. Please install
  the Android NDK

I found a link at Xamarin https://developer.xamarin.com/guides/cross-platform/ci/configuring_tfs/tfs-and-xa/ which says I need to log onto the build machine and copy and paste the Android NDK onto my remote machine.

But obviously with a hosted pool I cannot log onto machine.

Am I missing something in my setup?

答:
The original problem was about building a Xamarin Android App on an Azure DevOps hosted agent and having an error because the Android NDK can't be found.

Yes, the build will work if you disable options like EmbedAssembliesIntoApk or BundleAssemblies, but this is not a true solution, especially when you need those options to be enabled.

As the Android NDK path is not found when building on a hosted agent, the solution is to manually set the Android NDK path.
In the build task, in the MSBuild Options, provide the following Additional Argument:

VS2015 Hosted agent: /p:AndroidNdkDirectory="C:\java\androidsdk\android-ndk-r13b"

VS2017 Hosted agent: /p:AndroidNdkDirectory="$(latestAndroidNDKPath)"

If you want to know more about this issue I wrote an article that will give you more details:

Building a Xamarin Android App with Bundle assemblies into native code option enabled on an Azure Visual Studio Team Services (VSTS) hosted agent
(And getting the following error: "Error : Could not find a part of the path 'd:\platforms'."?)

How to retrieve the latest Android NDK on a VS2017 hosted agent:

```<code>$ndk_root = "C:\Microsoft\AndroidNDK64\"

if(Test-Path $ndk_root) {

    $androidNDKs = Get-ChildItem -Path $ndk_root | Sort-Object -Property Name -Descending | Select-Object -First 1

    $latestAndroidNDK = $androidNDKs.FullName;

    Write-Host "##vso[task.setvariable variable=latestAndroidNDKPath]$latestAndroidNDK"

} else {

    Write-Host "NDK is not installed at path $ndk_root"

    exit 1
}

Write-Host Variable '$(latestAndroidNDKPath)' is $latestAndroidNDK
</code>```

Body:
The original problem was about building a Xamarin Android App on an Azure DevOps hosted agent and having an error because the Android NDK can't be found.

Yes, the build will work if you disable options like EmbedAssembliesIntoApk or BundleAssemblies, but this is not a true solution, especially when you need those options to be enabled.

As the Android NDK path is not found when building on a hosted agent, the solution is to manually set the Android NDK path.
In the build task, in the MSBuild Options, provide the following Additional Argument:

VS2015 Hosted agent: /p:AndroidNdkDirectory="C:\java\androidsdk\android-ndk-r13b"

VS2017 Hosted agent: /p:AndroidNdkDirectory="$(latestAndroidNDKPath)"

If you want to know more about this issue I wrote an article that will give you more details:

Building a Xamarin Android App with Bundle assemblies into native code option enabled on an Azure Visual Studio Team Services (VSTS) hosted agent
(And getting the following error: "Error : Could not find a part of the path 'd:\platforms'."?)

How to retrieve the latest Android NDK on a VS2017 hosted agent:

$ndk_root = "C:\Microsoft\AndroidNDK64\"

if(Test-Path $ndk_root) {

    $androidNDKs = Get-ChildItem -Path $ndk_root | Sort-Object -Property Name -Descending | Select-Object -First 1

    $latestAndroidNDK = $androidNDKs.FullName;

    Write-Host "##vso[task.setvariable variable=latestAndroidNDKPath]$latestAndroidNDK"

} else {

    Write-Host "NDK is not installed at path $ndk_root"

    exit 1
}

Write-Host Variable '$(latestAndroidNDKPath)' is $latestAndroidNDK


问:
How to load an image into an Xcode 9 playground?
I've spent hours trying to simply gain access to image data in my Swift Playground.  I've followed many tutorials that recommend adding a resource folder as a sibling dir in the dir. your playground is in.  Or to drag images into the Resources folder in the playground Navigator.  Nothing has worked.  What do I have to do to load an image view in playground?</p>

答:
I solved this problem on my side when I

import PlaygroundSupport

mark Resources Folder and tap + icon

Choose Add files to 'Resources' and choose your image (here: image.jpg)

Instance your image via let image = UIImage(named: "image.jpg")

Xcode 12 Preview


问:
Getting error while talking to remote Oracle DB using Jenkins-CI
I am trying to connect to Oracle DB using Jenkins, I am trying to use the sqlplus-script-runner-plugin. Running into below issue

```<code>ERROR: ORACLE_HOME directory [/u01/app/oracle/product/11.2.0.4/db_1] does not exist!
</code>```

Sample Screenshot from Jenkins Job

I even try to add the Jenkins user to ointsall group on remote Oracle DB server. Can any one help me finding the problem here.

答: I've to install Oracle XE to talk to remote DB servers, it solved my problem. </p>

Body:
I am trying to connect to Oracle DB using Jenkins, I am trying to use the sqlplus-script-runner-plugin. Running into below issue

ERROR: ORACLE_HOME directory [/u01/app/oracle/product/11.2.0.4/db_1] does not exist!

Sample Screenshot from Jenkins Job

I even try to add the Jenkins user to ointsall group on remote Oracle DB server. Can any one help me finding the problem here.