问:
Elegantly Toggling Many Functions
Let's say I have a handful of functions that do things:

```<code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }
</code>```

And then just as many that disable their behaviors:

```<code>function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }
</code>```

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

```<code>var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'
</code>```

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

答:
```<code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

var what = 'things';

var doing = {
    stuff:   doStuff,
    things:  doThings,
    it:      doIt,
    this:   doThis,
    that:   doThat
};

var stopping = {
    stuff:   stopStuff,
    things:  stopThings,
    it:      stopIt,
    this:    stopThis,
    that:    stopThat
};

var a = Object.keys(stopping);
a.splice(a.indexOf(what), 1);
Object.keys(stopping).map(function(key) {
   return stopping[key]();
});
doing[what]();
</code>```

Title: Elegantly Toggling Many Functions

Body:
Let's say I have a handful of functions that do things:

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

And then just as many that disable their behaviors:

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.


来源: stackexchange

问:
How to vertically center elements in Bulma?
How can I vertically center this
 to that red colored section which is enclosing it?

And should I remove or add some classes here to improve this code? Please suggest me. Thanks!

I am new to CSS framework, never tried Bootstrap and instead opted for Bulma.

```<code><section id="eyes" class="section">
    <div class="container">
        <div class="columns is-vcentered">
            <div class="column">
                <h1>Eyes on what matters</h1>
                <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
            </div>
            <div class="column">
                <img class="image" src="img/roll.jpg" alt="">
            </div>
        </div>
    </div>
</section>
</code>```

In CSS apart from coloring elements, I've only done this:

```<code>section {
    height: 70vh;
}
</code>```

答:
I think it's a bit funny that .columns does not have display:flex; by default (should it have perhaps?). Anyway, if you use something that adds flex, for example:

```<code>class="columns is-flex is-vcentered"
</code>```

then you get display:flex from is-desktop and now suddenly is-vcentered works as intended.

Also I think the semantics is off since is-vcentered suggests that it is columns that gets vertically centered. But what it actually does (from source):

```<code>.columns.is-vcentered {
  -webkit-box-align: center;
     -ms-flex-align: center;
        align-items: center;
}
</code>```

is to make children of columns to be vertically centered inside columns. So you likely also need to set a height of your columns element for this to work.

I think is-vcentered should be named something like has-vcentered-content, but perhaps I'm missing something obvious.

tl;dr; Add height and flex to the columns-element for is-vcentered to do something.

Sorry, I guess this is more of a extrapolation of the problem and not a solution.

I believe the real solution is probably to use the existing hero-class here. (Which by the way centers manually using paddings, just like in Peter Leger's answer!).

ContentLicense: CC BY-SA 3.0

Body:
How can I vertically center this
 to that red colored section which is enclosing it?

And should I remove or add some classes here to improve this code? Please suggest me. Thanks!

I am new to CSS framework, never tried Bootstrap and instead opted for Bulma.

Eyes on what matters

Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.

In CSS apart from coloring elements, I've only done this:

section {
    height: 70vh;
}

Body:
I think it's a bit funny that .columns does not have display:flex; by default (should it have perhaps?). Anyway, if you use something that adds flex, for example:

class="columns is-flex is-vcentered"

then you get display:flex from is-desktop and now suddenly is-vcentered works as intended.

Also I think the semantics is off since is-vcentered suggests that it is columns that gets vertically centered. But what it actually does (from source):

.columns.is-vcentered {
  -webkit-box-align: center;
     -ms-flex-align: center;
        align-items: center;
}

is to make children of columns to be vertically centered inside columns. So you likely also need to set a height of your columns element for this to work.

I think is-vcentered should be named something like has-vcentered-content, but perhaps I'm missing something obvious.

tl;dr; Add height and flex to the columns-element for is-vcentered to do something.

Sorry, I guess this is more of a extrapolation of the problem and not a solution.

I believe the real solution is probably to use the existing hero-class here. (Which by the way centers manually using paddings, just like in Peter Leger's answer!).

ContentLicense: CC BY-SA 4.0


问:
Apply function to each cell in DataFrame in place in pandas
Is it possible to apply function to each cell in a DataFrame in place in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow in place application:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

frame = frame.applymap(format) will temporarily hold 2 copies of frame in
memory, which I don't want.

I know one can apply a function to each cell in place with a NumPy array: Mapping a NumPy array in place.

答:
If my understanding is correct, pandas inplace operations involve calling an .update_inplace() method, so for example, .replace() would compute the new, replaced data first, then update the dataframe accordingly.

.applymap() is a wrapper of .apply(); neither of these come with inplace options, but even if they did, they would still need to store all the output data in memory before modifying the dataframe.

From the source, .applymap() calls .apply(), which calls .aggregate(), which calls _aggregate(), which calls ._agg(), which is nothing more than a for loop run in Python <s>(i.e. not Cython -- I think)</s>.

<s>You could of course, modify the underlying NumPy array directly: the following code rounds the dataframe in place:

```<code>frame = pd.DataFrame(np.random.randn(100, 100))

for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        frame.values[i,j] = val

newvals = np.zeros(frame.shape[1])
for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        newvals[j] = val
    frame.values[i] = newvals
</code>```

The first method sets one element at a time, and takes about 1s, the second sets by row, and takes 100ms; .applymap(round) does it in 20ms.

However, interestingly, if we use frame = pd.DataFrame(np.random.randn(1, 10000)), both the first method and .applymap(round) take about 1.2s, and the second takes about 100ms.

Finally, frame = pd.DataFrame(np.random.randn(10000,1)) has the first and second method taking 1s (unsurprisingly), and .applymap(round) takes 10ms.

These results more or less show that .applymap is essentially iterating over each column.</s>

I tried running frame.applymap(round) with 3 different shapes: (10000,1), (100,100), and (1,10000). The first was fastest, and the third was slowest; this shows that .applymap() iterates over columns. The following code does roughly the same thing as .applymap(), in place:

```<code>newvals = np.zeros(frame.shape[1])
for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        newvals[j] = val
    frame.values[i] = newvals
</code>```

This one works with a copy of the underlying NumPy array:

```<code>newvals = np.zeros(frame.shape[1])
arr = frame.values
for i in frame.index:
    for j in frame.columns:
        val = round(arr[i,j])
        newvals[j] = val
        arr[i] = newvals
</code>```

With a 100x100 dataframe, the former took about 300ms for me to run, and the latter 60ms -- the difference is solely due to having to access .values in the dataframe!

Running the latter in Cython takes about 34ms, whereas .applymap(round) does it in 24ms. I have no idea why .applymap() is still faster here though.

To answer the question: there probably isn't an in-place implementation of .applymap(); if there was, it would most likely involve storing all the 'applied' values before making the in-place change.

If you want to do an .applymap() in-place, you could just iterate over the underlying NumPy array. However, this comes at a cost of performance -- the best solution is likely to iterate over the rows or columns: e.g. assign arr=df.values[i], apply the function on each element of arr, modify the dataframe by df.values[i] = arr, and iterating over all i.

Body:
Is it possible to apply function to each cell in a DataFrame in place in pandas?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow in place application:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

frame = frame.applymap(format) will temporarily hold 2 copies of frame in
memory, which I don't want.

I know one can apply a function to each cell in place with a NumPy array: Mapping a NumPy array in place.

Body:
If my understanding is correct, pandas inplace operations involve calling an .update_inplace() method, so for example, .replace() would compute the new, replaced data first, then update the dataframe accordingly.

.applymap() is a wrapper of .apply(); neither of these come with inplace options, but even if they did, they would still need to store all the output data in memory before modifying the dataframe.

From the source, .applymap() calls .apply(), which calls .aggregate(), which calls _aggregate(), which calls ._agg(), which is nothing more than a for loop run in Python <s>(i.e. not Cython -- I think)</s>.

<s>You could of course, modify the underlying NumPy array directly: the following code rounds the dataframe in place:

frame = pd.DataFrame(np.random.randn(100, 100))

for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        frame.values[i,j] = val

newvals = np.zeros(frame.shape[1])
for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        newvals[j] = val
    frame.values[i] = newvals

The first method sets one element at a time, and takes about 1s, the second sets by row, and takes 100ms; .applymap(round) does it in 20ms.

However, interestingly, if we use frame = pd.DataFrame(np.random.randn(1, 10000)), both the first method and .applymap(round) take about 1.2s, and the second takes about 100ms.

Finally, frame = pd.DataFrame(np.random.randn(10000,1)) has the first and second method taking 1s (unsurprisingly), and .applymap(round) takes 10ms.

These results more or less show that .applymap is essentially iterating over each column.</s>

I tried running frame.applymap(round) with 3 different shapes: (10000,1), (100,100), and (1,10000). The first was fastest, and the third was slowest; this shows that .applymap() iterates over columns. The following code does roughly the same thing as .applymap(), in place:

newvals = np.zeros(frame.shape[1])
for i in frame.index:
    for j in frame.columns:
        val = round(frame.values[i,j])
        newvals[j] = val
    frame.values[i] = newvals

This one works with a copy of the underlying NumPy array:

newvals = np.zeros(frame.shape[1])
arr = frame.values
for i in frame.index:
    for j in frame.columns:
        val = round(arr[i,j])
        newvals[j] = val
        arr[i] = newvals

With a 100x100 dataframe, the former took about 300ms for me to run, and the latter 60ms -- the difference is solely due to having to access .values in the dataframe!

Running the latter in Cython takes about 34ms, whereas .applymap(round) does it in 24ms. I have no idea why .applymap() is still faster here though.

To answer the question: there probably isn't an in-place implementation of .applymap(); if there was, it would most likely involve storing all the 'applied' values before making the in-place change.

If you want to do an .applymap() in-place, you could just iterate over the underlying NumPy array. However, this comes at a cost of performance -- the best solution is likely to iterate over the rows or columns: e.g. assign arr=df.values[i], apply the function on each element of arr, modify the dataframe by df.values[i] = arr, and iterating over all i.


问:
split string of spans into array of spans
I have a block of text wrapped in spans that I need to split into an array.

So currently I have

```<code>var s = `
   <span class="hoverable">c</span>
   <span class="hoverable">o</span>
   <span class="not-hoverable">o</span>`;
</code>```

I need

```<code>var s = [
   "<span class="hoverable">c</span>",
   "<span class="hoverable">o</span>",
   "<span class="not-hoverable">o</span>"];
</code>```

I've tried s.split(/<\/?span>/); to split accounting for  and closing  but

```<code>var s = [
  "<span class="hoverable">c",
  "<span class="hoverable">o",
  "<span class="not-hoverable">o",...]
</code>```

So it's not including the closing span.

答:
As always when a regexp question wanders over into HTML or XML territory, I suggest regexp is not the right tool. Use the proper HTML parser available in the language you are using. In case of JavaScript (implied by your use of var and string template syntax):

let s = `
   c
   o
   o`;
let d = document.createElement('div');
d.innerHTML = s;
let result = Array.from(d.children).map(e => e.outerHTML);
console.log(result);```

Body:
I have a block of text wrapped in spans that I need to split into an array.

So currently I have

var s = `
   c
   o
   o`;

I need

var s = [
   "c",
   "o",
   "o"];

I've tried s.split(/<\/?span>/); to split accounting for  and closing  but

var s = [
  "c",
  "o",
  "o",...]

So it's not including the closing span.

Body:
As always when a regexp question wanders over into HTML or XML territory, I suggest regexp is not the right tool. Use the proper HTML parser available in the language you are using. In case of JavaScript (implied by your use of var and string template syntax):

let s = `
   <span class="hoverable">c</span>
   <span class="hoverable">o</span>
   <span class="not-hoverable">o</span>`;
let d = document.createElement('div');
d.innerHTML = s;
let result = Array.from(d.children).map(e => e.outerHTML);
console.log(result);


问:
Textbox mandatory on clicking radio button
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button.When yes radiobutton is clicked. the quantity textbox should not be empty.but it can be empty if no radiobutton is clicked.This functionality should work when submit button is clicked with yes radiobutton is selected.any ideas?
MY VIEW:

```<code> <HTML>
    <head>
    radio
    </head>
    <body>
    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No<br />
    <label>Quantity</label><input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>
</body>
<div>
<script src="~/Scripts/radiobuttonvalidation.js"></script>
</div>
</html>
</code>```

im new to mvc and javascript help me with javascript code too.and the way i should link it with my view.
Javascript:

```<code>    function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}
</code>```

答:
HTML Required attribute can be really helpful in such scenarios.
Go through this Link for more information.
Also, Check Jquery Validator if you need more customization.

    radio

    <form id=radio>
     Add to electronic
     <input type="radio" name="yes" id="yes" onchange="validate(this)"/>Yes
     <input type="radio" name="yes" id="no" onchange="validate(this)"/>No

    Quantity
    <input type="text"size="25" name="quantity"id="quantity" required/>
    <button type=submit name=insert>insert</button>

```

Body:
I have a view where add to electronic has 2 radiobuttons yes & no. And a submit button.When yes radiobutton is clicked. the quantity textbox should not be empty.but it can be empty if no radiobutton is clicked.This functionality should work when submit button is clicked with yes radiobutton is selected.any ideas?
MY VIEW:

    radio

    <form id=radio>
     Add to electronic  <input type="radio" name="yes"onclick="validate(_this)"id="yes"/>Yes<input type="radio" name="yes" id="no" />No

    Quantity<input type="text"size="25"name="dir"id="dir" required/>
<button type=submit name=insert>insert</button>

im new to mvc and javascript help me with javascript code too.and the way i should link it with my view.
Javascript:

    function validate(_this) {
    if ($(_this).attr('id') == "yes") {
        $('#dir').attr('required');
        alert("Text Box required");
    }
    else {
        $('#dir').removeAttr('required');
        alert("Text Box not required");
    }
}

Body:
HTML Required attribute can be really helpful in such scenarios.
Go through this Link for more information.
Also, Check Jquery Validator if you need more customization.

<HTML>
    <head>
    radio
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script>
        function validate(_this)
        {
           if($(_this).attr('id') == "yes")
            {
                $('#quantity').attr('required');
                alert("Text Box required");
             }
            else
             {
                 $('#quantity').removeAttr('required');
                 alert("Text Box not required");
             }
        }

      </script>
    </head>
    <body>
    <form id=radio>
     Add to electronic
     <input type="radio" name="yes" id="yes" onchange="validate(this)"/>Yes
     <input type="radio" name="yes" id="no" onchange="validate(this)"/>No<br />
    <label>Quantity</label>
    <input type="text"size="25" name="quantity"id="quantity" required/>
    <button type=submit name=insert>insert</button>
</body>
</html>


问:
PHP while loop modify last iteration
I am trying to generate a JSON file from PHP. So far I have the following output:

```<code>"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]
</code>```

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like so:

```<code>    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT *
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    }
</code>```

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.

The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

```<code>$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}
</code>```

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.

答:
Please don't try to make JSON by hand. Try something like this instead:</p>

```<code>$students = [];

// This would happen in your loop.
$students[] = array("name" => "John");
$students[] = array("name" => "Alex");
$students[] = array("name" => "Siri");

// Feel free to drop the JSON_PRETTY_PRINT.
echo json_encode(array("students" => $students), JSON_PRETTY_PRINT) . "\n";

// Output:
// {
//     "students": [
//         {
//             "name": "John"
//         },
//         {
//             "name": "Alex"
//         },
//         {
//             "name": "Siri"
//         }
//     ]
// }
</code>```

Title: PHP while loop modify last iteration

Body:
I am trying to generate a JSON file from PHP. So far I have the following output:

"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like so:

    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT *
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    }

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.

