问:
optimized data base search algorithm
I'm developing a website with api that can be accessed from mobile clients, the app is something similar to http://zomato.com/

lets say we have table car(carID, model, maker, transmission, fuleType, otherOptions)

the user can query any of the fields, the query also might include fields in other tables for example if i create w separate table for makers and models.

of course I can query using like clause on all fields, is that the right way ? when there might be thousands of records ?

I need fast db response real time querying when using either the mobile app or the website.

I'm familiar with .Net the most but i would be glad if you give me any other recommendations and guide me through the starting point(libraries, existing open source projects).

note: the user will only have a search field and optional filters like model, category etc...

答:
Here is what i would do.

Build up your query using an IQueryable.  You can use if statements to check if any of your parameters have a value and if so append the where statement to your query.  Once your query is all set send it to memory with a .ToList or an .AsEnumerable.

```<code>public List<Data> Search (string param1, string param2)
{
    IQueryable<Data> query = db.SomeTable;

    if (!String.IsNullOrEmpty(param1))
        query = query.Where(m => m.Field1 == param1); // might use contain depending on your use case

    if (!String.IsNullOrEmpty(param2))
        query = query.Where(m => m.Field2 == param2);

    return query.ToList();
}
</code>```

I would also use a Skip and Take for pagination.

Edit: I wanted to note this is about as fast as you will get with a database that I know of, if anyone else knows a faster function please let me know.  You can achieve a quicker response by using a NoSQL database and static documents, but for several thousands of records a database should work just fine.

Title: optimized data base search algorithm

Body:
Here is what i would do.

Build up your query using an IQueryable.  You can use if statements to check if any of your parameters have a value and if so append the where statement to your query.  Once your query is all set send it to memory with a .ToList or an .AsEnumerable.

public List<Data> Search (string param1, string param2)
{
    IQueryable<Data> query = db.SomeTable;

    if (!String.IsNullOrEmpty(param1))
        query = query.Where(m => m.Field1 == param1); // might use contain depending on your use case

    if (!String.IsNullOrEmpty(param2))
        query = query.Where(m => m.Field2 == param2);

    return query.ToList();
}

I would also use a Skip and Take for pagination.

Edit: I wanted to note this is about as fast as you will get with a database that I know of, if anyone else knows a faster function please let me know.  You can achieve a quicker response by using a NoSQL database and static documents, but for several thousands of records a database should work just fine.


来源: stackexchange

问:
c++ how to initialize const elements of an array
i need a way to initialize const elements of an array for the program i am currently working on.
The problem is that i have to initialize these elements with a function, there is no way to do it like this:

```<code>const int array[255] = {1, 1278632, 188, ...};
</code>```

because its alot of data i have to generate.
What i tried is to memcpy data to the const int's but that can't work and hasn't worked.

```<code> const int array[255];

 void generateData(){
      for(int i = 0; i < 255; i++) {
          initializeSomehowTo(5, array[i]);
      }
 }
</code>```

I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it.

答:
How about this?</p>

