问:
Check if android device rotation possible
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

```<code>if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}
</code>```

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

答:
You can check availability of sensor. here is official docs

```<code>PackageManager manager = getPackageManager();
boolean hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);
</code>```

Role of Accelerometer

The accelerometer is a built-in electronic component that measures
  tilt and motion. It is also capable of detecting rotation and motion
  gestures such as swinging or shaking.

The most common use for it is to activate auto screen rotation on
  mobile devices when the user changes their orientation from portrait
  to landscape or vice-versa.

Body:
I want to know if the android device supports device rotation.
I thought any Android device supports the screen rotation but my Samsung Galaxy View doesn't support any rotation.

I only found this code:

if (android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
    Toast.makeText(getApplicationContext(), "Auto Rotate is ON", Toast.LENGTH_SHORT).show();

} else {
    Toast.makeText(getApplicationContext(), "Auto Rotate is OFF", Toast.LENGTH_SHORT).show();
}

But this only lets me know if the user set the Screen rotation off or on, I want to know if it is at all possible.

Please help me,
best wishes

Leo

Body:
You can check availability of sensor. here is official docs

PackageManager manager = getPackageManager();
boolean hasAccelerometer = manager.hasSystemFeature(PackageManager.FEATURE_SENSOR_ACCELEROMETER);

Role of Accelerometer

The accelerometer is a built-in electronic component that measures
  tilt and motion. It is also capable of detecting rotation and motion
  gestures such as swinging or shaking.

The most common use for it is to activate auto screen rotation on
  mobile devices when the user changes their orientation from portrait
  to landscape or vice-versa.


来源: stackexchange

问:
"Debug assertion failed" What's wrong with this sort? It should sort by year a dynamic list with movie objects
```<code>Debug Assertion Failed!

Program C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: c: program files (x86)\microsoft visual studio 14.0\vc\include\algorithm
Line: 2783

Expression: invalid iterator range
</code>```

<p>What's wrong with this sort? It should sort by year a dynamic list with movie objects. </p>

```<code>bool cmp(Movie &m1, Movie &m2) {
return m1.getYear() - m2.getYear() < 0;
}
void Controller::sortByYear() {
std::sort(this->repo.getMovies().getAllElems(), this->repo.getMovies().getAllElems() + this->repo.getMovies().getSize(), cmp);
}
</code>```

答:
This line from Repository.h is your problem:

```<code>DynamicVector getMovies() const { return movies; }
</code>```

You're returning a DynamicVector by value, instead of by reference, which means you're making a copy of the vector.

As a result, when the compiler hits

```<code>std::sort(
    this->repo.getMovies().getAllElems(),
    this->repo.getMovies().getAllElems() + this->repo.getMovies().getSize(),
    cmp);
</code>```

It gets compiled as, "Make a copy of movies and pass a pointer to the beginning of that copy. Make a second copy of movies and pass a pointer to the end of that copy. Then sort from the beginning of one copy to the end of the other copy." This results in an assertion.

Typical C++ style would instead do something like

```<code>DynamicVector& getMovies() { return movies; }
const DynamicVector& getMovies() const { return movies; }
</code>```

I.e., provide both const and non-const access to the vector.

ContentLicense: CC BY-SA 3.0

Body:
Debug Assertion Failed!

Program C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: c: program files (x86)\microsoft visual studio 14.0\vc\include\algorithm
Line: 2783

Expression: invalid iterator range

What's wrong with this sort? It should sort by year a dynamic list with movie objects.

bool cmp(Movie &m1, Movie &m2) {
return m1.getYear() - m2.getYear() < 0;
}
void Controller::sortByYear() {
std::sort(this->repo.getMovies().getAllElems(), this->repo.getMovies().getAllElems() + this->repo.getMovies().getSize(), cmp);
}

Body:
This line from Repository.h is your problem:

DynamicVector getMovies() const { return movies; }

You're returning a DynamicVector by value, instead of by reference, which means you're making a copy of the vector.

As a result, when the compiler hits

std::sort(
    this->repo.getMovies().getAllElems(),
    this->repo.getMovies().getAllElems() + this->repo.getMovies().getSize(),
    cmp);

It gets compiled as, "Make a copy of movies and pass a pointer to the beginning of that copy. Make a second copy of movies and pass a pointer to the end of that copy. Then sort from the beginning of one copy to the end of the other copy." This results in an assertion.

Typical C++ style would instead do something like

DynamicVector& getMovies() { return movies; }
const DynamicVector& getMovies() const { return movies; }

I.e., provide both const and non-const access to the vector.


问:
Check if image source is equal to an image
My current code exists as:

```<code><img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">
<script>
    function pictureChange(){
        if(fixedScreenimg.src == "img/homeScreen.png"){
            document.getElementById("fixedScreenimg").src="img/fixedScreen.jpg");
        }else{
            document.getElementByID("fixedScreenimg").src="img/homeScreen.png");
        }
    }
</script>
</code>```

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

答:
Try with single line if condition

```<code>function pictureChange() {
  var elem = document.getElementById("fixedScreenimg");

  elem.src = (elem.src == "img/homeScreen.png") ? "img/fixedScreen.jpg" : "img/homeScreen.png";
}
</code>```