The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.

Body:
Please don't try to make JSON by hand. Try something like this instead:

$students = [];

// This would happen in your loop.
$students[] = array("name" => "John");
$students[] = array("name" => "Alex");
$students[] = array("name" => "Siri");

// Feel free to drop the JSON_PRETTY_PRINT.
echo json_encode(array("students" => $students), JSON_PRETTY_PRINT) . "\n";

// Output:
// {
//     "students": [
//         {
//             "name": "John"
//         },
//         {
//             "name": "Alex"
//         },
//         {
//             "name": "Siri"
//         }
//     ]
// }


问:
How to group all values by semicolon separated in SQL query
Please help how to achieve data as per shown in attached image

Highlighted rows actually group on Item Number field

Thanks in advance

答:
You could use STRING_AGG

```<code>SELECT [Item Number],  STRING_AGG (CONCAT(TotalItem,'x',ItemName), ';') as tags
FROM dbo.TableName
GROUP BY [Item Number];
</code>```

Body:
You could use STRING_AGG

SELECT [Item Number],  STRING_AGG (CONCAT(TotalItem,'x',ItemName), ';') as tags
FROM dbo.TableName
GROUP BY [Item Number];


问:
How to output multiple line mysql string from database without quotes
I'm retrieving a string from a database that was entered by a form, but if the string is to long, it's generated with double quotes in the html.
This is how I'm retrieving the data:

```<code>echo '<p>' . $descr['field_value'] . '</P>';
</code>```

When I view the html source, the browser adds double quotes.

short single line strings do not show up with quotes.

Is there a way to force php to display strings without quotes?

答:
You should use echo '
' . htmlspecialchars($desc['field_value']) . '
';.

See http://php.net/manual/en/function.htmlspecialchars.php for more details.

ContentLicense: CC BY-SA 2.5

Body:
I'm retrieving a string from a database that was entered by a form, but if the string is to long, it's generated with double quotes in the html.
This is how I'm retrieving the data:

echo '
' . $descr['field_value'] . '
';

When I view the html source, the browser adds double quotes.

short single line strings do not show up with quotes.

Is there a way to force php to display strings without quotes?

Body:
You should use echo '<p>' . htmlspecialchars($desc['field_value']) . '</p>';.

See http://php.net/manual/en/function.htmlspecialchars.php for more details.


问:
Erasing DrawReversibleFrame from screen
I am having trouble with removing DrawReversibleFrame from the screen. Docs say to enter the function twice to remove it but it seems like it does not work with my logic layout.