```<code>#include <array>
typedef std::array<int, 255> Array;

const Array array = generateData();

Array generateData(){
    Array a;
    for(int i = 0; i < a.size(); i++) {
        initializeSomehowTo(a[i]);
    }
    return a;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i need a way to initialize const elements of an array for the program i am currently working on.
The problem is that i have to initialize these elements with a function, there is no way to do it like this:

const int array[255] = {1, 1278632, 188, ...};

because its alot of data i have to generate.
What i tried is to memcpy data to the const int's but that can't work and hasn't worked.

 const int array[255];

 void generateData(){
      for(int i = 0; i < 255; i++) {
          initializeSomehowTo(5, array[i]);
      }
 }

I hope you understand what i am trying, sorry if i doubled the question, i must have overlooked it.

Body:
How about this?

#include <array>
typedef std::array<int, 255> Array;

const Array array = generateData();

Array generateData(){
    Array a;
    for(int i = 0; i < a.size(); i++) {
        initializeSomehowTo(a[i]);
    }
    return a;
}


问:
Passing Array from AJAX to PHP, then passing data back as JSON
I am having a strange issue with my PHP / JSON data being returned by PHP.  Here is my PHP:

```<code>            <?php
            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Easy set variables
            */

            /* Array of database columns which should be read and sent back to DataTables. Use a space where
            * you want to insert a non-database field (for example a counter or static image)
            */

            // add your columns here!!!
                $aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
                //$aColumns = $_POST['selcolumns'];
                //$aColumns = explode("-", $aColumns);

                foreach ($aColumns as $col) {
                    file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
                }

                $server = "";
                $database = array("Database" => "");
                $conn = sqlsrv_connect($server, $database);
                if ($conn === false) die("```".print_r(sqlsrv_errors(), true));

            /* Indexed column (used for fast and accurate table cardinality) */
                $sIndexColumn = "GUID";

            /* DB table to use */
                $sTable = $_POST['table'];

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * If you just want to use the basic configuration for DataTables with PHP server-side, there is
            * no need to edit below this line
            */

            /*
            * Local functions
            */
                function fatal_error ( $sErrorMessage = '' ) {
                    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
                    die( $sErrorMessage );
                }

            /* Ordering */
                $sOrder = "";
                if ( isset( $_POST['order'] ) ) {
                    $sOrder = "ORDER BY ";
                    if ( $_POST['columns'][0]['orderable'] == "true" ) {
                        $sOrder .= "".$aColumns[ intval( $_POST['order'][0]['column'] ) ]." ".
                        ($_POST['order'][0]['dir']==='asc' ? 'asc' : 'desc');
                    }
                }

            /* escape function */
                function mssql_escape($data) {
                    if(is_numeric($data))
                    return $data;
                    $unpacked = unpack('H*hex', $data);
                    return '0x' . $unpacked['hex'];
                }

            /* Filtering */
                $sWhere = "";
                if ( isset($_POST['search']['value']) && $_POST['search']['value'] != "" ) {
                    $sWhere = "WHERE (";
                    for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                        $sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_POST['search']['value'] )."%' OR ";
                    }
                    $sWhere = substr_replace( $sWhere, "", -3 );
                    $sWhere .= ')';
                }

            /* Individual column filtering */
                for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                    if ( isset($_POST['columns'][$i]) && $_POST['columns'][$i]['searchable'] == "true" && $_POST['columns'][$i]['search']['value'] != '' ) {
                        if ( $sWhere == "" ) {
                            $sWhere = "WHERE ";
                        }
                        else {
                            $sWhere .= " AND ";
                        }
                        $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_POST['columns'][$i]['search']['value'])."%' ";
                    }
                }

            /* Add the custom Date/Time filter */

                if ( $sWhere == "" ) {
                    $sWhere = "WHERE (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
                }
                else {
                    $sWhere .= " AND (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
                }

            /* Paging */
                $top = (isset($_POST['start']))?((int)$_POST['start']):0 ;
                $limit = (isset($_POST['length']))?((int)$_POST['length'] ):5;
                $sQuery = "SELECT TOP $limit ".implode(', ', $aColumns)." FROM $sTable $sWhere ".(($sWhere=="")?" WHERE ":" AND ")." $sIndexColumn NOT IN ( SELECT TOP $top $sIndexColumn FROM $sTable $sOrder ) $sOrder";
                $rResult = sqlsrv_query($conn, $sQuery);
                if($rResult === false){
                    die(sqlsrv_errors(SQLSRV_ERR_ERRORS));
                }

            /* Data set length after filtering */
                $sQueryCnt = "SELECT * FROM $sTable $sWhere";
                $rResultCnt = sqlsrv_query($conn, $sQueryCnt, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
                $iFilteredTotal = sqlsrv_num_rows( $rResultCnt );

            /* Total data set length */
                $sQuery = "SELECT COUNT(GUID) FROM $sTable";
                $rResultTotal = sqlsrv_query($conn, $sQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
                $aResultTotal = sqlsrv_fetch_array($rResultTotal, SQLSRV_FETCH_NUMERIC);
                $iTotal = $aResultTotal[0];

            /* Output */
                $output = array(
                    "draw" => intval($_POST['draw']),
                    "recordsTotal" => $iTotal,
                    "recordsFiltered" => $iFilteredTotal,
                    "data" => array()
                );

                while ( $aRow = sqlsrv_fetch_array( $rResult, SQLSRV_FETCH_ASSOC) ) {
                    $row = array();
                    for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                        $row[$aColumns[$i]] = $aRow[ $aColumns[$i] ];
                    }
                    $output['data'][] = $row;
                }

                echo json_encode( $output );

            ?>
```

<p>The part of the code that has me stuck:</p>

```            $aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
            //$aColumns = $_POST['selcolumns'];
            //$aColumns = explode("-", $aColumns);

            foreach ($aColumns as $col) {
                file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
            }
```

<p>If I leave my code as is and run through the process I get the data back as expected and everything works.  I also get this output in my php-debug.txt:</p>

<p>Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer </p>

<p>If I modify these lines of my code to this:</p>

```            //$aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
            $aColumns = $_POST['selcolumns'];
            $aColumns = explode("-", $aColumns);

            foreach ($aColumns as $col) {
                file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
            }
```

I do not get the data back as expected.  I get a warning stating invalid JSON response and in my php-debug.txt I get this content:

Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer

It is driving me bonkers that the array has the same values either way and yet it doesn't work.  There is an extra space on the end of the php-debug.txt the 2nd time around, not sure where that comes from or if it is the problem.

Hopefully someone can point me in the right direction.

答: I figured out the problem.  For some reason there is an extra element being added to my array, but its an empty element so when I print there is nothing there.  I added this to my code array_pop($aColumns); and for now that resolved the problem.  Its kind of a dirty workout though, and I can't help but think that eventually there will come a scenario where the last element isn't blank and its something I need.  Would love to figure out a cleaner solution.</p>

Body:
I am having a strange issue with my PHP / JSON data being returned by PHP.  Here is my PHP:

            <?php
            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Easy set variables
            */

            /* Array of database columns which should be read and sent back to DataTables. Use a space where
            * you want to insert a non-database field (for example a counter or static image)
            */

            // add your columns here!!!
                $aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
                //$aColumns = $_POST['selcolumns'];
                //$aColumns = explode("-", $aColumns);

                foreach ($aColumns as $col) {
                    file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
                }

                $server = "";
                $database = array("Database" => "");
                $conn = sqlsrv_connect($server, $database);
                if ($conn === false) die("
".print_r(sqlsrv_errors(), true));

            /* Indexed column (used for fast and accurate table cardinality) */
                $sIndexColumn = "GUID";

            /* DB table to use */
                $sTable = $_POST['table'];

            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * If you just want to use the basic configuration for DataTables with PHP server-side, there is
            * no need to edit below this line
            */

            /*
            * Local functions
            */
                function fatal_error ( $sErrorMessage = '' ) {
                    header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
                    die( $sErrorMessage );
                }

            /* Ordering */
                $sOrder = "";
                if ( isset( $_POST['order'] ) ) {
                    $sOrder = "ORDER BY ";
                    if ( $_POST['columns'][0]['orderable'] == "true" ) {
                        $sOrder .= "".$aColumns[ intval( $_POST['order'][0]['column'] ) ]." ".
                        ($_POST['order'][0]['dir']==='asc' ? 'asc' : 'desc');
                    }
                }

            /* escape function */
                function mssql_escape($data) {
                    if(is_numeric($data))
                    return $data;
                    $unpacked = unpack('H*hex', $data);
                    return '0x' . $unpacked['hex'];
                }

            /* Filtering */
                $sWhere = "";
                if ( isset($_POST['search']['value']) && $_POST['search']['value'] != "" ) {
                    $sWhere = "WHERE (";
                    for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                        $sWhere .= $aColumns[$i]." LIKE '%".addslashes( $_POST['search']['value'] )."%' OR ";
                    }
                    $sWhere = substr_replace( $sWhere, "", -3 );
                    $sWhere .= ')';
                }

            /* Individual column filtering */
                for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                    if ( isset($_POST['columns'][$i]) && $_POST['columns'][$i]['searchable'] == "true" && $_POST['columns'][$i]['search']['value'] != '' ) {
                        if ( $sWhere == "" ) {
                            $sWhere = "WHERE ";
                        }
                        else {
                            $sWhere .= " AND ";
                        }
                        $sWhere .= $aColumns[$i]." LIKE '%".addslashes($_POST['columns'][$i]['search']['value'])."%' ";
                    }
                }

            /* Add the custom Date/Time filter */

                if ( $sWhere == "" ) {
                    $sWhere = "WHERE (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
                }
                else {
                    $sWhere .= " AND (TimeOccurred >= "."'".$_POST['datestart']."'"." AND TimeOccurred <= "."'".$_POST['dateend']."')";
                }

            /* Paging */
                $top = (isset($_POST['start']))?((int)$_POST['start']):0 ;
                $limit = (isset($_POST['length']))?((int)$_POST['length'] ):5;
                $sQuery = "SELECT TOP $limit ".implode(', ', $aColumns)." FROM $sTable $sWhere ".(($sWhere=="")?" WHERE ":" AND ")." $sIndexColumn NOT IN ( SELECT TOP $top $sIndexColumn FROM $sTable $sOrder ) $sOrder";
                $rResult = sqlsrv_query($conn, $sQuery);
                if($rResult === false){
                    die(sqlsrv_errors(SQLSRV_ERR_ERRORS));
                }

            /* Data set length after filtering */
                $sQueryCnt = "SELECT * FROM $sTable $sWhere";
                $rResultCnt = sqlsrv_query($conn, $sQueryCnt, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
                $iFilteredTotal = sqlsrv_num_rows( $rResultCnt );

            /* Total data set length */
                $sQuery = "SELECT COUNT(GUID) FROM $sTable";
                $rResultTotal = sqlsrv_query($conn, $sQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
                $aResultTotal = sqlsrv_fetch_array($rResultTotal, SQLSRV_FETCH_NUMERIC);
                $iTotal = $aResultTotal[0];

            /* Output */
                $output = array(
                    "draw" => intval($_POST['draw']),
                    "recordsTotal" => $iTotal,
                    "recordsFiltered" => $iFilteredTotal,
                    "data" => array()
                );

                while ( $aRow = sqlsrv_fetch_array( $rResult, SQLSRV_FETCH_ASSOC) ) {
                    $row = array();
                    for ( $i=0 ; $i<count($aColumns) ; $i++ ) {
                        $row[$aColumns[$i]] = $aRow[ $aColumns[$i] ];
                    }
                    $output['data'][] = $row;
                }

                echo json_encode( $output );

            ?>

The part of the code that has me stuck:

            $aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
            //$aColumns = $_POST['selcolumns'];
            //$aColumns = explode("-", $aColumns);

            foreach ($aColumns as $col) {
                file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
            }

If I leave my code as is and run through the process I get the data back as expected and everything works.  I also get this output in my php-debug.txt:

Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer

If I modify these lines of my code to this:

            //$aColumns = array( 'Action', 'TimeOccurred', 'UserName', 'IPv4From', 'ShareName', 'FullFilePath', 'NewPathName', 'FromServer' );
            $aColumns = $_POST['selcolumns'];
            $aColumns = explode("-", $aColumns);

            foreach ($aColumns as $col) {
                file_put_contents( '../php/php-debug.txt', $col." ", FILE_APPEND );
            }

I do not get the data back as expected.  I get a warning stating invalid JSON response and in my php-debug.txt I get this content:

Action TimeOccurred UserName IPv4From ShareName FullFilePath NewPathName FromServer

It is driving me bonkers that the array has the same values either way and yet it doesn't work.  There is an extra space on the end of the php-debug.txt the 2nd time around, not sure where that comes from or if it is the problem.

Hopefully someone can point me in the right direction.


问:
Is Setting a Variable Atomic in THESE conditions
I have this situation where I have a state variable; int state = (2, 1, 0)
and an infinite loop:

```<code>ret = BoolCompareAndSwap(state, 1, 2)
if (ret) {
    // Change something ...
    state = 0;
}
</code>```

Would this state setting be atomic?
Assuming to set a variable you must:

Take out from memory

Change value

Set new value

If some other thread came and compared the variable, it would be atomic since the actual value doesn't change until it it re-set in memory, Correct?

答:
Strictly speaking, C compilers would still be standard conforming if they wrote the state bitwise. After writing the first few bits, some other thread can read any kind of garbage.

Most compilers do no such thing (with the possible exception of compilers for ancient 4bit processors or even narrower ...), because it would be a performance loss.

Also, and more practically relevant, if any other thread writes (instead of only reading) to the state, that written value can get lost if you do not protect the described code against racing conditions.

As a side note, the described state change (read, modify, write) is never atomic. The question however when that non-atomicity is vulnerable, is valid and it is what I tried to answer above.

More generically speaking, thinking through all possible combinations of concurrent access is a valid protection mechanism. It is however extremely costly in many ways (design effort, test effort, risk during maintenance...).

Only if those costs are in total smaller than the intended saving (possibly performance), it is feasible to go that way, instead of using an appropriate protection mechanism.

Body:
I have this situation where I have a state variable; int state = (2, 1, 0)
and an infinite loop:

ret = BoolCompareAndSwap(state, 1, 2)
if (ret) {
    // Change something ...
    state = 0;
}

Would this state setting be atomic?
Assuming to set a variable you must:

Take out from memory

Change value

Set new value

If some other thread came and compared the variable, it would be atomic since the actual value doesn't change until it it re-set in memory, Correct?


问:
Detect click outside React component
I'm looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.

So in my component, I want to attach a click handler to the window. When the handler fires I need to compare the target with the dom children of my component.

The click event contains properties like "path" which seems to hold the dom path that the event has traveled. I'm not sure what to compare or how to best traverse it, and I'm thinking someone must have already put that in a clever utility function... No?

答:
None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.

Here is an approach that did work for me:

```<code>// Inside the component:
onBlur(event) {
    // currentTarget refers to this component.
    // relatedTarget refers to the element where the user clicked (or focused) which
    // triggered this event.
    // So in effect, this condition checks if the user clicked outside the component.
    if (!event.currentTarget.contains(event.relatedTarget)) {
        // do your thing.
    }
},
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Title: Detect click outside React component

Body:
None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.

Here is an approach that did work for me:

// Inside the component:
onBlur(event) {
    // currentTarget refers to this component.
    // relatedTarget refers to the element where the user clicked (or focused) which
    // triggered this event.
    // So in effect, this condition checks if the user clicked outside the component.
    if (!event.currentTarget.contains(event.relatedTarget)) {
        // do your thing.
    }
},

Hope this helps.


问:
SQL Server 2008 License for Full Text Search?
I have a client which would like to use SQL 2008 FTS...but I was wondering is there a seperate license for it or when you buy a certain edition of SQL (which?) you get it included?</p>

答:
Nope - not at all. FTS is built into Express editions (free) and upwards. The issue with licensing is for other parts of the Sql Server. Eg. Free edition only uses one Processor, has a DB size limit, etc.

For myself, I need to use as many processors as the machine has, so I can't use the free edition.

ContentLicense: CC BY-SA 2.5


问:
jquery attribute. jquery js

$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>// this is just the test

cell2.innerHTML = '<span  class="dum" style="color:'+testvalues[i]+'; font-size:20px;">'+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '</span>';

<div id="test-form" title="Event Information">
 <p>Event:</p>
 <input id= "ev" type="text"  name="fullname" disabled />
</div></code>```

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.

答:
Use the jQuery data attribute instead.</p>

```<code> document.getElementById("ev").value=$(this).data("name");
</code>```

Title: jquery attribute. jquery js

Body:
$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});

// this is just the test

cell2.innerHTML = ''+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '';

Event:

 <input id= "ev" type="text"  name="fullname" disabled />

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.

Body:
Use the jQuery data attribute instead.

 document.getElementById("ev").value=$(this).data("name");


问:
How to handle error states with LiveData?
The new LiveData can be used as a replacement for RxJava's observables in some scenarios. However, unlike Observable, LiveData has no callback for errors.

My question is: How should I handle errors in LiveData, e.g. when it's backed by some network resource that can fail to be retrieved due to an IOException?

答:
In my app, I had to translate RxJava Observables into LiveData. While doing that, I of course had to maintain the error state. Here's how I did it (Kotlin)</p>

```<code>class LiveDataResult<T>(val data: T?, val error: Throwable?)

class LiveObservableData<T>(private val observable: Observable<T>) : LiveData<LiveDataResult<T>>() {
    private var disposable = CompositeDisposable()

    override fun onActive() {
        super.onActive()

        disposable.add(observable.subscribe({
            postValue(LiveDataResult(it, null))
        }, {
            postValue(LiveDataResult(null, it))
        }))
    }

    override fun onInactive() {
        super.onInactive()

        disposable.clear()
    }
}
</code>```

Body:
In my app, I had to translate RxJava Observables into LiveData. While doing that, I of course had to maintain the error state. Here's how I did it (Kotlin)

class LiveDataResult<T>(val data: T?, val error: Throwable?)

class LiveObservableData<T>(private val observable: Observable<T>) : LiveData<LiveDataResult<T>>() {
    private var disposable = CompositeDisposable()

    override fun onActive() {
        super.onActive()

        disposable.add(observable.subscribe({
            postValue(LiveDataResult(it, null))
        }, {
            postValue(LiveDataResult(null, it))
        }))
    }

    override fun onInactive() {
        super.onInactive()

        disposable.clear()
    }
}


问:
Check if a node.js module is available
I'm looking for a way to find out if a module is available.

For example, I want to check if the module mongodb is available, programmatically.

Also, it shouldn't halt the program if a module isn't found, I want to handle this myself.

PS: I added this question because Google isn't helpful.

答:
ES6 simple solution with 1 line of code :</p>

```<code>const path = require('path');
const fs = require('fs');

function hasDependency(dep) {
        return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
}
</code>```

Title: Check if a node.js module is available

Body:
ES6 simple solution with 1 line of code :

const path = require('path');
const fs = require('fs');

function hasDependency(dep) {
        return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
}


问:
How to Place an Image on Top of a Background Image
I am trying to place an image on top of a background image. The background is contained within a div placed on the bottom of the containing div. I want to place an image on the bottom right-hand corner on top of the background image that's placed bottom center.

I have tried to use two background images but was unable to place the image on top of the repeating div without having issues with placement on mobile, because the text area shrinks and moves the image below the container.

I tried placing the image in-line but am unable to have it appear on top of the background.

Any ideas on what the best method would be to do this?

.gradient-bg.slide {
  background: url("http://www.clker.com/cliparts/f/d/b/5/1206555848388219874chlopaya_Bird.svg.med.png") no-repeat left top, linear-gradient(#ffcd74, #f8981d);
  /*background: #ffcd74;
    background: -moz-linear-gradient(top, #ffcd74 29%, #f8981d 78%);
    background: -webkit-linear-gradient(top, #ffcd74 29%,#f8981d 78%);
    background: linear-gradient(to bottom, #ffcd74 29%,#f8981d 78%);*/
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffcd74', endColorstr='#f8981d', GradientType=0);
}

.slide_cloud {
  background: url("https://preview.ibb.co/cyvOLv/harris_relativity_cloud_footer.png") no-repeat bottom center;
  background-size: inherit;
  padding: 20px;
  height: 500px;
  text-align: center;
}

.logo-image {
  background: url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/WikiSpecies_notext.svg/300px-WikiSpecies_notext.svg.png") no-repeat bottom right;
  padding-top: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="gradient-bg slide">
  <div class="slide slide_cloud">
    <h2>Generic Header</h2>
    <div class="logo-image">
    </div>
    <div class="slide-content">
      <div class="text">Generic text.</div>
    </div>
  </div>
</div></code>```

答:
Based on what you have explained I'm assuming this to be your desired layout.

```<code><div class="cloudbg">
<div class="bird">
<img src="http://www.clker.com/cliparts/f/d/b/5/1206555848388219874chlopaya_Bird.svg.med.png" height="75px" width="100px">
<h2>Generic Header</h2>
<div class="content">
<br> Generic Text
</div>
</div>
<div class="logo">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/WikiSpecies_notext.svg/300px-WikiSpecies_notext.svg.png" height="50px">
</div>
</code>```

I have used absolute positioning in the above code to place the objects. To get the header to come in the same line make it an inline element as shown below. Make sure to make changes to the values according to your needs.

```<code>.bird h2 {
display: inline;
vertical-align: top;
}

.cloudbg {
background:
url("https://preview.ibb.co/cyvOLv/harris_relativity_cloud_footer.png") no-
repeat bottom;
height: 350px;
text-align: center;
}

.bird {
display: inline;
float: left;
}

.content {
display: block;
}

.logo {
display: block;
position: absolute;
bottom: 2px;
right: 5px;
}
</code>```

Here is a working solution- https://jsfiddle.net/jts9owh4/

Body:
I am trying to place an image on top of a background image. The background is contained within a div placed on the bottom of the containing div. I want to place an image on the bottom right-hand corner on top of the background image that's placed bottom center.

I have tried to use two background images but was unable to place the image on top of the repeating div without having issues with placement on mobile, because the text area shrinks and moves the image below the container.

I tried placing the image in-line but am unable to have it appear on top of the background.

Any ideas on what the best method would be to do this?

.gradient-bg.slide {
  background: url("http://www.clker.com/cliparts/f/d/b/5/1206555848388219874chlopaya_Bird.svg.med.png") no-repeat left top, linear-gradient(#ffcd74, #f8981d);
  /*background: #ffcd74;
    background: -moz-linear-gradient(top, #ffcd74 29%, #f8981d 78%);
    background: -webkit-linear-gradient(top, #ffcd74 29%,#f8981d 78%);
    background: linear-gradient(to bottom, #ffcd74 29%,#f8981d 78%);*/
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffcd74', endColorstr='#f8981d', GradientType=0);
}

.slide_cloud {
  background: url("https://preview.ibb.co/cyvOLv/harris_relativity_cloud_footer.png") no-repeat bottom center;
  background-size: inherit;
  padding: 20px;
  height: 500px;
  text-align: center;
}

.logo-image {
  background: url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/WikiSpecies_notext.svg/300px-WikiSpecies_notext.svg.png") no-repeat bottom right;
  padding-top: 100px;
}

Generic Header

Generic text.

Body:
Based on what you have explained I'm assuming this to be your desired layout.

<div class="cloudbg">
<div class="bird">
<img src="http://www.clker.com/cliparts/f/d/b/5/1206555848388219874chlopaya_Bird.svg.med.png" height="75px" width="100px">
<h2>Generic Header</h2>
<div class="content">
<br> Generic Text
</div>
</div>
<div class="logo">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/WikiSpecies_notext.svg/300px-WikiSpecies_notext.svg.png" height="50px">
</div>

I have used absolute positioning in the above code to place the objects. To get the header to come in the same line make it an inline element as shown below. Make sure to make changes to the values according to your needs.

.bird h2 {
display: inline;
vertical-align: top;
}

.cloudbg {
background:
url("https://preview.ibb.co/cyvOLv/harris_relativity_cloud_footer.png") no-
repeat bottom;
height: 350px;
text-align: center;
}

.bird {
display: inline;
float: left;
}

.content {
display: block;
}

.logo {
display: block;
position: absolute;
bottom: 2px;
right: 5px;
}

Here is a working solution- https://jsfiddle.net/jts9owh4/


问:
What is the best way to listen for component resize events within an Angular2 component?
I'm writing an Angular2 component that needs to dynamically change its content when resized. I am using the experimental Renderer in @angular/core (v2.1.0) and can wire up a click listener with the following:

```<code>this.rollupListener = this.renderer.listen(this.rollUp, 'click', (event) => {
  ...
});
</code>```

But unfortunately I cannot do the same for a resize event - both 'resize' or 'onresize' do not work:

```<code>this.resizeListener = this.renderer.listen(this.container, 'resize', (event) => {
  // this never fires :(
});
</code>```

I am able to pick up on browser resize events using the following:

```<code>@HostListener('window:resize', ['$event.target'])
onResize() {
  ...
}
</code>```

But unfortunately not all component resizing in my application is due to a browser resize.

Basically, I'm looking for the JQuery equivalent of:

```<code>$(this.container).resize(() => {
  ...
});
</code>```

答:
I wrote this Angular2 directive to solve this.

You can install it by npm install bound-sensor.
The advantage of using this method is it tells you once the size of parent of component changes and it doesn't depend on window resize! Imagine you need to expand and refresh your content base on size of its parent, this solves it easily.

Body:
I'm writing an Angular2 component that needs to dynamically change its content when resized. I am using the experimental Renderer in @angular/core (v2.1.0) and can wire up a click listener with the following:

this.rollupListener = this.renderer.listen(this.rollUp, 'click', (event) => {
  ...
});

But unfortunately I cannot do the same for a resize event - both 'resize' or 'onresize' do not work:

this.resizeListener = this.renderer.listen(this.container, 'resize', (event) => {
  // this never fires :(
});

I am able to pick up on browser resize events using the following:

@HostListener('window:resize', ['$event.target'])
onResize() {
  ...
}

But unfortunately not all component resizing in my application is due to a browser resize.

Basically, I'm looking for the JQuery equivalent of:

$(this.container).resize(() => {
  ...
});


问:
How to access the uploaded extra data inside test script in AWS Device Farm?
I'm using Java-Appium-TestNG. I've uploaded a Excel file Testdata.xlsx containing my test data (using "Add Extra data" option). Which path I should mention inside the test script to access the TestData.xlsx?

答:
Note: Extra data should be uploaded in form of a zip file. So in your case the excel file should be placed inside a zip file first.

For Android, the extra data is extracted to the SD Card of the device.

For iOS, the extra data is extracted to the application data folder under .../aapt/data

A sample path on iOS would look like this:
private/var/mobile/Containers/Bundle/Application/64F3793F-5AFC-4C12-8BF4-XXXXXXXXXXXX/MySampleApp.app/aatp/data

Hope that helps.


问:
view how many people compelete the quiz on admin panel
I have a mysql database and I have admin panel and I have quiz on my site.

I want to add a table to count how many people complete the quiz and show it on my admin panel

I have a questions. Is the column type varchar right?

What code should I type to my admin.php to show the count?

What code should I type to my EXAMPLE_QUIZ.php to send the count to database?
and what code should i add to all quiz's php files ?
i hope someone help me :(

答:
got it. Your PHP code to increse your counter is: </p>

```<code><?php
$servername = "localhost";
$username   = "root";
$password   = "";
$db_name    = "route";

// Create connection
$mysqli = new mysqli($servername, $username, $password, $db_name);

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$sql = "UPDATE quizes SET count = count + 1 WHERE id = QUIZ_ID"; // be careful from injections again!

if($mysqli->query($sql) === true){
    echo "Done";
}else{
    echo "Error: " . $mysqli->error;
}

$mysqli->close;

?>
</code>```

Body:
got it. Your PHP code to increse your counter is:

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$db_name    = "route";

// Create connection
$mysqli = new mysqli($servername, $username, $password, $db_name);

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

$sql = "UPDATE quizes SET count = count + 1 WHERE id = QUIZ_ID"; // be careful from injections again!

if($mysqli->query($sql) === true){
    echo "Done";
}else{
    echo "Error: " . $mysqli->error;
}

$mysqli->close;

?>


答:
The easiest approach is to get the filled array from a function and use that to initialize your const (or constexpr) object. However, built-in arrays can't be copied but std::array<T, N> be:

```<code>std::array<T, 255> array = initializeData();
</code>```

If you need a built-in array, I can imagine initializing a static member of a class (template, actually) where the index is expanded from indices expanded from an std::make_index_sequence<255> and used as positional argument in the array, i.e., something along these lines:

```<code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>

int some_function(std::size_t i) { return i; }

template <typename> struct initialized_array_base;
template <std::size_t... I>
struct initialized_array_base<std::index_sequence<I...>> {
    static const int array[sizeof...(I)];
};

template <std::size_t... I>
int const initialized_array_base<std::index_sequence<I...>>::array[sizeof...(I)]
    = { some_function(I)... };

struct initialized_array
    :initialized_array_base<std::make_index_sequence<256>> {
};

int main() {
    std::copy(std::begin(initialized_array::array),
              std::end(initialized_array::array),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}
</code>```

Title: c++ how to initialize const elements of an array

Body:
The easiest approach is to get the filled array from a function and use that to initialize your const (or constexpr) object. However, built-in arrays can't be copied but std::array<T, N> be:

std::array<T, 255> array = initializeData();

If you need a built-in array, I can imagine initializing a static member of a class (template, actually) where the index is expanded from indices expanded from an std::make_index_sequence<255> and used as positional argument in the array, i.e., something along these lines:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>

int some_function(std::size_t i) { return i; }

template <typename> struct initialized_array_base;
template <std::size_t... I>
struct initialized_array_base<std::index_sequence<I...>> {
    static const int array[sizeof...(I)];
};

template <std::size_t... I>
int const initialized_array_base<std::index_sequence<I...>>::array[sizeof...(I)]
    = { some_function(I)... };

struct initialized_array
    :initialized_array_base<std::make_index_sequence<256>> {
};

int main() {
    std::copy(std::begin(initialized_array::array),
              std::end(initialized_array::array),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
}


问:
Having Issues with Node Express() Transferring Decoded User ID between Middleware and Route
I understand that there was a similar question asked to this one but it was never answered clearly (NodeJS Express Router, pass decoded object between middleware and route?).

I try to use the VerifyOrdinaryUser function as middleware in the favorites.js route. This function should create a field in the request called req.decoded containing user information. I need to access this user information in favorites.js but it shows up as undefined when I try to log it. Is there an issue regarding asynchronous code? I'm not sure how to fix this. Thank you!

Verify.js:

```<code>  //verify.js
   var User = require('../models/users');
   var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
   var config = require('../config.js');

    exports.getToken = function (user) {
        return jwt.sign(user, config.secretKey, {
            expiresIn: 3600
        });
    };

    exports.verifyOrdinaryUser = function (req, res, next) {
        // check header or url parameters or post parameters for token
        var token = req.body.token || req.query.token || req.headers['x-access-token'];

        // decode token
        if (token) {
            // verifies secret and checks exp
            jwt.verify(token, config.secretKey, function (err, decoded) {
                if (err) {
                    var err = new Error('You are not authenticated!');
                    err.status = 401;
                    return next(err);
                } else {
                    // if everything is good, save to request for use in other routes
                    req.decoded = decoded;
                    req.params.id = req.decoded._doc_id;
                    next();
                }
            });
        } else {
            // if there is no token
            // return an error
            var err = new Error('No token provided!');
            err.status = 403;
            return next(err);
        }
    };

    exports.verifyAdmin = function (req, res, next) {
        if (req.decoded._doc.admin == false) {
            next();
        } else {
            // if the user is not admin
            // return an error
            var err = new Error('You are not authorized to perform this operation!');
            err.status = 403;
            return next(err);
        }

    };
</code>```

Favorites.js:

```<code>var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/users');
var Favorite = require('../models/favorites');
var Verify = require('./verify');

router.get('/', Verify.verifyOrdinaryUser, function(res, req, next){
  console.log(req.decoded);
});
</code>```

App.js: (not necessary to look at)

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var index = require('./routes/index');
var users = require('./routes/users');
var dishes = require('./routes/dishes');
var favorites = require('./routes/favorites');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var User = require('./models/users');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(express.static(path.join(__dirname, 'public')));

var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
});

app.use('/', index);
app.use('/dishes', dishes);
app.use('/users', users);
app.use('/favorites', favorites);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
</code>```

答:
Is there an issue regarding asynchronous code?

No. You call next() in callback, so next middleware is called when async stuff is done.

Problem is because you messed up order of arguments. Try replace function(res, req, next) with
function(req, res, next).

Body:
I understand that there was a similar question asked to this one but it was never answered clearly (NodeJS Express Router, pass decoded object between middleware and route?).

I try to use the VerifyOrdinaryUser function as middleware in the favorites.js route. This function should create a field in the request called req.decoded containing user information. I need to access this user information in favorites.js but it shows up as undefined when I try to log it. Is there an issue regarding asynchronous code? I'm not sure how to fix this. Thank you!

Verify.js:

  //verify.js
   var User = require('../models/users');
   var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
   var config = require('../config.js');

    exports.getToken = function (user) {
        return jwt.sign(user, config.secretKey, {
            expiresIn: 3600
        });
    };

    exports.verifyOrdinaryUser = function (req, res, next) {
        // check header or url parameters or post parameters for token
        var token = req.body.token || req.query.token || req.headers['x-access-token'];

        // decode token
        if (token) {
            // verifies secret and checks exp
            jwt.verify(token, config.secretKey, function (err, decoded) {
                if (err) {
                    var err = new Error('You are not authenticated!');
                    err.status = 401;
                    return next(err);
                } else {
                    // if everything is good, save to request for use in other routes
                    req.decoded = decoded;
                    req.params.id = req.decoded._doc_id;
                    next();
                }
            });
        } else {
            // if there is no token
            // return an error
            var err = new Error('No token provided!');
            err.status = 403;
            return next(err);
        }
    };

    exports.verifyAdmin = function (req, res, next) {
        if (req.decoded._doc.admin == false) {
            next();
        } else {
            // if the user is not admin
            // return an error
            var err = new Error('You are not authorized to perform this operation!');
            err.status = 403;
            return next(err);
        }

    };

Favorites.js:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/users');
var Favorite = require('../models/favorites');
var Verify = require('./verify');

router.get('/', Verify.verifyOrdinaryUser, function(res, req, next){
  console.log(req.decoded);
});

App.js: (not necessary to look at)

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var index = require('./routes/index');
var users = require('./routes/users');
var dishes = require('./routes/dishes');
var favorites = require('./routes/favorites');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var User = require('./models/users');
app.use(passport.initialize());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use(express.static(path.join(__dirname, 'public')));

var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
});

app.use('/', index);
app.use('/dishes', dishes);
app.use('/users', users);
app.use('/favorites', favorites);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


问:
how to find time using python?
i want to run my function and then I want to find now's time using python.

then lets say after 2 hours my function should run again.

what should i do?

答:
Is your process going to be running for hours at a time and doing other things? If so you can mark the time like so:

```<code>from time import time

start_time = time()   # current time expressed as seconds since 1/1/1970

...

now = time()
if (now - start_time) >= (2 * 60 * 60):   # number of seconds in 2 hours
  do_function()
</code>```

Otherwise, if it will not need to do anything for 2 hours, you can do:

```<code>from time import sleep

quit_condition = False

if not quit_condition:
  sleep(2 * 60 * 60)     # control will not return to this thread for 2 hours
  quit_condition = do_function()
</code>```

In the second scenario, presumably your function will indicate whether or not the main loop can be exited.

Title: how to find time using python?

Body:
Is your process going to be running for hours at a time and doing other things? If so you can mark the time like so:

from time import time

start_time = time()   # current time expressed as seconds since 1/1/1970

...

now = time()
if (now - start_time) >= (2 * 60 * 60):   # number of seconds in 2 hours
  do_function()

Otherwise, if it will not need to do anything for 2 hours, you can do:

from time import sleep

quit_condition = False

if not quit_condition:
  sleep(2 * 60 * 60)     # control will not return to this thread for 2 hours
  quit_condition = do_function()

In the second scenario, presumably your function will indicate whether or not the main loop can be exited.


问:
Graphene Django and react-router-relay
I'm having real trouble figuring out the way that Graphene Django should be used with react-router-relay. Let's say I can use the following GraphQL query fine via the GraphiQL console on my Django server:

```<code>query {
  allThreads {
    edges {
      node {
        id
      }
    }
  }
}
</code>```

This is presumably Graphene's alternative to the commmon viewer wrapper used because Relay doesn't support connections on root queries. So I understand that allThreads is really a node (of type ThreadNodeConnection), and has an edges connections that I can query.

The trouble is I can't figure out how to use this with Relay, and specifically react-router-relay. I have a React view with a fragment on it like this (with a child Thread component elsewhere):

```<code>fragments: {
      store: () => Relay.QL`
        fragment on Query {
          allThreads (first:300) {
            edges {
              node {
                // child's fragment included here
              }
            },
          }
        }
      `,
    },
</code>```

Webpack checks this against my live schema and likes it. Then I create the following in my index.js for router:

```<code>const ViewerQueries = {
  store: () => Relay.QL`query { allThreads(first:300) }`
};

ReactDOM.render(
  <Router
    forceFetch
    environment={Relay.Store}
    render={applyRouterMiddleware(useRelay)}
    history={browserHistory}
  >
    <Route path='/' component={ThreadList} queries={ViewerQueries} />
  </Router>
  , document.getElementById('container')
)
</code>```

Already I'm feeling a little unsure because I figure I'm doing ViewerQueries wrong, but it's hard to know because everyone else uses this to accommodate their viewer wrapper on their GraphQL connections, but Graphene has a different wrapper on each connection, so this might only work for my single route, but that's okay for now. Webpack likes it against the schema again. But when I load the page, I get a 'bad request' and the error that:

"Fragment F1 cannot be spread here as objects of type
  ThreadNodeConnection can never be of type Query"

To be honest, that's about where I couldn't proceed, because I'm clearly not understanding something about either how Graphene Django constructs the schema, or how the GraphQL fragments should be written, or how the Route query should be written. Trouble is I can't figure out which of these things is wrong, and there don't seem to be any resources out there around people using these particular combinations of technologies.

For completeness, my Graphene Django schema setup is (slightly simplified):

project/threads/schema.py:

```<code>class ThreadNode(DjangoObjectType):
    class Meta:
        model = Thread
        interfaces = (relay.Node, )

...

class Query(graphene.AbstractType):
    all_threads = DjangoFilterConnectionField(ThreadNode)
    thread = relay.Node.Field(ThreadNode, id=graphene.Int())

    def resolve_all_threads(self, args, context, info):
        return Thread.objects.select_related('author__profile').all()

    def resolve_thread(self, args, context, info):
        id = args.get('id')

        if id is not None:
            return Thread.objects.get(pk=id)

        return None
</code>```

project/schema.py:

```<code>class Query(project.threads.schema.Query, graphene.ObjectType):
    pass

schema = graphene.Schema(query=Query)
</code>```

If anyone has used this particular combination before and has any advice, that'd be amazing.

答:
I had this same issue and after a long search i finally found this answer
https://github.com/facebook/relay/issues/1558#issuecomment-297010663

Since relay 1 don't support connections as root query. you should ad a viewer as a node interface to wrap your query.
So in your server main query (project/schema.py) you should add the following code:

```<code>class Query(project.threads.schema.Query, graphene.ObjectType):
   viewer = graphene.Field(lambda: Query)
   id = graphene.ID(required=True)

   def resolve_viewer(self, args, context, info):
    return info.parent_type

   def resolve_id(self, args, context, info):
      return 1

   class Meta:
      interfaces = (graphene.relay.Node,)
</code>```

Now  in you graphiql you can format your query like this:

```<code>query {
  viewer{
  allThreads(first:10) {
    edges {
      node {
        id
      }
    }
  }
}
}
</code>```

In client side you can create your container like this:

```<code>export default Relay.createContainer(ThreadList, {
    fragments: {
        viewer: () => Relay.QL`
     fragment on Query {
          id
          allThreads(first:10){
            edges{
              node{
               id
               }
            }
          }
      }
    `,
    },
});
</code>```

I hope this can help you

Title: Graphene Django and react-router-relay

Body:
I'm having real trouble figuring out the way that Graphene Django should be used with react-router-relay. Let's say I can use the following GraphQL query fine via the GraphiQL console on my Django server:

query {
  allThreads {
    edges {
      node {
        id
      }
    }
  }
}

This is presumably Graphene's alternative to the commmon viewer wrapper used because Relay doesn't support connections on root queries. So I understand that allThreads is really a node (of type ThreadNodeConnection), and has an edges connections that I can query.

The trouble is I can't figure out how to use this with Relay, and specifically react-router-relay. I have a React view with a fragment on it like this (with a child Thread component elsewhere):

fragments: {
      store: () => Relay.QL`
        fragment on Query {
          allThreads (first:300) {
            edges {
              node {
                // child's fragment included here
              }
            },
          }
        }
      `,
    },

Webpack checks this against my live schema and likes it. Then I create the following in my index.js for router:

const ViewerQueries = {
  store: () => Relay.QL`query { allThreads(first:300) }`
};

ReactDOM.render(
  <Router
    forceFetch
    environment={Relay.Store}
    render={applyRouterMiddleware(useRelay)}
    history={browserHistory}
  >
    <Route path='/' component={ThreadList} queries={ViewerQueries} />
  </Router>
  , document.getElementById('container')
)

Already I'm feeling a little unsure because I figure I'm doing ViewerQueries wrong, but it's hard to know because everyone else uses this to accommodate their viewer wrapper on their GraphQL connections, but Graphene has a different wrapper on each connection, so this might only work for my single route, but that's okay for now. Webpack likes it against the schema again. But when I load the page, I get a 'bad request' and the error that:

"Fragment F1 cannot be spread here as objects of type
  ThreadNodeConnection can never be of type Query"

To be honest, that's about where I couldn't proceed, because I'm clearly not understanding something about either how Graphene Django constructs the schema, or how the GraphQL fragments should be written, or how the Route query should be written. Trouble is I can't figure out which of these things is wrong, and there don't seem to be any resources out there around people using these particular combinations of technologies.

For completeness, my Graphene Django schema setup is (slightly simplified):

project/threads/schema.py:

class ThreadNode(DjangoObjectType):
    class Meta:
        model = Thread
        interfaces = (relay.Node, )

...

class Query(graphene.AbstractType):
    all_threads = DjangoFilterConnectionField(ThreadNode)
    thread = relay.Node.Field(ThreadNode, id=graphene.Int())

    def resolve_all_threads(self, args, context, info):
        return Thread.objects.select_related('author__profile').all()

    def resolve_thread(self, args, context, info):
        id = args.get('id')

        if id is not None:
            return Thread.objects.get(pk=id)

        return None

project/schema.py:

class Query(project.threads.schema.Query, graphene.ObjectType):
    pass

schema = graphene.Schema(query=Query)

If anyone has used this particular combination before and has any advice, that'd be amazing.

Body:
I had this same issue and after a long search i finally found this answer
https://github.com/facebook/relay/issues/1558#issuecomment-297010663

Since relay 1 don't support connections as root query. you should ad a viewer as a node interface to wrap your query.
So in your server main query (project/schema.py) you should add the following code:

class Query(project.threads.schema.Query, graphene.ObjectType):
   viewer = graphene.Field(lambda: Query)
   id = graphene.ID(required=True)

   def resolve_viewer(self, args, context, info):
    return info.parent_type

   def resolve_id(self, args, context, info):
      return 1

   class Meta:
      interfaces = (graphene.relay.Node,)

Now  in you graphiql you can format your query like this:

query {
  viewer{
  allThreads(first:10) {
    edges {
      node {
        id
      }
    }
  }
}
}

In client side you can create your container like this:

export default Relay.createContainer(ThreadList, {
    fragments: {
        viewer: () => Relay.QL`
     fragment on Query {
          id
          allThreads(first:10){
            edges{
              node{
               id
               }
            }
          }
      }
    `,
    },
});

I hope this can help you


问:
Linq query with in clause and max
I have a simple sql query but I cannot convert it to LINQ:

```<code>select * from client_software where update_date in
    (select max(update_date) AS UPDATE_DATE from client_software a
        where a.client_code = client_software.client_code and
            a.software_code = client_software.software_code)
</code>```

Can somebody help?

答:
Can you please give this a try:</p>

```<code>var q = entity.client_software.Where(r => r.update_date.Value
== entity.client_software.Where(u => u.client_code == r.client_code &&
u.software_code == r.software_code).Max(s => s.update_date)).ToList();
</code>```

Title: Linq query with in clause and max

Body:
I have a simple sql query but I cannot convert it to LINQ:

select * from client_software where update_date in
    (select max(update_date) AS UPDATE_DATE from client_software a
        where a.client_code = client_software.client_code and
            a.software_code = client_software.software_code)

Can somebody help?

Body:
Can you please give this a try:

var q = entity.client_software.Where(r => r.update_date.Value
== entity.client_software.Where(u => u.client_code == r.client_code &&
u.software_code == r.software_code).Max(s => s.update_date)).ToList();


问:
Using Python 3, how to print a panda series with categories
How do I print the car_data Series using Python 3?</p>

```<code>import pandas as pd

car_colors = pd.Series(['Blue', 'Red', 'Green'], dtype='category')

car_data = pd.Series(pd.Categorical(['Yellow', 'Green', 'Red', 'Blue', Purple'], categories=car_colors, ordered=False))

print(str(car_colors)) # works

# both print statements below give this error:
# ValueError: object __array_method not producing an array
print(str(car_data))
print(car_data.to_string())
</code>```

答:
Let's try this, pd.Categorical, category takes and index-like values

```<code>car_colors = ['Blue', 'Red', 'Green']

car_data = pd.Series(pd.Categorical(['Yellow', 'Green', 'Red', 'Blue', 'Purple'], categories=car_colors, ordered=False))

print(str(car_colors)) # works
#Works now too....
print(str(car_data))
print(car_data.to_string())
</code>```

Output:

```<code>['Blue', 'Red', 'Green']
0      NaN
1    Green
2      Red
3     Blue
4      NaN
dtype: category
Categories (3, object): [Blue, Red, Green]
0      NaN
1    Green
2      Red
3     Blue
4      NaN
Categories (3, object): [Blue, Red, Green]
</code>```

Body:
How do I print the car_data Series using Python 3?

import pandas as pd

car_colors = pd.Series(['Blue', 'Red', 'Green'], dtype='category')

car_data = pd.Series(pd.Categorical(['Yellow', 'Green', 'Red', 'Blue', Purple'], categories=car_colors, ordered=False))

print(str(car_colors)) # works

# both print statements below give this error:
# ValueError: object __array_method not producing an array
print(str(car_data))
print(car_data.to_string())

Body:
Let's try this, pd.Categorical, category takes and index-like values

car_colors = ['Blue', 'Red', 'Green']

car_data = pd.Series(pd.Categorical(['Yellow', 'Green', 'Red', 'Blue', 'Purple'], categories=car_colors, ordered=False))

print(str(car_colors)) # works
#Works now too....
print(str(car_data))
print(car_data.to_string())

Output:

['Blue', 'Red', 'Green']
0      NaN
1    Green
2      Red
3     Blue
4      NaN
dtype: category
Categories (3, object): [Blue, Red, Green]
0      NaN
1    Green
2      Red
3     Blue
4      NaN
Categories (3, object): [Blue, Red, Green]


问:
Android - PageView in new BottomNavigationBar - prevent reload fragments
In my StartActivity the BottomNavigationBar Listener has the following setup:

```<code>private GuideFragment guideFragment = new GuideFragment();
private MapFragment mapFragment = new MapFragment();
private MoreFragment moreFragment = new MoreFragment();

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;
        switch (item.getItemId()) {
            case R.id.navigation_guide:
                selectedFragment = guideFragment;
                break;
            case R.id.navigation_map:
                selectedFragment = mapFragment;
                break;
            case R.id.navigation_more:
                selectedFragment = moreFragment;
                break;
        }
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.content, selectedFragment);
        transaction.commit();
        return true;
    }

};
</code>```

As I mentioned above I want to prevent that the selected fragments always reloads the sources/view.
I tried out some stuff like - in the fragments:

```<code>if (rootView == null)
     inflater.inflate...
</code>```

But the fragments still recreate the view and load (in my case) webresources new.

I read something that a PageView could help, especially

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

should do the magic.

My main question is where should I implement a PageViewer - Is it possible in my StartActivity?
Or can I solve the problem in an other way?

答:
I did it boys!
There is no ViewPager necessary.

Here is my solution (all coded in StartActivity not in Fragments):

```<code>private final GuideFragment guideFragment = new GuideFragment();
private final MapFragment mapFragment = new MapFragment();
private final MoreFragment moreFragment = new MoreFragment();
private final android.app.FragmentManager fm = getFragmentManager();
Fragment active = guideFragment;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_guide:
                if(active != guideFragment) {
                    fm.beginTransaction().show(guideFragment).commit();
                }
                else {
                    fm.beginTransaction().hide(active).show(guideFragment).commit();
                }
                active = guideFragment;
                break;
            case R.id.navigation_map:
                fm.beginTransaction().hide(active).show(mapFragment).commit();
                active = mapFragment;
                break;
            case R.id.navigation_more:
                fm.beginTransaction().hide(active).show(moreFragment).commit();
                active = moreFragment;
                break;
        }

        return true;
    }

};
</code>```

and in onCreate list the transaction commits.

```<code>fm.beginTransaction().add(R.id.content,moreFragment).commit();
fm.beginTransaction().add(R.id.content, mapFragment).commit();
fm.beginTransaction().add(R.id.content, guideFragment).commit();
</code>```

It is very important to commit the first tabs fragment last(fragm3,fragm2,fragm1) if you have 3 tabs.

Highly speed performance on the smartphone now by not loading every fragment new/refresh.

Body:
In my StartActivity the BottomNavigationBar Listener has the following setup:

private GuideFragment guideFragment = new GuideFragment();
private MapFragment mapFragment = new MapFragment();
private MoreFragment moreFragment = new MoreFragment();

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;
        switch (item.getItemId()) {
            case R.id.navigation_guide:
                selectedFragment = guideFragment;
                break;
            case R.id.navigation_map:
                selectedFragment = mapFragment;
                break;
            case R.id.navigation_more:
                selectedFragment = moreFragment;
                break;
        }
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.content, selectedFragment);
        transaction.commit();
        return true;
    }

};

As I mentioned above I want to prevent that the selected fragments always reloads the sources/view.
I tried out some stuff like - in the fragments:

if (rootView == null)
     inflater.inflate...

But the fragments still recreate the view and load (in my case) webresources new.

I read something that a PageView could help, especially

offScreenPageLimit

should do the magic.

My main question is where should I implement a PageViewer - Is it possible in my StartActivity?
Or can I solve the problem in an other way?

Body:
I did it boys!
There is no ViewPager necessary.

Here is my solution (all coded in StartActivity not in Fragments):

private final GuideFragment guideFragment = new GuideFragment();
private final MapFragment mapFragment = new MapFragment();
private final MoreFragment moreFragment = new MoreFragment();
private final android.app.FragmentManager fm = getFragmentManager();
Fragment active = guideFragment;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_guide:
                if(active != guideFragment) {
                    fm.beginTransaction().show(guideFragment).commit();
                }
                else {
                    fm.beginTransaction().hide(active).show(guideFragment).commit();
                }
                active = guideFragment;
                break;
            case R.id.navigation_map:
                fm.beginTransaction().hide(active).show(mapFragment).commit();
                active = mapFragment;
                break;
            case R.id.navigation_more:
                fm.beginTransaction().hide(active).show(moreFragment).commit();
                active = moreFragment;
                break;
        }

        return true;
    }

};

and in onCreate list the transaction commits.

fm.beginTransaction().add(R.id.content,moreFragment).commit();
fm.beginTransaction().add(R.id.content, mapFragment).commit();
fm.beginTransaction().add(R.id.content, guideFragment).commit();

It is very important to commit the first tabs fragment last(fragm3,fragm2,fragm1) if you have 3 tabs.

Highly speed performance on the smartphone now by not loading every fragment new/refresh.


问:
PHPhotoLibrary get album names
I've been trying to find an alternative for getting the album names with the Photos API in iOS 8. With ALAssets, we can use: valueForProperty:ALAssetsGroupPropertyName however with the Photos API, I can't seem to find an alternative. There is: localizedTitle under PHAssetCollection but that isn't right either, it just gives me the city names. I'm looking for something that can return the actual names of the groups, including ones synced with iTunes.

I'd appreciate any help to see how you do this in your apps. Apple is encouraging us to only use the Photos API for apps linked with 8.0, so I'd rather not use both ALAssetLibrary and Photos.

Code:

```<code>- (NSString *)nameForAlbumInCollection:(id)collection
{
    NSString *title = nil;

    if ([PHAsset class])
    {
        title = [collection localizedTitle];
    }
    else
    {
        title = [collection valueForProperty:ALAssetsGroupPropertyName];
    }

    return title;
}