```

Body:
My current code exists as:

As  you can see, I'm attempting to check whether the image source of an element matches a given path to an image, and if so, change the result of the image changing when a button is pressed. However, this doesn't seem to work.

I've attempted to use getAttribute and the like.

Any pointers?

Thanks.

Body:
Try with single line if condition

function pictureChange() {
  var elem = document.getElementById("fixedScreenimg");

  elem.src = (elem.src == "img/homeScreen.png") ? "img/fixedScreen.jpg" : "img/homeScreen.png";
}

<img id="fixedScreenimg" src="img/fixedScreen.jpg" class="img-responsive" alt="">


问:
how to print same value as entered in above textbox
The user is asked to enter his/her name and the same name should be displayed in the username asked below by default.
I have tried this code, but it doesn't help me out!

```<code><tr>
        <td class="TrackMediumBlue" align="right" width="138">Manager  Name   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">                </td>
      </tr>
      <tr>
        <td class="TrackMediumBlue" align="right" width="138">UserName   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName" type="TEXT" value="<?php echo ManagerName ?>" size="40"  maxlength="100">                </td>
      </tr>
</code>```

Please help me out!

答:
```<code><script>
document.getElementById('ManagerName').addEventListener('blur', function() {
    document.getElementById('ManagerName2').value = this.value;
});
</script>
<tr>
        <td class="TrackMediumBlue" align="right" width="138">Manager  Name   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">                </td>
      </tr>
      <tr>
        <td class="TrackMediumBlue" align="right" width="138">UserName   :</td>
        <td width="13"> </td>
        <td width="477">
        <input name="ManagerName2" type="TEXT" value="" size="40"  maxlength="100">                </td>
      </tr>
</code>```

Body:
The user is asked to enter his/her name and the same name should be displayed in the username asked below by default.
I have tried this code, but it doesn't help me out!

        Manager  Name   :

        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">

        UserName   :

        <input name="ManagerName" type="TEXT" value="<?php echo ManagerName ?>" size="40"  maxlength="100">

Please help me out!

Body:
<script>
document.getElementById('ManagerName').addEventListener('blur', function() {
    document.getElementById('ManagerName2').value = this.value;
});
</script>
<tr>
        <td class="TrackMediumBlue" align="right" width="138">Manager  Name   :</td>
        <td width="13">&nbsp;</td>
        <td width="477">
        <input name="ManagerName" type="TEXT" id="ManagerName" size="40"  maxlength="100">                </td>
      </tr>
      <tr>
        <td class="TrackMediumBlue" align="right" width="138">UserName   :</td>
        <td width="13">&nbsp;</td>
        <td width="477">
        <input name="ManagerName2" type="TEXT" value="" size="40"  maxlength="100">                </td>
      </tr>


问:
How to put hyperlink in jquery datatables plugin in codeigniter
I am using DataTables to generate a table. There is a column containing username

For example: ...

I need every row in this column to have a hyperlink when anyone clicks on username then it redirects to edit page, For example, the first row would be a hyperlink to view?id=1321755 etc.

What is the simplest way I can do so?

Here is my code of view:

```<code><table id="book-table" class="table table-bordered table-striped table-hover">
     <thead>
     <tr class="">
      <th>Name</th>
      <th>Date</th>
      <th>Work</th>
      <th>Partner</th>
      <th>Director</th>
      <th>Time</th>
      <th>Task</th>
      <th>Status</th>
    </tr>
     </thead>
     <tbody>
     </tbody>
     </table>