```<code>using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
    private Point? _start;
    private Rectangle _previousBounds;

    public Form1()
    {
        InitializeComponent();
    }

    private void OnMouseDown(object sender,MouseEventArgs e)
    {
        _start = e.Location;
    }

    private void OnMouseMove(object sender,MouseEventArgs e)
    {
        if (_start.HasValue)
        {
            ReverseFrame();
            DrawFrame(e.Location);
        }
    }

    private void OnMouseUp(object sender,MouseEventArgs e)
    {
        ReverseFrame();
        _start = null;
    }

    private void ReverseFrame()
    {
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);

    }
    private void DrawFrame(Point end)
    {
        ReverseFrame();

        var size = new Size(end.X - _start.Value.X, end.Y - _start.Value.Y);
        _previousBounds = new Rectangle(_start.Value, size);
        _previousBounds = RectangleToScreen(_previousBounds);
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);
    }
}
}
</code>```

This is my result when I drag my mouse on the form. http://imgur.com/a/Kh4h7

The pesudo code should work like this which I feel like I am doing.

MouseDown:

Draw rectangle.

Save rectangle bounds.

--

MouseMove (w/ left button down):

Redraw previous rectangle to erase.

Calculate next rectangle.

Draw next rectangle.

Save rectangle bounds.

Rinse/Repeat (indefinitely)

--

MouseUp:

Redraw last rectangle to erase.

答:
Take a look at this example

MouseUp handler in the example is point of interest.

```<code> private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // If the MouseUp event occurs, the user is not dragging.
            isDrag = false;

            // Draw the rectangle to be evaluated. Set a dashed frame style
            // using the FrameStyle enumeration.
            ControlPaint.DrawReversibleFrame(theRectangle, this.BackColor, FrameStyle.Dashed);

            // Find out which controls intersect the rectangle and
            // change their color. The method uses the RectangleToScreen
            // method to convert the Control's client coordinates
            // to screen coordinates.
            Rectangle controlRectangle;
            for (int i = 0; i < Controls.Count; i++)
            {
                controlRectangle = Controls[i].RectangleToScreen(Controls[i].ClientRectangle);
                if (controlRectangle.IntersectsWith(theRectangle))
                {
                    Controls[i].BackColor = Color.BurlyWood;
                }
            }

            // Reset the rectangle.
            theRectangle = new Rectangle(0, 0, 0, 0);
        }
</code>```

Specifically, I put following line under comment when tested it and got the same result as yours.

```<code>// ControlPaint.DrawReversibleFrame(theRectangle, this.BackColor, FrameStyle.Dashed);
</code>```

Update

I tested your code. I think your rectangle _previousBounds is not getting drawn for the second time.

Title: Erasing DrawReversibleFrame from screen

Body:
I am having trouble with removing DrawReversibleFrame from the screen. Docs say to enter the function twice to remove it but it seems like it does not work with my logic layout.

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
    private Point? _start;
    private Rectangle _previousBounds;

    public Form1()
    {
        InitializeComponent();
    }

    private void OnMouseDown(object sender,MouseEventArgs e)
    {
        _start = e.Location;
    }

    private void OnMouseMove(object sender,MouseEventArgs e)
    {
        if (_start.HasValue)
        {
            ReverseFrame();
            DrawFrame(e.Location);
        }
    }

    private void OnMouseUp(object sender,MouseEventArgs e)
    {
        ReverseFrame();
        _start = null;
    }

    private void ReverseFrame()
    {
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);

    }
    private void DrawFrame(Point end)
    {
        ReverseFrame();

        var size = new Size(end.X - _start.Value.X, end.Y - _start.Value.Y);
        _previousBounds = new Rectangle(_start.Value, size);
        _previousBounds = RectangleToScreen(_previousBounds);
        ControlPaint.DrawReversibleFrame(_previousBounds, Color.Red, FrameStyle.Dashed);
    }
}
}

This is my result when I drag my mouse on the form. http://imgur.com/a/Kh4h7

The pesudo code should work like this which I feel like I am doing.

MouseDown:

Draw rectangle.

Save rectangle bounds.

--

MouseMove (w/ left button down):

Redraw previous rectangle to erase.

Calculate next rectangle.

Draw next rectangle.

Save rectangle bounds.

Rinse/Repeat (indefinitely)

--

MouseUp:

Redraw last rectangle to erase.

Body:
Take a look at this example

MouseUp handler in the example is point of interest.

 private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            // If the MouseUp event occurs, the user is not dragging.
            isDrag = false;

            // Draw the rectangle to be evaluated. Set a dashed frame style
            // using the FrameStyle enumeration.
            ControlPaint.DrawReversibleFrame(theRectangle, this.BackColor, FrameStyle.Dashed);

            // Find out which controls intersect the rectangle and
            // change their color. The method uses the RectangleToScreen
            // method to convert the Control's client coordinates
            // to screen coordinates.
            Rectangle controlRectangle;
            for (int i = 0; i < Controls.Count; i++)
            {
                controlRectangle = Controls[i].RectangleToScreen(Controls[i].ClientRectangle);
                if (controlRectangle.IntersectsWith(theRectangle))
                {
                    Controls[i].BackColor = Color.BurlyWood;
                }
            }

            // Reset the rectangle.
            theRectangle = new Rectangle(0, 0, 0, 0);
        }

Specifically, I put following line under comment when tested it and got the same result as yours.

// ControlPaint.DrawReversibleFrame(theRectangle, this.BackColor, FrameStyle.Dashed);

Update

I tested your code. I think your rectangle _previousBounds is not getting drawn for the second time.


问:
How to get tensorflow to do a convolution on a 2 x 2 matrix with a 1 x 2 kernel?
I have the following matrix:

and the following kernel:

If I do a convolution with no padding and slide by 1 row, I should get the following answer:

Because:

Based the documentation of  tf.nn.conv2d, I thought this code expresses what I just described above:

```<code>import tensorflow as tf

input_batch = tf.constant([
    [
        [[.0], [1.0]],
        [[2.], [3.]]
    ]
])

kernel = tf.constant([
    [
        [[1.0, 2.0]]
    ]
])

conv2d = tf.nn.conv2d(input_batch, kernel, strides=[1, 1, 1, 1], padding='VALID')
sess = tf.Session()

print(sess.run(conv2d))
</code>```

But it produces this output:

```<code>[[[[ 0.  0.]
   [ 1.  2.]]

  [[ 2.  4.]
   [ 3.  6.]]]]
</code>```

And I have no clue how that is computed. I've tried experimenting with different values for the strides padding parameter but still am not able to produce the result I expected.

答:
You have not correctly read my explanation in the tutorial you linked. After a straight-forward modification of no-padding, strides=1 you suppose to get the following code.

```<code>import tensorflow as tf
k = tf.constant([
    [1, 2],
], dtype=tf.float32, name='k')
i = tf.constant([
    [0, 1],
    [2, 3],
], dtype=tf.float32, name='i')
kernel = tf.reshape(k, [1, 2, 1, 1], name='kernel')
image  = tf.reshape(i, [1, 2, 2, 1], name='image')

res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
# VALID means no padding
with tf.Session() as sess:
   print sess.run(res)
</code>```

Which gives you the result you expected: [2., 8.]. Here I got a vector instead of the column because of squeeze operator.

One problem I see with your code (there might be other) is that your kernel is of the shape (1, 1, 1, 2), but it suppose to be (1, 2, 1, 1).

Body:
I have the following matrix:

and the following kernel:

If I do a convolution with no padding and slide by 1 row, I should get the following answer:

Because:

Based the documentation of  tf.nn.conv2d, I thought this code expresses what I just described above:

import tensorflow as tf

input_batch = tf.constant([
    [
        [[.0], [1.0]],
        [[2.], [3.]]
    ]
])

kernel = tf.constant([
    [
        [[1.0, 2.0]]
    ]
])

conv2d = tf.nn.conv2d(input_batch, kernel, strides=[1, 1, 1, 1], padding='VALID')
sess = tf.Session()

print(sess.run(conv2d))

But it produces this output:

[[[[ 0.  0.]
   [ 1.  2.]]

  [[ 2.  4.]
   [ 3.  6.]]]]

And I have no clue how that is computed. I've tried experimenting with different values for the strides padding parameter but still am not able to produce the result I expected.

Body:
You have not correctly read my explanation in the tutorial you linked. After a straight-forward modification of no-padding, strides=1 you suppose to get the following code.

import tensorflow as tf
k = tf.constant([
    [1, 2],
], dtype=tf.float32, name='k')
i = tf.constant([
    [0, 1],
    [2, 3],
], dtype=tf.float32, name='i')
kernel = tf.reshape(k, [1, 2, 1, 1], name='kernel')
image  = tf.reshape(i, [1, 2, 2, 1], name='image')

res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
# VALID means no padding
with tf.Session() as sess:
   print sess.run(res)

Which gives you the result you expected: [2., 8.]. Here I got a vector instead of the column because of squeeze operator.

One problem I see with your code (there might be other) is that your kernel is of the shape (1, 1, 1, 2), but it suppose to be (1, 2, 1, 1).


问:
How can I declare a function returning a type from a Typescript-enabled library in Typescript
I'm using a library (Axios) that has Typescript declarations included in its package.