- (void)setup
{
    self.recentsCollectionDataSource = [[NSMutableOrderedSet alloc]init];
    self.favoritesCollectionDataSource = [[NSMutableOrderedSet alloc]init];
    self.albumsTableDataSource = [[NSMutableOrderedSet alloc]init];

    NSMutableArray *segmentTitles = [[NSMutableArray alloc]init];

    self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];

    if (!self.parentController.canTakeOrChooseVideo)
    {
        fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i",PHAssetMediaTypeImage];
    }

    for (PHAssetCollection *sub in self.assetsFetchResult)
    {
        PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:nil];

        for (PHAsset *asset in assetsInCollection)
        {
            NSLog(@"%@",[self nameForAlbumInCollection:sub]);

            [self.recentsCollectionDataSource addObject:asset];

            if (![segmentTitles containsObject:@"Recents"])
            {
                [segmentTitles addObject:@"Recents"];
                [segmentTitles addObject:@"Albums"];
            }

            if (asset.isFavorite)
            {
                [self.favoritesCollectionDataSource addObject:asset];

                if (![segmentTitles containsObject:@"Favorites"])
                {
                    [segmentTitles addObject:@"Favorites"];
                }
            }
        }
    }
}
</code>```

答: The bitmask won't work as PHAssetCollectionTypeAlbum, PHAssetCollectionTypeSmartAlbum and PHAssetCollectionTypeMoment are not specified as bit fields.  They take values 1, 2, 3.  For a bitmask to work they would have to take values 1, 2, 4, which each value being on a different bit.</p>

Title: PHPhotoLibrary get album names

Body:
I've been trying to find an alternative for getting the album names with the Photos API in iOS 8. With ALAssets, we can use: valueForProperty:ALAssetsGroupPropertyName however with the Photos API, I can't seem to find an alternative. There is: localizedTitle under PHAssetCollection but that isn't right either, it just gives me the city names. I'm looking for something that can return the actual names of the groups, including ones synced with iTunes.

I'd appreciate any help to see how you do this in your apps. Apple is encouraging us to only use the Photos API for apps linked with 8.0, so I'd rather not use both ALAssetLibrary and Photos.

Code:

- (NSString *)nameForAlbumInCollection:(id)collection
{
    NSString *title = nil;

    if ([PHAsset class])
    {
        title = [collection localizedTitle];
    }
    else
    {
        title = [collection valueForProperty:ALAssetsGroupPropertyName];
    }

    return title;
}

- (void)setup
{
    self.recentsCollectionDataSource = [[NSMutableOrderedSet alloc]init];
    self.favoritesCollectionDataSource = [[NSMutableOrderedSet alloc]init];
    self.albumsTableDataSource = [[NSMutableOrderedSet alloc]init];

    NSMutableArray *segmentTitles = [[NSMutableArray alloc]init];

    self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil];

    if (!self.parentController.canTakeOrChooseVideo)
    {
        fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i",PHAssetMediaTypeImage];
    }

    for (PHAssetCollection *sub in self.assetsFetchResult)
    {
        PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:nil];

        for (PHAsset *asset in assetsInCollection)
        {
            NSLog(@"%@",[self nameForAlbumInCollection:sub]);

            [self.recentsCollectionDataSource addObject:asset];

            if (![segmentTitles containsObject:@"Recents"])
            {
                [segmentTitles addObject:@"Recents"];
                [segmentTitles addObject:@"Albums"];
            }

            if (asset.isFavorite)
            {
                [self.favoritesCollectionDataSource addObject:asset];

                if (![segmentTitles containsObject:@"Favorites"])
                {
                    [segmentTitles addObject:@"Favorites"];
                }
            }
        }
    }
}


问:
SSRS Export to Excel results in (500) Server Error
I have an SSRS report (SSRS 2012) that when I try to export to Excel, always crashes after a minute or so with a 500 server error.

The report itself runs successfully.  And I can successfully export the result to CSV, which actually only takes a few seconds to do after the report itself has rendered.

I am experiencing this on result sets greater than around 20000 records; my current example has 36000 records - it crashes the Excel export but the CSV export is successful.

I've tried checking the SSRS logs (C:\Program Files\Microsoft SQL Server\MSRS11.SQL2012\Reporting Services\LogFiles) no errors are shown in there, just a couple entries for RenderForNewSession and RenderFromSession pointing to my report.

The Event Viewer Application log shows a Warning entry for ASP.NET 2.0:

Exception information:
    Exception type: COMException
    Exception message: This network connection does not exist. (Exception from HRESULT: 0x800708CA)

Is there any place else I might find useful debugging information? I'd really rather not have to direct the client to "not export large reports to Excel, use CSV instead" if I don't have to. Or are there any known issues or quirks when exporting to Excel from the SSRS web report viewer?

EDIT:

After some further digging, I've found some more info but have yet to find an actual solution.  I did find where I could turn up the debugging level in the logs - in the ReportingSErvicesService.exe.config file there are two settings, DefaultTraceSwitch and Components underneath an RSTrace tag. They have default values of 3 but bumping each to 4 provides what appears to be a verbose logging output.

That was interesting, but didn't really point me to anything new other than confirming that it looks like the client execution is timing out.

Next I've come across a TechNet article that at least seems to describe the various places I might be able to set an SSRS timeout.  From what I can tell it seems like the Excel export renderer is hitting an execution timeout somewhere, but all of the SSRS settings appear to cover plenty of headroom for running anything.

Should the web.config httpRuntime executionTimeout setting override the machine.config settings? The TechNet article implies that the machine.config settings seems to line up with the timeout I'm seeing when exporting, but the ReportServer web.config has an executionTimeout setting much larger than the ASP.NET default setting.

答:
One thought for you is the output of the data has something Excel cannot handle but the csv can.  So line breaks in the data or something along those lines.

What happens if you limit your results to just 1 row returned if possible?  No rows returned?  Does it then output the Excel?

Also, I know from SSRS you can output data onto new tabs, are you using that functionality and perhaps running out of tabs?

Reporting Services export to Excel with Multiple Worksheets


答:
to determine current time, you can use pythons datetime module

```<code>from datetime import datetime
print datetime.datetime.now();
</code>```

To run script every two hours - this is a job to crontab deamon. This is a special process in UNIX systems that executed commands in periods of time.

Read about setting up cron jobs here: http://blog.dreamhosters.com/kbase/index.cgi?area=2506

Title: how to find time using python?

Body:
i want to run my function and then I want to find now's time using python.

then lets say after 2 hours my function should run again.

what should i do?

Body:
to determine current time, you can use pythons datetime module

from datetime import datetime
print datetime.datetime.now();

To run script every two hours - this is a job to crontab deamon. This is a special process in UNIX systems that executed commands in periods of time.

Read about setting up cron jobs here: http://blog.dreamhosters.com/kbase/index.cgi?area=2506


问:
How and what does npm link do in this example?
I'm installing react-native-elements and in the installation guide there is this command:

npm i react-native-vector-icons --save && react-native link react-native-vector-icons

I am curious what this part of the command does and why it is necessary: react-native link react-native-vector-icons

答: As you might know, React Native allows you to interface with the native APIs of the OS via JavaScript. In order to establish this interface, some configuration is required in the native side (linking libraries, adding search paths and assets...), and since this process is relatively repetitive and can be automated, the RN folks made the link command in order to set up modules with native code more easily. In the case of React Native Vector Icons, it will add the font files and other configuration to your project, for both Android and iOS.


问:
On 8088/86, does a shift/rotate by CL alter the value in CL?
In the iAP88/86 documentation, the timing information for the shifts and rotates depends on the shift count in CL (p2-64). This seems to imply that it's looping over the count in CL, doing that many single-bit shifts.

So my question is, does CL still have the same value after the rotate/shift completes, or does the operation count it down, similar to how the LOOP instruction behaves?

答:
On the Intel 8088, shift or rotate by a value in CL leaves CL unchanged. This is true for these instructions: RCL RCR ROL ROR SAL SAR SHL SHR

Semantics for these instructions on the Intel 8088 are specified in the iAPX 88 Book from July 1981.

Taking ROL for exposition, syntax is: ROL destination,count

The encoding specification establishes the value of the symbol COUNT used in the semantics spec. For the relevant instruction form the value of CL is assigned to the symbol:

```<code>if v = 0 then COUNT = 1
else COUNT = (CL)
</code>```

The semantics spec indicates the value of the symbol COUNT is assigned to a temporary variable. The register CL is never changed.

```<code>(temp) ← COUNT
do while (temp) ≠ 0
  (CF) ← high-order bit of (EA)
  (EA) ← (EA) * 2 + (CF)
  (temp) ← (temp)-1