<script type="text/javascript">
$(document).ready(function() {
    $('#book-table').DataTable({
        "ajax": {
            url : "<?php echo site_url("digital_admin/hodm/books_page") ?>",
            type : 'GET'
        },
    });
});
</script>
</code>```

Here is my controller code:

```<code>public function books_page()
     {

          // Datatables Variables
          $draw = intval($this->input->get("draw"));
          $start = intval($this->input->get("start"));
          $length = intval($this->input->get("length"));

          $books = $this->pojo->get_books();

          $data = array();

          foreach($books->result() as $r) {

               $data[] = array(
                    $r->user_name,
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
          }

          $output = array(
               "draw" => $draw,
                 "recordsTotal" => $books->num_rows(),
                 "recordsFiltered" => $books->num_rows(),
                 "data" => $data
            );
          echo json_encode($output);
          exit();
     }
</code>```

Kindly help me to find the answer

答:
@Michael Thanx for the help.

Here is the final code which is working.

```<code>$data[] = array(
                    '<a href="edit_hodm/'.$r->id.'" >'. $r->user_name .'</a>',
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
</code>```

Body:
I am using DataTables to generate a table. There is a column containing username

For example: ...

I need every row in this column to have a hyperlink when anyone clicks on username then it redirects to edit page, For example, the first row would be a hyperlink to view?id=1321755 etc.

What is the simplest way I can do so?

Here is my code of view:

      Name
      Date
      Work
      Partner
      Director
      Time
      Task
      Status

Here is my controller code:

public function books_page()
     {

          // Datatables Variables
          $draw = intval($this->input->get("draw"));
          $start = intval($this->input->get("start"));
          $length = intval($this->input->get("length"));

          $books = $this->pojo->get_books();

          $data = array();

          foreach($books->result() as $r) {

               $data[] = array(
                    $r->user_name,
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );
          }

          $output = array(
               "draw" => $draw,
                 "recordsTotal" => $books->num_rows(),
                 "recordsFiltered" => $books->num_rows(),
                 "data" => $data
            );
          echo json_encode($output);
          exit();
     }

Kindly help me to find the answer

Body:
@Michael Thanx for the help.

Here is the final code which is working.

$data[] = array(
                    '<a href="edit_hodm/'.$r->id.'" >'. $r->user_name .'</a>',
                    $r->date,
                    $r->t_name,
                    $r->partner,
                    $r->director,
                    $r->duration,
                    $r->task,
                    $r->status
               );


问:
Entity framework 6 mocking include method on dbset
Have been googling for a solution to the problem on how to mock the include method on dbset in EF6.
The problem is well documented here :-

http://entityframework.codeplex.com/discussions/461731

Unfortunately though there does not seem to be a valid solution in there.

Has anyone found a workaround to this?

I do understand that we shouldn't really be mocking the EF6 context, but the project lead has insisted on it.

Thanks in advance.

答:
using Moq framework this method works with everything I throw at it.

```<code>    public static Mock<DbSet<T>> GetMockSet<T>(this ObservableCollection<T> list) where T : class
    {
        var queryable = list.AsQueryable();
        var mockList = new Mock<DbSet<T>>(MockBehavior.Loose);

        mockList.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
        mockList.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
        mockList.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        mockList.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockList.Setup(m => m.Include(It.IsAny<string>())).Returns(mockList.Object);
        mockList.Setup(m => m.Local).Returns(list);
        mockList.Setup(m => m.Add(It.IsAny<T>())).Returns((T a) => { list.Add(a); return a; });
        mockList.Setup(m => m.AddRange(It.IsAny<IEnumerable<T>>())).Returns((IEnumerable<T> a) => { foreach (var item in a.ToArray()) list.Add(item); return a; });
        mockList.Setup(m => m.Remove(It.IsAny<T>())).Returns((T a) => { list.Remove(a); return a; });
        mockList.Setup(m => m.RemoveRange(It.IsAny<IEnumerable<T>>())).Returns((IEnumerable<T> a) => { foreach (var item in a.ToArray()) list.Remove(item); return a; });

        return mockList;
    }
</code>```

to use it just do:

```<code>    mockContext.Setup(p => p.<DbSetToMock>).Returns(<observableCollection to use as data>.GetMockSet().Object);`
</code>```

This works grate if the context implements a Interface as you never have to do anything with EF.

EDIT:

The reason for the extra bits is we can check the result on the test, if we add or remove we can check the passed collection and it will have the result after the test.

Body:
using Moq framework this method works with everything I throw at it.

    public static Mock<DbSet<T>> GetMockSet<T>(this ObservableCollection<T> list) where T : class
    {
        var queryable = list.AsQueryable();
        var mockList = new Mock<DbSet<T>>(MockBehavior.Loose);

        mockList.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
        mockList.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
        mockList.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
        mockList.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryable.GetEnumerator());
        mockList.Setup(m => m.Include(It.IsAny<string>())).Returns(mockList.Object);
        mockList.Setup(m => m.Local).Returns(list);
        mockList.Setup(m => m.Add(It.IsAny<T>())).Returns((T a) => { list.Add(a); return a; });
        mockList.Setup(m => m.AddRange(It.IsAny<IEnumerable<T>>())).Returns((IEnumerable<T> a) => { foreach (var item in a.ToArray()) list.Add(item); return a; });
        mockList.Setup(m => m.Remove(It.IsAny<T>())).Returns((T a) => { list.Remove(a); return a; });
        mockList.Setup(m => m.RemoveRange(It.IsAny<IEnumerable<T>>())).Returns((IEnumerable<T> a) => { foreach (var item in a.ToArray()) list.Remove(item); return a; });

        return mockList;
    }

to use it just do:

    mockContext.Setup(p => p.<DbSetToMock>).Returns(<observableCollection to use as data>.GetMockSet().Object);`

This works grate if the context implements a Interface as you never have to do anything with EF.

EDIT:

The reason for the extra bits is we can check the result on the test, if we add or remove we can check the passed collection and it will have the result after the test.


问:
How to go back to Previous Activity?
Someone ask me a question a week ago and till now i did not get the answer of that question.The question was how we can go back to previous Activity by pressing back button of device without using intent or finish(). </p>

答:
There is no need to do any code for return to  previous activity by on pressing back button of device, android system maintain stack for activity and do that job for you.

If you want add back button in action bar then do it.

Add below code in onCreate method

```<code>getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
</code>```

And in Menifest.xml file inside your activity add below code

```<code><meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
</code>```

In android:value add your parent activity to which you want to redirect.

For more reference visit below link...

https://developer.android.com/training/implementing-navigation/ancestral.html

Title: How to go back to Previous Activity?

Body:
There is no need to do any code for return to  previous activity by on pressing back button of device, android system maintain stack for activity and do that job for you.

If you want add back button in action bar then do it.

Add below code in onCreate method

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

And in Menifest.xml file inside your activity add below code

<meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />

In android:value add your parent activity to which you want to redirect.

For more reference visit below link...

https://developer.android.com/training/implementing-navigation/ancestral.html


问:
How do I use jQuery ajax request for footable v3 - from a webservice?
I'm not sure why, but the footable docs only show a method of getting data from a file, but not from a webservice, so i tried all sorts of combinations for getting data returned, in json format, into the footable instance, but no luck.
Their example shows the following:

```<code>$('.table').footable({
    "rows": $.get('rows.json')
});
</code>```

(presuming the columns are already defined) and this works.
However, in my ajax query, I tried

```<code>$('.table').footable({
    "rows": data.d
});
</code>```

and no errors happen, the data is in the correct format (verified with an online JSON schema checker), but nothing happens (no errors in the console).

The ajax query i tested thoroughly (works, and I can even parse the data.d returned), so I'm lost as how to proceed.

```<code>$.ajax({
    type: "POST",
    url: "/Search.asmx/GetListingsByPageSort",
    data: '{"sp":' + JSON.stringify(sp) + '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $('.table').footable({
            "rows": data.d
        });
    },
    error: function (xhr, status) {
        alert("fail: " + status);
    }
});
</code>```

The HTML is

```<code>    <table class="table" data-paging="true">
<thead>
        <tr>
            <th class="hdrcolVdr" data-class="expand" data-type="html" data-name="vendor">Vendor </th>
            <th class="hdrcolMan" data-breakpoints="xs sm" data-type="html" data-name="manufacturer">Manufacturer </th>
            <th class="hdrcolProd" data-breakpoints="xs sm md" data-type="html" data-name="product_name">Product </th>
            <th class="hdrcolPrice" data-breakpoints="xs" data-type="html" data-name="price">Price </th>
            <th class="hdrcolI" data-breakpoints="xs sm" data-type="html">Info </th>
        </tr>
    </thead>
    </table>
