问:
Xamarin async task initiation
Here i have two different approaches to define and call async task method

1.

```<code>using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace foo{
    public class bar{
        public bar(){
            LoadData();
        }

        private async void LoadData(){
            var data=await getData<List<string>>("http://foobar.com/city");
        }

        private Task<T> getData<T>(string url){
            return Task.Run(async()=>{
                try{
                    var client=new HttpClient();
                    var response=await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
                        var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
                        return data;
                    }
                }catch(Exception){}

                return default(T);
            });
        }
    }
}
</code>```

2.

```<code>using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace foo{
    public class bar{
        public bar(){
            LoadData();
        }

        private async void LoadData(){
            var data=await getData<List<string>>("http://foobar.com/city");
        }

        private async Task<T> getData<T>(string url){
            try{
                var client=new HttpClient();
                var response=await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
                    var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
                    return data;
                }
            }catch(Exception){}

            return default(T);
        }
    }
}
</code>```

difference of these in getData method. 1 just using Task and 2. using async Task.

both of these run normally as expected, but which is the right or best approaches to use?
and please give some explanation

答:
In method 1 you are explicitly creating a Task, with all the overhead of running it, and using it to await other tasks.

Method 2 is the way to go as you aren't creating the unnecessary overhead of the extra Task.

Additionally, unless you know exactly what you are doing, do not use async void - Async/Await - Best Practices in Asynchronous Programming

Title: Xamarin async task initiation

Body:
Here i have two different approaches to define and call async task method

1.

using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace foo{
    public class bar{
        public bar(){
            LoadData();
        }

        private async void LoadData(){
            var data=await getData<List<string>>("http://foobar.com/city");
        }

        private Task<T> getData<T>(string url){
            return Task.Run(async()=>{
                try{
                    var client=new HttpClient();
                    var response=await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
                        var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
                        return data;
                    }
                }catch(Exception){}

                return default(T);
            });
        }
    }
}

2.

using System.IO;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;

namespace foo{
    public class bar{
        public bar(){
            LoadData();
        }

        private async void LoadData(){
            var data=await getData<List<string>>("http://foobar.com/city");
        }

        private async Task<T> getData<T>(string url){
            try{
                var client=new HttpClient();
                var response=await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                using(var reader=new StreamReader(await response.Content.ReadAsStreamAsync())){
                    var data = JsonConvert.DeserializeObject<T>(await reader.ReadToEndAsync());
                    return data;
                }
            }catch(Exception){}

            return default(T);
        }
    }
}

difference of these in getData method. 1 just using Task and 2. using async Task.

both of these run normally as expected, but which is the right or best approaches to use?
and please give some explanation


来源: stackexchange

问:
Could somebody tell me where the heck the IndexError is? (Python)
I am having trouble figuring out where the IndexError in the code is so could somebody help me out

Here's the code

```<code>def gap(g, m, n):
    def is_prime(n):
        for i in range(2, n):
            if n % i == 0:
                return False
        return True
    result = []
    r = []
    primes = [p for p in range(m, n) if is_prime(p)]
    for i in range(len(primes) - 1):
        if primes[i] - primes[i + 1] == g:
            r.append(primes[i - 1])
            r.append(primes[i])
    result.append(r[0])
    result.append(r[1])
    if result == []:
        return None
    else:
        return result
print (gap(2, 100, 110))
</code>```

and here's the output

```<code>Traceback (most recent call last):
  File "C:\Users\Harry\Documents\randompythonprograms\editable.py", line 20, in <module>
    print (gap(2, 100, 110))
  File "C:\Users\Harry\Documents\randompythonprograms\editable.py", line 14, in gap
    result.append(r[0])
IndexError: list index out of range
</code>```

答:
This is the reason for an error.

```<code>r.append(primes[i - 1])
</code>```

It takes i as first value id of list and you pass (i - 1).

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble figuring out where the IndexError in the code is so could somebody help me out

Here's the code

def gap(g, m, n):
    def is_prime(n):
        for i in range(2, n):
            if n % i == 0:
                return False
        return True
    result = []
    r = []
    primes = [p for p in range(m, n) if is_prime(p)]
    for i in range(len(primes) - 1):
        if primes[i] - primes[i + 1] == g:
            r.append(primes[i - 1])
            r.append(primes[i])
    result.append(r[0])
    result.append(r[1])
    if result == []:
        return None
    else:
        return result
print (gap(2, 100, 110))

and here's the output

Traceback (most recent call last):
  File "C:\Users\Harry\Documents\randompythonprograms\editable.py", line 20, in <module>
    print (gap(2, 100, 110))
  File "C:\Users\Harry\Documents\randompythonprograms\editable.py", line 14, in gap
    result.append(r[0])
IndexError: list index out of range

Body:
This is the reason for an error.

r.append(primes[i - 1])

It takes i as first value id of list and you pass (i - 1).


问:
Server-side Performance Testing of a php Web Application
Before I get marked as dupe of articles like:

```<code>[http://stackoverflow.com/questions/635123/what-is-a-good-tool-or-site-to-use-to-performance-test-a-web-page-site][1]
</code>```

Most of the answers on pages like that indicate performance testing of the html, using firebug, YSlow and so on.  Loadrunner is cited, which is good, but what I'd like is a set of tools for performance testing the php itself to identify bottlenecks in the code.

It's a LAMP setup.

So, maybe:

Code coverage testing

Lint for php?

Something like valgrind for c, but for php

any other tool to really hammer the php code and look for flaws or inefficiencies

Currently the best one I've found for it may be JMeter, but I'm only just starting to explore it.

All suggestions appreciated!

答:
Hey, I use XDebug and KCachegrind to check out whats going on server side.

http://kcachegrind.sourceforge.net/html/Home.html

http://www.xdebug.org/

They are pretty easy to set up and have been invaluable to me in identifying bottlenecks in my code.

ContentLicense: CC BY-SA 2.5

Body:
Before I get marked as dupe of articles like:

[http://stackoverflow.com/questions/635123/what-is-a-good-tool-or-site-to-use-to-performance-test-a-web-page-site][1]

Most of the answers on pages like that indicate performance testing of the html, using firebug, YSlow and so on.  Loadrunner is cited, which is good, but what I'd like is a set of tools for performance testing the php itself to identify bottlenecks in the code.

It's a LAMP setup.

So, maybe:

Code coverage testing

Lint for php?

Something like valgrind for c, but for php

any other tool to really hammer the php code and look for flaws or inefficiencies

Currently the best one I've found for it may be JMeter, but I'm only just starting to explore it.

All suggestions appreciated!


问:
CURRENT_TIMESTAMP in milliseconds
Is there any way to get milliseconds out of a timestamp in MySql or PostgreSql (or others just out of curiosity)?

```<code>SELECT CURRENT_TIMESTAMP
--> 2012-03-08 20:12:06.032572
</code>```

Is there anything like this:

```<code>SELECT CURRENT_MILLISEC
--> 1331255526000
</code>```

or the only alternative is to use the DATEDIFF from the era?

答:
In Mysql 5.7+ you can execute

```<code>select current_timestamp(6)
</code>```

for more details

https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

Title: CURRENT_TIMESTAMP in milliseconds

Body:
Is there any way to get milliseconds out of a timestamp in MySql or PostgreSql (or others just out of curiosity)?

SELECT CURRENT_TIMESTAMP
--> 2012-03-08 20:12:06.032572

Is there anything like this:

SELECT CURRENT_MILLISEC
--> 1331255526000

or the only alternative is to use the DATEDIFF from the era?

Body:
In Mysql 5.7+ you can execute

select current_timestamp(6)

for more details

https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html


问:
how to like/unlike with button using toggleclass
this is my like button...

HTML code

```<code><div class="btn">
  <div class="boxcoracao">
    <span class="coracao" id = "<?php echo $postid?>" name = "like">br>   Love</span>
  </div>
</div>
</code>```

Jquery inside HTML

```<code><script>
 $(".btn ").click(function(){
   $('.boxcoracao .coracao', this).toggleClass("ativo");
});
</script>
</code>```

it works when i click and unclick the button the button changes but what my problem is how can i use this function to save data to my database. sample when 1st click the button it will like.. and when i click the button again it will unlike. can you help me how to query this ?

like table

```<code>postid  |  postmember |  likeid
   50          12           1
</code>```

postid by the name itself the id of the post..
postmember is the id of the user who posted sample user 12 posted and the id is 50..
likeid is the user who likes the post of the other user sample user 1 like the post of user 12..

答:
Try this:

```<code>$(".btn ").click(function(){
   $('.boxcoracao .coracao', this).toggleClass("ativo");
   // make an ajax call here to send the data to the server and save it in database
});
</code>```

If condition be like:

```<code>var selection = '';
if( $(this).val() == 'like' )
{
    selection = 'liked';
}
else
{
    selection = 'like';
}
</code>```

pass this variable selection in ajax() call.

and on page reload check the status from database to show like / unlike icon respectively.

Body:
this is my like button...

HTML code

    <span class="coracao" id = "<?php echo $postid?>" name = "like">br>   Love

Jquery inside HTML

it works when i click and unclick the button the button changes but what my problem is how can i use this function to save data to my database. sample when 1st click the button it will like.. and when i click the button again it will unlike. can you help me how to query this ?

like table

postid  |  postmember |  likeid
   50          12           1

postid by the name itself the id of the post..
postmember is the id of the user who posted sample user 12 posted and the id is 50..
likeid is the user who likes the post of the other user sample user 1 like the post of user 12..

Body:
Try this:

$(".btn ").click(function(){
   $('.boxcoracao .coracao', this).toggleClass("ativo");
   // make an ajax call here to send the data to the server and save it in database
});

If condition be like:

var selection = '';
if( $(this).val() == 'like' )
{
    selection = 'liked';
}
else
{
    selection = 'like';
}

pass this variable selection in ajax() call.

and on page reload check the status from database to show like / unlike icon respectively.


答:
```<code>for i in range(len(primes) - 1):
    if primes[i] - primes[i + 1] == g:
        r.append(primes[i - 1])
        r.append(primes[i])
result.append(r[0])
result.append(r[1])
</code>```

You have defined r to be an empty array and is still and empty array after the loop. You can check it by adding a simple print statement. So its an array without an index 0 or 1 so it throws out that error.

Title: Could somebody tell me where the heck the IndexError is? (Python)

Body:
for i in range(len(primes) - 1):
    if primes[i] - primes[i + 1] == g:
        r.append(primes[i - 1])
        r.append(primes[i])
result.append(r[0])
result.append(r[1])

You have defined r to be an empty array and is still and empty array after the loop. You can check it by adding a simple print statement. So its an array without an index 0 or 1 so it throws out that error.


问:
Weirdly occational mySQL error code 1271
I want to do a DB query that counts number of entries based on a mess of criteria. Here's what I have so far:

```<code>MySQL Error
Message: MySQL Query Error
SQL: SELECT COUNT(distinct p0.placeid) FROM uchome_place p0 INNER JOIN uchome_place_hours ph ON (p0.placeid=ph.placeid AND ph.weekdays=DATE_FORMAT(NOW(), "%w") AND ph.start<=TIME_FORMAT(TIMESTAMPADD(HOUR,2,NOW()), "%H:%i:%s") AND ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE p0.book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s") )
Error: Illegal mix of collations for operation '>='
Errno.: 1271
</code>```

This message is in response to me trying to feed the mySQL server with this query through PHP. However, when I try to feed the same mySQL server with the same query through phpMyAdmin, the query runs without errors as shown in this linked picture.

I did some further testing and found that the Illegal mix of collations comes from:

```<code>ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s")
</code>```

How exactly can the PHP-fed query be regarded as Illegal mix of collations while the phpMyAdmin-fed query be regarded as runnable? I need the ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s") query be fed with PHP not phpMyAdmin so I need explanations on how the error occurs in PHP  but not in phpMyAdmin, and how to fix this.

PS: the query in code block is already shortened as per Tim Biegeleisen's request. Original query is way longer, as shown in this linked picture.

PPS: Added additional materials requested by lbu. However, I fail to see what his point is.

```<code><?php
class dbstuff {
    var $querynum = 0;
    var $link;
    var $charset;
    function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {
        if($pconnect) {
            if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {
                $halt && $this->halt('Can not connect to MySQL server');
            }
        }
        else
        {
            if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw, 1)) {
                $halt && $this->halt('Can not connect to MySQL server');
            }
        }
        if($this->version() > '4.1')
        {
            if($this->charset) {
                @mysql_query("SET character_set_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary", $this->link);
            }
            if($this->version() > '5.0.1') {
                @mysql_query("SET sql_mode=''", $this->link);
            }
        }
        if($dbname) {
            @mysql_select_db($dbname, $this->link);
        }
    }
    function query($sql, $type = '') {
        $func = ($type=='UNBUFFERED' && function_exists('mysql_unbuffered_query')) ?'mysql_unbuffered_query':'mysql_query';
        if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
            $this->halt('MySQL Query Error', $sql);
        }
        $this->querynum++;
        return $query;
    }
    function error() {
        return (($this->link) ? mysql_error($this->link) : mysql_error());
    }
    function errno() {
        return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
    }
    function fetch_row($query) {
        $query = mysql_fetch_row($query);
        return $query;
    }
    function version() {
        return mysql_get_server_info($this->link);
    }
    function close() {
        return mysql_close($this->link);
    }
    function halt($message = '', $sql = '') {
        $dberror = $this->error();
        $dberrno = $this->errno();
        echo "<div style=\"position:absolute;font-size:11px;font-family:verdana,arial;background:#EBEBEB;padding:0.5em;\">
            <b>MySQL Error</b><br>
            <b>Message</b>: $message<br>
            <b>SQL</b>: $sql<br>
            <b>Error</b>: $dberror<br>
            <b>Errno.</b>: $dberrno<br>
            </div>";
        exit();
    }
}
error_reporting(7);
set_magic_quotes_runtime(0);
$_SGLOBAL=array();
if(empty($_SGLOBAL['db'])){
    $_SGLOBAL['db']=new dbstuff;
    $_SGLOBAL['db']->charset='utf8mb4';
    $_SGLOBAL['db']->connect('localhost',$username,$password,$dbname);
}
$fullsql="SELECT COUNT(distinct p0.placeid) FROM uchome_place p0 INNER JOIN uchome_place_hours ph ON (p0.placeid=ph.placeid AND ph.weekdays=DATE_FORMAT(NOW(), \"%w\") AND ph.start<=TIME_FORMAT(TIMESTAMPADD(HOUR,2,NOW()), \"%H:%i:%s\") AND ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), \"%H:%i:%s\") )";
$res=$_SGLOBAL['db']->query($fullsql);
if(false===$res)
{
    $place_list=false;
}
else
{
    $row=$_SGLOBAL['db']->fetch_row($res);
    if(false===$row)
    {
        $place_list='';
    }
    else
    {
        $place_list=$row[0];
    }
}
$_SGLOBAL['db']->close();
die(json_encode($place_list));
?>
</code>```

答:
Finally, I ended up solving this question myself. Thanks to rkosegi for hints.

Specifically, problem in my code was that the collation_connection of my DB was not explicitly defined. Which means the DB uses its default value, latin1, in the CASE statement's numbers. Since the column to be CASEd to, book_period, is collated in utf8_general_ci,  this causes error 1271 for PHP-fed MySQL statements.

Solution code:

```<code><?php
class dbstuff {
    var $querynum = 0;
    var $kink;
    var $charset;
    function connect($dbhost, $dbuser, $dbpw, $dbname, $halt=true){
        if(!$this->kink = @mysqli_connect($dbhost, $dbuser, $dbpw, $dbname)){
            $halt && $this->halt('Can not connect to MySQL server');
        }
        if($this->version() > '4.1')
        {
            if($this->charset) {
                @mysqli_query($this->kink,"SET character_set_connection=".$this->charset.",collation_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary");
                #Question's faulty SQL below. Notice the missing collation_connection
                #mysqli_query($this->kink,"SET character_set_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary");
            }
            if($this->version() > '5.0.1') {
                @mysql_query($this->kink,"SET sql_mode=''");
            }
        }
    }
...#rest of the code are unchanged
}
...
?>
</code>```

Body:
I want to do a DB query that counts number of entries based on a mess of criteria. Here's what I have so far:

MySQL Error
Message: MySQL Query Error
SQL: SELECT COUNT(distinct p0.placeid) FROM uchome_place p0 INNER JOIN uchome_place_hours ph ON (p0.placeid=ph.placeid AND ph.weekdays=DATE_FORMAT(NOW(), "%w") AND ph.start<=TIME_FORMAT(TIMESTAMPADD(HOUR,2,NOW()), "%H:%i:%s") AND ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE p0.book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s") )
Error: Illegal mix of collations for operation '>='
Errno.: 1271

This message is in response to me trying to feed the mySQL server with this query through PHP. However, when I try to feed the same mySQL server with the same query through phpMyAdmin, the query runs without errors as shown in this linked picture.

I did some further testing and found that the Illegal mix of collations comes from:

ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s")

How exactly can the PHP-fed query be regarded as Illegal mix of collations while the phpMyAdmin-fed query be regarded as runnable? I need the ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), "%H:%i:%s") query be fed with PHP not phpMyAdmin so I need explanations on how the error occurs in PHP  but not in phpMyAdmin, and how to fix this.

PS: the query in code block is already shortened as per Tim Biegeleisen's request. Original query is way longer, as shown in this linked picture.

PPS: Added additional materials requested by lbu. However, I fail to see what his point is.

<?php
class dbstuff {
    var $querynum = 0;
    var $link;
    var $charset;
    function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $halt = TRUE) {
        if($pconnect) {
            if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {
                $halt && $this->halt('Can not connect to MySQL server');
            }
        }
        else
        {
            if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw, 1)) {
                $halt && $this->halt('Can not connect to MySQL server');
            }
        }
        if($this->version() > '4.1')
        {
            if($this->charset) {
                @mysql_query("SET character_set_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary", $this->link);
            }
            if($this->version() > '5.0.1') {
                @mysql_query("SET sql_mode=''", $this->link);
            }
        }
        if($dbname) {
            @mysql_select_db($dbname, $this->link);
        }
    }
    function query($sql, $type = '') {
        $func = ($type=='UNBUFFERED' && function_exists('mysql_unbuffered_query')) ?'mysql_unbuffered_query':'mysql_query';
        if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
            $this->halt('MySQL Query Error', $sql);
        }
        $this->querynum++;
        return $query;
    }
    function error() {
        return (($this->link) ? mysql_error($this->link) : mysql_error());
    }
    function errno() {
        return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
    }
    function fetch_row($query) {
        $query = mysql_fetch_row($query);
        return $query;
    }
    function version() {
        return mysql_get_server_info($this->link);
    }
    function close() {
        return mysql_close($this->link);
    }
    function halt($message = '', $sql = '') {
        $dberror = $this->error();
        $dberrno = $this->errno();
        echo "

            MySQL Error

            Message: $message

            SQL: $sql

            Error: $dberror

            Errno.: $dberrno

";
        exit();
    }
}
error_reporting(7);
set_magic_quotes_runtime(0);
$_SGLOBAL=array();
if(empty($_SGLOBAL['db'])){
    $_SGLOBAL['db']=new dbstuff;
    $_SGLOBAL['db']->charset='utf8mb4';
    $_SGLOBAL['db']->connect('localhost',$username,$password,$dbname);
}
$fullsql="SELECT COUNT(distinct p0.placeid) FROM uchome_place p0 INNER JOIN uchome_place_hours ph ON (p0.placeid=ph.placeid AND ph.weekdays=DATE_FORMAT(NOW(), \"%w\") AND ph.start<=TIME_FORMAT(TIMESTAMPADD(HOUR,2,NOW()), \"%H:%i:%s\") AND ph.end>=TIME_FORMAT( TIMESTAMPADD( MINUTE,(CASE book_period WHEN 1 THEN 60 WHEN 2 THEN 120 WHEN 6 THEN 30 ELSE 15 END) ,NOW() ), \"%H:%i:%s\") )";
$res=$_SGLOBAL['db']->query($fullsql);
if(false===$res)
{
    $place_list=false;
}
else
{
    $row=$_SGLOBAL['db']->fetch_row($res);
    if(false===$row)
    {
        $place_list='';
    }
    else
    {
        $place_list=$row[0];
    }
}
$_SGLOBAL['db']->close();
die(json_encode($place_list));
?>

