问:
how to get each data from a parseJSON array
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

```<code><html>
<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
  <script type="text/javascript">
    var BASE_URL = "<?php echo base_url(); ?>";
    </script>
 <script type="text/javascript">
  // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(drawChart);

function drawChart() {

     $.ajax({

   type: 'POST',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "json",

    success: function (data1) {
    // Create our data table out of JSON data loaded from server.
    var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('string', 'solid');
  var jsonData = $.parseJSON(data1);

  for (var i = 0; i < jsonData.length; i++) {
        data.addRows([jsonData[i].timeline, jsonData[i].solid_t1]);
  }
  var options = {

    title: 'Solid chart',
    width: 900,
    height: 500,

  };

  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
   }
});
}
  </script>
</head>
<body>

  <div id="line_chart"></div>
</body>
</html>
</code>```

Here under is the function getdata in my controller:

```<code>    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}
</code>```

I tried to output the json_encode data, and I am able to get the result below:

```<code>[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]
</code>```

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

```<code>function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}
</code>```

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

```<code>$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});
</code>```

答:
This

```<code>dataType: "json",
</code>```

ensures that you are expecting json as response (documentation here), so you don't need to do

```<code>var jsonData = $.parseJSON(data1);
</code>```

data1 is already a javascript object

Body:
I am trying to draw a linechart by using Google chart API, and I am use PHP codeignitor to retrieve data from mySQL database.

So far, I am able to retrieve the data, but I just couldn't parse the Json data, and fill them into linechart. below is the view I am actually loaded.

Here under is the function getdata in my controller:

    function getdata(){
  $this->load->model('Chart');
  $this->load->helper('url');
    $data  = $this->Chart->getdata_solid();
    print_r(json_encode($data, true));
}

I tried to output the json_encode data, and I am able to get the result below:

[{"timeline":"430","solid_t1":"12"},{"timeline":"030","solid_t1":"8.1"},{"timeline":"830","solid_t1":"32"},{"timeline":"1230","solid_t1":"10"},{"timeline":"1630","solid_t1":"100"},{"timeline":"2030","solid_t1":"8"}]

Can someone help me on this, thanks.

Update

Hi Guys, I put the function in my model here, maybe because my query result is array, not a object?

function getdata_solid(){
  $this->db->select('timeline');
  $this->db->select('solid_t1');
  $this->db->from("varnish_mvs");
  $this->db->where('date_selected', '2017-03-25');
  //$this->db->where('timeline', $timeline);
  $query = $this->db->get();
  return $query->result_array();

}

Final Update: I finally solved this issue by changing the way of loading google chart functions. here under are my final working codes. I hope it may help for someone who has the same issue.

$(document).ready(function() {

     $.ajax({

   type: 'POST',
    //url: 'http://localhost/charts/charts/getdata',
    url: BASE_URL+'index.php/Chart_varnish/getdata',
    dataType: "JSON",
    success: function (data1) {

     // alert(data1);
       // Load the Visualization API and the line package.
  google.charts.load('current', {'packages':['corechart']});
  // Set a callback to run when the Google Visualization API is loaded.
  google.charts.setOnLoadCallback(function(){
    drawChart(data1);
  });

   }
});

     function drawChart(data1) {

        var data = new google.visualization.DataTable();
  data.addColumn('string', 'timeline');
  data.addColumn('number', 'solid_t1');
  var dataArray = [];
  /*$.each(data1, function(i, obj){
    dataArray.push([obj.timeline, parseInt(obj.solid_t1)]);
  });*/
  var jsonData = $.parseJSON(data1);
   for (var i = 0; i < jsonData.length; i++) {
        dataArray.push([jsonData[i].timeline, parseInt(jsonData[i].solid_t1)]);
      }
  //dataArray.push([jsonData[0].timeline, parseInt(jsonData[0].solid_t1)], [jsonData[1].timeline, parseInt(jsonData[1].solid_t1)])
  //dataArray.push(['2', 3], ['6', 5]);
  alert(dataArray);
  data.addRows(dataArray);
  var options = {
    title:'Solid chart',
    width: 900,
    height: 500,
  };
  var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
  chart.draw(data, options);
     }

});

Body:
This

dataType: "json",

ensures that you are expecting json as response (documentation here), so you don't need to do

var jsonData = $.parseJSON(data1);

data1 is already a javascript object


来源: stackexchange