</code>```

Stumped.

答:
I've found (after hard work) that the problem comes from the asynch way of gatting the response from the GET/POST.
In my code this works:

rows : $.get('js/rw1.json')

but this didn't work:

rows : $.get("rest.php")

Even if they both gave the same values (seen tracking the net traffic).

I've solved forcing jQuery in synchronous mode so it waits for the response of the GET. Probably not a nice solution but it works. This is my code :

rows : ajaxRows();

where ajaxRows is:

```<code>function ajaxRows(){
    var retu;
    jQuery.ajaxSetup({async:false});
    retu = $.get("rest.php");
    jQuery.ajaxSetup({async:true});
    return retu;
}
</code>```

In your code maybe you should add to the $.ajax params:

async:false

HTH

Marco

Body:
I'm not sure why, but the footable docs only show a method of getting data from a file, but not from a webservice, so i tried all sorts of combinations for getting data returned, in json format, into the footable instance, but no luck.
Their example shows the following:

$('.table').footable({
    "rows": $.get('rows.json')
});

(presuming the columns are already defined) and this works.
However, in my ajax query, I tried

$('.table').footable({
    "rows": data.d
});

and no errors happen, the data is in the correct format (verified with an online JSON schema checker), but nothing happens (no errors in the console).

The ajax query i tested thoroughly (works, and I can even parse the data.d returned), so I'm lost as how to proceed.

$.ajax({
    type: "POST",
    url: "/Search.asmx/GetListingsByPageSort",
    data: '{"sp":' + JSON.stringify(sp) + '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $('.table').footable({
            "rows": data.d
        });
    },
    error: function (xhr, status) {
        alert("fail: " + status);
    }
});

The HTML is

            Vendor
            Manufacturer
            Product
            Price
            Info

Stumped.

Body:
I've found (after hard work) that the problem comes from the asynch way of gatting the response from the GET/POST.
In my code this works:

rows : $.get('js/rw1.json')

but this didn't work:

rows : $.get("rest.php")

Even if they both gave the same values (seen tracking the net traffic).

I've solved forcing jQuery in synchronous mode so it waits for the response of the GET. Probably not a nice solution but it works. This is my code :

rows : ajaxRows();

where ajaxRows is:

function ajaxRows(){
    var retu;
    jQuery.ajaxSetup({async:false});
    retu = $.get("rest.php");
    jQuery.ajaxSetup({async:true});
    return retu;
}

In your code maybe you should add to the $.ajax params:

async:false

HTH

Marco


问:
File operations in Jenkins Pipeline
I have a pipeline flow defined as:

```<code>node("linux_label") {
    println("hostname".execute().txt)
    def filename = "${WORKSPACE}/submoduleinfo.txt"
    stage("Submodule info") {
        def submoduleString = sh script: "git -C ${WORKSPACE} submodule status > ${filename}", returnStdout: true
    }
    String fileContents = new File("$filename}").text
    operateOnFile(fileContents)
}
</code>```

At "new File" I will get an error saying no such file exists. after some troublehshooting I see that the hostname printout will output the jenkins master and not the node "linux_label" where the workspace resides.

Is this how Piepeline should work, i.e. all code that is not part of stage/steps/etc are executed on the jenkins master and not on the wanted node?

What would be a good workaround where I do an operation in one stage and want to operate on the file in the node {} domain?

答:
That is how pipeline works.   You can use readFile to read file from a workspace.  Since you are using just a content of the file for your processing, this will work.

From tutorial:

readFile step loads a text file from the workspace and returns its
  content (do not try to use java.io.File methods — these will refer to
  files on the master where Jenkins is running, not in the current
  workspace).

In one of our use case, we added some additional functions using Shared pipeline library.

Title: File operations in Jenkins Pipeline

Body:
I have a pipeline flow defined as:

node("linux_label") {
    println("hostname".execute().txt)
    def filename = "${WORKSPACE}/submoduleinfo.txt"
    stage("Submodule info") {
        def submoduleString = sh script: "git -C ${WORKSPACE} submodule status > ${filename}", returnStdout: true
    }
    String fileContents = new File("$filename}").text
    operateOnFile(fileContents)
}

At "new File" I will get an error saying no such file exists. after some troublehshooting I see that the hostname printout will output the jenkins master and not the node "linux_label" where the workspace resides.

Is this how Piepeline should work, i.e. all code that is not part of stage/steps/etc are executed on the jenkins master and not on the wanted node?

What would be a good workaround where I do an operation in one stage and want to operate on the file in the node {} domain?


问:
Fetching JSON and iterating through the values in react-native
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

```<code>import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);
</code>```

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

```<code>renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
</code>```

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

```<code>{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}
</code>```

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

```<code>fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }
</code>```

console.log(responseData) shows:

```<code>03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }
</code>```

console.log(this.state.results.movies);

```<code>03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]
</code>```

答:
responseData has to be an array for the Array#map() method to be available as a method on it.

You are setting results to an object containing the value of your responseData:

```<code>this.setState({
  results : { responseData } // Object literal notation albeit possibly incorrect depending on the value of responseData
});
</code>```

Remove surrounding braces if you are sure responseData is an array:

```<code>this.setState({
  results :  JSON.parse(responseData);
  // You'll want to parse your JSON data here too :)
  // If responseData is an array, you'll be able to call .map on it
});