Body:
Finally, I ended up solving this question myself. Thanks to rkosegi for hints.

Specifically, problem in my code was that the collation_connection of my DB was not explicitly defined. Which means the DB uses its default value, latin1, in the CASE statement's numbers. Since the column to be CASEd to, book_period, is collated in utf8_general_ci,  this causes error 1271 for PHP-fed MySQL statements.

Solution code:

<?php
class dbstuff {
    var $querynum = 0;
    var $kink;
    var $charset;
    function connect($dbhost, $dbuser, $dbpw, $dbname, $halt=true){
        if(!$this->kink = @mysqli_connect($dbhost, $dbuser, $dbpw, $dbname)){
            $halt && $this->halt('Can not connect to MySQL server');
        }
        if($this->version() > '4.1')
        {
            if($this->charset) {
                @mysqli_query($this->kink,"SET character_set_connection=".$this->charset.",collation_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary");
                #Question's faulty SQL below. Notice the missing collation_connection
                #mysqli_query($this->kink,"SET character_set_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary");
            }
            if($this->version() > '5.0.1') {
                @mysql_query($this->kink,"SET sql_mode=''");
            }
        }
    }
...#rest of the code are unchanged
}
...
?>


问:
Nuget Package Installs Via Console But No Reference Added For C++ Project
I am trying to install the NuGet package detailed on this webpage: https://learn.microsoft.com/en-us/azure/storage/storage-c-plus-plus-how-to-use-blobs

For reference, the instructions are:

Windows: In Visual Studio, click Tools > NuGet Package Manager > Package Manager Console. Type the following command into the NuGet Package Manager console and press ENTER.

This works... kind of.  The package is downloaded locally, but the reference isn't being added to my project.  When I install the package manually or from the PM Console, no reference is added.

Instructions I've been able to find (such as here) just insist that the references will be automagically added.  Which is great when it works, but it provides no debug reference point or how to add them manually.

Are there other options I'm missing?

Thanks.

答:
the reference isn't being added to my project. When I install the package manually or from the PM Console, no reference is added

That is because NuGet cannot directly add references to native projects, the ‘native’ target framework is not recognized within the \lib folder.
For the detail information, you can refer to the Support for Native Projects.

Besides, after installed the wastorage package, you will notice that the blob.h and storage_account.h were added to External Dependencies:

Then you can add the following include statements to the top of the C++ file successfully where you want to use the Azure storage APIs to access blobs:

```<code>#include <was/storage_account.h>
#include <was/blob.h>
</code>```

Update:
According to the JuniorIncanter comment, add the .targets, and .props file in the .vcxproj:

```<code>  <ImportGroup Label="ExtensionTargets">
<Import Project="..\packages\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\wastorage.v120.3.0.0\build\native\wastorage.v120.targets" Condition="Exists('..\packages\wastorage.v120.3.0.0\build\native\wastorage.v120.targets')" />
<Import Project="..\packages\wastorage.v140.3.0.0\build\native\wastorage.v140.targets" Condition="Exists('..\packages\wastorage.v140.3.0.0\build\native\wastorage.v140.targets')" />
</code>```

Body:
the reference isn't being added to my project. When I install the package manually or from the PM Console, no reference is added

That is because NuGet cannot directly add references to native projects, the ‘native’ target framework is not recognized within the \lib folder.
For the detail information, you can refer to the Support for Native Projects.

Besides, after installed the wastorage package, you will notice that the blob.h and storage_account.h were added to External Dependencies:

Then you can add the following include statements to the top of the C++ file successfully where you want to use the Azure storage APIs to access blobs:

#include <was/storage_account.h>
#include <was/blob.h>

Update:
According to the JuniorIncanter comment, add the .targets, and .props file in the .vcxproj:

  <ImportGroup Label="ExtensionTargets">
<Import Project="..\packages\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v120.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets" Condition="Exists('..\packages\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.2.9.1\build\native\cpprestsdk.v140.windesktop.msvcstl.dyn.rt-dyn.targets')" />
<Import Project="..\packages\wastorage.v120.3.0.0\build\native\wastorage.v120.targets" Condition="Exists('..\packages\wastorage.v120.3.0.0\build\native\wastorage.v120.targets')" />
<Import Project="..\packages\wastorage.v140.3.0.0\build\native\wastorage.v140.targets" Condition="Exists('..\packages\wastorage.v140.3.0.0\build\native\wastorage.v140.targets')" />


问:
My UIActionSheet isn't clickable, and now I can't do anything
I open a UIActionSheet with [actionSheet openInView:view] ... and it opens in the iPhone simulator.  And you can't click on it.

Any ideas?

答:
There is one particular issue with action sheets where the cancel button is not touchable when you present a UIActionSheet from a view inside a tab bar controller. To work around this you should present the action sheet from the tab bar controller's view:</p>

```<code>[actionSheet openInView:self.tabbarController.view];
</code>```

Body:
There is one particular issue with action sheets where the cancel button is not touchable when you present a UIActionSheet from a view inside a tab bar controller. To work around this you should present the action sheet from the tab bar controller's view:

[actionSheet openInView:self.tabbarController.view];


问:
Decoding not working with Base64
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

```<code>document.write(atob("hi"));
</code>```

This does not:

```<code>var tempvar = "hello";
document.write(atob(tempvar));
</code>```

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.

答:
Your Question

What am I doing wrong?

The string being passed to atob() is a string literal of length 5 (and not technically a base-64 encoded string). The browser console should reveal an exception in the error log (see explanation in The cause below).

The cause

Per the MDN documentation of atob():

Throws

Throws a DOMException if the length of passed-in string is not a multiple of 4. 1

The length of the string literal "hello" (i.e. 5) is not a multiple of 4. Thus the exception is thrown instead of returning the decoded version of the string literal.

A Solution

One solution is to either use a string that has actually been encoded (e.g. with btoa()) or at least has a length of four (e.g. using String.prototype.substring()). See the snippet below for an example.

var tempvar = "hello";
window.addEventListener("DOMContentLoaded", function(readyEvent) {
    var container = document.getElementById("container");
    //encode the string
    var encoded = btoa(tempvar);
    container.innerHTML = encoded;

    var container2 = document.getElementById("container2");
    //decode the encoded string
    container2.innerHTML = atob(encoded);

    var container3 = document.getElementById("container3");
    //decode the first 4 characters of the string
    container3.innerHTML = atob(tempvar.substring(0, 4));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div> btoa(tempvar): <span id="container"></span></div>
<div> atob(decoded): <span id="container2"></span></div>
<div> atob(tempvar.substring(0, 4)): <span id="container3"></span></div> </code>```

1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob

Title: Decoding not working with Base64

Body:
Encoding my URL works perfectly with base-64 encoding. So does decoding but not with the string literal variable.

This works:

document.write(atob("hi"));

This does not:

var tempvar = "hello";
document.write(atob(tempvar));

What am I doing wrong? Nothing is displayed. But if I quote "tempvar", then it of course works but is not the same thing since "tempvar" is a string, not a variable.

Body:
Your Question

What am I doing wrong?

The string being passed to atob() is a string literal of length 5 (and not technically a base-64 encoded string). The browser console should reveal an exception in the error log (see explanation in The cause below).

The cause

Per the MDN documentation of atob():

Throws

Throws a DOMException if the length of passed-in string is not a multiple of 4. 1

The length of the string literal "hello" (i.e. 5) is not a multiple of 4. Thus the exception is thrown instead of returning the decoded version of the string literal.

A Solution

One solution is to either use a string that has actually been encoded (e.g. with btoa()) or at least has a length of four (e.g. using String.prototype.substring()). See the snippet below for an example.

var tempvar = "hello";
window.addEventListener("DOMContentLoaded", function(readyEvent) {
    var container = document.getElementById("container");
    //encode the string
    var encoded = btoa(tempvar);
    container.innerHTML = encoded;

    var container2 = document.getElementById("container2");
    //decode the encoded string
    container2.innerHTML = atob(encoded);

    var container3 = document.getElementById("container3");
    //decode the first 4 characters of the string
    container3.innerHTML = atob(tempvar.substring(0, 4));
});

<div> btoa(tempvar): <span id="container"></span></div>
<div> atob(decoded): <span id="container2"></span></div>
<div> atob(tempvar.substring(0, 4)): <span id="container3"></span></div>

1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/atob


问:
How to deal with private images in laravel 5?
I am new to Laravel and trying to store private images so that only authenticated users can access them. Firstly I stored images in Public/UserImages folder. But here all the pictures are accessible to unauthenticated users as well by going to Inspect Element of chrome and then changing the user IDs. Kindly help out me...  </p>

答:
I got the same issue some days ago and came up with this solution:

First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:

```<code>// This goes inside your controller method handling the POST request.

$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);
</code>```

The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg

Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function __invoke($file_path)
    {
        if (!Storage::disk('local')->exists($file_path)) {
            abort(404);
        }

        $local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;

        return response()->file($local_path);
    }
}
</code>```

The last thing is register the route inside your routes/web.php file:

```<code>Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])
</code>```

So there you have it, a pretty reusable snippet for all your projects that deals with private files :)

Body:
I got the same issue some days ago and came up with this solution:

First thing you have to do is upload the file to a non-public directory. My app is storing scanned invoices, so I'm going to place them inside storage/app/invoices. The code for uploading the file and generating the url would be:

// This goes inside your controller method handling the POST request.

$path = $request->file('invoice')->store('invoices');
$url = env('APP_URL') . Illuminate\Support\Facades\Storage::url($path);

The url returned should result in something like http://yourdomain.com/storage/invoices/uniquefilename.jpg