I'd like to declare a function that takes an AxiosResponse (declared in the library's .d.ts file) as a parameter. I have the following:

```<code>function persistEvents(response: AxiosResponse) {
  ...
}
</code>```

However, in VS code, I'm encountering the error "Cannot find name 'AxiosResponse'".

What do I need to do to be able to declare a function parameter or return that's from my library?

答:
To reference types declared in another package, you will need to import them into the .ts or .d.ts file in which you wish to use them.

Adding the following import should solve your problem:

import { AxiosResponse } from "axios";
```

Body:
I'm using a library (Axios) that has Typescript declarations included in its package.

I'd like to declare a function that takes an AxiosResponse (declared in the library's .d.ts file) as a parameter. I have the following:

function persistEvents(response: AxiosResponse) {
  ...
}

However, in VS code, I'm encountering the error "Cannot find name 'AxiosResponse'".

What do I need to do to be able to declare a function parameter or return that's from my library?


问:
Input from file in C, data types
thanks in advance for taking the time to read through my question...

```<code>/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}
</code>```

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

答:
fscanf won't help you if there are no exponents so you're on your own.  That means splitting the string at the +/-, calling atof() on the left, atoi() (or atof()) on the right and multiplying the first by the first to 10 raised to the second:</p>

```<code>char *splitAt(char *s, char *stops)
{
   if (!s) return 0;
   char *t;
   for (t = s; *t && strchr(stops, *t) == NULL; t++)
       ;
   int len = t - s;
   t = malloc(len + 1);
   strncpy(t, s, len);
   t[len] = '\0';
   return t;
}

double parse_my_float(char *input)
{
    /* allocates a new string */
    char *mantissaStr = splitAt(input, "+-"); /* check for null! */
    double mantissa = atof(mantissaStr);
    int len = strlen(mantissaStr);
    free(mantissaStr);
    int exponent = atoi(input + len);
    return mantissa * pow(10, exponent);
}
</code>```

Title: Input from file in C, data types

Body:
thanks in advance for taking the time to read through my question...

/* Binary search for use with Gen_window.comp */
#include <stdio.h>

int main()
{
  char line[1000];
  double sig, E;

  FILE *fp, *fopen();
  fp = fopen("sig_data", "r");

  if (fp==NULL){
        printf("Error opening file!");
  }
  else {
        printf("Processing file...");
  }

  while( (fgets(line, 25, fp) != NULL) ){
        fscanf(fp, "%lf\t%lf", &E, &sig);
        printf("\nThe energy is: %lf eV\nThe corresponding cross section is: %lf barns\n",E, sig);
  }

}

Numbers in the file are of the format X.XXXXXX+X or X.XXXXXX-X accordingly.  Does C have a way to specify this as input?  Is it a bother that there is no 'e'.  I cannot find any documentation that tells about inputing exponential, only returning exponential...

I do not need it to print that exact format, any other exponential format would be fine.

I realize there should be some specifiers and precision in my %lf, or maybe it should be %e, but I have tried everything that makes sense to me, so I am basically leaving it blank.

Thanks for your help.

Body:
fscanf won't help you if there are no exponents so you're on your own.  That means splitting the string at the +/-, calling atof() on the left, atoi() (or atof()) on the right and multiplying the first by the first to 10 raised to the second:

char *splitAt(char *s, char *stops)
{
   if (!s) return 0;
   char *t;
   for (t = s; *t && strchr(stops, *t) == NULL; t++)
       ;
   int len = t - s;
   t = malloc(len + 1);
   strncpy(t, s, len);
   t[len] = '\0';
   return t;
}

double parse_my_float(char *input)
{
    /* allocates a new string */
    char *mantissaStr = splitAt(input, "+-"); /* check for null! */
    double mantissa = atof(mantissaStr);
    int len = strlen(mantissaStr);
    free(mantissaStr);
    int exponent = atoi(input + len);
    return mantissa * pow(10, exponent);
}


问:
Create a dictionary that has summary value from list / Combine two different dictionaries to summarize value
I am new to python and working with dictionaries and list.
Here is the list

```<code>detail = [(1, [u'apple', u'2017-07-03T08:03:32Z', 'boston']),

 (2, [u'orange', u'2017-07-03T08:58:35Z', 'NOLOCATION']),

 (3, [u'grape', u'2017-07-03T12:14:12Z', 'boston']),

 (4, [u'cherry', u'2017-07-04T13:16:44Z', 'new york']),

 (5, [u'strawberry', u'2017-07-06T10:56:22Z', 'san francisco']),

 (6, [u'plum', u'2017-07-06T10:56:22Z', 'seattle'])]
</code>```

I want to summarize this, so that - for each date, I get split of counts for each location. Something  like this -

```<code>details_summary = {'2017-07-03':[(boston,2), (NOLOCATION,1)], '2017-07-04':
[new york,1], '2017-07-06':[(san francisco,1),(seattle,1)]}
</code>```

I want it in this format, because I want to generate map (visualization) for each date (key), and location points(value).

I ended up creating two different dictionaries that look like this -

```<code>location = {u'boston': 2, 'NOLOCATION': 1, u'new york': 1, u'san francisco':
1, u'seattle': 1}

date = {'2017-07-03':3, '2017-07-04':1, '2017-07-06':2}
</code>```

Now, I want to summarize so that I get, split of counts in different location for each date and I am stuck here.

答:
```<code>from collections import Counter
d = {}
for k, (w, t, l) in detail:
    date = t.split('T')[0] # you can choose to enhance date "isolation"
    if date in d:
        d[date].append(l)
    else:
        d[date] = [l]