// this.state.results.movies.map should now work
// (given the structure of the expected JSON)
</code>```

Body:
I'm new to react native, and I'm trying to simply iterate through a sample json file but am receiving the error undefined is not a function (evaluating 'this.state.results.map')

I have set the state initially to be an object, so not sure why i am receiving this error.

Here is the JS:

import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View, StyleSheet, TouchableHighlight } from 'react-native';

var REQUEST_URL = 'https://facebook.github.io/react-native/movies.json';

class WPReact extends Component {
  constructor(props) {
    super(props);
    this.state = {results: []};
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          results : { responseData }
        });
      })
      .done();
  }
  render() {
    return this.renderJSON();
  }
  renderJSON() {
    contents = this.state.results.map((item) => {
      <View key={item.movies.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.movies.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }
}

var Dimensions = require('Dimensions');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  textContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 30,
    textAlign: 'center',
    margin: 10,
  },
  text: {
    fontSize: 18,
    paddingLeft: 20,
    paddingRight: 20,
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// App registration and rendering
AppRegistry.registerComponent('AwesomeProject', () => WPReact);

EDIT

So i have edited the renderJSON() to and also removed the braces of responseData as you said, as it was already an object:

renderJSON() {

    console.log(this.state.results.description);
    contents = this.state.results.movies.map((item) => {
      <View key={item.title} style={ styles.container }>
        <Text style={styles.title}>
          {item.title}
        </Text>
      </View>
     });
    return (
      <View style={styles.container}>
        {contents}
      </View>
    );
  }

I added a console log to see if i can output some of the data, and i can see the description. The sample JSON i am using is (demo from react):

{
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

I can log the description and title. But I am still receiving: ReactNativeJS: undefined is not an object (evaluating 'this.state.results.movies.map')

And if I try logging console.log(this.state.results.movies[0].title) I am receiving undefined is not an object (evaluating 'this.state.results.movies[0]')

fetchData() {
    fetch(REQUEST_URL)
      .then((response) => response.json())
      .then((responseData) => {
        console.log(responseData);
        this.setState({
          results : responseData
        });
      })
      .done();
  }

console.log(responseData) shows:

03-29 13:49:53.028  3062  4143 I ReactNativeJS: { title: 'The Basics - Networking',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   description: 'Your app fetched this from a remote endpoint!',
03-29 13:49:53.028  3062  4143 I ReactNativeJS:   movies:
03-29 13:49:53.028  3062  4143 I ReactNativeJS:    [ { title: 'Star Wars', releaseYear: '1977' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Back to the Future', releaseYear: '1985' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'The Matrix', releaseYear: '1999' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Inception', releaseYear: '2010' },
03-29 13:49:53.028  3062  4143 I ReactNativeJS:      { title: 'Interstellar', releaseYear: '2014' } ] }

console.log(this.state.results.movies);

03-29 14:18:05.483  3062  4726 I ReactNativeJS: undefined
03-29 14:18:05.510  3062  4726 I ReactNativeJS: [ { title: 'Star Wars', releaseYear: '1977' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Back to the Future', releaseYear: '1985' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'The Matrix', releaseYear: '1999' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Inception', releaseYear: '2010' },
03-29 14:18:05.510  3062  4726 I ReactNativeJS:   { title: 'Interstellar', releaseYear: '2014' } ]

Body:
responseData has to be an array for the Array#map() method to be available as a method on it.

You are setting results to an object containing the value of your responseData:

this.setState({
  results : { responseData } // Object literal notation albeit possibly incorrect depending on the value of responseData
});

Remove surrounding braces if you are sure responseData is an array:

this.setState({
  results :  JSON.parse(responseData);
  // You'll want to parse your JSON data here too :)
  // If responseData is an array, you'll be able to call .map on it
});

// this.state.results.movies.map should now work
// (given the structure of the expected JSON)


问:
How to change image when checkbox checked
i have this floating image called back in my service
MyService.java

```<code>    back = new ImageView(this);
    back.setBackgroundResource(R.drawable.quick_launch_pressed_pink);
    back.setImageResource(R.drawable.back);