Now you have to create a controller that uses the auth middleware to ensure the user is authenticated. Then, define a method that grabs the file from the private directory and returns it as a file response. That would be:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class FileController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function __invoke($file_path)
    {
        if (!Storage::disk('local')->exists($file_path)) {
            abort(404);
        }

        $local_path = config('filesystems.disks.local.root') . DIRECTORY_SEPARATOR . $file_path;

        return response()->file($local_path);
    }
}

The last thing is register the route inside your routes/web.php file:

Route::get('/storage/{file_name}', 'FileController')->where(['file_name' => '.*'])

So there you have it, a pretty reusable snippet for all your projects that deals with private files :)


问:
Align button to the left side near ChartContainer default Icons
I have button (called BUTTON LEFT) in the sap.suite.ui.commons.ChartContainer:

```<code><ChartContainer
    id="chartContainer"
    showFullScreen="true"
    autoAdjustHeight="true">

    <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT"/>
    </dimensionSelectors>

    <content>
        <ChartContainerContent
            icon = "sap-icon://line-chart"
            title = "Line Chart">

            <content>
                <viz:VizFrame id="chartContainerVizFrame" height="700px" width="100%" uiConfig="{applicationSet:'fiori'}"></viz:VizFrame>
            </content>
        </ChartContainerContent>
    </content>
</ChartContainer>
</code>```

I need to align this button to the left side near ChartContainer legend icon. Now it looks like:

But I would like to get something like this:

Here is working example, feel free to edit it.

I am looking for the solution which will be inside in the sap.suite.ui.commons.ChartContainer. I do not want to use css for this if possible. Also I can not use width property of ToolbalSpacer (e.g. width="100px"), because I need ToolbalSpacer changing width when the screen resolution is changed. I know that I can change ToolbarSpacer according to screen resolution but I would like to not use this approach.

Thanks for any hint.

答:
```<code>  <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT" />
  </dimensionSelectors>
</code>```

This is the least thing I could do for this situation.

Body:
I have button (called BUTTON LEFT) in the sap.suite.ui.commons.ChartContainer:

<ChartContainer
    id="chartContainer"
    showFullScreen="true"
    autoAdjustHeight="true">

    <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT"/>
    </dimensionSelectors>

    <content>
        <ChartContainerContent
            icon = "sap-icon://line-chart"
            title = "Line Chart">

            <content>
                <viz:VizFrame id="chartContainerVizFrame" height="700px" width="100%" uiConfig="{applicationSet:'fiori'}"></viz:VizFrame>
            </content>
        </ChartContainerContent>
    </content>
</ChartContainer>

I need to align this button to the left side near ChartContainer legend icon. Now it looks like:

But I would like to get something like this:

Here is working example, feel free to edit it.

I am looking for the solution which will be inside in the sap.suite.ui.commons.ChartContainer. I do not want to use css for this if possible. Also I can not use width property of ToolbalSpacer (e.g. width="100px"), because I need ToolbalSpacer changing width when the screen resolution is changed. I know that I can change ToolbarSpacer according to screen resolution but I would like to not use this approach.

Thanks for any hint.

Body:
  <dimensionSelectors>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:ToolbarSpacer/>
       <m:Button id="idButton" text="BUTTON LEFT" />
  </dimensionSelectors>

This is the least thing I could do for this situation.


Title: SQL Server : deleting records with similar time

Body:
I would like to delete records that have same (or similar) time. This is the sample data:

ID | Name | DateTime
---+------+--------------------
1  | Joe  | 2017-03-01 11:33:13
1  | Joe  | 2017-03-01 11:33:14
1  | Joe  | 2017-03-01 11:33:15
1  | Joe  | 2017-03-01 11:55:30
2  | John | 2017-02-15 08:55:48
2  | John | 2017-02-15 08:55:49
2  | John | 2017-02-15 08:56:30
2  | John | 2017-02-15 10:15:40

After deleting:

ID | Name | DateTime
---+------+---------------------
1  | Joe  | 2017-03-01 11:33:13
1  | Joe  | 2017-03-01 11:55:30
2  | John | 2017-02-15 08:55:48
2  | John | 2017-02-15 10:15:40

Deletes all similar times (e.g. 10 minutes) for users

Please help me how to do it. Thanks

Body:
CREATE TABLE #TABLE1
    ([ID] INT, [NAME] VARCHAR(4), [DATETIME] DATETIME)

INSERT INTO #TABLE1
    ([ID], [NAME], [DATETIME])
VALUES
    (1, 'JOE', '2017-03-01 11:33:13'),
    (1, 'JOE', '2017-03-01 11:33:14'),
    (1, 'JOE', '2017-03-01 11:33:15'),
    (1, 'JOE', '2017-03-01 11:55:30'),
    (2, 'JOHN', '2017-02-15 08:55:48'),
    (2, 'JOHN', '2017-02-15 08:55:49'),
    (2, 'JOHN', '2017-02-15 08:56:30'),
    (2, 'JOHN', '2017-02-15 10:15:40')

SELECT  A.ID,A.NAME,A.[DATETIME] FROM
(SELECT *,ROW_NUMBER() OVER( PARTITION BY (  CAST(CONVERT(CHAR(16), [DATETIME],113) AS DATETIME)) ORDER BY [NAME]) AS RN FROM #TABLE1
)A
WHERE RN=1 ORDER BY ID

output

ID  NAME        DATETIME
1   Joe        2017-03-01 11:33:13.000
1   Joe        2017-03-01 11:55:30.000
2   John       2017-02-15 08:55:48.000
2   John       2017-02-15 10:15:40.000


问:
Use jquery to Append streaming video from a php page containing basically object tags. when different links for videos are clicked
Im a newbie to jquery.
I really require assistance with putting jquery in my code

i have some links i.e. link1 link2 link3

i also have a div tag

 WHICH IS WHERE THE VIDEOS OBTAINED WILL BE APPENDED.

I have a php page that fetches A STREAMING video with an <object> tag FROM MANY 4 IP CAMERAS

what i'm trying to do is when i click on the link[i] with href="page?ip="ipadd, i want the video jquery to fetch the page that calls the video and APPEND it to the div tag.

I was thinking of being able to send a get request with the ip address (which is the href on the links) to the php page handling the video, so it can use the ip address to pick the correct video from the correct video (IM STREAMING THEM FROM AN IP CAMERA.) That is why i want to use jquery to load each video as the link is being clicked. But i really have no clue on how that works.

Ok Gaby i have added a line check my sample page now i added the

```<code> $('a.video-link').click(function(event){
 event.preventDefault(); ....}
</code>```

my page now becomes

```<code><html>
<head>
<script type="text/javascript" src="jsfile.js"></script>

</head>
<body>

<a href="akin3.html" class="video-link" >link 1</a>
...

<div class="vid" >
</div>
<script>
$(document).ready(function(){
$('a.video-link').click(function(event){
 event.preventDefault();
  // get the contents of the clicked Url and then append them at the div with class vid
  $.get( this.href,
         function(data){
               $('.vid').append( data );
         }
       );
  return false;
});
});
</script>
</body>
</html>
</code>```

but when i click on the link it appends. if i try to click a link that i have clicked previously, it clears the div tag and jumps to the link that i an clicking the second time. i need it to append that link still(being able to append a link multiple time). any help??

答:
add a class to your links for example video-link

```<code><a href=".." class="video-link">link 1</a>
<a href=".." class="video-link">link 2</a>
</code>```

and use

```<code>$('a.video-link').click(function(){
  // load and put the contents of the url in the div with class vid
  $('div.vid').load( this.href );
  return false;
});
</code>```

reference: the .load() method

The above solution will replace the contents of the vid div.

If you want to append it at the end (keeping the current contents) then use

```<code>$('a.video-link').click(function(){
  // get the contents of the clicked Url and then append them at the div with class vid
  $.get( this.href,
         function(data){
               $('div.vid').append( data );
         }
       );
  return false;
});
</code>```

reference: the .get() method

Body:
Im a newbie to jquery.
I really require assistance with putting jquery in my code

i have some links i.e. link1 link2 link3

i also have a div tag

 WHICH IS WHERE THE VIDEOS OBTAINED WILL BE APPENDED.

I have a php page that fetches A STREAMING video with an <object> tag FROM MANY 4 IP CAMERAS

what i'm trying to do is when i click on the link[i] with href="page?ip="ipadd, i want the video jquery to fetch the page that calls the video and APPEND it to the div tag.

I was thinking of being able to send a get request with the ip address (which is the href on the links) to the php page handling the video, so it can use the ip address to pick the correct video from the correct video (IM STREAMING THEM FROM AN IP CAMERA.) That is why i want to use jquery to load each video as the link is being clicked. But i really have no clue on how that works.