if COUNT = 1 then
  if high-order bit of (EA) ≠ (CF)
    then (OF) ← 1
  else (OF) ← 0
else (OF) undefined
</code>```

Body:
On the Intel 8088, shift or rotate by a value in CL leaves CL unchanged. This is true for these instructions: RCL RCR ROL ROR SAL SAR SHL SHR

Semantics for these instructions on the Intel 8088 are specified in the iAPX 88 Book from July 1981.

Taking ROL for exposition, syntax is: ROL destination,count

The encoding specification establishes the value of the symbol COUNT used in the semantics spec. For the relevant instruction form the value of CL is assigned to the symbol:

if v = 0 then COUNT = 1
else COUNT = (CL)

The semantics spec indicates the value of the symbol COUNT is assigned to a temporary variable. The register CL is never changed.

(temp) ← COUNT
do while (temp) ≠ 0
  (CF) ← high-order bit of (EA)
  (EA) ← (EA) * 2 + (CF)
  (temp) ← (temp)-1
if COUNT = 1 then
  if high-order bit of (EA) ≠ (CF)
    then (OF) ← 1
  else (OF) ← 0
else (OF) undefined


问:
Bypassing the IncompleteRead exception
I am writing a Twitter stream listener in Python3 using Tweepy. I get this error after streaming for a while:

```<code>urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))
</code>```

How can I just bypass this, reconnect and keep going?

I have done:

```<code>from requests.packages.urllib3.exceptions import ReadTimeoutError, IncompleteRead
</code>```

And:

```<code>while True:
    try:
        twitter_stream.filter(track=keywordlist, follow=userlist)

    except IncompleteRead:
        continue