</code>```

i want to change the ImageResource by calling MyService on another class, but my application force closed. here is my code on MainActivity.java

```<code>    public void addListenerOnCb() {

    chb = (CheckBox) findViewById(R.id.cb);
    final MyService ms = new MyService();
    chb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkIos checked?
            if (((CheckBox) v).isChecked()) {
                ms.back.setImageResource(R.drawable.home);
            }

        }
    });

}
</code>```

答:
use this for CheckBox</p>

```<code>    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            if(b)
                           {
              // do something
                            }
                            else
                             {
                          // do another something
                               }
                        }
                    });
</code>```

Body:
i have this floating image called back in my service
MyService.java

    back = new ImageView(this);
    back.setBackgroundResource(R.drawable.quick_launch_pressed_pink);
    back.setImageResource(R.drawable.back);

i want to change the ImageResource by calling MyService on another class, but my application force closed. here is my code on MainActivity.java

    public void addListenerOnCb() {

    chb = (CheckBox) findViewById(R.id.cb);
    final MyService ms = new MyService();
    chb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //is chkIos checked?
            if (((CheckBox) v).isChecked()) {
                ms.back.setImageResource(R.drawable.home);
            }

        }
    });

}

Body:
use this for CheckBox

    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            if(b)
                           {
              // do something
                            }
                            else
                             {
                          // do another something
                               }
                        }
                    });


问:
angularjs How to escape “${variable}” in html?
I want to show a string like ${date} to the div element:

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

the content will be display like:

```<code>please use the ${date} as the substitute tag to the name.
</code>```

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

答:
You could use $ instead of writing $ in your code. It is the HTML representation for the dollar sign, and should prevent that expression from being recognized as a variable.

```<code><div>please use the ${date} as the substitute tag to the name</div>
</code>```

You can find a full list of these codes at the W3 Character Entity Reference.

Body:
I want to show a string like ${date} to the div element:

please use the ${date} as the substitute tag to the name

the content will be display like:

please use the ${date} as the substitute tag to the name.

but the browser regards the ${date} as a javascript variable, so how to escape the ${date} string within angularjs?

Body:
You could use &#36; instead of writing $ in your code. It is the HTML representation for the dollar sign, and should prevent that expression from being recognized as a variable.

<div>please use the &#36;{date} as the substitute tag to the name</div>

You can find a full list of these codes at the W3 Character Entity Reference.


问:
Angular - getting GET variable using $location
I'm tring to get a GET var from the url using Angular $location.search() but it didn't work.

This is the code:

jsfiddle

and this is the GET

```<code>var app = angular.module('myApp',[]);

app.controller('odinvite', function ($scope, $location)
    {
        //$scope.mytry = 5;
        $scope.mytry =$location.search().username;
    }
);
</code>```

What's the problem? There is other way besides?

thanks!

EDIT -

I tried to add manually hash to the url like this - "mydomain.com/foo.php#?username=7" and it worked!
But I don't to add hash every time and I want the $location to grab it automatically.

I also tried to add this -

```<code> app.config(['$locationProvider', function($locationProvider) {
        $locationProvider.html5Mode(true);
    }]);
</code>```

to solve it but it gave me an error -

```<code>Error: [$location:nobase] http://errors.angularjs.org/1.4.8/$location/nobase
    at angular.js:38
    at hf.$get (angular.js:12196)
    at Object.e [as invoke] (angular.js:4523)
    at angular.js:4340
    at d (angular.js:4482)
    at Object.e [as invoke] (angular.js:4514)
    at M.instance (angular.js:9182)
    at D (angular.js:8299)
    at g (angular.js:7731)
    at angular.js:7611
(anonymous) @ angular.js:12520
(anonymous) @ angular.js:9292
$apply @ angular.js:16157
(anonymous) @ angular.js:1679
e @ angular.js:4523
c @ angular.js:1677
yc @ angular.js:1697
Zd @ angular.js:1591
(anonymous) @ angular.js:29013
b @ angular.js:3057
If @ angular.js:3346
d @ angular.js:3334
</code>```

答:
Your example is working with the second link. It will not work with the first link because the fiddle link https://jsfiddle.net/bar2o6gf/3/ does not contain a username

so, I mocked the url using,'url' property of $location

$location.url('http://fiddle.jshell.net/bar2o6gf/3/show/light/?username=7');

Here is the code,

<!DOCTYPE html>

      $location.url() = {{location.url()}}

      $location.search() = {{loc1}}

      keyword valus is  {{mytry}}

  {{mytry}}

```

Here is a DEMO

Body:
I'm tring to get a GET var from the url using Angular $location.search() but it didn't work.

This is the code:

jsfiddle

and this is the GET

var app = angular.module('myApp',[]);