details_summary = {k: Counter(d[k]).items() for k in d.keys()}
</code>```

Body:
I am new to python and working with dictionaries and list.
Here is the list

detail = [(1, [u'apple', u'2017-07-03T08:03:32Z', 'boston']),

 (2, [u'orange', u'2017-07-03T08:58:35Z', 'NOLOCATION']),

 (3, [u'grape', u'2017-07-03T12:14:12Z', 'boston']),

 (4, [u'cherry', u'2017-07-04T13:16:44Z', 'new york']),

 (5, [u'strawberry', u'2017-07-06T10:56:22Z', 'san francisco']),

 (6, [u'plum', u'2017-07-06T10:56:22Z', 'seattle'])]

I want to summarize this, so that - for each date, I get split of counts for each location. Something  like this -

details_summary = {'2017-07-03':[(boston,2), (NOLOCATION,1)], '2017-07-04':
[new york,1], '2017-07-06':[(san francisco,1),(seattle,1)]}

I want it in this format, because I want to generate map (visualization) for each date (key), and location points(value).

I ended up creating two different dictionaries that look like this -

location = {u'boston': 2, 'NOLOCATION': 1, u'new york': 1, u'san francisco':
1, u'seattle': 1}

date = {'2017-07-03':3, '2017-07-04':1, '2017-07-06':2}

Now, I want to summarize so that I get, split of counts in different location for each date and I am stuck here.


问:
FilterProxyListModel examples in CodenameOne
Since Codename One supports a subset of base Java Object Functionality, I can't use Vector.sort() to sort my data before adding it into a DefaultListModel.  so Looking for other sorting options in Codename One, I found the FilterProxyListModel.

I can't find an example of how to properly initialize the FilterProxyListModel as it's using an interesting but tricky "Proxy" design pattern that I'm unfamiliar with.    Here's how I've implemented it so far, but the component doesn't show any elements in the simulator when I do it this way.  This is in the "initListModel..." method for my List from the GUI Builder:

```<code>protected boolean initListModelLearnableTopicsList(List cmp){

    Vector learnableListModel = new Vector;
    //omitting initialization of learnableListModel as a Vector of HashTables with key/value pairs to display
    ...

    FilterProxyListModel<DefaultListModel> fpListModel = new FilterProxyListModel<DefaultListModel>(new DefaultListModel(learnableListModel)) {
        @Override
        protected int compare(Object a, Object b, boolean ascending) {
            //details omitted... uses data in the LearnableListModel to provide sort order
        }

        @Override
        protected boolean check(Object o, String str) {
            //force all results to pass filter since original method fails when a Map object without a key of "name" is in the list
            return true;
        }

    };

    fpListModel.sort(true);

    cmp.setModel(fpListModel);
}
</code>```

Am I doing something wrong here?  is there an example somewhere I should be using as a guide to doing this properly?

答: You can use Collections.sort(vector); the filter model is for list classes which we don't really recommend as much https://www.codenameone.com/blog/avoiding-lists.html

Body:
Since Codename One supports a subset of base Java Object Functionality, I can't use Vector.sort() to sort my data before adding it into a DefaultListModel.  so Looking for other sorting options in Codename One, I found the FilterProxyListModel.

I can't find an example of how to properly initialize the FilterProxyListModel as it's using an interesting but tricky "Proxy" design pattern that I'm unfamiliar with.    Here's how I've implemented it so far, but the component doesn't show any elements in the simulator when I do it this way.  This is in the "initListModel..." method for my List from the GUI Builder:

protected boolean initListModelLearnableTopicsList(List cmp){

    Vector learnableListModel = new Vector;
    //omitting initialization of learnableListModel as a Vector of HashTables with key/value pairs to display
    ...

    FilterProxyListModel<DefaultListModel> fpListModel = new FilterProxyListModel<DefaultListModel>(new DefaultListModel(learnableListModel)) {
        @Override
        protected int compare(Object a, Object b, boolean ascending) {
            //details omitted... uses data in the LearnableListModel to provide sort order
        }

        @Override
        protected boolean check(Object o, String str) {
            //force all results to pass filter since original method fails when a Map object without a key of "name" is in the list
            return true;
        }

    };

    fpListModel.sort(true);

    cmp.setModel(fpListModel);
}

Am I doing something wrong here?  is there an example somewhere I should be using as a guide to doing this properly?


问:
short Glitch in making android dynamic
I am sending a json request using params and the glitch is when I hardcode the user name and password , it works and when I set the variables it doesn't ?
What to write inplace of "ankur@gmail.com" & "123456"

```<code>    EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();
    params.put("user_email","ankur@gmail.com");
    params.put("user_password","123456");
    Log.d("jsonobject", "jsonobjectResponse: "+params);

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                            new Response.Listener<JSONObject>() {   .........
</code>```

logs

```<code>07-06 12:23:32.365 4701-4701/com.production.vy.triqsquad D/jsonobject: jsonobjectResponse: {user_password=, user_email=}
07-06 12:23:56.046 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:04.765 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:07.584 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
</code>```

why the password is before username when I am writing username above password

答:
Try this

```<code>.........

// remove the '\u0022'
String temp = username.getText().toString().trim();
String temp1 =password.getText().toString().trim();

.........

final HashMap<String,String> params = new HashMap<String, String>();
params.put("user_email", temp);
params.put("user_password", temp1);
Log.d("jsonobject", "jsonobjectResponse: "+params);
</code>```

What I'm thinking is that you do not have to insert '\u0022' yourself. JsonObjectRequest will do it for you when it stringify.

Are you developing the server too? If so, you can also access your server to see what is your server receiving to better troubleshoot your current problem.

Others will provide better answers if you were to submit the logcat/console errors too.

Title: short Glitch in making android dynamic

Body:
I am sending a json request using params and the glitch is when I hardcode the user name and password , it works and when I set the variables it doesn't ?
What to write inplace of "ankur@gmail.com" & "123456"

    EditText username = (EditText)findViewById(R.id.edituser);
            EditText password = (EditText)findViewById(R.id.editpass);
            Button button = (Button)findViewById(R.id.signin);
            final JSONObject jsonObject = new JSONObject();
            String temp = '\u0022' +username.getText().toString().trim()+'\u0022';
            String temp1 ='\u0022'+password.getText().toString().trim()+'\u0022';

.........

final HashMap<String,String> params = new HashMap<String, String>();
    params.put("user_email","ankur@gmail.com");
    params.put("user_password","123456");
    Log.d("jsonobject", "jsonobjectResponse: "+params);

.........

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,new JSONObject(params),
                            new Response.Listener<JSONObject>() {   .........

logs

07-06 12:23:32.365 4701-4701/com.production.vy.triqsquad D/jsonobject: jsonobjectResponse: {user_password=, user_email=}
07-06 12:23:56.046 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:04.765 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
07-06 12:24:07.584 4701-4701/com.production.vy.triqsquad D/aaa: onErrorResponse: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

why the password is before username when I am writing username above password

Body:
Try this

.........

// remove the '\u0022'
String temp = username.getText().toString().trim();
String temp1 =password.getText().toString().trim();

.........

final HashMap<String,String> params = new HashMap<String, String>();
params.put("user_email", temp);
params.put("user_password", temp1);
Log.d("jsonobject", "jsonobjectResponse: "+params);

What I'm thinking is that you do not have to insert '\u0022' yourself. JsonObjectRequest will do it for you when it stringify.

Are you developing the server too? If so, you can also access your server to see what is your server receiving to better troubleshoot your current problem.

Others will provide better answers if you were to submit the logcat/console errors too.


问:
Removing divs without removing their content in plain Javascript
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

```<code><div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>
</code>```

Expected output would be like shown below.

```<code><p>some text
   <label> Test content </label>
</p>
<span>some text</span>
<label> Test content </label>
<a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a>
</code>```

答:
1.Using pure java-script:-

var divs=document.getElementsByTagName('div');
var counter = divs.length-1;
for(i=counter;i>=0;i--){
 divs[i].outerHTML = divs[i].innerHTML;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      creepiness
    </div>
  </div>
</div></code>```

2.You can use jQuery unwrap() also:-

$(document).ready(function(){
  $('div').contents().unwrap();
});```
<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>
<div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      creepiness
    </div>
  </div>
</div></code>```

Body:
Could anyone help me on how I can remove div tags without removing their content in JavaScript?

This is my html from which I need to remove all div tags:

some text
     Test content

    some text

       Test content
      creepiness

Expected output would be like shown below.

some text
    Test content

some text
 Test content
creepiness

Body:
1.Using pure java-script:-

var divs=document.getElementsByTagName('div');
var counter = divs.length-1;
for(i=counter;i>=0;i--){
 divs[i].outerHTML = divs[i].innerHTML;
}

<div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>

2.You can use jQuery unwrap() also:-

$(document).ready(function(){
  $('div').contents().unwrap();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1" class="someclass">
  <p>some text
    <label> Test content </label>
  </p>
  <div id="id2" style="overfolw:scroll">
    <span>some text</span>
    <div id="level3">
      <label> Test content </label>
      <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a>
    </div>
  </div>
</div>


答:
You have two options:

Method 1: rtrim

Use rtrim($jsonfield, ',')

Method 2: implode

Add to $jsonfield as array - $jsonfield[]=.... and then use implode(',', $jsonfield).

Important:

More than these, why do you want to generate JSON using loop? You can use json_encode function.

Title: PHP while loop modify last iteration

Body:
I am trying to generate a JSON file from PHP. So far I have the following output:

"students":[
    {"name": "John"},
    {"name": "Alex"},
    {"name": "Siri"},
]

There is a comma after each student, when I clearly have to remove the final comma. Normally I would perform a while loop with an if statement. However, my database structure makes this situation different.

My PHP code looks like so:

    while ($getschools = $schools->fetch_assoc()){
        $findschools = $dbcon->query("SELECT *
            FROM school_".$getstate['texas']."
            WHERE students = '".$studentGPA['best']."'");
        while ($beststudents = $findschools->fetch_assoc()){
            $jsonfield.= '{"name":"'.$getstudent['firstname'].'"},';
        }
    }

The code might have a few missing parts, but hopefully the context is clear. I am using php variables from previous fetch requests to acquire data from multiple tables.

In my example there are multiple tables corresponding to the schools in Texas. I am getting the firstnames of every student from those multiple schools (or tables). I am attempting to apply this information to a JSON output.

The $jsonfield line shows the loop portion of my code. I am trying to figure out how to implement a code like this in my example:

$i = 0;
$countstudents = $getschools->num_rows;
if ($i < $countstudents){
$jsonfield.=',';
}

This way my commas are only applied to the parts of my data that are not the final iteration of my loop.


问:
ASP.NET DataList - defining "columns/rows" when repeating horizontal and using flow layout
Here is my DataList:

```<code><asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>
</code>```

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

```<code><div>
 <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
</div>
<div>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
</div>
[etc]
</code>```

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

```<code> <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
<br>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
<br>
</code>```

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

答: I may be confused, but why not just use a repeater and a custom item template?</p>

OwnerDisplayName: irobinson

Body:
Here is my DataList:

<asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

[etc]

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

LastEditorDisplayName: bdukes

OwnerDisplayName: Mike Robinson


问:
Why catalina.home_IS_UNDEFINED directory is generated by Logback in the same project directory?
I have written logback configuration file for my application, but when I was doing maven clean install(mvn clean install), it generated a catalina.home_IS_UNDEFINED directory with log file in the project directory.
Why this directory generated ?

I don't want it to be in my project directory.

Any help to address this issue ?

Here is the configuration file.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date{HH:mm:ss.SSS} %-5p [%t] %c{1} - %m%n</pattern>
        </encoder>
    </appender>

    <appender name="MY_APP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${catalina.home}/logs/myApplication.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${catalina.home}/logs/myApplication.%d{yyyy-MM-dd}.log</FileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%-5p  %date{HH:mm:ss.SSS} [%t] %c{1} - %m%n</pattern>
        </encoder>
        <append>true</append>
    </appender>

    <logger name="org.springframework" level="WARN"/>

    <root>
        <priority value="INFO"/>
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="MY_APP_LOG"/>
    </root>

</configuration>
</code>```

答:
I had a similar problem and determined that it was caused by my unit tests lacking a proper Tomcat environment.

My minimal solution was to add the following src/test/resources/logback.xml to my Maven project directory:

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="catalina.home" value="target" />
</configuration>
</code>```

Logs generated by the unit tests then ended up in the target directory rather than the top level directory of the project.

Body:
I have written logback configuration file for my application, but when I was doing maven clean install(mvn clean install), it generated a catalina.home_IS_UNDEFINED directory with log file in the project directory.
Why this directory generated ?

I don't want it to be in my project directory.

Any help to address this issue ?

Here is the configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date{HH:mm:ss.SSS} %-5p [%t] %c{1} - %m%n</pattern>
        </encoder>
    </appender>

    <appender name="MY_APP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${catalina.home}/logs/myApplication.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${catalina.home}/logs/myApplication.%d{yyyy-MM-dd}.log</FileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>%-5p  %date{HH:mm:ss.SSS} [%t] %c{1} - %m%n</pattern>
        </encoder>
        <append>true</append>
    </appender>

    <logger name="org.springframework" level="WARN"/>

    <root>
        <priority value="INFO"/>
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="MY_APP_LOG"/>
    </root>

</configuration>

Body:
I had a similar problem and determined that it was caused by my unit tests lacking a proper Tomcat environment.

My minimal solution was to add the following src/test/resources/logback.xml to my Maven project directory:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property name="catalina.home" value="target" />
</configuration>

Logs generated by the unit tests then ended up in the target directory rather than the top level directory of the project.


问:
How to multiply each number in array by 2 in ruby
I have an array with characters, numbers and float values.

```<code> a[] = {'a',2,2.5}
</code>```

I have to multiply each integer and float by 2 and no operation should be done on character.

My solution -

```<code>def self.double_numbers(input)
        input.map do |input_element|
            if input_element.is_a? Integer
                input_element.to_i * 2
            elsif input_element.is_a? Float
                input_element.to_Float * 2
            end
        end
    end
</code>```

It is not working, for input

```<code>   a[] = {'a',2,2.5}
</code>```

It is returning

0 4 4

答:
I have to multiply each integer and float by 2 and no operation should
  be done on character.

here you go:

```<code>> a = ["a", 2, 2.5]
> a.map{|e| e.is_a?(Numeric) ? e * 2 : e}
#=> ["a", 4, 5.0]
</code>```

Note:  a[] = {'a',2,2.5} not a correct syntax for array.

Body:
I have an array with characters, numbers and float values.

 a[] = {'a',2,2.5}

I have to multiply each integer and float by 2 and no operation should be done on character.

My solution -

def self.double_numbers(input)
        input.map do |input_element|
            if input_element.is_a? Integer
                input_element.to_i * 2
            elsif input_element.is_a? Float
                input_element.to_Float * 2
            end
        end
    end

It is not working, for input

   a[] = {'a',2,2.5}

It is returning

0 4 4

Body:
I have to multiply each integer and float by 2 and no operation should
  be done on character.

here you go:

> a = ["a", 2, 2.5]
> a.map{|e| e.is_a?(Numeric) ? e * 2 : e}
#=> ["a", 4, 5.0]

Note:  a[] = {'a',2,2.5} not a correct syntax for array.


问:
Unable to get date xAxis working with unix timestamp
I am having some trouble understanding the Anychart axis documentation.

Using this example https://jsfiddle.net/gvb29tc2/2/ i have some data points i want to plot using the unix date stamp for x-axis.

```<code>[
1497786600,                                       // <- ID
'Sun Jun 18 2017 19:53:35 GMT+0800 (SGT)',        // <- date
1497786815630,                                    // <- unix date
...
]
</code>```

I select it using x: new Date([2]), but i cant get it to display. Just outputs a single vertical line. Also, i wanted the major tick on 5min and minor on 2min. Can't get that working either.

Since all i am trying is a simple line chart, i think i'm missing something stupid. Can someone explain where i'm going wrong please ?

答:
You shouldn't use any functions in mapping settings.
Right way is

```<code>x:[2]
</code>```

After that you can work with mapped value as timestamp
https://jsfiddle.net/gvb29tc2/4/

Body:
I am having some trouble understanding the Anychart axis documentation.

Using this example https://jsfiddle.net/gvb29tc2/2/ i have some data points i want to plot using the unix date stamp for x-axis.

[
1497786600,                                       // <- ID
'Sun Jun 18 2017 19:53:35 GMT+0800 (SGT)',        // <- date
1497786815630,                                    // <- unix date
...
]

I select it using x: new Date([2]), but i cant get it to display. Just outputs a single vertical line. Also, i wanted the major tick on 5min and minor on 2min. Can't get that working either.

Since all i am trying is a simple line chart, i think i'm missing something stupid. Can someone explain where i'm going wrong please ?

Body:
You shouldn't use any functions in mapping settings.
Right way is

x:[2]

After that you can work with mapped value as timestamp
https://jsfiddle.net/gvb29tc2/4/


问:
Protractor config file to use both jasmine and cucumber specs
I have end to end tests written using jasmine and behavioural driven tests written using chai and cucumber. I have two configurations file to run these tests. How can I make use of single protractor config file to run specs of jasmine and cucumber ?</p>

```<code>//cucumber.conf.js
exports.config = {
  framework: 'custom',
  frameworkPath: require.resolve('protractor-cucumber-framework'),
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['test/e2e/cucumber/*.feature'],
  capabilities: {
    'browserName': 'firefox',

},
baseUrl: '',

  cucumberOpts: {
    require: ['test/e2e/cucumber/*.steps.js'],
    tags: [],
    strict: true,
    format: ["pretty"],
    dryRun: false,
    compiler: []
  }

  //e2e.conf.js
  exports.config = {
      framework: 'jasmine2',
    seleniumAddress: 'http://localhost:4444/wd/hub',

      specs: ['test/e2e/e2e-spec.js'],
      capabilities: {
        'browserName': 'firefox',
    },
    baseUrl: '',
      jasmineNodeOpts: {
       showColors: true,
     }
</code>```

答:
In a basic setup you can't because you need to provide for example the framework and you can't have 2 frameworks in 1 default configuration file.

What you can do is use a command line argument and a cli tool like yargs and do something like this. If you run protractor through for example a npm script you can do something like this

npm run e2e -- --bdd

// the commmand line tool
const argv = require('yargs').argv;

// place you default config here, that should hold all the configs that are used with
// Jsasmine and CucumberJS
const config = {
  baseUrl: '',
  capabilities: {
    'browserName': 'firefox',

  },
  seleniumAddress: 'http://localhost:4444/wd/hub'
};

// If you pass --bdd to your commandline it will use cucumberjs, default is jasmine 2
if (argv.bdd) {
  config.framework = 'custom';
  config.frameworkPath = require.resolve('protractor-cucumber-framework');
  config.specs = ['test/e2e/cucumber/*.feature'];
  config.cucumberOpts = {
    require: ['test/e2e/cucumber/*.steps.js'],
    tags: [],
    strict: true,
    format: ["pretty"],
    dryRun: false,
    compiler: []
  };
} else {
  config.framework = 'jasmine2';
  config.specs = ['test/e2e/e2e-spec.js'];
  config.jasmineNodeOpts = {
    showColors: true,
  };
}

exports.config = config;```

Body:
I have end to end tests written using jasmine and behavioural driven tests written using chai and cucumber. I have two configurations file to run these tests. How can I make use of single protractor config file to run specs of jasmine and cucumber ?

//cucumber.conf.js
exports.config = {
  framework: 'custom',
  frameworkPath: require.resolve('protractor-cucumber-framework'),
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['test/e2e/cucumber/*.feature'],
  capabilities: {
    'browserName': 'firefox',

},
baseUrl: '',

  cucumberOpts: {
    require: ['test/e2e/cucumber/*.steps.js'],
    tags: [],
    strict: true,
    format: ["pretty"],
    dryRun: false,
    compiler: []
  }

  //e2e.conf.js
  exports.config = {
      framework: 'jasmine2',
    seleniumAddress: 'http://localhost:4444/wd/hub',

      specs: ['test/e2e/e2e-spec.js'],
      capabilities: {
        'browserName': 'firefox',
    },
    baseUrl: '',
      jasmineNodeOpts: {
       showColors: true,
     }


问:
mysqli_affected_rows() when update
I have a trouble in this code, can anybody help?:(
There's my code:</p>

```<code>$query = "UPDATE subjects SET
              menu_name = '{$menu_name}',
              position = {$position},
              visible = {$visible}
              WHERE id = {$id}";
    $result = mysqli_query($connection, $query);
    if (mysqli_affected_rows() == 1) {
      $message = "The subject was successfully updated.";
    } else {
      $message = "The subject update failed.";
      $message .= "<br>" . mysqli_error();
    }

  } else {
    $message = "There were " . count($errors) . " errors in the form.";
  }
</code>```

答:
```<code>if (mysqli_affected_rows( **$result** == 1)
</code>```

Use $result variable in the bracket.

Title: mysqli_affected_rows() when update

Body:
I have a trouble in this code, can anybody help?:(
There's my code:

$query = "UPDATE subjects SET
              menu_name = '{$menu_name}',
              position = {$position},
              visible = {$visible}
              WHERE id = {$id}";
    $result = mysqli_query($connection, $query);
    if (mysqli_affected_rows() == 1) {
      $message = "The subject was successfully updated.";
    } else {
      $message = "The subject update failed.";
      $message .= "
" . mysqli_error();
    }

  } else {
    $message = "There were " . count($errors) . " errors in the form.";
  }

Body:
if (mysqli_affected_rows( **$result** == 1)

Use $result variable in the bracket.


问:
how to make a server listen to a path in nodejs
Can anyone help me figure out how to make a server in nodejs to listen to a specific path in localhost? If I replace the following path by 'port: 3000' then the localhost:3000 works properly but I just cannot find out how to carry out with path.</p>

```<code>var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen({path:__dirname + '/example.html'});
app.get('/',function(req, res){
res.sendFile(__dirname + '/example.html');
});
</code>```

答:
To do this you can try:

```<code>    var express = require('express');
    var app = express();
    app.listen('/tmp/sock');
</code>```

See http://expressjs.com/en/api.html#app.listen for more details

Body:
Can anyone help me figure out how to make a server in nodejs to listen to a specific path in localhost? If I replace the following path by 'port: 3000' then the localhost:3000 works properly but I just cannot find out how to carry out with path.

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen({path:__dirname + '/example.html'});
app.get('/',function(req, res){
res.sendFile(__dirname + '/example.html');
});

Body:
To do this you can try:

    var express = require('express');
    var app = express();
    app.listen('/tmp/sock');

See http://expressjs.com/en/api.html#app.listen for more details


问:
Unprovision type in Service Fabric
In order to uninstall an application in Service Fabric, I need a workflow similar to the one in the Explorer: Delete Application and then Unprovision Type.

While FabricClient's ApplicationManager has a DeleteApplicationAsync method, there doesn't seem to be any way to Unprovision or Unregister for the type.

The Azure docs on github mention a cmdlet called Unregister-ServiceFabricApplicationType, however the links in that doc are all broken.

Is it possible to unprovision the type via FabricClient?

答: You can use the UnprovisionApplicationAsync method to unprovision the application type.  Deploy and remove applications using FabricClient has an example.</p>

Title: Unprovision type in Service Fabric


问:
legend not showing properly in d3
Can any of you let me know why the legend is not showing properly in my code. I paste the link of the blocks here: https://bl.ocks.org/abrahamdu/2038544bffad6b5b25760b42ef519a7e</p>

答:
The problem is the x position for both rectangles and texts:

```<code>legend.append("text")
    .attr("x", width + 10)
    //etc...

legend.append("rect")
    .attr("x", width - 10)
    //etc...
</code>```

You may think that it puts them next to the right border of the SVG, but it doesn't: the parent <g> element is being translated to width/2. Thus, those legends are way outside the SVG limits.

Solution: Don't translate those <g> elements...

```<code>.attr("transform", function(d,i){ return "translate(0," + i * 30 + ")";});
//look at the zero here ----------------------------^
</code>```

... and use radius to set the rectangles and texts positions:

```<code>legend.append("text")
    .attr("x", radius + 30)
</code>```

Here is the demo:

var margin = {
  top: 30,
  right: 30,
  bottom: 50,
  left: 30
};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var radius = Math.min(width, height) / 2;

var color = d3.scaleOrdinal(["#0095D9", "#9C9536", "#F5E837"]);

var data = [{
  "type": "Sky",
  "pop": 0.75
}, {
  "type": "Shady side of pyramid",
  "pop": 0.07
}, {
  "type": "Sunny side of pyramid",
  "pop": 0.18
}];

var g = d3.select("svg")
  .append("g")
  .attr("transform", "translate(" + width / 1.8 + "," + height / 1.6 + ")");

var pie = d3.pie().sort(null)
  .value(function(d) {
    return d.pop;
  })(data);

var arc = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(0)
  .startAngle(function(d) {
    return d.startAngle + Math.PI * 1.2;
  })
  .endAngle(function(d) {
    return d.endAngle + Math.PI * 1.2;
  });;

var label = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(radius - 10);

var pyramid = g.selectAll(".arc")
  .data(pie)
  .enter()
  .append("g")
  .attr("class", "arc");

pyramid.append("path")
  .attr("d", arc)
  .style("fill", function(d) {
    return color(d.data.type);
  });

var legend = pyramid.append("g")
  .attr("class", "legend")
  .attr("font-family", "sans-serif")
  .attr("font-size", 20)
  .attr("text-anchor", "start")
  .selectAll("g")
  .data(pie)
  .enter().append("g")
  .attr("transform", function(d, i) {
    return "translate(0," + i * 30 + ")";
  });

legend.append("text")
  .attr("x", radius + 30)
  .attr("y", 9.5)
  .attr("dy", "0.32em")
  .text(function(d) {
    return d.data.type;
  });

legend.append("rect")
  .attr("x", radius + 10)
  .attr("width", 19)
  .attr("height", 19)
  .attr("fill", function(d) {
    return color(d.data.type);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: lightgrey;
}</code>```

<svg width="960" height="500"></svg>```

Title: legend not showing properly in d3

Body:
The problem is the x position for both rectangles and texts:

legend.append("text")
    .attr("x", width + 10)
    //etc...

legend.append("rect")
    .attr("x", width - 10)
    //etc...

You may think that it puts them next to the right border of the SVG, but it doesn't: the parent <g> element is being translated to width/2. Thus, those legends are way outside the SVG limits.

Solution: Don't translate those <g> elements...

.attr("transform", function(d,i){ return "translate(0," + i * 30 + ")";});
//look at the zero here ----------------------------^

... and use radius to set the rectangles and texts positions:

legend.append("text")
    .attr("x", radius + 30)

Here is the demo:

var margin = {
  top: 30,
  right: 30,
  bottom: 50,
  left: 30
};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var radius = Math.min(width, height) / 2;

var color = d3.scaleOrdinal(["#0095D9", "#9C9536", "#F5E837"]);

var data = [{
  "type": "Sky",
  "pop": 0.75
}, {
  "type": "Shady side of pyramid",
  "pop": 0.07
}, {
  "type": "Sunny side of pyramid",
  "pop": 0.18
}];

var g = d3.select("svg")
  .append("g")
  .attr("transform", "translate(" + width / 1.8 + "," + height / 1.6 + ")");

var pie = d3.pie().sort(null)
  .value(function(d) {
    return d.pop;
  })(data);

var arc = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(0)
  .startAngle(function(d) {
    return d.startAngle + Math.PI * 1.2;
  })
  .endAngle(function(d) {
    return d.endAngle + Math.PI * 1.2;
  });;

var label = d3.arc()
  .outerRadius(radius - 10)
  .innerRadius(radius - 10);

var pyramid = g.selectAll(".arc")
  .data(pie)
  .enter()
  .append("g")
  .attr("class", "arc");

pyramid.append("path")
  .attr("d", arc)
  .style("fill", function(d) {
    return color(d.data.type);
  });

var legend = pyramid.append("g")
  .attr("class", "legend")
  .attr("font-family", "sans-serif")
  .attr("font-size", 20)
  .attr("text-anchor", "start")
  .selectAll("g")
  .data(pie)
  .enter().append("g")
  .attr("transform", function(d, i) {
    return "translate(0," + i * 30 + ")";
  });

legend.append("text")
  .attr("x", radius + 30)
  .attr("y", 9.5)
  .attr("dy", "0.32em")
  .text(function(d) {
    return d.data.type;
  });

legend.append("rect")
  .attr("x", radius + 10)
  .attr("width", 19)
  .attr("height", 19)
  .attr("fill", function(d) {
    return color(d.data.type);
  });

body {
  background-color: lightgrey;
}

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


问:
Kotlin: For-loop range must have an 'iterator()' method
If I use var charSet = 1..10 it works, but when I am using the below code, I'm getting this error.

```<code>var charSet = "A".."Z"
for (value in charSet) {
  println("$value")
}
</code>```

For-loop range must have an 'iterator()' method.

Please let me know how to resolve this.

答:
Its giving current output.Change your double quotes into single quotes      </p>

```<code>    var charSet = 'A'..'Z'
    for (value in charSet) {
        println("$value")
    }
</code>```

Body:
If I use var charSet = 1..10 it works, but when I am using the below code, I'm getting this error.

var charSet = "A".."Z"
for (value in charSet) {
  println("$value")
}

For-loop range must have an 'iterator()' method.

Please let me know how to resolve this.

Body:
Its giving current output.Change your double quotes into single quotes

    var charSet = 'A'..'Z'
    for (value in charSet) {
        println("$value")
    }


问:
Java Self Contained Packaging skipping most types
I'm trying to figure out how to use javapackager to create a self-contained Java application

Here's the output I'm seeing:

```<code>javapackager -deploy -native -outdir packages -outfile Game -srcdir src -srcfiles Game.jar -appclass Main -name "Game" -title "Game demo"
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Bundler Windows Application Image skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.
Bundler EXE Installer skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.
Bundler MSI Installer skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.
</code>```

I don't understand why it is suggesting that I use a fx:jar task for creating my jar. How do I need to create the jar using plain command line in order to get this working? I'm following example 7-2 from the documentation here: https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/self-contained-packaging.html

I'm able to compile, build the jar, and run the jar just fine.

答:
I was finally able to get this working. It can be a little finicky. I made a bare minimum demo project to create a self-contained distribution of a LWJGL application, which you can reference here: https://gitlab.com/charles-mulic/lwjgl-self-contained-app

Successfully tested both the resulting .exe and .exe installer. Should work for other platforms too, just need to adapt the batch script contents.

Here's a Gradle version that is a little cleaner: https://gitlab.com/charles-mulic/lwjgl-self-contained-app-gradle

Body:
I'm trying to figure out how to use javapackager to create a self-contained Java application

Here's the output I'm seeing:

javapackager -deploy -native -outdir packages -outfile Game -srcdir src -srcfiles Game.jar -appclass Main -name "Game" -title "Game demo"
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Bundler Windows Application Image skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.
Bundler EXE Installer skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.
Bundler MSI Installer skipped because of a configuration problem: Main application jar is missing.
Advice to fix: Make sure to use fx:jar task to create main application jar.

I don't understand why it is suggesting that I use a fx:jar task for creating my jar. How do I need to create the jar using plain command line in order to get this working? I'm following example 7-2 from the documentation here: https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/self-contained-packaging.html

I'm able to compile, build the jar, and run the jar just fine.


问:
Why does foreachPartition error out for streaming datasets?
I am migrating from Spark Streaming to Structured Streaming and I am facing issue with the following code:

def processDataSet(inputDataset: Dataset[MyMessage], foobar: FooBar) = {
    inputDataset.foreachPartition { partitionIterator =>
      val filteredIterator = partitionIterator.filter(foobar.filter)
      ...
      ...
    }
}
val streamingQuery = inputDataset
  .writeStream
  .trigger(ProcessingTime("5 seconds"))
  .outputMode("append")
  .format("console")
  .start
```

It errors out with the following AnalysisException:

Caused by: org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;

Is foreachPartition not supported on streaming queries? Is writeStream.foreach the only way to implement foreachPartition in this case?

I'd like to avoid sending each event as it comes, but rather accumulate all rows, form one giant POST request body and send it to a HTTP endpoint. So if 1000 events in a batch and 5 partitions, generate 5 requests in parallel with 200 events in each request body.

答:
TL;DR Yes. foreachPartition action is not supported and you should use ForeachWriter instead.

Quoting the scaladoc of foreachPartition:

foreachPartition(f: (Iterator[T]) ⇒ Unit): Unit Applies a function f to each partition of this Dataset.

As you may have found out by now, foreach is an action and therefore triggers Spark execution.

Since you work with streaming Datasets, triggering their execution is not allowed using "traditional" methods like foreach.

Quoting Structured Streaming's Unsupported Operations:

In addition, there are some Dataset methods that will not work on streaming Datasets. They are actions that will immediately run queries and return results, which does not make sense on a streaming Dataset. Rather, those functionalities can be done by explicitly starting a streaming query (see the next section regarding that).

Among the streaming alternatives is foreach operator (aka sink). That's how to do foreachPartition in Structured Streaming.

Quoting Using Foreach:

The foreach operation allows arbitrary operations to be computed on the output data.

To use this, you will have to implement the interface ForeachWriter, which has methods that get called whenever there is a sequence of rows generated as output after a trigger.

I'd like to avoid sending each event as it comes, but rather accumulate all rows, form one giant POST request body and send it to a HTTP endpoint. So if 1000 events in a batch and 5 partitions, generate 5 requests in parallel with 200 events in each request body.

That seems like an aggregation before writing the Dataset to a sink, doesn't it? Use groupBy operator and collect_list function to group rows so when you writeStream you'll have as many groups as you want.

I'd rather avoid dealing with this low-level feature of RDD called partitions as a way to optimize writes unless there is no other way.

Body:
I am migrating from Spark Streaming to Structured Streaming and I am facing issue with the following code:

def processDataSet(inputDataset: Dataset[MyMessage], foobar: FooBar) = {
    inputDataset.foreachPartition { partitionIterator =>
      val filteredIterator = partitionIterator.filter(foobar.filter)
      ...
      ...
    }
}
val streamingQuery = inputDataset
  .writeStream
  .trigger(ProcessingTime("5 seconds"))
  .outputMode("append")
  .format("console")
  .start

It errors out with the following AnalysisException:

Caused by: org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();;

Is foreachPartition not supported on streaming queries? Is writeStream.foreach the only way to implement foreachPartition in this case?

I'd like to avoid sending each event as it comes, but rather accumulate all rows, form one giant POST request body and send it to a HTTP endpoint. So if 1000 events in a batch and 5 partitions, generate 5 requests in parallel with 200 events in each request body.


问:
Pulling Docker Image from Docker Hub : NOt Found
I am using docker in windows 10.
MY docker is working properly but when i try to pull Image from docker hub via cmd:

C:\Users\pca90>docker pull hello-world Using default tag: latest Error
response from daemon: Get https://registry-1.docker.io/v2/: Not Found

答:
Just issue these commands in a terminal or command window

```<code>docker-machine restart default # Restart the environment

eval $(docker-machine env default) # Refresh your environment settings
</code>```

after running above it will work

If not then please update your question with the output from issuing

```<code>docker info
</code>```

Body:
Just issue these commands in a terminal or command window

docker-machine restart default # Restart the environment

eval $(docker-machine env default) # Refresh your environment settings

after running above it will work

If not then please update your question with the output from issuing

docker info


问:
Android Studio Can't Connect Firebase Assistant
I am trying to connect to Firebase from Android Studio Assistance but getting following error despite having internet connection.

Firebase
A config file "G:\ANDROID\GoFishing\app\google-services.json" was found, but it indicates a project ID "gofishing-149406" that you don't appear to have access to. Request access or delete the file in order to proceed with the connection process.

答:
just Delete that config and go again to firebase console and download a new file and make sure that you have given the access to the project if done problem solved if not make sure that you are not usinfg the the package which was already integrated and restricted access for another apps if so create a a new package and do the same process
if it wont help
just delete that file (config) and go to assistant and click on connect to fire base and give all the credentials and give the new name to package and go with it every thing runs properly </p>

<p>hope it will hep you for sure  </p>

Body:
just Delete that config and go again to firebase console and download a new file and make sure that you have given the access to the project if done problem solved if not make sure that you are not usinfg the the package which was already integrated and restricted access for another apps if so create a a new package and do the same process
if it wont help
just delete that file (config) and go to assistant and click on connect to fire base and give all the credentials and give the new name to package and go with it every thing runs properly

hope it will hep you for sure


问:
Rails - Given a block of text, auto-link links
on mysite I have the ability to add comments. Sometimes users enter comments will links (href. ...)

I would like to have those links to be clickable/linkable (a href) when the comment is displayed to users.

how with Rails 3 can I take a comment, and look for links and then wrap those links in an a href tag that opens in a new window?

Thanks

答:
The simplest way is to use the auto_link method built into rails.

Note: In Rails 3.1 auto_link has been moved into a separate gem.


问:
Sample groups and preserve row order
I have a dataframe such as:

```<code>df <- data.frame(id = factor(c(12321,12321,12321,4445,4445,4445,4445,787,787,787)),
                 word = c("please", "stop", "that", "the", "fox", "jumps", "that", "please", "eat", "noodles"),
                 word_id = c(12,5,28,99,214,800,28,12,78,912))
</code>```

And I am attempting to take a sample of the data frame while preserving the id group and the word and word_id order.

I tried newDF <- df %>% group_by(id) %>% sample_frac(0.33) but this takes a sample of each group.

I would like to result in a dataframe that takes a sample of all id groups in the original dataframe and preserves the order of the columns. So if I want to take a 33% sample of df I will end up with 33% of the id groups and the columns remain in order.

```<code>newDF <- data.frame(id = factor(c(12321,12321,12321,4445,4445,4445,4445)),
                    word = c("please", "stop", "that", "the", "fox", "jumps", "that"),
                    word_id = c(12,5,28,99,214,800,28))
</code>```

答:
Adding to alistaire's comment:</p>

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

newDF1 <- df %>%
  group_by(id) %>%
  nest() %>%
  sample_frac(1/3) %>%
  unnest()

newDF2 <- anti_join(df, newDF1, by = "id")
</code>```

Title: Sample groups and preserve row order

Body:
I have a dataframe such as:

df <- data.frame(id = factor(c(12321,12321,12321,4445,4445,4445,4445,787,787,787)),
                 word = c("please", "stop", "that", "the", "fox", "jumps", "that", "please", "eat", "noodles"),
                 word_id = c(12,5,28,99,214,800,28,12,78,912))

And I am attempting to take a sample of the data frame while preserving the id group and the word and word_id order.

I tried newDF <- df %>% group_by(id) %>% sample_frac(0.33) but this takes a sample of each group.

I would like to result in a dataframe that takes a sample of all id groups in the original dataframe and preserves the order of the columns. So if I want to take a 33% sample of df I will end up with 33% of the id groups and the columns remain in order.

newDF <- data.frame(id = factor(c(12321,12321,12321,4445,4445,4445,4445)),
                    word = c("please", "stop", "that", "the", "fox", "jumps", "that"),
                    word_id = c(12,5,28,99,214,800,28))

Body:
Adding to alistaire's comment:

library(dplyr)
library(tidyr)

newDF1 <- df %>%
  group_by(id) %>%
  nest() %>%
  sample_frac(1/3) %>%
  unnest()

newDF2 <- anti_join(df, newDF1, by = "id")