Ok Gaby i have added a line check my sample page now i added the

 $('a.video-link').click(function(event){
 event.preventDefault(); ....}

my page now becomes

link 1
...

but when i click on the link it appends. if i try to click a link that i have clicked previously, it clears the div tag and jumps to the link that i an clicking the second time. i need it to append that link still(being able to append a link multiple time). any help??

Body:
add a class to your links for example video-link

<a href=".." class="video-link">link 1</a>
<a href=".." class="video-link">link 2</a>

and use

$('a.video-link').click(function(){
  // load and put the contents of the url in the div with class vid
  $('div.vid').load( this.href );
  return false;
});

reference: the .load() method

The above solution will replace the contents of the vid div.

If you want to append it at the end (keeping the current contents) then use

$('a.video-link').click(function(){
  // get the contents of the clicked Url and then append them at the div with class vid
  $.get( this.href,
         function(data){
               $('div.vid').append( data );
         }
       );
  return false;
});

reference: the .get() method


问:
User level restrictions on ethereum
I have two queries related to ethereum. I am trying to do a proof of concept that required multiple users to have access to a blockchain node.

(1). Can I have like a million user accounts on Ethereum's Node. Or does ethereum has restriction in the number of accounts.

(2). I want to have user level restrictions in place. So, for instance there are two customers transacting with few other customers. Each of the customers should see his own transaction. Simply said.

For instance, both the below transactions happen on a blockchain node.
A->B 5 USD
C->D 10 USD

A and B should only see 5 USD transaction on their UI.
C and D should only see 10 USD transaction on their UI.
Bank should see both the transactions.

Is the above possible on ethereum or do we have some restrictions on above.

Responses are appreciated

答:
In the public Ethereum network:

Q1: You can have data about as many accounts as you require. Someone pays the gas cost of all state commits. This data is on all verifier nodes, so generally-speaking, everyone has a copy.

Q2: It's possible to design smart contracts to enforce these sorts of rules, but one should keep in mind that all information on the chain is visible to a determined adversary even if the contract(s) is designed to restrict access. Since all nodes verify all transactions, it follows that all data is visible to all nodes.

There are some variants of Ethereum that apply different approaches to verification and confidentiality.

Different between various blockchain protocols

Hope it helps.

Title: User level restrictions on ethereum


问:
Anaconda: ImportError: cannot import name InsecureRequestWarning
I'm trying to create a conda environment using git-bash and win10:

```<code>$ conda create --name my_env
An unexpected error has occurred.

Traceback (most recent call last):
  File "c:\Miniconda2\Scripts\conda-script.py", line 5, in <module>
    sys.exit(conda.cli.main())
  File "c:\Miniconda2\lib\site-packages\conda\cli\main.py", line 164, in main
    return conda_exception_handler(_main, *args)
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 607, in conda_exception_handler
    print_unexpected_error_message(e)
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 561, in print_unexpected_error_message
    info_stdout, info_stderr = get_info()
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 531, in get_info
    args.func(args, p)
  File "c:\Miniconda2\lib\site-packages\conda\cli\main_info.py", line 142, in execute
    from conda.api import get_index
  File "c:\Miniconda2\lib\site-packages\conda\api.py", line 1, in <module>
    from .core.index import get_index
  File "c:\Miniconda2\lib\site-packages\conda\core\index.py", line 9, in <module>
    from .repodata import collect_all_repodata
  File "c:\Miniconda2\lib\site-packages\conda\core\repodata.py", line 22, in <module>
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: cannot import name InsecureRequestWarning
</code>```

How can I fix this?

答:
Try this</p>

```<code>pip install -U requests
</code>```

Body:
I'm trying to create a conda environment using git-bash and win10:

$ conda create --name my_env
An unexpected error has occurred.

Traceback (most recent call last):
  File "c:\Miniconda2\Scripts\conda-script.py", line 5, in <module>
    sys.exit(conda.cli.main())
  File "c:\Miniconda2\lib\site-packages\conda\cli\main.py", line 164, in main
    return conda_exception_handler(_main, *args)
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 607, in conda_exception_handler
    print_unexpected_error_message(e)
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 561, in print_unexpected_error_message
    info_stdout, info_stderr = get_info()
  File "c:\Miniconda2\lib\site-packages\conda\exceptions.py", line 531, in get_info
    args.func(args, p)
  File "c:\Miniconda2\lib\site-packages\conda\cli\main_info.py", line 142, in execute
    from conda.api import get_index
  File "c:\Miniconda2\lib\site-packages\conda\api.py", line 1, in <module>
    from .core.index import get_index
  File "c:\Miniconda2\lib\site-packages\conda\core\index.py", line 9, in <module>
    from .repodata import collect_all_repodata
  File "c:\Miniconda2\lib\site-packages\conda\core\repodata.py", line 22, in <module>
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
ImportError: cannot import name InsecureRequestWarning

How can I fix this?

Body:
Try this

pip install -U requests


问:
Convert ExpandoObject to abstract object using Automapper
Sample Class:

```<code>public abstract class SomeBase
{
    protected int _x = 100;
    public abstract int X { get; }
    protected int _y = 200;
    public abstract int Y { get; }
}

public class SomeBody : SomeBase
{
    public override int X { get { return _x + 10; } }

    public override int Y { get { return _y + 20; } }
    private int _z = 300;
    public int Z { get { return _z + 30; } }
}

public class SomeOne : SomeBase
{
    public override int X { get { return _x - 10; } }

    public override int Y { get { return _y - 20; } }
    private int _a = 300;
    public int A { get { return _a - 30; } }
}
</code>```

Object to ExpandoObject Method:

```<code>public static ExpandoObject ToExpandoObject<T>(this T target)
{
    var jsonSerializerSettings = new JsonSerializerSettings();
    jsonSerializerSettings.Converters.Add(new StringEnumConverter());

    var json = JsonConvert.SerializeObject(target, Formatting.Indented, jsonSerializerSettings);
    var expandoObject = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());

    return expandoObject;
}
</code>```

Convert ExpandoObject to abstract object:

```<code>//someBase
//X = 110, Y = 220, Z = 330
SomeBase someBase = new SomeBody();
//someOne
//X = 90, Y = 180, A = 270
dynamic someOne = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<SomeBase, SomeBase>();
});
//I want
//someBase
//X = 90, Y = 180, A = 270
Mapper.Map<ExpandoObject, SomeBase>(someOne, someBase);
</code>```

But error occurs.

Instances of abstract classes can not be created

How can we handle this problem?

AutoMapper version is 6.02

*Please consider using Google translator because English is immature.

UPDATE:

I know about abstract.

I just want to know if AutoMapper can do the following:

```<code>SomeBody someBody = new SomeBody();
//someBase
//X = 110, Y = 220, Z = 330
SomeBase someBase = someBody;
SomeOne someOne = new SomeOne();
//someBase
//X = 90, Y = 180, A = 270
someBase = someOne;
</code>```

UPDATE Again...

TestClass

```<code>public class TestClass
{
    public int IntValue { get; set; }
    public SomeBase SomeBase { get; set; }
}
</code>```

My final goal is :

```<code>var testClass = new TestClass();
testClass.IntValue = 10;
testClass.SomeBase = new SomeBody();

dynamic expandoObject = testClass.ToExpandoObject();
expandoObject.SomeBase = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<TestClass, TestClass>();
});
///Mapping the expandoObject object that changed the property to the testClass object again
///My expectation is that the type of SomeBase Property in testClass is SomeOne.
Mapper.Map<ExpandoObject, TestClass>(expandoObject, testClass);
</code>```

Thank you very much for helping me with insufficient English and insufficient explanation.

My solution

```<code>var testClass = new TestClass();
testClass.IntValue = 10;
testClass.SomeBase = new SomeBody();

dynamic expandoObject = testClass.ToExpandoObject();
expandoObject.SomeBase = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ExpandoObject, SomeBase>().ConvertUsing(new SomeBaseConverter());
    cfg.CreateMap<FirstItem, FirstItem>();
});

Mapper.Map<ExpandoObject, TestClass>(expandoObject, testClass);

Debug.WriteLine(testClass.SomeBase.GetType().ToString());
///"Sample.Common.Models.SomeOne"
</code>```

SomeBaseConverter:

```<code>public class SomeBaseConverter : ITypeConverter<object, SomeBase>
{
    public SomeBase Convert(dynamic source, SomeBase destination, ResolutionContext context)
    {
        var dictionary = source as IDictionary<string, object>;

        if (dictionary.ContainsKey("Z"))
        {
            var someBody = new SomeBody();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<ExpandoObject, SomeBody>());
            config.CreateMapper().Map(source, someBody);

            destination = someBody;
        }
        else
        {
            var someOne = new SomeOne();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<ExpandoObject, SomeOne>());
            config.CreateMapper().Map(source, someOne);

            destination = someOne;
        }

        return destination;
    }
}
</code>```

答:
See the MSDN article re abstract classes.

The important part for you is:

An abstract class cannot be instantiated.

You need to map to one of the derived classes, or remove the abstract modifier from the base class.

AutoMapper is great if you have statically-typed objects. It handles polymorphism very well:

```<code>Mapper.CreateMap<SomeBase1, SomeBase2>()
    .Include<SomeBody1, SomeBody2>()
    .Include<SomeOne1, SomeOne2>();

Mapper.CreateMap<SomeBody1, SomeBody2>();
Mapper.CreateMap<SomeOne1, SomeOne2>();

// for a single object:

SomeBase1 source = GetDatum();
SomeBase2 = Mapper.Map<SomeBase1, SomeBase2>();

// for an IEnumerable:

IEnumerable<SomeBase1> source = GetData();
IEnumerable<SomeBase2> = Mapper.Map<IEnumerable<SomeBase1>, IEnumerable<SomeBase2>>(source);
</code>```

But you're using ExpandoObject, so it's more difficult. If you can differentiate which class you need by the data in the ExpandoObject, you could try something like this:

```<code>Mapper.CreateMap<ExpandoObject, SomeBase>()
    .ConstructUsing((ExpandoObject input) => {
        if (input.X == 5)
        {
            return new SomeOne();
        }
        else
        {
            return new SomeBody();
        }
    });
</code>```

and then the code you were using before Mapper.Map<Expandoobject, SomeBase>(...) will work. Otherwise, you could specifically tell it which type to map to: Mapper.DynamicMap<SomeBody>(someOne);

Body:
Sample Class:

public abstract class SomeBase
{
    protected int _x = 100;
    public abstract int X { get; }
    protected int _y = 200;
    public abstract int Y { get; }
}

public class SomeBody : SomeBase
{
    public override int X { get { return _x + 10; } }

    public override int Y { get { return _y + 20; } }
    private int _z = 300;
    public int Z { get { return _z + 30; } }
}

public class SomeOne : SomeBase
{
    public override int X { get { return _x - 10; } }

    public override int Y { get { return _y - 20; } }
    private int _a = 300;
    public int A { get { return _a - 30; } }
}

Object to ExpandoObject Method:

public static ExpandoObject ToExpandoObject<T>(this T target)
{
    var jsonSerializerSettings = new JsonSerializerSettings();
    jsonSerializerSettings.Converters.Add(new StringEnumConverter());

    var json = JsonConvert.SerializeObject(target, Formatting.Indented, jsonSerializerSettings);
    var expandoObject = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());

    return expandoObject;
}