</code>```

But still getting the error.

答:
The exception you're getting is a urllib3.exceptions.ProtocolError exception.

Try:

```<code>from urllib3.exceptions import ProtocolError

while True:
    try:
        twitter_stream.filter(track=keywordlist, follow=userlist)

    except ProtocolError:
        continue
</code>```

Title: Bypassing the IncompleteRead exception

Body:
I am writing a Twitter stream listener in Python3 using Tweepy. I get this error after streaming for a while:

urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read))

How can I just bypass this, reconnect and keep going?

I have done:

from requests.packages.urllib3.exceptions import ReadTimeoutError, IncompleteRead

And:

while True:
    try:
        twitter_stream.filter(track=keywordlist, follow=userlist)

    except IncompleteRead:
        continue

But still getting the error.

Body:
The exception you're getting is a urllib3.exceptions.ProtocolError exception.

Try:

from urllib3.exceptions import ProtocolError

while True:
    try:
        twitter_stream.filter(track=keywordlist, follow=userlist)

    except ProtocolError:
        continue


答:
```<code>var ans = from cs in client_software
          where cs.update_date == (from a in client_software where a.client_code == cs.client_code && a.software_code == cs.software_code select a).Max(cs2 => cs2.update_date)
          select cs;
</code>```

Using a group by may be clearer in this case:

```<code>var ans2 = from cs in client_software
          group cs by new { cs.client_code, cs.software_code } into csg
          from cs in csg
          where cs.update_date == csg.Max(cs => cs.update_date)
          select cs;