app.controller('odinvite', function ($scope, $location)
    {
        //$scope.mytry = 5;
        $scope.mytry =$location.search().username;
    }
);

What's the problem? There is other way besides?

thanks!

EDIT -

I tried to add manually hash to the url like this - "mydomain.com/foo.php#?username=7" and it worked!
But I don't to add hash every time and I want the $location to grab it automatically.

I also tried to add this -

 app.config(['$locationProvider', function($locationProvider) {
        $locationProvider.html5Mode(true);
    }]);

to solve it but it gave me an error -

Error: [$location:nobase] http://errors.angularjs.org/1.4.8/$location/nobase
    at angular.js:38
    at hf.$get (angular.js:12196)
    at Object.e [as invoke] (angular.js:4523)
    at angular.js:4340
    at d (angular.js:4482)
    at Object.e [as invoke] (angular.js:4514)
    at M.instance (angular.js:9182)
    at D (angular.js:8299)
    at g (angular.js:7731)
    at angular.js:7611
(anonymous) @ angular.js:12520
(anonymous) @ angular.js:9292
$apply @ angular.js:16157
(anonymous) @ angular.js:1679
e @ angular.js:4523
c @ angular.js:1677
yc @ angular.js:1697
Zd @ angular.js:1591
(anonymous) @ angular.js:29013
b @ angular.js:3057
If @ angular.js:3346
d @ angular.js:3334

Body:
Your example is working with the second link. It will not work with the first link because the fiddle link https://jsfiddle.net/bar2o6gf/3/ does not contain a username

so, I mocked the url using,'url' property of $location

$location.url('http://fiddle.jshell.net/bar2o6gf/3/show/light/?username=7');

Here is the code,

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <head>
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-app="myApp" ng-controller="odinvite">
      <div>
        <br />
        <br />

      $location.url() = {{location.url()}}<br />
      $location.search() = {{loc1}}<br />
      keyword valus is  {{mytry}}
  </div>
  {{mytry}}
    </div>

<script>
var app = angular.module('myApp',[]);

app.controller('odinvite', function ($scope, $location)
    {
        //$scope.mytry = 5;

        $scope.location = $location;
      $location.url('http://fiddle.jshell.net/bar2o6gf/3/show/light/?username=7');
  $scope.loc1 = $location.search() ;
    if($location.url().indexOf('username') > -1){
        $scope.mytry= $location.search().username ;

    }

    }
);

</script>

</body>
</html>

Here is a DEMO


问:
NodeJS & ExpressJS: How to store user info in session after logged in?
I did lot of research but I am new on this, I couldn't find something concrete.
When a user is logged-in I would like to store some user info in session like Name, Profile_picture, Id, so I can use it for example in the navigation bar.

How can I achieve this?

For example in PHP is too easy just adding this line of code the information stays in what ever page you visit (before session expire)

```<code>session_start();
$_SESSION['user_id']
</code>```

答:
You have to create an express-session: https://www.npmjs.com/package/express-sessions

and then store the session like this:

```<code>let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));
</code>```

This session will be stored during your visit on the webpage. If you want to set values to the cookie, simply request the cookie in a request and set somekind of value:

```<code>router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })
</code>```

Body:
I did lot of research but I am new on this, I couldn't find something concrete.
When a user is logged-in I would like to store some user info in session like Name, Profile_picture, Id, so I can use it for example in the navigation bar.

How can I achieve this?

For example in PHP is too easy just adding this line of code the information stays in what ever page you visit (before session expire)

session_start();
$_SESSION['user_id']

Body:
You have to create an express-session: https://www.npmjs.com/package/express-sessions

and then store the session like this:

let session = require("express-session");

app.use(session({
    secret: "secret",
    resave: false,
    saveUninitialized: true,
    cookie: {secure: true,
        httpOnly: true,
        maxAge: 1000 * 60 * 60 * 24
    }
}));

This session will be stored during your visit on the webpage. If you want to set values to the cookie, simply request the cookie in a request and set somekind of value:

router.route("/login")
    .post(function(req, res) {

        req.session.Auth = req.body.user // => user values?
    })


问:
Group consecutive dates together with Python
Given:

```<code>dates = [
  datetime(2014, 10, 11),

  datetime(2014, 10, 1),
  datetime(2014, 10, 2),
  datetime(2014, 10, 3),

  datetime(2014, 10, 5),
  datetime(2014, 10, 5),
  datetime(2014, 10, 6),

  datetime(2014, 10, 22),
  datetime(2014, 10, 20),
  datetime(2014, 10, 21),

  datetime(2014, 10, 9),

  datetime(2014, 10, 7),
  datetime(2014, 10, 6)
]
</code>```

Expected output:

```<code>expect = [
  [datetime(2014, 10, 1), datetime(2014, 10, 3)],
  [datetime(2014, 10, 5), datetime(2014, 10, 7)],
   datetime(2014, 10, 9),
   datetime(2014, 10, 11),
  [datetime(2014, 10, 20), datetime(2014, 10, 22)]
]
</code>```

Implementation in Python:

```<code>from datetime import datetime, timedelta

def parse_date_ranges(dates):
    if(not dates or not len(dates) > 0):
        return False

    # make sure to order dates
    dates.sort()

    # init values
    result  = []
    tupl    = [dates[0], dates[0]]
    it      = iter(dates)
    date    = True

    def add_tuple_to_result(tuple):
        # if first part of tuple differs from last part -> add full tuple
        # else -> add first part of tuple only
        result.append(tupl if tupl[0] != tupl[1] else tupl[0])

    while date:
        # get next date or False if no next date
        date = next(it, False)

        # filter double dates
        if(date in tupl):
            continue

        elif(date):
            if(date - timedelta(days=1) == tupl[1]):
                # consecutive date, so add date to end of current tuple
                tupl[1] = date
            else:
                # gap larger than 1 day: add current tuple to result
                # and create new tuple
                add_tuple_to_result(tupl)
                tupl = [date, date]

        else:
            # date == false, so this is the last step.
            # add the current tuple to result
            add_tuple_to_result(tupl)

    return result
</code>```

See https://gist.github.com/mattes/8987332 for some more tests, too.

Question

The implementation works, but I am new to Python. So I was wondering if there are better ways to solve this issue? Or is it just fine?

答:
Adapting this answer to use datetime objects. This covers non-unique and non-sorted input and is python3 compatible too:

```<code>import itertools
from datetime import datetime, timedelta

def datetimes_to_ranges(iterable):
    iterable = sorted(set(iterable))
    keyfunc = lambda t: t[1] - timedelta(days=t[0])
    for key, group in itertools.groupby(enumerate(iterable), keyfunc):
        group = list(group)
        if len(group) == 1:
            yield group[0][1]
        else:
            yield group[0][1], group[-1][1]
</code>```

Example:

```<code>>>> for i in datetimes_to_ranges(dates): i
...
(datetime.datetime(2014, 10, 1, 0, 0), datetime.datetime(2014, 10, 3, 0, 0))
(datetime.datetime(2014, 10, 5, 0, 0), datetime.datetime(2014, 10, 7, 0, 0))
datetime.datetime(2014, 10, 9, 0, 0)
datetime.datetime(2014, 10, 11, 0, 0)
(datetime.datetime(2014, 10, 20, 0, 0), datetime.datetime(2014, 10, 22, 0, 0))
</code>```

Body:
Given:

dates = [
  datetime(2014, 10, 11),

  datetime(2014, 10, 1),
  datetime(2014, 10, 2),
  datetime(2014, 10, 3),

  datetime(2014, 10, 5),
  datetime(2014, 10, 5),
  datetime(2014, 10, 6),

  datetime(2014, 10, 22),
  datetime(2014, 10, 20),
  datetime(2014, 10, 21),

  datetime(2014, 10, 9),

  datetime(2014, 10, 7),
  datetime(2014, 10, 6)
]

Expected output:

expect = [
  [datetime(2014, 10, 1), datetime(2014, 10, 3)],
  [datetime(2014, 10, 5), datetime(2014, 10, 7)],
   datetime(2014, 10, 9),
   datetime(2014, 10, 11),
  [datetime(2014, 10, 20), datetime(2014, 10, 22)]
]

Implementation in Python:

from datetime import datetime, timedelta

def parse_date_ranges(dates):
    if(not dates or not len(dates) > 0):
        return False

    # make sure to order dates
    dates.sort()

    # init values
    result  = []
    tupl    = [dates[0], dates[0]]
    it      = iter(dates)
    date    = True

    def add_tuple_to_result(tuple):
        # if first part of tuple differs from last part -> add full tuple
        # else -> add first part of tuple only
        result.append(tupl if tupl[0] != tupl[1] else tupl[0])

    while date:
        # get next date or False if no next date
        date = next(it, False)

        # filter double dates
        if(date in tupl):
            continue

        elif(date):
            if(date - timedelta(days=1) == tupl[1]):
                # consecutive date, so add date to end of current tuple
                tupl[1] = date
            else:
                # gap larger than 1 day: add current tuple to result
                # and create new tuple
                add_tuple_to_result(tupl)
                tupl = [date, date]

        else:
            # date == false, so this is the last step.
            # add the current tuple to result
            add_tuple_to_result(tupl)

    return result

See https://gist.github.com/mattes/8987332 for some more tests, too.

Question

The implementation works, but I am new to Python. So I was wondering if there are better ways to solve this issue? Or is it just fine?

Body:
Adapting this answer to use datetime objects. This covers non-unique and non-sorted input and is python3 compatible too:

import itertools
from datetime import datetime, timedelta

def datetimes_to_ranges(iterable):
    iterable = sorted(set(iterable))
    keyfunc = lambda t: t[1] - timedelta(days=t[0])
    for key, group in itertools.groupby(enumerate(iterable), keyfunc):
        group = list(group)
        if len(group) == 1:
            yield group[0][1]
        else:
            yield group[0][1], group[-1][1]

Example:

>>> for i in datetimes_to_ranges(dates): i
...
(datetime.datetime(2014, 10, 1, 0, 0), datetime.datetime(2014, 10, 3, 0, 0))
(datetime.datetime(2014, 10, 5, 0, 0), datetime.datetime(2014, 10, 7, 0, 0))
datetime.datetime(2014, 10, 9, 0, 0)
datetime.datetime(2014, 10, 11, 0, 0)
(datetime.datetime(2014, 10, 20, 0, 0), datetime.datetime(2014, 10, 22, 0, 0))