Convert ExpandoObject to abstract object:

//someBase
//X = 110, Y = 220, Z = 330
SomeBase someBase = new SomeBody();
//someOne
//X = 90, Y = 180, A = 270
dynamic someOne = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<SomeBase, SomeBase>();
});
//I want
//someBase
//X = 90, Y = 180, A = 270
Mapper.Map<ExpandoObject, SomeBase>(someOne, someBase);

But error occurs.

Instances of abstract classes can not be created

How can we handle this problem?

AutoMapper version is 6.02

*Please consider using Google translator because English is immature.

UPDATE:

I know about abstract.

I just want to know if AutoMapper can do the following:

SomeBody someBody = new SomeBody();
//someBase
//X = 110, Y = 220, Z = 330
SomeBase someBase = someBody;
SomeOne someOne = new SomeOne();
//someBase
//X = 90, Y = 180, A = 270
someBase = someOne;

UPDATE Again...

TestClass

public class TestClass
{
    public int IntValue { get; set; }
    public SomeBase SomeBase { get; set; }
}

My final goal is :

var testClass = new TestClass();
testClass.IntValue = 10;
testClass.SomeBase = new SomeBody();

dynamic expandoObject = testClass.ToExpandoObject();
expandoObject.SomeBase = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<TestClass, TestClass>();
});
///Mapping the expandoObject object that changed the property to the testClass object again
///My expectation is that the type of SomeBase Property in testClass is SomeOne.
Mapper.Map<ExpandoObject, TestClass>(expandoObject, testClass);

Thank you very much for helping me with insufficient English and insufficient explanation.

My solution

var testClass = new TestClass();
testClass.IntValue = 10;
testClass.SomeBase = new SomeBody();

dynamic expandoObject = testClass.ToExpandoObject();
expandoObject.SomeBase = new SomeOne().ToExpandoObject();

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<ExpandoObject, SomeBase>().ConvertUsing(new SomeBaseConverter());
    cfg.CreateMap<FirstItem, FirstItem>();
});

Mapper.Map<ExpandoObject, TestClass>(expandoObject, testClass);

Debug.WriteLine(testClass.SomeBase.GetType().ToString());
///"Sample.Common.Models.SomeOne"

SomeBaseConverter:

public class SomeBaseConverter : ITypeConverter<object, SomeBase>
{
    public SomeBase Convert(dynamic source, SomeBase destination, ResolutionContext context)
    {
        var dictionary = source as IDictionary<string, object>;

        if (dictionary.ContainsKey("Z"))
        {
            var someBody = new SomeBody();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<ExpandoObject, SomeBody>());
            config.CreateMapper().Map(source, someBody);

            destination = someBody;
        }
        else
        {
            var someOne = new SomeOne();

            var config = new MapperConfiguration(cfg => cfg.CreateMap<ExpandoObject, SomeOne>());
            config.CreateMapper().Map(source, someOne);

            destination = someOne;
        }

        return destination;
    }
}

Body:
See the MSDN article re abstract classes.

The important part for you is:

An abstract class cannot be instantiated.

You need to map to one of the derived classes, or remove the abstract modifier from the base class.

AutoMapper is great if you have statically-typed objects. It handles polymorphism very well:

Mapper.CreateMap<SomeBase1, SomeBase2>()
    .Include<SomeBody1, SomeBody2>()
    .Include<SomeOne1, SomeOne2>();

Mapper.CreateMap<SomeBody1, SomeBody2>();
Mapper.CreateMap<SomeOne1, SomeOne2>();

// for a single object:

SomeBase1 source = GetDatum();
SomeBase2 = Mapper.Map<SomeBase1, SomeBase2>();

// for an IEnumerable:

IEnumerable<SomeBase1> source = GetData();
IEnumerable<SomeBase2> = Mapper.Map<IEnumerable<SomeBase1>, IEnumerable<SomeBase2>>(source);

But you're using ExpandoObject, so it's more difficult. If you can differentiate which class you need by the data in the ExpandoObject, you could try something like this:

Mapper.CreateMap<ExpandoObject, SomeBase>()
    .ConstructUsing((ExpandoObject input) => {
        if (input.X == 5)
        {
            return new SomeOne();
        }
        else
        {
            return new SomeBody();
        }
    });

and then the code you were using before Mapper.Map<Expandoobject, SomeBase>(...) will work. Otherwise, you could specifically tell it which type to map to: Mapper.DynamicMap<SomeBody>(someOne);


问:
201 Created or 303 See Other after a POST request
From a RESTful interface, what should be the best status code after a successful POST action?

201 Created

303 See Other

Note: considering in the HTTP server answer, the Location key can be present.

I'm confused. Thanks for any answers.

答:
201 Created says "the resource is created and here's the URL of that resource".

303 See Other says "nothing went wrong and you should check this URL for more information".

The primary distinction is that you would expect a conforming client to always GET the URL from the Location header in the case of a 303 See Other.  You would only expect a 201 Created to result in a GET on the URL if the client decides they need to fetch the resource from the server.

I would generally advise against sending a 303 See Other for anything but web forms or if you have developed a multi-stage API, where you must perform subsequent requests after the first.


问:
GWT replacement for java.net.URL
I have to replace the protocol part of a already existing url in GWT. The java.net package has a class which was build for exactly that purpose: URL. Sadly GWT does not emulate the java.net package.

How can I reassemble a url in GWT without creating my own parser? (I know about UrlBuilder, but UrlBuilder won't take an existing URL)

Example: I have a url in a string "http://myserver.com/somepath/file.html?param" and I want to replace the protocol part with "https".

答:
```<code>public void onModuleLoad() {
    Button btn = new Button("change protocol");
    btn.addClickHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
            UrlBuilder builder = Window.Location.createUrlBuilder().setProtocol("https");
            Window.Location.replace(builder.buildString());
        }
    });
    RootPanel.get().add(btn);
}
</code>```

Title: GWT replacement for java.net.URL


答:
You'll need to include an if statement inside the click function.</p>

```<code>$(".btn ").click(function(){
   $('.boxcoracao .coracao', this).toggleClass("ativo");

  if( $(this).hasClass("ativo") ) {
    // the query to exicute if the class has been added
  }
  else {
    // the query to exicute if the class has been removed
  }
});
</code>```

Title: how to like/unlike with button using toggleclass

Body:
this is my like button...

HTML code

    <span class="coracao" id = "<?php echo $postid?>" name = "like">br>   Love

Jquery inside HTML

it works when i click and unclick the button the button changes but what my problem is how can i use this function to save data to my database. sample when 1st click the button it will like.. and when i click the button again it will unlike. can you help me how to query this ?

like table

postid  |  postmember |  likeid
   50          12           1

postid by the name itself the id of the post..
postmember is the id of the user who posted sample user 12 posted and the id is 50..
likeid is the user who likes the post of the other user sample user 1 like the post of user 12..

Body:
You'll need to include an if statement inside the click function.

$(".btn ").click(function(){
   $('.boxcoracao .coracao', this).toggleClass("ativo");

  if( $(this).hasClass("ativo") ) {
    // the query to exicute if the class has been added
  }
  else {
    // the query to exicute if the class has been removed
  }
});


问:
passing a data structure around
I've inherited an old program with a data structure that is basically image reading (x,y, and a few properties).  it works ok but i have to do a major expansion/refactor now, so i want to address some issues with my knowledge now

```<code>        public struct DataSet
        {
            public double X;
            public double Y;
            public double A;
            public double B;
            public double C;
        }
        List<List<DataSet>> RasterSet = List<List<DataSet>>();

        //create the structure from the image file using X,Y,A,B,C

        sublist = new List<DataSet>();
        RasterSet.Add(sublist);
</code>```

the question is, i've always assumed through my reading that passing a big struct around is expensive, so i've been making the struct and RasterSet list as public static.  I'd really rather fix this, but i don't know how.

I'm ONLY using the RasterSet List<List<Struct>>; the whole reason for the struct is that is how the image software i'm talking to gives me it's data.

Even better would be to understand if there is a way to keep the "structure" (X,Y,A,B,C) without the struct (reference rather than value) but i have no idea how or if.

i'm lacking in experience here, but the reading on struct is very focused on the old chestnut "when to use a struct" and not a lot of practical examples (i don't need what is a struct and when to use it advice please).

答: You can try using ref. More info on this MSDN page.

Title: passing a data structure around

Body:
I've inherited an old program with a data structure that is basically image reading (x,y, and a few properties).  it works ok but i have to do a major expansion/refactor now, so i want to address some issues with my knowledge now

        public struct DataSet
        {
            public double X;
            public double Y;
            public double A;
            public double B;
            public double C;
        }
        List<List<DataSet>> RasterSet = List<List<DataSet>>();

        //create the structure from the image file using X,Y,A,B,C

        sublist = new List<DataSet>();
        RasterSet.Add(sublist);

the question is, i've always assumed through my reading that passing a big struct around is expensive, so i've been making the struct and RasterSet list as public static.  I'd really rather fix this, but i don't know how.

I'm ONLY using the RasterSet List<List<Struct>>; the whole reason for the struct is that is how the image software i'm talking to gives me it's data.

Even better would be to understand if there is a way to keep the "structure" (X,Y,A,B,C) without the struct (reference rather than value) but i have no idea how or if.

i'm lacking in experience here, but the reading on struct is very focused on the old chestnut "when to use a struct" and not a lot of practical examples (i don't need what is a struct and when to use it advice please).


答:
Using ajax would be an option.