</code>```

Title: Linq query with in clause and max

Body:
var ans = from cs in client_software
          where cs.update_date == (from a in client_software where a.client_code == cs.client_code && a.software_code == cs.software_code select a).Max(cs2 => cs2.update_date)
          select cs;

Using a group by may be clearer in this case:

var ans2 = from cs in client_software
          group cs by new { cs.client_code, cs.software_code } into csg
          from cs in csg
          where cs.update_date == csg.Max(cs => cs.update_date)
          select cs;


问:
Handling 'ctrl+s' keypress event for browser
I was trying to implement the CTRL+S feature for a browser based application. I made a search and came across two scripts in the following to questions

Best cross-browser method to capture CTRL+S with JQuery?

Ctrl+S preventDefault in Chrome

However, when I tried to implement it, it worked but, I still get the default browser save dialog box/window.

My Code:For shortcut.js:

 shortcut.add("Ctrl+S",function() {
     alert("Hi there!");
 },
 {
     'type':'keydown',
     'propagate':false,
     'target':document
});
```
<p>jQuery hotkeys.js:</p>
<pre class="lang-js prettyprint-override"><code>$(document).bind('keydown', 'ctrl+s', function(e) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
});
</code>```

I believe e.preventDefault(); should do the trick, but for some reason it doesn't work. Where am I going wrong.Sorry if it is simple, still learning jJvascript.

答:
People are still viewing this it seems, so it's probably worth pointing out that there is no need for jQuery on this one, here:

```<code>function keydown (event) {
    var isCtrlKeyDown = navigator.platform.indexOf("Mac") > -1 ? event.metaKey : event.ctrlKey,
        isSDown = (event.key && event.key === "s") || (event.keyCode || event.which) === 83 // falls back to keycode if no event.key

    if (isCtrlKeyDown && isSDown) {
        // prevent default event on newer browsers
        if (event.preventDefault) {
            event.preventDefault()
        }

        // ... your code here ...

        // prevent default event on older browsers
        return false
    }
}