问:
javascript merge regular expression
When /^\.\/(?!main(\.js)?$)/ means require all src files except ./main.js,
/^\.\/(?!style.*)/ means require all src files except ./style/*

Then I use /^\.\/(?!main(\.js)?$) | ^\.\/(?!style.*)/ want to require all src files except ./main.js and ./style/* but not work

Thank you for your help.

答:
You do not need to repeat consuming patterns, just put the conditions inside the negative lookahead:

```<code>/^\.\/(?!style|main(\.js)?$)/
       ^^^^^^^^^^^^^^^^^^
</code>```

See the regex demo.

Details:

^ - start of string

\.\/ - a ./ substring

(?!style|main(\.js)?$) - a negative lookahead failing the match if immediately to the right of the current location, there is:

style - a literal style substring

main(\.js)?$ - main or main.js substrings at the end of the string ($)

However, you note that style should be followed with / in the requirement, but your regex does not have that check. You may append (\/|$) after style to enforce that check (a / or end of string should appear right after style):

```<code>/^\.\/(?!style(\/|$)|main(\.js)?$)/
</code>```

With this regex, ./style-main.js will be matched.

ContentLicense: CC BY-SA 3.0

Title: javascript merge regular expression

Body:
You do not need to repeat consuming patterns, just put the conditions inside the negative lookahead:

/^\.\/(?!style|main(\.js)?$)/
       ^^^^^^^^^^^^^^^^^^

See the regex demo.

Details:

^ - start of string

\.\/ - a ./ substring

(?!style|main(\.js)?$) - a negative lookahead failing the match if immediately to the right of the current location, there is:

style - a literal style substring

main(\.js)?$ - main or main.js substrings at the end of the string ($)

However, you note that style should be followed with / in the requirement, but your regex does not have that check. You may append (\/|$) after style to enforce that check (a / or end of string should appear right after style):

/^\.\/(?!style(\/|$)|main(\.js)?$)/

With this regex, ./style-main.js will be matched.


问:
PHP converting hours and minutes into a decimal
I am calculating hours and minutes into variables but i would like to convert this into a decimal number

For example, 1 hour 30 minutes should display as 1.5 and 2 hours 15 minutes would display as 2.25

答:
Something like this?</p>

```<code>function convert($hours, $minutes) {
    return $hours + round($minutes / 60, 2);
}
</code>```

Body:
Something like this?

function convert($hours, $minutes) {
    return $hours + round($minutes / 60, 2);
}


答:
```<code>$hrs = "2:15:0";
$decimalHours = decimal($hrs);

function decimal($time)
{
    $hms = explode(":", $time);
    return ($hms[0] + ($hms[1]/60) + ($hms[2]/3600));
}

echo $decimalHours;
</code>```

Try this code

Title: PHP converting hours and minutes into a decimal

Body:
I am calculating hours and minutes into variables but i would like to convert this into a decimal number

For example, 1 hour 30 minutes should display as 1.5 and 2 hours 15 minutes would display as 2.25

Body:
$hrs = "2:15:0";
$decimalHours = decimal($hrs);

function decimal($time)
{
    $hms = explode(":", $time);
    return ($hms[0] + ($hms[1]/60) + ($hms[2]/3600));
}

echo $decimalHours;

Try this code


问:
How to get previous and next month clickListener in MaterialCalanderView
I am using materialcalanderview to display calander. On click of previous and next month buttons (Swipe buttons) I have to do some operations. How can I get the clicklistener for these swipe buttons</p>

答:
Got the solution.
MonthChangeListener you can use. Putting a code snippet below</p>

```<code>calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
        @Override
        public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
            Toast.makeText(getContext(),"Month Changed",Toast.LENGTH_LONG).show();
        }
    });
</code>```

Body:
Got the solution.
MonthChangeListener you can use. Putting a code snippet below

calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
        @Override
        public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
            Toast.makeText(getContext(),"Month Changed",Toast.LENGTH_LONG).show();
        }
    });


问:
Is it possible to read results of the XmlSerializer being sent by HTTPClient?
I am using an extension method to post xml using the HTTPClient which works great.

My question: Is it possible to read, log, or display the results of the XmlSerializer data that is being sent/posted ?

```<code>    public static class HttpExtensions  {
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(requestUri
                                , value
                                , new XmlMediaTypeFormatter { UseXmlSerializer = true }
                                );
    }
}
</code>```

答:
PostAsync hides the actually sent HttpRequestMessage from you, though you can retrieve it from the response, too so you can trace both the request and response contents:

```<code>var response = await client.PostAsync(uri, value, formatter);
Log(response);
</code>```

If you really want to log the request only, create the request manually:

```<code>var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StreamContent(myXmlStream);
Log(request);
var response = await client.SendAsync(request);
Log(response);
</code>```

And now you can create one or two Log overloads. I show it for the response, which includes both the request and response log. This is independent from the format, works for both XML and json content.

```<code>protected virtual void Log(HttpResponseMessage response)
{
    // Use any log/trace engine here, this example uses Debug
    Debug.WriteLine($"Response of the API Call [{response.RequestMessage.Method}] {response.RequestMessage.RequestUri}: {response.StatusCode} {FormatResponse(response)}");
}

private static string FormatResponse(HttpResponseMessage response)
{
    var result = new StringBuilder();
    result.AppendLine();
    result.AppendLine("Original request:");
    result.AppendLine(FormatHttpMessage(response.RequestMessage.Headers, response.RequestMessage.Content));
    result.AppendLine();
    result.AppendLine("Obtained response:");
    result.AppendLine(FormatHttpMessage(response.Headers, response.Content));
}

private static string FormatHttpMessage(HttpHeaders headers, HttpContent content)
{
    var result = new StringBuilder();
    var headersString = headers.ToString();
    if (!string.IsNullOrWhiteSpace(headersString))
    {
        result.AppendLine("Headers:");
        result.AppendLine(headersString);
        result.AppendLine();
    }

    if (content != null)
    {
        result.AppendLine("Content:");
        result.AppendLine(content.ReadAsStringAsync().Result);
    }

    return result.ToString();
}
</code>```

Body:
I am using an extension method to post xml using the HTTPClient which works great.

My question: Is it possible to read, log, or display the results of the XmlSerializer data that is being sent/posted ?

    public static class HttpExtensions  {
    public static Task<HttpResponseMessage> PostAsXmlWithSerializerAsync<T>(this HttpClient client, string requestUri, T value)
    {
        return client.PostAsync(requestUri
                                , value
                                , new XmlMediaTypeFormatter { UseXmlSerializer = true }
                                );
    }
}

Body:
PostAsync hides the actually sent HttpRequestMessage from you, though you can retrieve it from the response, too so you can trace both the request and response contents:

var response = await client.PostAsync(uri, value, formatter);
Log(response);

If you really want to log the request only, create the request manually:

var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Content = new StreamContent(myXmlStream);
Log(request);
var response = await client.SendAsync(request);
Log(response);

And now you can create one or two Log overloads. I show it for the response, which includes both the request and response log. This is independent from the format, works for both XML and json content.

protected virtual void Log(HttpResponseMessage response)
{
    // Use any log/trace engine here, this example uses Debug
    Debug.WriteLine($"Response of the API Call [{response.RequestMessage.Method}] {response.RequestMessage.RequestUri}: {response.StatusCode} {FormatResponse(response)}");
}

private static string FormatResponse(HttpResponseMessage response)
{
    var result = new StringBuilder();
    result.AppendLine();
    result.AppendLine("Original request:");
    result.AppendLine(FormatHttpMessage(response.RequestMessage.Headers, response.RequestMessage.Content));
    result.AppendLine();
    result.AppendLine("Obtained response:");
    result.AppendLine(FormatHttpMessage(response.Headers, response.Content));
}

private static string FormatHttpMessage(HttpHeaders headers, HttpContent content)
{
    var result = new StringBuilder();
    var headersString = headers.ToString();
    if (!string.IsNullOrWhiteSpace(headersString))
    {
        result.AppendLine("Headers:");
        result.AppendLine(headersString);
        result.AppendLine();
    }

    if (content != null)
    {
        result.AppendLine("Content:");
        result.AppendLine(content.ReadAsStringAsync().Result);
    }

    return result.ToString();
}


问:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:
Sorry am getting this errors in my errors logs

```<code>PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in /home/payassur/public_html/admin/index.php:13
Stack trace:
#0 /home/payassur/public_html/admin/index.php(13): PDO->query('SELECT * FROM u...')
#1 {main}
  thrown in /home/payassur/public_html/admin/index.php on line 13
</code>```

below is line 13

```<code>  $query = $db->query("SELECT * FROM users WHERE id = $u_id");
</code>```

答:
You're query is open to SQL injection, people have figured this out and thus are trying to inject the database. That is why you having those errors in your error log. You should start using prepared statements to prevent SQL injections</p>

```<code>if (isset($u_id) && trim($u_id) != '') {
    $stmt = $db->prepare('SELECT * FROM users WHERE id = :u_id');
    $stmt->exectue(array('u_id' => $u_id,));
    $result = $stmt->fetchAll();
}else{
    $results = [];
}
</code>```

Body:
Sorry am getting this errors in my errors logs

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in /home/payassur/public_html/admin/index.php:13
Stack trace:
#0 /home/payassur/public_html/admin/index.php(13): PDO->query('SELECT * FROM u...')
#1 {main}
  thrown in /home/payassur/public_html/admin/index.php on line 13

below is line 13

  $query = $db->query("SELECT * FROM users WHERE id = $u_id");

Body:
You're query is open to SQL injection, people have figured this out and thus are trying to inject the database. That is why you having those errors in your error log. You should start using prepared statements to prevent SQL injections

if (isset($u_id) && trim($u_id) != '') {
    $stmt = $db->prepare('SELECT * FROM users WHERE id = :u_id');
    $stmt->exectue(array('u_id' => $u_id,));
    $result = $stmt->fetchAll();
}else{
    $results = [];
}


问:
Need to add fade in to image om slideshow
I need to add a fade in and fade out annimation to my image on existing code for slide show. The images must fade in /fade out when user click the buttons. Here is my code.

HTML:

```<code><div id="imageSlider">
</code>```

```<code>  <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button>

  <button id="nextBTN" onclick="next()"> <b>Next</b> </button>
</div>
</code>```

Javascript:

```<code>var images = [
  "HTMLcert.jpg",
  "CSScert.jpg",
  "javaScriptCert.jpg",
  "PHPcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  slider.src = images[num];
}
</code>```

how can I add fade in and out to existing java script code .

答:
You can add and remove a class to the active slider element in your javascript function like this:

```<code>var slider = document.getElementById("slider");
slider.className += " active";
setTimeout(function(){
  slider.classList.remove("active");
}, 100);
</code>```

And then your css will look something like this:

```<code>.active {
   animation: fade 1s;
}

@keyframes fade {
  from { opacity: 0; }
  to { opacity: 1 }
}
</code>```

Body:
I need to add a fade in and fade out annimation to my image on existing code for slide show. The images must fade in /fade out when user click the buttons. Here is my code.

HTML:

  <button id="prevBTN" onclick="prev()"> Prev </button>

  <button id="nextBTN" onclick="next()"> Next </button>

Javascript:

var images = [
  "HTMLcert.jpg",
  "CSScert.jpg",
  "javaScriptCert.jpg",
  "PHPcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  slider.src = images[num];
}

how can I add fade in and out to existing java script code .

Body:
You can add and remove a class to the active slider element in your javascript function like this:

var slider = document.getElementById("slider");
slider.className += " active";
setTimeout(function(){
  slider.classList.remove("active");
}, 100);

And then your css will look something like this:

.active {
   animation: fade 1s;
}

@keyframes fade {
  from { opacity: 0; }
  to { opacity: 1 }
}


问:
Converting a date to a (non human-readable) string in Swift 3
I have a Date object, like so:

```<code> 2017-06-08 08:36:16 +0000
</code>```

I need to convert this to a string, in this form:

```<code>"2017-06-08T08:36:16Z"
</code>```

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

答:
Following two formats will work for you.
yyyy-MM-dd HH:mm:ss Z
and yyyy-MM-dd'T'HH:mm:ss'Z'

```<code>let input = "2017-06-08 08:36:16 +0000"
let dateFormater = DateFormatter.init()
dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormater.date(from: input) {
    dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    let output = dateFormater.string(from: date)
    print(output)
}
</code>```

Body:
I have a Date object, like so:

 2017-06-08 08:36:16 +0000

I need to convert this to a string, in this form:

"2017-06-08T08:36:16Z"

The REST api I am posting to only accepts dates as strings.

Most info I find online is about converting dates to human readable formats. If possible, I could probably even just "stringify" my date object, however trying to cast it as such obviously fails. There are tons of "convert date to string" questions out there, but haven't ran across any like this yet.

Any idea how to do this?

Body:
Following two formats will work for you.
yyyy-MM-dd HH:mm:ss Z
and yyyy-MM-dd'T'HH:mm:ss'Z'

let input = "2017-06-08 08:36:16 +0000"
let dateFormater = DateFormatter.init()
dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
if let date = dateFormater.date(from: input) {
    dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
    let output = dateFormater.string(from: date)
    print(output)
}


问:
Excel Count down Issue?
I have this pivot table that produce this table,the first column is pending days which represent how long the part is requested till today the next one is part code and next to it I have Total amount of my Inventory. what I want to do is a formula that allocate a number to the fields if their total-amount is > 0.
here is where my problem lies:

if you pay attention to the red ones their total amount is 3 but we have four request from this part and I want for the last one instead of number 1 the formula insert #N/A so that I can Comment correctly.

like this:

appreciate any help in advance.

答:
You can use a COUNTIF function with a relevant and absolute reference to see whether the total amount of parts has already been reached. Try this:

```<code>=IF(COUNTIF($B$2:B2,B2)>C2,NA(),1)
</code>```

Broken down, this formula counts how many of the parts have already been requested and if this exceeds the total amount of parts it will return #N/A, otherwise it will return 1.

Title: Excel Count down Issue?

Body:
You can use a COUNTIF function with a relevant and absolute reference to see whether the total amount of parts has already been reached. Try this:

=IF(COUNTIF($B$2:B2,B2)>C2,NA(),1)

Broken down, this formula counts how many of the parts have already been requested and if this exceeds the total amount of parts it will return #N/A, otherwise it will return 1.


问:
Date Time Format / Region Settings incorrect on a Web Server
I wonder if someone has stumbled upon this type of scenario before. Please tell me how you fixed it.

So, on my development PC, my date format is DD/MM/YYYY. It shows the same format when I "Run"(F5) the project and test stuff.
However, when publishing to the web server and a user goes to the date, the format is in MM/DD/YYYY.

For your information:
The settings on the Web Server are exactly the same as on the development PC. Both have the same region, the same dateTime format in Control Panel -> Region.

I do not code any funny regional settings in my code because it is just a dateTimePicker displaying a javascript calender from which the user chooses.

Code for reference:
The datetimepicker:

```<code>       <script type="text/javascript">
                                $(document).ready(function() {
                                // Datepicker Popups calender to Choose date.
                                $(function() {
                                $("#datepicker_end").datepicker();
                                // Pass the user selected date format.
                                $("#format").change(function() {
                                    $("#datepicker_end").datepicker("option", "dateFormat", "dd-mm-yy");
                                });
                                });
                                });
                </script>

        <script type="text/javascript">
                                $(".date-pick").datepicker();
                                $(".date-pick").datepicker('setDate', new Date());
                                var now = new Date();
                                var day = ("0" + now.getDate()).slice(-2);
                                var month = ("0" + (now.getMonth() + 1)).slice(-2);
                                var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
                                $('#datepicker_start').datepicker({ dateFormat: 'dd-mm-yyyy' }).val(today);
                                $('#datepicker_start').show();
                </script>
</code>```

That's everything I can give you. Tried googling multiple things but can't find a solution. Thanks.

EDIT
Okay, I did the formatting piece as Frederico suggested. No luck.
Anyone else have some other ideas/suggestions??

答:
Sure, you are not the only one, check this:

jQuery UI DatePicker - Change Date Format

the solution is:

```<code>var date = $('#datepicker').datepicker({ dateFormat: 'DD/MM/YYYY' }).val();
</code>```

for making it fixed. The format may change depending on settings on your browser.

```<code><script type="text/javascript">
    $(document).ready(function() {
      // Datepicker Popups calender to Choose date.
      $(function() {
        $("#datepicker_start").datepicker();
        // Pass the user selected date format.
        $("#format").change(function() {
          $("#datepicker_start").datepicker({ dateFormat: 'DD/MM/YYYY' });
        });
      });
   });
</script>
</code>```

Body:
I wonder if someone has stumbled upon this type of scenario before. Please tell me how you fixed it.

So, on my development PC, my date format is DD/MM/YYYY. It shows the same format when I "Run"(F5) the project and test stuff.
However, when publishing to the web server and a user goes to the date, the format is in MM/DD/YYYY.

For your information:
The settings on the Web Server are exactly the same as on the development PC. Both have the same region, the same dateTime format in Control Panel -> Region.

I do not code any funny regional settings in my code because it is just a dateTimePicker displaying a javascript calender from which the user chooses.

Code for reference:
The datetimepicker:

That's everything I can give you. Tried googling multiple things but can't find a solution. Thanks.

EDIT
Okay, I did the formatting piece as Frederico suggested. No luck.
Anyone else have some other ideas/suggestions??

Body:
Sure, you are not the only one, check this:

jQuery UI DatePicker - Change Date Format

the solution is:

var date = $('#datepicker').datepicker({ dateFormat: 'DD/MM/YYYY' }).val();

for making it fixed. The format may change depending on settings on your browser.

<script type="text/javascript">
    $(document).ready(function() {
      // Datepicker Popups calender to Choose date.
      $(function() {
        $("#datepicker_start").datepicker();
        // Pass the user selected date format.
        $("#format").change(function() {
          $("#datepicker_start").datepicker({ dateFormat: 'DD/MM/YYYY' });
        });
      });
   });
</script>


问:
PHPMailer timeout o some server
from yesterday I'm desperately trying to run a very simple e-mail script with PHPMailer, latest version.

The most absurd thing is that the same script on two servers does not work, but on another it does.

This is my attempt (from PHPMailer examples):

```<code>date_default_timezone_set('Etc/UTC');

require '../PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();

$mail->SMTPDebug = 3;

$mail->Debugoutput = 'html';

$mail->Host = "smtp.live.com";

$mail->Port = 587;

$mail->SMTPAuth = true;

$mail->Username = "xxxx@xxxx.com";

$mail->Password = "xxxxx";

$mail->setFrom('from@example.com', 'First Last');

$mail->addReplyTo('replyto@example.com', 'First Last');

$mail->addAddress('whoto@example.com', 'John Doe');

$mail->Subject = 'PHPMailer SMTP test';

$mail->Body = 'Test';

$mail->AltBody = 'This is a plain-text message body';

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}
</code>```

Output debug:

```<code>2017-06-08 08:43:55 Connection: opening to smtp.live.com:587, timeout=300, options=array ()

2017-06-08 08:44:58 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.live.com:587 (Connection timed out) [/home/public_html/work/PHPMailer/class.smtp.php line 292]

2017-06-08 08:44:58 SMTP ERROR: Failed to connect to server: Connection timed out (110)

SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
</code>```

I think it depends on the configuration of the server. Which parameter do I have to look at?

Thanks in advance

答:
No Need To Used:     $mail->isSMTP();

Comment This ...     $mail->isSMTP();

```<code><?php

//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');

require '../PHPMailerAutoload.php';
require_once('../class.phpmailer.php');

$mail = new PHPMailer;
//$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtp.live.com";
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = "xxxx@xxxx.com";
$mail->Password = "xxxxx";
$mail->setFrom('from@example.com', 'First Last');
$mail->addReplyTo('replyto@example.com', 'First Last');
$mail->addAddress('whoto@example.com', 'John Doe');
$mail->Subject = 'PHPMailer SMTP test';
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";

$body = file_get_contents('test.html');
$body = eregi_replace("[\]",'',$body);
$mail->MsgHTML($body);

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

?>
</code>```

```<code>$mail->Timeout =   60; // set the timeout (seconds)
$mail->SMTPKeepAlive = true; // don't close the connection between messages
</code>```

Title: PHPMailer timeout o some server

Body:
from yesterday I'm desperately trying to run a very simple e-mail script with PHPMailer, latest version.

The most absurd thing is that the same script on two servers does not work, but on another it does.

This is my attempt (from PHPMailer examples):

date_default_timezone_set('Etc/UTC');

require '../PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();

$mail->SMTPDebug = 3;

$mail->Debugoutput = 'html';

$mail->Host = "smtp.live.com";

$mail->Port = 587;

$mail->SMTPAuth = true;

$mail->Username = "xxxx@xxxx.com";

$mail->Password = "xxxxx";

$mail->setFrom('from@example.com', 'First Last');

$mail->addReplyTo('replyto@example.com', 'First Last');

$mail->addAddress('whoto@example.com', 'John Doe');

$mail->Subject = 'PHPMailer SMTP test';

$mail->Body = 'Test';

$mail->AltBody = 'This is a plain-text message body';

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

Output debug:

2017-06-08 08:43:55 Connection: opening to smtp.live.com:587, timeout=300, options=array ()

2017-06-08 08:44:58 Connection failed. Error #2: stream_socket_client(): unable to connect to smtp.live.com:587 (Connection timed out) [/home/public_html/work/PHPMailer/class.smtp.php line 292]

2017-06-08 08:44:58 SMTP ERROR: Failed to connect to server: Connection timed out (110)

SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I think it depends on the configuration of the server. Which parameter do I have to look at?

Thanks in advance

Body:
No Need To Used:     $mail->isSMTP();

Comment This ...     $mail->isSMTP();

<?php

//error_reporting(E_ALL);
error_reporting(E_STRICT);
date_default_timezone_set('America/Toronto');

require '../PHPMailerAutoload.php';
require_once('../class.phpmailer.php');

$mail = new PHPMailer;
//$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = "smtp.live.com";
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = "xxxx@xxxx.com";
$mail->Password = "xxxxx";
$mail->setFrom('from@example.com', 'First Last');
$mail->addReplyTo('replyto@example.com', 'First Last');
$mail->addAddress('whoto@example.com', 'John Doe');
$mail->Subject = 'PHPMailer SMTP test';
$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";

$body = file_get_contents('test.html');
$body = eregi_replace("[\]",'',$body);
$mail->MsgHTML($body);

//send the message, check for errors
if (!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message sent!";
}

?>

$mail->Timeout =   60; // set the timeout (seconds)
$mail->SMTPKeepAlive = true; // don't close the connection between messages


问:
Rule of 3 Default Member Deprecation in C++11
According to the below widely-known table, automatic compiler generation of default copy constructor and copy assignment is deprecated in C++11 when one or more of the copy assignment, copy constructor, and destructor is/are supplied by the user (the red cells indicate deprecation). This makes perfect sense in light of the "Rule of 3". However, the table shows that generation of the default destructor is not deprecated in the case of user-supplied copy constructor/assignment.

What is the rationale behind this design decision?

答:
Why should it be deprecated? It's perfectly possible for an object to require special copying properties, but its for destruction to be fully determined by its sub-object destructors. Consider a simple cloning pointer:

```<code>template <class T>
class cloning_ptr
{
  std::unique_ptr<T> p;

public:
  cloning_ptr(const cloning_ptr &src) : p(std::make_unique<T>(*src.p) {}
  cloning_ptr(cloning_ptr &&) = default;

  cloning_ptr& operator= (cloning_ptr rhs)
  { swap(p, rhs.p); return *this; }
};
</code>```

There's zero reason to provide a destructor that does anything different from the defaulted one.

The other way around is different: if you need to do special things in a dtor, that probably means there is some non-standard ownership modeled in the class. Non-standard ownership will most likely need handling in copy operations, too.

Body:
Why should it be deprecated? It's perfectly possible for an object to require special copying properties, but its for destruction to be fully determined by its sub-object destructors. Consider a simple cloning pointer:

template <class T>
class cloning_ptr
{
  std::unique_ptr<T> p;

public:
  cloning_ptr(const cloning_ptr &src) : p(std::make_unique<T>(*src.p) {}
  cloning_ptr(cloning_ptr &&) = default;

  cloning_ptr& operator= (cloning_ptr rhs)
  { swap(p, rhs.p); return *this; }
};

There's zero reason to provide a destructor that does anything different from the defaulted one.

The other way around is different: if you need to do special things in a dtor, that probably means there is some non-standard ownership modeled in the class. Non-standard ownership will most likely need handling in copy operations, too.


问:
Need to allow encoded slashes on Apache
I'm currently trying to place a URL within a URL. For example:

```<code>http://example.com/url/http%3A%2F%2Fwww.url2.com
</code>```

I'm aware that I have to encode the URL, which I have done, but now I am getting a 404 error back from the server rather than my app. I think my problem lies with apache and can be fixed with the AllowEncodedSlashes On directive.

I've tried putting the directive at the bottom of the httpd.conf to no effect, and am unsure what to do next. Am I putting it in the right place? If so, does anyone have any other solutions?

答:
This issue is not related to Apache Bug 35256. Rather, it is related to Bug 46830. The AllowEncodedSlashes setting is not inherited by virtual hosts, and virtual hosts are used in many default Apache configurations, such as the one in Ubuntu. The workaround is to add the AllowEncodedSlashes setting inside a <VirtualHost> container (/etc/apache2/sites-available/default in Ubuntu).

Bug 35256: %2F will be decoded in PATH_INFO (Documentation to AllowEncodedSlashes says no decoding will be done)

Bug 46830: If AllowEncodedSlashes On is set in the global context, it is not inherited by virtual hosts. You must explicitly set AllowEncodedSlashes On in every <VirtalHost> container.

The documentation for how the different configuration sections are merged says:

Sections inside <VirtualHost> sections are applied after the corresponding sections outside the virtual host definition. This allows virtual hosts to override the main server configuration.

Title: Need to allow encoded slashes on Apache

Body:
I'm currently trying to place a URL within a URL. For example:

http://example.com/url/http%3A%2F%2Fwww.url2.com

I'm aware that I have to encode the URL, which I have done, but now I am getting a 404 error back from the server rather than my app. I think my problem lies with apache and can be fixed with the AllowEncodedSlashes On directive.

I've tried putting the directive at the bottom of the httpd.conf to no effect, and am unsure what to do next. Am I putting it in the right place? If so, does anyone have any other solutions?

ContentLicense: CC BY-SA 4.0


问:
Python - Use pytest to test test methods written in subclass
I am a novice to pytest. I have a scenario wherein i wanted to test some test methods written in a subclass.

Assume that the following is my code structure

```<code>class Superclass:
    def __init__(self, a):
        self.a = a
    def dummy_print():
        print("This is a dummy function")

class TestSubClass(Superclass):

def test_1_eq_1():
    assert 1 == 1
</code>```

Upon executing the following command

```<code>py.test -s -v test_filename.py
</code>```

I get the following error messgae:

cannot collect test class 'Test_Super' because it has a init constructor

The same is mentioned in the pytest documentation as well.

Is there a workaround for this?

I need the superclass' __init__() method because all my test files would need to inherit from the super class.

答:
Pytest is different beast than, say unittests. It prohibits class hierarchies, which you can see in the warning message.

If you need some pre-initialization steps, do them using fixtures:

```<code>@pytest.fixture(autouse=True)
def pre_run_initialization():
    # do before test
    yield
    # do after test
</code>```

Body:
I am a novice to pytest. I have a scenario wherein i wanted to test some test methods written in a subclass.

Assume that the following is my code structure

class Superclass:
    def __init__(self, a):
        self.a = a
    def dummy_print():
        print("This is a dummy function")

class TestSubClass(Superclass):

def test_1_eq_1():
    assert 1 == 1

Upon executing the following command

py.test -s -v test_filename.py

I get the following error messgae:

cannot collect test class 'Test_Super' because it has a init constructor

The same is mentioned in the pytest documentation as well.

Is there a workaround for this?

I need the superclass' __init__() method because all my test files would need to inherit from the super class.

Body:
Pytest is different beast than, say unittests. It prohibits class hierarchies, which you can see in the warning message.

If you need some pre-initialization steps, do them using fixtures:

@pytest.fixture(autouse=True)
def pre_run_initialization():
    # do before test
    yield
    # do after test


问:
Android Activity Life-cycle
I need to save my filters after closing Activity. I'm using onSaveInstanceState() to achieve it.

```<code>protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("age", sbAge.getProgress());
    savedInstanceState.putInt("age", spMyStatus.getSelectedItemPosition());
    if(rbMaleMe.isChecked())
        savedInstanceState.putInt("sex", 1);
    else if(rbFemaleMe.isChecked())
        savedInstanceState.putInt("sex", 2);
}
`
</code>```

In onRestoreInstanceState() method:

```<code>protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    sbAge.setProgress(savedInstanceState.getInt("age"));
    spMyStatus.setSelection(savedInstanceState.getInt("status"));
    if(savedInstanceState.getInt("sex") == 1)
        rbMaleMe.isChecked();
    else if (savedInstanceState.getInt("sex") == 2)
        rbFemaleMe.isChecked();
}
</code>```

In onCreate() method:

```<code>if (savedInstanceState != null)
{
    savedInstanceState.getInt("age");
    savedInstanceState.getInt("sex");
    savedInstanceState.getInt("status");
}
</code>```

but it doesn't work.
Just shows empty views when I close and restart the activity.

onClick():

```<code>switch (v.getId()) {
    case R.id.btnSaveInfo:
        onStop();
        finish();
        break;
}
</code>```

答:
onSaveInstanceState() is called when the OS kills your Activity (to reclaim resources for example). It will not be called when you explicitly call finish().

If you would still like to persist your values, you could use SharedPreferences.

(on a side note, do not call onStop() explicitly)

Title: Android Activity Life-cycle

Body:
I need to save my filters after closing Activity. I'm using onSaveInstanceState() to achieve it.

protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("age", sbAge.getProgress());
    savedInstanceState.putInt("age", spMyStatus.getSelectedItemPosition());
    if(rbMaleMe.isChecked())
        savedInstanceState.putInt("sex", 1);
    else if(rbFemaleMe.isChecked())
        savedInstanceState.putInt("sex", 2);
}
`

In onRestoreInstanceState() method:

protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    sbAge.setProgress(savedInstanceState.getInt("age"));
    spMyStatus.setSelection(savedInstanceState.getInt("status"));
    if(savedInstanceState.getInt("sex") == 1)
        rbMaleMe.isChecked();
    else if (savedInstanceState.getInt("sex") == 2)
        rbFemaleMe.isChecked();
}

In onCreate() method:

if (savedInstanceState != null)
{
    savedInstanceState.getInt("age");
    savedInstanceState.getInt("sex");
    savedInstanceState.getInt("status");
}

but it doesn't work.
Just shows empty views when I close and restart the activity.

onClick():

switch (v.getId()) {
    case R.id.btnSaveInfo:
        onStop();
        finish();
        break;
}


问:
Blowfish file encryption without keygenerator
How do I encrypt my files without using the KeyGenerator using the Blowfish Algorithm?

here's part of my code

```<code>Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis = new FileInputStream(plain);

FileOutputStream fos = new FileOutputStream(copy);
CipherOutputStream out2 = new CipherOutputStream(fos, cipher);
byte[] buffer = new byte[1024];
while (fis.read(buffer)>=0) {
    out2.write(buffer);
}
</code>```

答:
If you have a key you can provide it using the SecretKeySpec like this:</p>

```<code>byte[] key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
SecretKey keySpec = new SecretKeySpec(key, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
</code>```

Body:
How do I encrypt my files without using the KeyGenerator using the Blowfish Algorithm?

here's part of my code

Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis = new FileInputStream(plain);

FileOutputStream fos = new FileOutputStream(copy);
CipherOutputStream out2 = new CipherOutputStream(fos, cipher);
byte[] buffer = new byte[1024];
while (fis.read(buffer)>=0) {
    out2.write(buffer);
}

Body:
If you have a key you can provide it using the SecretKeySpec like this:

byte[] key = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
SecretKey keySpec = new SecretKeySpec(key, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);


问:
Triggering an Airflow DAG from terminal not working
I'm trying to use airflow to define a specific workflow that I want to manually trigger from the command line.

I create the DAG and add a bunch of tasks.

```<code>dag = airflow.DAG(
    "DAG_NAME",
    start_date=datetime(2015, 1, 1),
    schedule_interval=None,
    default_args=args)
</code>```

I then run in the terminal

```<code>airflow trigger_dag DAG_NAME
</code>```

and nothing happens. The scheduler is running in another thread. Any direction is much appreciated. Thank You

答:
first make sure your database connection string on the airflow is working, weather it be on postgres, sqlite(by default) or any other database. Then run the command

```<code> airflow initdb
</code>```

This command should not be showing any connection errors

Secondly make sure your webserver is running on a separate thread

```<code>airflow webserver
</code>```

Then run your schdeuler on a different thread

```<code>airflow scheduler
</code>```

Finally trigger your dag on a different thread after the scheduler is running

```<code>airflow trigger_dag dag_id
</code>```

Also make sure the dag name and task are present in the dag and task list

```<code>airflow list_dags
airflow list_tasks dag_id
</code>```

And if the dag is switched off in your UI then toggle it on.

Body:
I'm trying to use airflow to define a specific workflow that I want to manually trigger from the command line.

I create the DAG and add a bunch of tasks.

dag = airflow.DAG(
    "DAG_NAME",
    start_date=datetime(2015, 1, 1),
    schedule_interval=None,
    default_args=args)

I then run in the terminal

airflow trigger_dag DAG_NAME

and nothing happens. The scheduler is running in another thread. Any direction is much appreciated. Thank You

Body:
first make sure your database connection string on the airflow is working, weather it be on postgres, sqlite(by default) or any other database. Then run the command

 airflow initdb

This command should not be showing any connection errors

Secondly make sure your webserver is running on a separate thread

airflow webserver

Then run your schdeuler on a different thread

airflow scheduler

Finally trigger your dag on a different thread after the scheduler is running

airflow trigger_dag dag_id

Also make sure the dag name and task are present in the dag and task list

airflow list_dags
airflow list_tasks dag_id

And if the dag is switched off in your UI then toggle it on.


问:
Good way to sanitize input in classic asp
I have to update old projects at work. I do not have any experience with classic asp, although i'm familiar with php scripting.

Are there any functions I should use?

Can you provide me with a good function for some basic protection?

Is there something like a parameterized query in asp?

Thanks!

答: There is a bunch of functions starting with Is, such as IsNumber, IsArray etcetera, that might be of interest. Also if you're expecting a integer, you could use CLng(Request("blabla")) to get it, thus if it's not a integer the CLng function will raise an error.

OwnerDisplayName: Sander Versluys

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sander Versluys


问:
MS SQL Server Row GUID Column
I apologize for asking what seems like a tired question, but no forum response or documentation I've read seems to provide an adequate answer.

What is the purpose of the Row GUID Column property in MS SQL Server 2008?

Let me extend on that. I've seen "Don't use GUID as the PK" repeated as the answer for this question, which seems to be completely unrelated to me. If I set Row GUID Column is it forcing that GUID column to be the primary key or something?

To rephrase my original question: If I have a GUID column in my table that does not play any role in indexing, do I stand to gain anything from setting that GUID column as the Row GUID Column?

答:
The ROWGUIDCOLUMN is used primarily in replication scenarios where you need to combine the contents of several satelite databases' tables into one central DB.

Adding a ROWGUIDCOLUMN to the tables being replicated ensures that the replication engine can use the ROWGUIDCOLUMN field to differentiate between records with the same primary key values.

Because this is a feature primarily used to ensure smooth replication, you should avoid using this column as your primary key. Your primary key should be a logical business entity that is under your control and which doesn't affect the operational characteristics of specific features of your chosen DB engine.

Title: MS SQL Server Row GUID Column


问:
AngularJS: Animate ng-hide / ng-show height of li by using css transitions
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

```<code>li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}
</code>```

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

答:
I have come across the same problem myself in the past and discovered as you have that the height must be set, this is in order for the transition to calculate what needs to happen. Two ways I have managed to get round the problem:

CSS way:

```<code>li {
  transition: max-height 1s linear;
  overflow: hidden;
  max-height: 500px; // Any value above what you expect to be the biggest
}

li.ng-hide {
  max-height: 0;
}
</code>```

The above method has a two drawbacks in that, one you'll need to know an upper limit and two there will be a slight jump in animation. A better way might be to calculate the height with javascript:

** UPDATE FROM JQUERY **

```<code>var listItems = document.getElementsByTagName("li")

for (var i = 0; i < listItems.length; i++) {
  listItems[i].style.height = listItems[i].clientHeight + 'px';
}
</code>```

Then you'd need the css:

```<code>li.ng-hide {
  height: 0 !important;
}
</code>```

To override the style attribute. Here is a pen of this example with a little bit extra in to illustrate the solution.

Body:
I am using Angular to hide/show items of a unordered list. Since the effect is a bit too fast for the user to notice the disappearance/appearance of my lis, I want to add a transition on the height.

li {
  transition: height 1s linear;
  overflow: hidden;
}

li.ng-hide {
  height: 0;
}

This is where my problem is : the transition does not affect the lis, unless I set them a height, which I don't want, since I don't exactly know how big they are.

Here is a plunker to illustrate that. I've made the test on lis and divs and I've also tried without Angular which does not seem to be the responsible.

How can I make the transition work without setting the height of my elements ?

Body:
I have come across the same problem myself in the past and discovered as you have that the height must be set, this is in order for the transition to calculate what needs to happen. Two ways I have managed to get round the problem:

CSS way:

li {
  transition: max-height 1s linear;
  overflow: hidden;
  max-height: 500px; // Any value above what you expect to be the biggest
}

li.ng-hide {
  max-height: 0;
}

The above method has a two drawbacks in that, one you'll need to know an upper limit and two there will be a slight jump in animation. A better way might be to calculate the height with javascript:

** UPDATE FROM JQUERY **

var listItems = document.getElementsByTagName("li")

for (var i = 0; i < listItems.length; i++) {
  listItems[i].style.height = listItems[i].clientHeight + 'px';
}

Then you'd need the css:

li.ng-hide {
  height: 0 !important;
}

To override the style attribute. Here is a pen of this example with a little bit extra in to illustrate the solution.


问:
Locate mouse position relative to transformed plane
I've set up a jsfiddle illustrating my situation: http://jsfiddle.net/j5o0w5qc/1/

Basically, I've got three nested HTML elements: a viewport div on the outside, a stage div in the middle, and a canvas on the inside. The stage div provides a perspective setting for 3d transformations applied to the canvas. The viewport has overflow: hidden; so we don't see anything outside of the viewport. It also has a listener attached, listening for mousedown.

In my actual app that I'm building, the canvas might be transformed to any arbitrary 3d transformation, involving translation and rotation in 3d space. What I would like to happen is for the viewport div to intercept a click, and draw a spot on the canvas in the place you clicked. I'm intercepting the event with the viewport div, and I'm using offsetX and offsetY in Chrome. This works great for Chrome, but I know I can't rely on offsetX and offsetY in other browsers, so I'd like to use pageX and pageY, normalized via jQuery, but I'm not sure quite how to do that.

What I've currently got in the jsfiddle works great in Chrome, except when you click in the viewport NOT on the canvas. When you click on the canvas, it draws a dot there, regardless of the canvas's transformation. Chrome is doing all the hard work and giving me exactly what I want with offsetX and offsetY. However, when you click in the viewport NOT on the canvas, I guess it's giving me offsetX and offsetY values relative to the viewport, rather than the canvas, and then interpreting that and drawing a dot on the canvas. For example, if I transform the canvas and then click in the upper right corner of the viewport, a dot appears in the upper right corner of the canvas, regardless of where that corner actually appears on the page.

In Firefox, however, it works great as long as there is no transformation applied to the canvas, but as soon as the canvas is transformed, all of a sudden, the dot being drawn is displaced, and I can't figure out how to take my pageX and pageY values and figure out exactly where in the canvas I am clicking.

Does anyone have any brilliant solutions? I've been bashing my head against this problem for far too long. I'm pretty sure I need to manually calculate some 3d transformation matrices or something, and I've spent hours writing methods to return the inverse of a matrix, and to multiply a matrix by a vector, and all sorts of stuff, but none of it has actually solved the problem for me, and I'm not sure what I'm missing.

Stackoverflow says code is required with jsfiddle links, so here's all my code:

HTML:

```<code><div id="viewport">
    <div id="stage">
        <canvas id="myCanvas" width="300" height="300"></canvas>
    </div>
</div>

<div id="stuff">
    <button onclick="transformMe()">Transform</button>
    <input id="blah" type="text" size="45"></input>
</div>
</code>```

CSS:

```<code>#viewport, #stage, #myCanvas {
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
}

#viewport {
    border: 1px solid #000;
    overflow: hidden;
}

#stage {
    perspective: 1000px;
    transform-style: preserve-3d;
}

#myCanvas {
    background-color: green;
    transform-style: preserve-3d;
}

#stuff {
    position: absolute;
    top: 350px;
}
</code>```

Javascript:

```<code>var counter = 0;

$('#viewport').mousedown(function _drawOnCanvas (e)
{
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var xpos, ypos;

    if (typeof e.offsetX=='undefined')
    {
        xpos = e.pageX - $('#myCanvas').offset().left;
        ypos = e.pageY - $('#myCanvas').offset().top;
    }
    else
    {
        xpos = e.offsetX;
        ypos = e.offsetY;
    }

    ctx.fillRect(xpos-5, ypos-5, 10, 10);
});

function transformMe()
{
    counter++;
    var angle = (counter * 30) % 360;
    $('#myCanvas').css('transform','perspective(1000px) rotate3d(5,6,7,' + angle + 'deg)');
    $('input').val('counter: ' + counter + ', angle: ' + angle);
};
</code>```

答:
If you change viewport to myCanvas in line 3 of the either Kyle S or Dom's jsfiddles:

```<code>$('#myCanvas').mousedown(function _drawOnCanvas (e)
</code>```

it no longer places a dot when you "click in the viewport NOT on the canvas."

It seems there's a new issue with Firefox - if there's a transformation it only lets you paint on half ( the bottom left of diagonal - but depends on transformation ).

Body:
I've set up a jsfiddle illustrating my situation: http://jsfiddle.net/j5o0w5qc/1/

Basically, I've got three nested HTML elements: a viewport div on the outside, a stage div in the middle, and a canvas on the inside. The stage div provides a perspective setting for 3d transformations applied to the canvas. The viewport has overflow: hidden; so we don't see anything outside of the viewport. It also has a listener attached, listening for mousedown.

In my actual app that I'm building, the canvas might be transformed to any arbitrary 3d transformation, involving translation and rotation in 3d space. What I would like to happen is for the viewport div to intercept a click, and draw a spot on the canvas in the place you clicked. I'm intercepting the event with the viewport div, and I'm using offsetX and offsetY in Chrome. This works great for Chrome, but I know I can't rely on offsetX and offsetY in other browsers, so I'd like to use pageX and pageY, normalized via jQuery, but I'm not sure quite how to do that.

What I've currently got in the jsfiddle works great in Chrome, except when you click in the viewport NOT on the canvas. When you click on the canvas, it draws a dot there, regardless of the canvas's transformation. Chrome is doing all the hard work and giving me exactly what I want with offsetX and offsetY. However, when you click in the viewport NOT on the canvas, I guess it's giving me offsetX and offsetY values relative to the viewport, rather than the canvas, and then interpreting that and drawing a dot on the canvas. For example, if I transform the canvas and then click in the upper right corner of the viewport, a dot appears in the upper right corner of the canvas, regardless of where that corner actually appears on the page.

In Firefox, however, it works great as long as there is no transformation applied to the canvas, but as soon as the canvas is transformed, all of a sudden, the dot being drawn is displaced, and I can't figure out how to take my pageX and pageY values and figure out exactly where in the canvas I am clicking.

Does anyone have any brilliant solutions? I've been bashing my head against this problem for far too long. I'm pretty sure I need to manually calculate some 3d transformation matrices or something, and I've spent hours writing methods to return the inverse of a matrix, and to multiply a matrix by a vector, and all sorts of stuff, but none of it has actually solved the problem for me, and I'm not sure what I'm missing.

Stackoverflow says code is required with jsfiddle links, so here's all my code:

HTML:

        <canvas id="myCanvas" width="300" height="300"></canvas>

    <button onclick="transformMe()">Transform</button>
    <input id="blah" type="text" size="45"></input>

CSS:

#viewport, #stage, #myCanvas {
    width: 300px;
    height: 300px;
    position: absolute;
    top: 0;
    left: 0;
}

#viewport {
    border: 1px solid #000;
    overflow: hidden;
}

#stage {
    perspective: 1000px;
    transform-style: preserve-3d;
}

#myCanvas {
    background-color: green;
    transform-style: preserve-3d;
}

#stuff {
    position: absolute;
    top: 350px;
}

Javascript:

var counter = 0;

$('#viewport').mousedown(function _drawOnCanvas (e)
{
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var xpos, ypos;

    if (typeof e.offsetX=='undefined')
    {
        xpos = e.pageX - $('#myCanvas').offset().left;
        ypos = e.pageY - $('#myCanvas').offset().top;
    }
    else
    {
        xpos = e.offsetX;
        ypos = e.offsetY;
    }

    ctx.fillRect(xpos-5, ypos-5, 10, 10);
});

function transformMe()
{
    counter++;
    var angle = (counter * 30) % 360;
    $('#myCanvas').css('transform','perspective(1000px) rotate3d(5,6,7,' + angle + 'deg)');
    $('input').val('counter: ' + counter + ', angle: ' + angle);
};

Body:
If you change viewport to myCanvas in line 3 of the either Kyle S or Dom's jsfiddles:

$('#myCanvas').mousedown(function _drawOnCanvas (e)

it no longer places a dot when you "click in the viewport NOT on the canvas."

It seems there's a new issue with Firefox - if there's a transformation it only lets you paint on half ( the bottom left of diagonal - but depends on transformation ).


问:
Transform CSS { ul li:hover a } in JQUERY .hover
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

```<code>ul li:hover a {
    color: #FFF;
}
</code>```

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

```<code>$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});
</code>```

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

```<code>$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});
</code>```

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

```<code><ul class="menu">

      <li><a href="#">text</a></li>

      <li><a href="#">text</a>

        <ul class="submenu">
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
          <li><a href="#">text</a></li>
        </ul>

      </li>

      <li><a href="#">text</a></li>

</ul>
</code>```

答:
Please let me know if this is along the right track of what you're asking.

I haven't got it working fully, but give this a look and see if it helps:
my JSFiddle

Here's the code so far:

```<code>   $(document).ready(function() {
       var sm;                       // submenu
       var delay = 500;              // delay before applying changes
       var tID;                      // timeout id
       var color_on  = '#fff'
         , color_off = '#000';
       var oPrev;

       $('ul.menu > li > a').hover(
          function() {
             if (tID && $(this) === oPrev) {clearTimeout(tID);}
             oPrev = $(this);
             sm  = $(this).next('.submenu');
             if(sm){sm.stop(true, true).fadeIn('slow');}
          },
          function() {
             if (tID) {clearTimeout(tID);}
             tID = setTimeout(
                      function() {
                         sm.stop(true, true).fadeOut('slow');
                      }, delay);
          }
       );

       $('.submenu > li > a').hover(
           function() {
              if (tID) {clearTimeout(tID);}
              oPrev.css('color',color_on);
              $(this).stop(true, true).fadeIn('slow');
           },
           function() {
              if (tID) {clearTimeout(tID);}
              sm  = $(this);
              tID = setTimeout(
                       function() {
                          oPrev.css('color','');
                          sm.closest('ul').stop(true, true).fadeOut('slow');
                       }, delay);
           }
       );
   });
</code>```

And CSS:

```<code>   a
   {
       color           : #000;
       text-decoration : none;
   }
   a:hover
   {
       color           : #fff;
   }

   ul li
   {
       background      : orange;
       border          : 1px solid black;
       display         : inline-block;
       padding         : 0 1em;
       vertical-align  : top;
   }

   .menu
   {
       background      : #ccc;
       border          : 1px solid black;
       display         : inline-block;
       padding         : .25em 1em;
       vertical-align  : top;
   }
   .submenu
   {
       border          : 1px solid black;
       border-width    : 1px 0 0 0;
       display         : none;
   }
   .submenu li
   {
       background      : red;
       border-width    : 0;
   }
   .submenu li a:hover
   {
       color           : #fff;
   }
</code>```

Note: I'm not saying this is the best answer, nor is it a complete solution, but maybe something in here will assist someone in finding the correct solution.

Body:
I want to now if there's a way to transform this css properties in a jquery .hover, or control this by javascript to change the colour dynamically.

CSS:

ul li:hover a {
    color: #FFF;
}

Can anyone Help ?

EDIT:

My problem is:

I have a drop down menu and i want that when I hover the menu the text color change and when I hover the submenu the hover state stays for both.

JQuery:

$("ul li").hover(function () {
    $(this).stop().animate({ backgroundColor: "white"}, 500);
}, function () {
    $(this).stop().animate({ backgroundColor: "black"}, 400);
});

To animate background color on hover in menu and submenu.

For example if the text are black I want to make the text white on hover. For this I use:(Submenu example, for menu change the selector of course)

$('ul.submenu li a').hover(function () {
    $(this).css({color:'#FFFFFF'});
}, function () {
    $(this).css({color:'#00FF00'});
});

All This works fine, but when I hover the submenu the menu returns to the original state(because the mouseleave is activated on hover out). All I want is that when I hover submenu the hover state in menu stays active as well.

I've tried many things but all give me problems, only thing that works is css, but I need to control the text colours dynamically too.

HTML Structure:

text

text

text

text

text

text

Body:
Please let me know if this is along the right track of what you're asking.

I haven't got it working fully, but give this a look and see if it helps:
my JSFiddle

Here's the code so far:

   $(document).ready(function() {
       var sm;                       // submenu
       var delay = 500;              // delay before applying changes
       var tID;                      // timeout id
       var color_on  = '#fff'
         , color_off = '#000';
       var oPrev;

       $('ul.menu > li > a').hover(
          function() {
             if (tID && $(this) === oPrev) {clearTimeout(tID);}
             oPrev = $(this);
             sm  = $(this).next('.submenu');
             if(sm){sm.stop(true, true).fadeIn('slow');}
          },
          function() {
             if (tID) {clearTimeout(tID);}
             tID = setTimeout(
                      function() {
                         sm.stop(true, true).fadeOut('slow');
                      }, delay);
          }
       );

       $('.submenu > li > a').hover(
           function() {
              if (tID) {clearTimeout(tID);}
              oPrev.css('color',color_on);
              $(this).stop(true, true).fadeIn('slow');
           },
           function() {
              if (tID) {clearTimeout(tID);}
              sm  = $(this);
              tID = setTimeout(
                       function() {
                          oPrev.css('color','');
                          sm.closest('ul').stop(true, true).fadeOut('slow');
                       }, delay);
           }
       );
   });

And CSS:

   a
   {
       color           : #000;
       text-decoration : none;
   }
   a:hover
   {
       color           : #fff;
   }

   ul li
   {
       background      : orange;
       border          : 1px solid black;
       display         : inline-block;
       padding         : 0 1em;
       vertical-align  : top;
   }

   .menu
   {
       background      : #ccc;
       border          : 1px solid black;
       display         : inline-block;
       padding         : .25em 1em;
       vertical-align  : top;
   }
   .submenu
   {
       border          : 1px solid black;
       border-width    : 1px 0 0 0;
       display         : none;
   }
   .submenu li
   {
       background      : red;
       border-width    : 0;
   }
   .submenu li a:hover
   {
       color           : #fff;
   }

Note: I'm not saying this is the best answer, nor is it a complete solution, but maybe something in here will assist someone in finding the correct solution.


问:
Javascript: nice human readable join of list
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

```<code>"Content tagged " + tags_titles.join(" and ");
</code>```

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

答:
From my view, This is an simple approach

```<code>var tags = ['tag1', 'tag2', 'tag3'];

console.log("Content tagged " + tags.slice(0, -1).join(', ')+' and '+tags.slice(-1));
</code>```

Hope it helps you :)
JsFiddle

Body:
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

"Content tagged " + tags_titles.join(" and ");

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

Body:
From my view, This is an simple approach

var tags = ['tag1', 'tag2', 'tag3'];

console.log("Content tagged " + tags.slice(0, -1).join(', ')+' and '+tags.slice(-1));

Hope it helps you :)
JsFiddle


问:
problem with JsonStore and JsonReader
In my ExtJS application I use EditorGridPanel to show data from server.

```<code>var applicationsGrid = new Ext.grid.EditorGridPanel({
    region: 'west',
    layout: 'fit',
    title: '<img src="../../Content/img/app.png" />  Приложения',
    collapsible: true,
    margins: '0 0 5 5',
    split: true,
    width: '30%',
    listeners: { 'viewready': { fn: function() { applicationsGridStatusBar.setText('Приложений: ' + applicationsStore.getTotalCount()); } } },
    store: applicationsStore,
    loadMask: { msg: 'Загрузка...' },
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true,
        listeners: { 'rowselect': { fn: applicationsGrid_onRowSelect} }
    }),
    viewConfig: { forceFit: true },
    tbar: [{
        icon: '../../Content/img/add.gif',
        text: 'Добавить'
    }, '-', {
        icon: '../../Content/img/delete.gif',
        text: 'Удалить'
    }, '-'],
    bbar: applicationsGridStatusBar,
    columns: [{
        header: 'Приложения',
        dataIndex: 'ApplicationName',
        tooltip: 'Наименование приложения',
        sortable: true,
        editor: {
            xtype: 'textfield',
            allowBlank: false
        }
    }, {
        header: '<img src="../../Content/img/user.png" />',
        dataIndex: 'UsersCount',
        align: 'center',
        fixed: true,
        width: 50,
        tooltip: 'Количество пользователей приложения',
        sortable: true
    }, {
        header: '<img src="../../Content/img/role.gif" />',
        dataIndex: 'RolesCount',
        align: 'center',
        fixed: true,
        width: 50,
        tooltip: 'Количество ролей приложения',
        sortable: true}]
    });
</code>```

When I use JsonStore without reader it works, but when I try to update any field it uses my 'create' url instead of 'update'.

```<code>var applicationsStore = new Ext.data.JsonStore({
    root: 'applications',
    totalProperty: 'total',
    idProperty: 'ApplicationId',
    messageProperty: 'message',
    fields: [{ name: 'ApplicationId' }, { name: 'ApplicationName', allowBlank: false }, { name: 'UsersCount', allowBlank: false }, { name: 'RolesCount', allowBlank: false}],
    id: 'app1234',
    proxy: new Ext.data.HttpProxy({
        api: {
            create: '/api/applications/getapplicationslist1',
            read: '/api/applications/getapplicationslist',
            update: '/api/applications/getapplicationslist2',
            destroy: '/api/applications/getapplicationslist3'
        }
    }),
    autoSave: true,
    autoLoad: true,
    writer: new Ext.data.JsonWriter({
        encode: false,
        listful: false,
        writeAllFields: false
    })
});
</code>```

I believe that the problem is that I don't use reader, but when I use JsonReader grid stops showing any data at all.

```<code>var applicationReader = new Ext.data.JsonReader({
    root: 'applications',
    totalProperty: 'total',
    idProperty: 'ApplicationId',
    messageProperty: 'message',
    fields: [{ name: 'ApplicationId' }, { name: 'ApplicationName', allowBlank: false }, { name: 'UsersCount', allowBlank: false }, { name: 'RolesCount', allowBlank: false}]
});

var applicationsStore = new Ext.data.JsonStore({
    id: 'app1234',
    proxy: new Ext.data.HttpProxy({
        api: {
            create: '/api/applications/getapplicationslist1',
            read: '/api/applications/getapplicationslist',
            update: '/api/applications/getapplicationslist2',
            destroy: '/api/applications/getapplicationslist3'
        }
    }),
    reader: applicationReader,
    autoSave: true,
    autoLoad: true,
    writer: new Ext.data.JsonWriter({
        encode: false,
        listful: false,
        writeAllFields: false
    })
});
</code>```

So, does anyone know what the problem might be and how to solve it. The data returned from my server is Json-formated and seams to be ok

```<code>{"message":"test","total":2,"applications":[{"ApplicationId":"f82dc920-17e7-45b5-98ab-03416fdf52b2","ApplicationName":"Archivist","UsersCount":6,"RolesCount":3},{"ApplicationId":"054e2e78-e15f-4609-a9b2-81c04aa570c8","ApplicationName":"Test","UsersCount":1,"RolesCount":0}]}
</code>```

答:
Looking at the source for Ext.data.Api I would say that the verbs are screwed up:

restActions : {
            create  : 'POST',
            read    : 'GET',
            update  : 'PUT',
            destroy : 'DELETE'
        },

For me the create should be a PUT and the update should be a POST. But I guess the Sencha guys have a different idea.
Btw, the source is taken from Ext 3.3.1

I guess you could override the restActions object to work as you would expect:

```<code>Ext.data.Api.restActions = {
create  : 'PUT',
read    : 'GET',
update  : 'POST',
destroy : 'DELETE' };
</code>```

Title: problem with JsonStore and JsonReader

Body:
In my ExtJS application I use EditorGridPanel to show data from server.

var applicationsGrid = new Ext.grid.EditorGridPanel({
    region: 'west',
    layout: 'fit',
    title: '  Приложения',
    collapsible: true,
    margins: '0 0 5 5',
    split: true,
    width: '30%',
    listeners: { 'viewready': { fn: function() { applicationsGridStatusBar.setText('Приложений: ' + applicationsStore.getTotalCount()); } } },
    store: applicationsStore,
    loadMask: { msg: 'Загрузка...' },
    sm: new Ext.grid.RowSelectionModel({
        singleSelect: true,
        listeners: { 'rowselect': { fn: applicationsGrid_onRowSelect} }
    }),
    viewConfig: { forceFit: true },
    tbar: [{
        icon: '../../Content/img/add.gif',
        text: 'Добавить'
    }, '-', {
        icon: '../../Content/img/delete.gif',
        text: 'Удалить'
    }, '-'],
    bbar: applicationsGridStatusBar,
    columns: [{
        header: 'Приложения',
        dataIndex: 'ApplicationName',
        tooltip: 'Наименование приложения',
        sortable: true,
        editor: {
            xtype: 'textfield',
            allowBlank: false
        }
    }, {
        header: '',
        dataIndex: 'UsersCount',
        align: 'center',
        fixed: true,
        width: 50,
        tooltip: 'Количество пользователей приложения',
        sortable: true
    }, {
        header: '',
        dataIndex: 'RolesCount',
        align: 'center',
        fixed: true,
        width: 50,
        tooltip: 'Количество ролей приложения',
        sortable: true}]
    });

When I use JsonStore without reader it works, but when I try to update any field it uses my 'create' url instead of 'update'.

var applicationsStore = new Ext.data.JsonStore({
    root: 'applications',
    totalProperty: 'total',
    idProperty: 'ApplicationId',
    messageProperty: 'message',
    fields: [{ name: 'ApplicationId' }, { name: 'ApplicationName', allowBlank: false }, { name: 'UsersCount', allowBlank: false }, { name: 'RolesCount', allowBlank: false}],
    id: 'app1234',
    proxy: new Ext.data.HttpProxy({
        api: {
            create: '/api/applications/getapplicationslist1',
            read: '/api/applications/getapplicationslist',
            update: '/api/applications/getapplicationslist2',
            destroy: '/api/applications/getapplicationslist3'
        }
    }),
    autoSave: true,
    autoLoad: true,
    writer: new Ext.data.JsonWriter({
        encode: false,
        listful: false,
        writeAllFields: false
    })
});

I believe that the problem is that I don't use reader, but when I use JsonReader grid stops showing any data at all.

var applicationReader = new Ext.data.JsonReader({
    root: 'applications',
    totalProperty: 'total',
    idProperty: 'ApplicationId',
    messageProperty: 'message',
    fields: [{ name: 'ApplicationId' }, { name: 'ApplicationName', allowBlank: false }, { name: 'UsersCount', allowBlank: false }, { name: 'RolesCount', allowBlank: false}]
});

var applicationsStore = new Ext.data.JsonStore({
    id: 'app1234',
    proxy: new Ext.data.HttpProxy({
        api: {
            create: '/api/applications/getapplicationslist1',
            read: '/api/applications/getapplicationslist',
            update: '/api/applications/getapplicationslist2',
            destroy: '/api/applications/getapplicationslist3'
        }
    }),
    reader: applicationReader,
    autoSave: true,
    autoLoad: true,
    writer: new Ext.data.JsonWriter({
        encode: false,
        listful: false,
        writeAllFields: false
    })
});

So, does anyone know what the problem might be and how to solve it. The data returned from my server is Json-formated and seams to be ok

{"message":"test","total":2,"applications":[{"ApplicationId":"f82dc920-17e7-45b5-98ab-03416fdf52b2","ApplicationName":"Archivist","UsersCount":6,"RolesCount":3},{"ApplicationId":"054e2e78-e15f-4609-a9b2-81c04aa570c8","ApplicationName":"Test","UsersCount":1,"RolesCount":0}]}

Body:
Looking at the source for Ext.data.Api I would say that the verbs are screwed up:

restActions : {
            create  : 'POST',
            read    : 'GET',
            update  : 'PUT',
            destroy : 'DELETE'
        },

For me the create should be a PUT and the update should be a POST. But I guess the Sencha guys have a different idea.
Btw, the source is taken from Ext 3.3.1

I guess you could override the restActions object to work as you would expect:

Ext.data.Api.restActions = {
create  : 'PUT',
read    : 'GET',
update  : 'POST',
destroy : 'DELETE' };


答:
Try this,</p>

```<code>var arr = ['tag1', 'tag2', 'tag3'];
var lastStr = arr.pop();
var str = "Content tagged " + arr.join(", ") + " and " + lastStr;
</code>```

Title: Javascript: nice human readable join of list

Body:
Try this,

var arr = ['tag1', 'tag2', 'tag3'];
var lastStr = arr.pop();
var str = "Content tagged " + arr.join(", ") + " and " + lastStr;


问:
Scatter plot a DataFrame grouped by 2 columns and having an aggregation
I am trying to do a scatter plot over the number of items in the DataFrame for each date/time combination. I've grouped data like this:

```<code>dff = pd.DataFrame(df.groupby(['date', 'time']).size().rename('count'))
</code>```

and it looks like this:

```<code>                           count
date         time
2017-05-19   15:00         1
             15:30         1
             16:00         1
             16:30         1
             17:00         1
2017-05-23   10:00         2
             10:30         2
             11:00         2
...
</code>```

Now, how can I scatter plot the counts having dates on the X axis and times on the Y axis? plt.scatter(x, y, s=area, c=colors) is the signature, but however I try to select x and y from dff, it fails to find the keys. Also, scatter expects floats on the axes, while I have strings.

答:
This requires accessing the MultiIndex values like so:

```<code># replicating sample data (foo is just dummy data for the count)
grouped = df.groupby(['date', 'time'])['foo'].count()
date        time
2015-01-01  15:00:00    1
            15:30:00    1
2015-01-02  16:00:00    2
Name: foo, dtype: int64

plt.scatter(x=grouped.index.get_level_values(0), y=grouped.index.get_level_values(1), s=[20*4**n for n in grouped.values])
plt.show()
</code>```

You'll need to play with the s argument in scatter(), here's the doc I was using for this- pyplot scatter plot marker size.

Body:
I am trying to do a scatter plot over the number of items in the DataFrame for each date/time combination. I've grouped data like this:

dff = pd.DataFrame(df.groupby(['date', 'time']).size().rename('count'))

and it looks like this:

                           count
date         time
2017-05-19   15:00         1
             15:30         1
             16:00         1
             16:30         1
             17:00         1
2017-05-23   10:00         2
             10:30         2
             11:00         2
...

Now, how can I scatter plot the counts having dates on the X axis and times on the Y axis? plt.scatter(x, y, s=area, c=colors) is the signature, but however I try to select x and y from dff, it fails to find the keys. Also, scatter expects floats on the axes, while I have strings.

Body:
This requires accessing the MultiIndex values like so:

# replicating sample data (foo is just dummy data for the count)
grouped = df.groupby(['date', 'time'])['foo'].count()
date        time
2015-01-01  15:00:00    1
            15:30:00    1
2015-01-02  16:00:00    2
Name: foo, dtype: int64

plt.scatter(x=grouped.index.get_level_values(0), y=grouped.index.get_level_values(1), s=[20*4**n for n in grouped.values])
plt.show()

You'll need to play with the s argument in scatter(), here's the doc I was using for this- pyplot scatter plot marker size.


问:
D3 - get number of dimensions in radial chart
This is probably a basic selector in D3, but can't find it. I just want to get the count of the number of dimensions (rings) in this radial chart.

http://blockbuilder.org/anonymous/1b5e5b56c33ef5c8840160da3e403105

Counting from the inner most blue ring/circle to the outermost ring (e.g. NodeLinkTreeLayout) the count is 5.

What d3 query or property can I use to get this number?

答:
For counting the number of layers, or rings as you called them, you just need to find the depth property with the highest value in the data array:

```<code>var rings = d3.max(partition.nodes(root), function(d){
    return d.depth
}) + 1;
console.log("the number of rings is " + rings)
</code>```

Since depth is zero-based, I'm adding 1 to the maximum value.

Have a look at the console in the updated blockbuilder: http://blockbuilder.org/anonymous/9ac9d8a21f366202f077393b67239cc3

Body:
For counting the number of layers, or rings as you called them, you just need to find the depth property with the highest value in the data array:

var rings = d3.max(partition.nodes(root), function(d){
    return d.depth
}) + 1;
console.log("the number of rings is " + rings)

Since depth is zero-based, I'm adding 1 to the maximum value.

Have a look at the console in the updated blockbuilder: http://blockbuilder.org/anonymous/9ac9d8a21f366202f077393b67239cc3


问:
Reading Avro messages from Kafka with Spark 2.0.2 (structured streaming)
I have a spark 2.0 application that reads messages from kafka using spark streaming (with spark-streaming-kafka-0-10_2.11).

Structured streaming looks really cool so I wanted to try and migrate the code but I can't figure out how to use it.

in the regular streaming I used kafkaUtils to createDstrean and in the parameters I passed it was the value deserializer.

in the Structured streaming the doc says that I should deserialize using DataFrame functions but I can't figure exactly what that means.

I looked at examples such as this example but my Avro object in Kafka is quit complex and cannot be simply casted like the String in the example..

So far I tried this kind of code (which I saw here in a different question):

```<code>import spark.implicits._

  val ds1 = spark.readStream.format("kafka").
    option("kafka.bootstrap.servers","localhost:9092").
    option("subscribe","RED-test-tal4").load()

  ds1.printSchema()
  ds1.select("value").printSchema()
  val ds2 = ds1.select($"value".cast(getDfSchemaFromAvroSchema(Obj.getClassSchema))).show()
  val query = ds2.writeStream
    .outputMode("append")
    .format("console")
    .start()
</code>```

and I get "data type mismatch: cannot cast BinaryType to StructType(StructField(...."

how can I deserialize the value?

答:
Use the following steps:

Define a Kafka message.

Define a consumer Utility, which returns a DataSet of YourAvroObject.

Define your logical code.

Kafka Message:

```<code>case class KafkaMessage(key: String, value: Array[Byte],
                                    topic: String, partition: String, offset: Long, timestamp: Timestamp)
</code>```

Kafka Consumer:

```<code>import java.util.Collections

import com.typesafe.config.{Config, ConfigFactory}
import io.confluent.kafka.serializers.KafkaAvroDeserializer
import org.apache.avro.Schema
import org.apache.avro.generic.GenericRecord
import org.apache.spark.sql.SparkSession

import scala.reflect.runtime.universe._

object KafkaAvroConsumer {

  private val conf: Config = ConfigFactory.load().getConfig("kafka.consumer")
  val valueDeserializer = new KafkaAvroDeserializer()
  valueDeserializer.configure(Collections.singletonMap("schema.registry.url",
    conf.getString("schema.registry.url")), false)

  def transform[T <: GenericRecord : TypeTag](msg: KafkaMessage, schemaStr: String) = {
    val schema = new Schema.Parser().parse(schemaStr)
    Utils.convert[T](schema)(valueDeserializer.deserialize(msg.topic, msg.value))
  }

  def createDataStream[T <: GenericRecord with Product with Serializable : TypeTag]
  (schemaStr: String)
  (subscribeType: String, topics: String, appName: String, startingOffsets: String = "latest") = {

    val spark = SparkSession
      .builder
      .master("local[*]")
      .appName(appName)
      .getOrCreate()

    import spark.implicits._

    // Create DataSet representing the stream of KafkaMessage from kafka
    val ds = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", conf.getString("bootstrap.servers"))
      .option(subscribeType, topics)
      .option("startingOffsets", "earliest")
      .load()
      .as[KafkaMessage]
      .map(msg => KafkaAvroConsumer.transform[T](msg, schemaStr)) // Transform it Avro object.

    ds
  }

}
</code>```

Update

Utils:

```<code>import org.apache.avro.Schema
import org.apache.avro.file.DataFileReader
import org.apache.avro.generic.{GenericDatumReader, GenericRecord}
import org.apache.avro.specific.SpecificData

import scala.reflect.runtime.universe._

object Utils {

  def convert[T <: GenericRecord: TypeTag](targetSchema: Schema)(record: AnyRef): T = {
      SpecificData.get.deepCopy(targetSchema, record).asInstanceOf[T]
  }

}
</code>```

Body:
I have a spark 2.0 application that reads messages from kafka using spark streaming (with spark-streaming-kafka-0-10_2.11).

Structured streaming looks really cool so I wanted to try and migrate the code but I can't figure out how to use it.

in the regular streaming I used kafkaUtils to createDstrean and in the parameters I passed it was the value deserializer.

in the Structured streaming the doc says that I should deserialize using DataFrame functions but I can't figure exactly what that means.

I looked at examples such as this example but my Avro object in Kafka is quit complex and cannot be simply casted like the String in the example..

So far I tried this kind of code (which I saw here in a different question):

import spark.implicits._

  val ds1 = spark.readStream.format("kafka").
    option("kafka.bootstrap.servers","localhost:9092").
    option("subscribe","RED-test-tal4").load()

  ds1.printSchema()
  ds1.select("value").printSchema()
  val ds2 = ds1.select($"value".cast(getDfSchemaFromAvroSchema(Obj.getClassSchema))).show()
  val query = ds2.writeStream
    .outputMode("append")
    .format("console")
    .start()

and I get "data type mismatch: cannot cast BinaryType to StructType(StructField(...."

how can I deserialize the value?

Body:
Use the following steps:

Define a Kafka message.

Define a consumer Utility, which returns a DataSet of YourAvroObject.

Define your logical code.

Kafka Message:

case class KafkaMessage(key: String, value: Array[Byte],
                                    topic: String, partition: String, offset: Long, timestamp: Timestamp)

Kafka Consumer:

import java.util.Collections

import com.typesafe.config.{Config, ConfigFactory}
import io.confluent.kafka.serializers.KafkaAvroDeserializer
import org.apache.avro.Schema
import org.apache.avro.generic.GenericRecord
import org.apache.spark.sql.SparkSession

import scala.reflect.runtime.universe._

object KafkaAvroConsumer {

  private val conf: Config = ConfigFactory.load().getConfig("kafka.consumer")
  val valueDeserializer = new KafkaAvroDeserializer()
  valueDeserializer.configure(Collections.singletonMap("schema.registry.url",
    conf.getString("schema.registry.url")), false)

  def transform[T <: GenericRecord : TypeTag](msg: KafkaMessage, schemaStr: String) = {
    val schema = new Schema.Parser().parse(schemaStr)
    Utils.convert[T](schema)(valueDeserializer.deserialize(msg.topic, msg.value))
  }

  def createDataStream[T <: GenericRecord with Product with Serializable : TypeTag]
  (schemaStr: String)
  (subscribeType: String, topics: String, appName: String, startingOffsets: String = "latest") = {

    val spark = SparkSession
      .builder
      .master("local[*]")
      .appName(appName)
      .getOrCreate()

    import spark.implicits._

    // Create DataSet representing the stream of KafkaMessage from kafka
    val ds = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", conf.getString("bootstrap.servers"))
      .option(subscribeType, topics)
      .option("startingOffsets", "earliest")
      .load()
      .as[KafkaMessage]
      .map(msg => KafkaAvroConsumer.transform[T](msg, schemaStr)) // Transform it Avro object.

    ds
  }

}

Update

Utils:

import org.apache.avro.Schema
import org.apache.avro.file.DataFileReader
import org.apache.avro.generic.{GenericDatumReader, GenericRecord}
import org.apache.avro.specific.SpecificData

import scala.reflect.runtime.universe._

object Utils {

  def convert[T <: GenericRecord: TypeTag](targetSchema: Schema)(record: AnyRef): T = {
      SpecificData.get.deepCopy(targetSchema, record).asInstanceOf[T]
  }

}


问:
Unable to take username and password in Twitter account using Selenium
I am using below code to login in twitter</p>

```<code>    driver.get("https://twitter.com/login/");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input")).sendKeys("viaxpath");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input")).sendKeys("viaxpath");
</code>```

答:
Here is the Answer to your Question:

You can consider constructing an xpath which uniquely identifies the username and password fields and can be easily traverse-able by Selenium. Here is your own code with some simple tweaks which works at my end:

```<code>WebDriver driver =  new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://twitter.com/login/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//div[@class='clearfix field']/input[@name='session[username_or_email]']")).sendKeys("id@domain.com");
driver.findElement(By.xpath("//div[@class='clearfix field']/input[@name='session[password]']")).sendKeys("password");
</code>```

Let me know if this Answers your Question.

Body:
I am using below code to login in twitter

    driver.get("https://twitter.com/login/");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input")).sendKeys("viaxpath");
    driver.findElement(By.xpath("//*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input")).sendKeys("viaxpath");

Body:
Here is the Answer to your Question:

You can consider constructing an xpath which uniquely identifies the username and password fields and can be easily traverse-able by Selenium. Here is your own code with some simple tweaks which works at my end:

WebDriver driver =  new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://twitter.com/login/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//div[@class='clearfix field']/input[@name='session[username_or_email]']")).sendKeys("id@domain.com");
driver.findElement(By.xpath("//div[@class='clearfix field']/input[@name='session[password]']")).sendKeys("password");

Let me know if this Answers your Question.


问:
How do I best create a button with a left aligned icon and the text centered in the remaining area
I need to have a button that looks like this:

Right now I went for a view with two buttons inside it. But the problem with that is that I can either hook up the two individual buttons to the same outlet, or add a UITapGestureRecognizer to the container view.

I went with the second option because I thought it would be cleaner, but that only works when I disable the buttons (and therefore disable the press-down animation).

Am I on the right track, and should I just find a way to trigger the button's animation when the UITapGestureRecognizer calls my method? Or is there a better way to do this?

答:
You want to use a single UIButton and adjust the imageEdgeInsets & titleEdgeInsets.

For a Swift example:

```<code>extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}
</code>```

Body:
You want to use a single UIButton and adjust the imageEdgeInsets & titleEdgeInsets.

For a Swift example:

extension UIButton {
    func centerTextAndImage(spacing: CGFloat) {
        let insetAmount = spacing / 2
        imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
        titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
        contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
    }
}