$("#postWrapper").on("click", ".likeToggle", function(){

 // grabe the variables you need

 var postid = $("#postid").attr("data-postid"); //postid
 var postmember = $("#postmember").attr("data-postmember"); // postmember
 var likeid = $("#likeid").attr("data-likeid"); // likeid

  $(this).toggleClass("likeColor");

  if ($(this).hasClass("likeColor")){

    console.log("LIKE");
    $(this).text("dislike"); // update the text to show what the next click would be
    togglePost("like", postid, postmember,likeid); // run function

  } else {

    console.log("DISLIKE");
    $(this).text("like"); // update the text to show what the next click would be
    togglePost("dislike", postid, postmember,likeid); // run function

  }
 // send ajax to process.php

 function togglePost(action, postid, postmember, likeid){

  $.ajax({
        type: "post",
        url: "process.php",
        data: "action="+action+"&postid="+postid+"&postmember="+postmember+"&likeid="+likeid,
        success: function(data){

         alert("success");

        },
        error: function(e){
         alert("error");
        }
      });

 }

  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.likeColor {
  background: red;
}</code>```

  POST ID: 50
  CREATED BY: 12

post contents are written here....

currently LOGGED IN as Member: 10

  <button class="likeToggle">like</button>

```

Body:
Using ajax would be an option.

$("#postWrapper").on("click", ".likeToggle", function(){

 // grabe the variables you need

 var postid = $("#postid").attr("data-postid"); //postid
 var postmember = $("#postmember").attr("data-postmember"); // postmember
 var likeid = $("#likeid").attr("data-likeid"); // likeid

  $(this).toggleClass("likeColor");

  if ($(this).hasClass("likeColor")){

    console.log("LIKE");
    $(this).text("dislike"); // update the text to show what the next click would be
    togglePost("like", postid, postmember,likeid); // run function

  } else {

    console.log("DISLIKE");
    $(this).text("like"); // update the text to show what the next click would be
    togglePost("dislike", postid, postmember,likeid); // run function

  }
 // send ajax to process.php

 function togglePost(action, postid, postmember, likeid){

  $.ajax({
        type: "post",
        url: "process.php",
        data: "action="+action+"&postid="+postid+"&postmember="+postmember+"&likeid="+likeid,
        success: function(data){

         alert("success");

        },
        error: function(e){
         alert("error");
        }
      });

 }

  });

.likeColor {
  background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<!-- index.php -->
<div id="postWrapper">
  <span id='postid' data-postid="50">POST ID: 50</span>
  <span id='postmember' data-postmember="12">CREATED BY: 12</span><br><br>
  <p>post contents are written here....</p><br>
  <br><hr><br>
  <div id='likeid' data-likeid="10">currently LOGGED IN as Member: 10</div><br>

  <button class="likeToggle">like</button>
</div>

<!-- process.php -->
<!--

  /*
  // you need to add 1 more row here and call it id and make it autoincrement INT or inserts wont work.

id = 1 | postid = 50 | postmember = 12 | likeid = 1
id = 2 | postid = 50 | postmember = 12 | likeid = 22
id = 3 | postid = 50 | postmember = 12 | likeid = 1001
id = 4 | postid = 50 | postmember = 12 | likeid = 21
id = 5 |postid = 50 | postmember = 12 | likeid = 44
*/

   $action = $_POST['action'];
   $likeid = $_POST['likeid'];
   $postmember= $_POST['postmember'];
   $postid = $_POST['postid']

 UpdateLikes($postid, $postmember, $likeid, $action);

 function UpdateLikes($postid, $postmember, $likeid, $action){

 if ($action == "dislike"){
  $query = mysql_query("DELETE FROM liketable WHERE
   postid = '$postid' &&
   likeid = '$likeid'
   ");
 } else {

  // before inserting you might want to check if they alredy liked or not before adding their count again.
  $query = mysql_query("INSERT INTO liketable
   ( postid,  postmember, likeid ) VALUES
     ('$postid','$postmember','$likeid')");
 }

  }

  -->


问:
Hosting WCF service on azure
I got a wcf service which I'd like to run on azure, but I got several problems:

First: do I choose a web role or a worker role for running the wcf service?

Second: The client uses a call to log into the service, afterwards the service should remember who is logged in (sessions). The problem is, for firewall reasons I probably should use some http-binding. But these seem not to support sessions??

Or do I need AppFabric for sessions (what is AppFabric anyway?)?

Is there a good complete tutorial how to host wcf service?

答:
You will need to create web role for WCF service.

Here is a good tutorial on hosting wcf service on azure. I followed it and I could host a service on azure.

AppFabric is like a bus, which you can use for user authentication or getting some data from azure application.

Title: Hosting WCF service on azure


问:
Getting a machine's external IP address with Python
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x</p>

```<code>import os
import urllib2

def check_in():

    fqn = os.uname()[1]
    ext_ip = urllib2.urlopen('http://whatismyip.org').read()
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
</code>```

答:
```<code>import requests
import re

def getMyExtIp():
    try:
        res = requests.get("http://whatismyip.org")
        myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group()
        if myIp != "":
            return myIp
    except:
        pass
    return "n/a"
</code>```

Body:
Looking for a better way to get a machines current external IP #... Below works, but would rather not rely on an outside site to gather the information ... I am restricted to using standard Python 2.5.1 libraries bundled with Mac OS X 10.5.x

import os
import urllib2

def check_in():

    fqn = os.uname()[1]
    ext_ip = urllib2.urlopen('http://whatismyip.org').read()
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)


问:
How to check if user is in a certain table
I have my user table in django, and to differ all the users I created two tables, (Teacher and Student).

Both tables are getting an fk from user

So, in order to make authorization how do I check if one's user is in a certain table.

I need to check it this way

```<code>def test_func(self):
    return self.request.user.check..if..it..exists..in..table
</code>```

My models are like this.

```<code>class Teacher(models.Model):
   User = models.OneToOneField(settings.AUTH_USER_MODEL)
</code>```

答:
This depends on how your models are set up.

If your Teacher model looks something like this;

```<code>class Teacher(models.Model):
    user = models.ForeignKey(User)
</code>```

Then you should be able to check if the user is a teacher by using the implicit backref;

```<code>self.request.user.teacher_set.exists()
</code>```

As the question has been updated to show that the model is slightly different than I anticipated, here is an update.

```<code>class Teacher(models.Model):
    user = models.OneToOneField(User)
</code>```

Which means that the backref will be a little different.

```<code>hasattr(self.request.user, "teacher")
</code>```

As you've mentioned that you are doing this inside a django template, I'm pretty sure that the following will work:

```<code>{% if user.teacher %}
</code>```

Body:
I have my user table in django, and to differ all the users I created two tables, (Teacher and Student).

Both tables are getting an fk from user

So, in order to make authorization how do I check if one's user is in a certain table.

I need to check it this way

def test_func(self):
    return self.request.user.check..if..it..exists..in..table

My models are like this.

class Teacher(models.Model):
   User = models.OneToOneField(settings.AUTH_USER_MODEL)

Body:
This depends on how your models are set up.

If your Teacher model looks something like this;

class Teacher(models.Model):
    user = models.ForeignKey(User)

Then you should be able to check if the user is a teacher by using the implicit backref;

self.request.user.teacher_set.exists()

As the question has been updated to show that the model is slightly different than I anticipated, here is an update.

class Teacher(models.Model):
    user = models.OneToOneField(User)

Which means that the backref will be a little different.

hasattr(self.request.user, "teacher")

As you've mentioned that you are doing this inside a django template, I'm pretty sure that the following will work:

{% if user.teacher %}


问:
Formatting issue for mobile responsive github page using bootstrap
Wondering how to fix the mobile version of my github page, which I made tweaking a bootstrap template. On the mobile version only, the navbar cuts off the top of the first image in my portfolio. I can't figure out how to fix it, I think the problem is in the navbar:

```<code>     <!-- navbar-->
<header class="header">
  <div role="navigation" class="navbar navbar-default navbar-fixed-top">
    <div class="container">
      <div class="navbar-header page-scroll"><a href="index.html" class="navbar-brand">CHLOE WATSON COLLAGE</a>
        <div class="navbar-buttons">
          <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle navbar-btn ">Menu<i class="fa fa-align-justify"></i></button>
        </div>
      </div>
      <div id="navigation" class="collapse navbar-collapse navbar-right">
        <ul class="nav navbar-nav">
          <li class="page-scroll">
              <a href="#portfolio">WORKS</a>
          </li>
          <li class = "page-scroll">
              <a href="#about">ABOUT</a>
          </li>
          <li class="page-scroll">
              <a href="#contact">CONTACT</a>
          </li>
      </div>
    </div>
  </div>
</header>
</code>```

Any help greatly appreciated! Thanks! I've also linked to my repository if the above code is not enough.

https://github.com/chloewatson/chloewatson.github.io/blob/master/index.html

答:
fist thing you brand name CHLOE WATSON COLLAGE so long for mobile device remove   letter spacing in mobile

```<code>@media (min-width:0px) and (max-width:767px) {
.navbar a.navbar-brand {
             letter-spacing: 0;
            }
}
</code>```

i thing it's ok but if these not working then  use second css add your css file in last line

```<code>    @media (min-width:0px) and (max-width:767px) {
        #portfolio {
            padding-top: 121px;
        }
       .navbar a.navbar-brand {
         letter-spacing: 0;
        }
    }
</code>```

Body:
Wondering how to fix the mobile version of my github page, which I made tweaking a bootstrap template. On the mobile version only, the navbar cuts off the top of the first image in my portfolio. I can't figure out how to fix it, I think the problem is in the navbar:

CHLOE WATSON COLLAGE

          <button type="button" data-toggle="collapse" data-target=".navbar-collapse" class="navbar-toggle navbar-btn ">Menu</button>

              WORKS

              ABOUT

              CONTACT

Any help greatly appreciated! Thanks! I've also linked to my repository if the above code is not enough.

https://github.com/chloewatson/chloewatson.github.io/blob/master/index.html

Body:
fist thing you brand name CHLOE WATSON COLLAGE so long for mobile device remove   letter spacing in mobile

@media (min-width:0px) and (max-width:767px) {
.navbar a.navbar-brand {
             letter-spacing: 0;
            }
}

i thing it's ok but if these not working then  use second css add your css file in last line

    @media (min-width:0px) and (max-width:767px) {
        #portfolio {
            padding-top: 121px;
        }
       .navbar a.navbar-brand {
         letter-spacing: 0;
        }
    }


答:
Since you haven't posted your models, I am giving you a rough idea how to do it.

in your views.py -

```<code>from .models import Teacher,Student

def test_func(request):
    user = request.user
    if (Teacher.objects.filter(user=user).count() > 0) or (Student.objects.filter(user=user).count > 0):
        #do your stuffs here..
</code>```

Title: How to check if user is in a certain table

Body:
Since you haven't posted your models, I am giving you a rough idea how to do it.

in your views.py -

from .models import Teacher,Student

def test_func(request):
    user = request.user
    if (Teacher.objects.filter(user=user).count() > 0) or (Student.objects.filter(user=user).count > 0):
        #do your stuffs here..


问:
C++ Nested for loops incorrect output
I am trying to make a program that receives from the user 4 student names and 3 test scores for each student. I have a problem when it comes to displaying every name with its 3 test scores.
For example if I have John, Bob, Michael, and Mary, all 4 student display along with Mary's 3 test scores.

Here is the function that I have for getting the data from the user:

```<code>void Student::getName()
{
    for (int i = 0; i < 4; ++i)
    {
        cout << "Enter name: ";
        cin >> name[i];
        for (int j = 0; j < 3; j++)
        {
            cout << "Enter grade: ";
            cin >> testScores[j];
        }
    }
}
</code>```

And this is the function that I have for displaying the data:

```<code>void Student::setName()
    {
        for (int i = 0; i < 4; ++i)
        {
            cout << "\nName: " << name[i] << endl;
            for (int j =0; j <3; j++)
            {
                cout << "Grade: " << testScores[j] << endl;
            }
        }
    }
</code>```

The first function works fine but I have problem with the output of the second function. Any suggestions? Thank you.

答:
Make testScores a 2D array instead of a single dimension array otherwise you will overwrite student 1's grades with those of student 2 which in turn will be overwritten by those of student 3 and so on leaving you with just the grades of student 4.

int testScores[4][3];

Then

replace

cin >> testScores[j];

with

cin >> testScores[i][j];

in the first function.

And

replace

cout << "Grade: " << testScores[j] << endl;

with

cout << "Grade: " << testScores[i][j] << endl;

Title: C++ Nested for loops incorrect output

Body:
I am trying to make a program that receives from the user 4 student names and 3 test scores for each student. I have a problem when it comes to displaying every name with its 3 test scores.
For example if I have John, Bob, Michael, and Mary, all 4 student display along with Mary's 3 test scores.

Here is the function that I have for getting the data from the user:

void Student::getName()
{
    for (int i = 0; i < 4; ++i)
    {
        cout << "Enter name: ";
        cin >> name[i];
        for (int j = 0; j < 3; j++)
        {
            cout << "Enter grade: ";
            cin >> testScores[j];
        }
    }
}

And this is the function that I have for displaying the data:

void Student::setName()
    {
        for (int i = 0; i < 4; ++i)
        {
            cout << "\nName: " << name[i] << endl;
            for (int j =0; j <3; j++)
            {
                cout << "Grade: " << testScores[j] << endl;
            }
        }
    }

The first function works fine but I have problem with the output of the second function. Any suggestions? Thank you.


问:
How to remove specific duration from video using ffmpeg
i've tried many ways to solve the problem, i also tried this code before

```<code>ffmpeg -i movie.mp4 -vf trim=3:8 cut.mp4
</code>```

but for the result, the audio is still there but the video is gone. all i want is the video and audio both are removed.
can anyone help me how resolve this?

答:
Use</p>

```<code>ffmpeg -i movie.mp4 -vf "select='not(between(t,3,8))',setpts=N/FRAME_RATE/TB" -af aselect='not(between(t,3,8))',asetpts=N/SR/TB cut.mp4
</code>```

Body:
i've tried many ways to solve the problem, i also tried this code before

ffmpeg -i movie.mp4 -vf trim=3:8 cut.mp4

but for the result, the audio is still there but the video is gone. all i want is the video and audio both are removed.
can anyone help me how resolve this?

Body:
Use

ffmpeg -i movie.mp4 -vf "select='not(between(t,3,8))',setpts=N/FRAME_RATE/TB" -af aselect='not(between(t,3,8))',asetpts=N/SR/TB cut.mp4


问:
XmlDocument.Load finds illegal characters in my file path
I have a file with xml in it. The path contains a character "ñ" in it, but the full path was url encoded before being saved to the file, so this character is percent encoded along with a number of other characters in the path.

I try to load the file with the following code, and the Exists portion succeeds, but then the Load() call fails with a

System.ArgumentException: Illegal characters in path.

```<code>if (File.Exists(path))
{
    var xd = new XmlDocument();
    xd.Load(path);
}
</code>```

I have a bunch of these files with the url encoding being used, but it's only these accented characters that cause problems.

Any ideas?

答:
If I'm not mistaken, your problem has to do with encoding.  the Load method defaults to UTF-8, which interprets the special characters differently.  One workaround for this, would be to pass IO.Files.ReadAllText(path) to the LoadXml method of the XmlDocument:

```<code>xd.LoadXml(IO.Files.ReadAllText(path));
</code>```

Body:
I have a file with xml in it. The path contains a character "ñ" in it, but the full path was url encoded before being saved to the file, so this character is percent encoded along with a number of other characters in the path.

I try to load the file with the following code, and the Exists portion succeeds, but then the Load() call fails with a

System.ArgumentException: Illegal characters in path.

if (File.Exists(path))
{
    var xd = new XmlDocument();
    xd.Load(path);
}

I have a bunch of these files with the url encoding being used, but it's only these accented characters that cause problems.

Any ideas?

Body:
If I'm not mistaken, your problem has to do with encoding.  the Load method defaults to UTF-8, which interprets the special characters differently.  One workaround for this, would be to pass IO.Files.ReadAllText(path) to the LoadXml method of the XmlDocument:

xd.LoadXml(IO.Files.ReadAllText(path));


问:
How to sum the values of a JavaScript object?
I'd like to sum the values of an object.

I'm used to python where it would just be:

```<code>sample = { 'a': 1 , 'b': 2 , 'c':3 };
summed =  sum(sample.itervalues())
</code>```

The following code works, but it's a lot of code:

```<code>function obj_values(object) {
  var results = [];
  for (var property in object)
    results.push(object[property]);
  return results;
}

function list_sum( list ){
  return list.reduce(function(previousValue, currentValue, index, array){
      return previousValue + currentValue;
  });
}

function object_values_sum( obj ){
  return list_sum(obj_values(obj));
}

var sample = { a: 1 , b: 2 , c:3 };
var summed =  list_sum(obj_values(a));
var summed =  object_values_sum(a)
</code>```

Am i missing anything obvious, or is this just the way it is?

答:
I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:</p>

```<code>var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
    parskey = parseInt(array[key]);
    sum += parskey;
};
return(sum);
</code>```

Body:
I'd like to sum the values of an object.

I'm used to python where it would just be:

sample = { 'a': 1 , 'b': 2 , 'c':3 };
summed =  sum(sample.itervalues())

The following code works, but it's a lot of code:

function obj_values(object) {
  var results = [];
  for (var property in object)
    results.push(object[property]);
  return results;
}

function list_sum( list ){
  return list.reduce(function(previousValue, currentValue, index, array){
      return previousValue + currentValue;
  });
}

function object_values_sum( obj ){
  return list_sum(obj_values(obj));
}

var sample = { a: 1 , b: 2 , c:3 };
var summed =  list_sum(obj_values(a));
var summed =  object_values_sum(a)

Am i missing anything obvious, or is this just the way it is?

Body:
I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:

var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
    parskey = parseInt(array[key]);
    sum += parskey;
};
return(sum);


问:
id showing undefined when trying to implement delete in angularjs
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

```<code>http://localhost:50802/api/User/BUser/[object%20Object]
</code>```

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

```<code>$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };
</code>```

HTML

```<code> <tr ng-repeat="d in UserList">

                        <td>{{d.description}}</td>
                        <td>{{d.path}}</td>
                        <td><button ng-click="DeleteUser()">Delete </button></td>

                    </tr>
</code>```

here my Asp.net Controller

```<code>[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }
</code>```

答:
Your function inside the controller expects the parameter Id and data, i assume your data refers to the Object user, change the html as follows,

```<code>  <td><button ng-click="DeleteUser(d)">Delete </button></td>
</code>```

and then,

```<code>$scope.DeleteUser = function (user) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + user.UId,
            data: user
        }).then(function (response) {
            alert(response.data);
        })
    };
</code>```

Body:
Trying to implement delete funtion in angularjs. The backend in asp.net is working fine. when i check with postman its working fine. now am trying to the front end for that. when i hit the delete button. its not getting the UId. its showing like this.

http://localhost:50802/api/User/BUser/[object%20Object]

am totally new to angular. i dont know whether this angular code is correct or not.And another thing is i need to implement user confirmation popup window also. please help me...

angular controller.

$scope.DeleteUser = function (data, UId) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + UId,

            data: JSON.stringify(data)
        }).then(function (response) {
            alert(response.data);

        })
    };

HTML

                        {{d.description}}
                        {{d.path}}
                        <button ng-click="DeleteUser()">Delete </button>

here my Asp.net Controller

[HttpDelete]
        [Route("DeleteBanner/{UId}")]
        public async Task<IHttpActionResult> DeleteBanner(int UId)
        {
            int? result = await _service.DeleteBannerAsync(UId);

            return Ok();

        }

Body:
Your function inside the controller expects the parameter Id and data, i assume your data refers to the Object user, change the html as follows,

  <td><button ng-click="DeleteUser(d)">Delete </button></td>

and then,

$scope.DeleteUser = function (user) {
        $http({
            method: "post",
            url: urls.api + 'User/BUser/' + user.UId,
            data: user
        }).then(function (response) {
            alert(response.data);
        })
    };


答:
One way is to query both tables: </p>

```<code>teacher = Teacher.objects.filter(user=self.request.user)
student = Student.objects.filter(user=self.request.user)
if teacher or student:
     # do what you want.
</code>```

Body:
One way is to query both tables:

teacher = Teacher.objects.filter(user=self.request.user)
student = Student.objects.filter(user=self.request.user)
if teacher or student:
     # do what you want.