// register the event
if (document.addEventListener) {
    document.addEventListener("keydown", keydown)
} else {
    document.onkeydown = keydown
}
</code>```

That should work in all browsers, this will also work for folks using alternative keyboard layouts from QWERTY on Windows, which reports incorrect key codes (at least on Chrome 56 on Windows 10 in my testing)

However, this looks kind of clunky, and confusing, so if you are only supporting modern browsers, you can do the following instead:

```<code>document.addEventListener("keydown", function keydown (event) {
    if (navigator.platform === "MacIntel" ? event.metaKey : event.ctrlKey && event.key === "s") {
        event.preventDefault()

        // ... your code here ...
    }
})
</code>```

Body:
I was trying to implement the CTRL+S feature for a browser based application. I made a search and came across two scripts in the following to questions

Best cross-browser method to capture CTRL+S with JQuery?

Ctrl+S preventDefault in Chrome

However, when I tried to implement it, it worked but, I still get the default browser save dialog box/window.

My Code:For shortcut.js:

 shortcut.add("Ctrl+S",function() {
     alert("Hi there!");
 },
 {
     'type':'keydown',
     'propagate':false,
     'target':document
});

jQuery hotkeys.js:

$(document).bind('keydown', 'ctrl+s', function(e) {
    e.preventDefault();
    alert('Ctrl+S');
    return false;
});

I believe e.preventDefault(); should do the trick, but for some reason it doesn't work. Where am I going wrong.Sorry if it is simple, still learning jJvascript.

Body:
People are still viewing this it seems, so it's probably worth pointing out that there is no need for jQuery on this one, here:

function keydown (event) {
    var isCtrlKeyDown = navigator.platform.indexOf("Mac") > -1 ? event.metaKey : event.ctrlKey,
        isSDown = (event.key && event.key === "s") || (event.keyCode || event.which) === 83 // falls back to keycode if no event.key

    if (isCtrlKeyDown && isSDown) {
        // prevent default event on newer browsers
        if (event.preventDefault) {
            event.preventDefault()
        }

        // ... your code here ...

        // prevent default event on older browsers
        return false
    }
}

// register the event
if (document.addEventListener) {
    document.addEventListener("keydown", keydown)
} else {
    document.onkeydown = keydown
}

That should work in all browsers, this will also work for folks using alternative keyboard layouts from QWERTY on Windows, which reports incorrect key codes (at least on Chrome 56 on Windows 10 in my testing)

However, this looks kind of clunky, and confusing, so if you are only supporting modern browsers, you can do the following instead:

document.addEventListener("keydown", function keydown (event) {
    if (navigator.platform === "MacIntel" ? event.metaKey : event.ctrlKey && event.key === "s") {
        event.preventDefault()

        // ... your code here ...
    }
})