问:
Sort a column within groups in Pandas
I am new to pandas. I'm trying to sort a column within each group. So far, I was able to group first and second column values together and calculate the mean value in third column. But I am still struggling to sort 3rd column.

This is my input dataframe
This is my dataframe after applying groupby and mean function

I used the following line of code to group input dataframe,
    df_o=df.groupby(by=['Organization Group','Department']).agg({'Total Compensation':np.mean})

Please let me know how to sort the last column for each group in 1st column using pandas.

答:
It seems you need sort_values:

```<code>#for return df add parameter as_index=False
df_o=df.groupby(['Organization Group','Department'],
                 as_index=False)['Total Compensation'].mean()
df_o = df_o.sort_values(['Total Compensation','Organization Group'])
</code>```

Sample:

```<code>df = pd.DataFrame({'Organization Group':['a','b','a','a'],
                   'Department':['d','f','a','a'],
                   'Total Compensation':[1,8,9,1]})

print (df)
  Department Organization Group  Total Compensation
0          d                  a                   1
1          f                  b                   8
2          a                  a                   9
3          a                  a                   1

df_o=df.groupby(['Organization Group','Department'],
                as_index=False)['Total Compensation'].mean()
print (df_o)
  Organization Group Department  Total Compensation
0                  a          a                   5
1                  a          d                   1
2                  b          f                   8

df_o = df_o.sort_values(['Total Compensation','Organization Group'])
print (df_o)
  Organization Group Department  Total Compensation
1                  a          d                   1
0                  a          a                   5
2                  b          f                   8
</code>```

Title: Sort a column within groups in Pandas

Body:
It seems you need sort_values:

#for return df add parameter as_index=False
df_o=df.groupby(['Organization Group','Department'],
                 as_index=False)['Total Compensation'].mean()
df_o = df_o.sort_values(['Total Compensation','Organization Group'])

Sample:

df = pd.DataFrame({'Organization Group':['a','b','a','a'],
                   'Department':['d','f','a','a'],
                   'Total Compensation':[1,8,9,1]})

print (df)
  Department Organization Group  Total Compensation
0          d                  a                   1
1          f                  b                   8
2          a                  a                   9
3          a                  a                   1

df_o=df.groupby(['Organization Group','Department'],
                as_index=False)['Total Compensation'].mean()
print (df_o)
  Organization Group Department  Total Compensation
0                  a          a                   5
1                  a          d                   1
2                  b          f                   8

df_o = df_o.sort_values(['Total Compensation','Organization Group'])
print (df_o)
  Organization Group Department  Total Compensation
1                  a          d                   1
0                  a          a                   5
2                  b          f                   8


来源: stackexchange

问:
Why would you use num_rows
Whenever i need something from a database, lets say when a user login, and i need to verify & get the userdata, i do it this way:

Check if user exists with num_rows

Get userdata with fetch_array

So my questions are the following:

I'm just thinking, isn't there an easier way to do all this. Like just use fetch_array and if it doesn't exist, it will return false or whatever it does.

If there is a 1-statement way to do this, what do you need num_rows for?

答:
I know it's not perfect answer but i usually do this</p>

```<code>$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$num_rows = mysql_num_rows(mysql_query("SELECT * FROM table1", $link));
echo "$num_rows Rows\n";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why would you use num_rows

Body:
I know it's not perfect answer but i usually do this

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$num_rows = mysql_num_rows(mysql_query("SELECT * FROM table1", $link));
echo "$num_rows Rows\n";


问:
How to pass values into inAppBrowser from ionic controller?
I am developing an hybrid mobile app in ionic and cordova. In this app I am using ngCordova InAppBrowse  for load a html page into app.

Controller Code:

```<code>module.controller('MyCtrl', function($cordovaInAppBrowser) {
  $scope.name="Rakesh";
  var options = {
      location: 'yes',
      clearcache: 'yes',
      toolbar: 'no'
    };

  $cordovaInAppBrowser.open('mypage.html', '_blank', options)
  .then(function(event) {
        // success
  })
  .catch(function(event) {
        // error
  });
  $rootScope.$on('$cordovaInAppBrowser:loadstart', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:loaderror', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:exit', function(e, event){
  });
});
</code>```

HTML Page (mypage.html)

```<code><!DOCTYPE html>
<html>
<head>
 <title>InAppBrowser - Test Page</title>
</head>
<body>
    <form name="sendParam" method="post" action="https://www.example.com/payment">
                <input type="text" id="name" name="name" value="" />
                <input type="submit" value="enter">
    </form >
</body>
</html>
</code>```

What I Want?

I want to set or pass MyCtrl's $scope.name value to mypage.html name text field.

答:
You Can not pass values to the controller to inAppBrowser using the $scope, inAppBrowser use to open the external web page to your mobile application.

If you want to pass value from ionic application to external page you must be pass the value using URL like
http://html.net/page.php?paramOne=1254&paramTwo=ABC
and you can get that value using  $_GET['paramOne'] in PHP or else other server side language.

OR else You can get that value using javascript using below link
Get url parameter jquery Or How to Get Query String Values In js

Hope i help you :)

Body:
I am developing an hybrid mobile app in ionic and cordova. In this app I am using ngCordova InAppBrowse  for load a html page into app.

Controller Code:

module.controller('MyCtrl', function($cordovaInAppBrowser) {
  $scope.name="Rakesh";
  var options = {
      location: 'yes',
      clearcache: 'yes',
      toolbar: 'no'
    };

  $cordovaInAppBrowser.open('mypage.html', '_blank', options)
  .then(function(event) {
        // success
  })
  .catch(function(event) {
        // error
  });
  $rootScope.$on('$cordovaInAppBrowser:loadstart', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:loadstop', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:loaderror', function(e, event){
  });
  $rootScope.$on('$cordovaInAppBrowser:exit', function(e, event){
  });
});

HTML Page (mypage.html)

<!DOCTYPE html>

 <title>InAppBrowser - Test Page</title>

    <form name="sendParam" method="post" action="https://www.example.com/payment">
                <input type="text" id="name" name="name" value="" />
                <input type="submit" value="enter">
    </form >

What I Want?

I want to set or pass MyCtrl's $scope.name value to mypage.html name text field.


问:
How to set text view if something happened in another class
I have a text view in my ActivityMain and I have an adapter(for my recycler view) that if the user touches something value of text view should be changed.

Text view is in another part of the screen and is not related to recycler view.

how can I do that?

thank you.

答:
put a Receiver inside your ActivityMain Class like

```<code>BroadcastReceiver receiverFragmentImages = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                textView.setText(intent.getStringExtra("extra"));
        }
    };
</code>```

and register it like...

```<code>registerReceiver(receiverFragmentImages , new IntentFilter("trigger"));
</code>```

and call it like

```<code>Intent intent = new Intent("trigger");
intent.putStringExtra("extra", "data");
 sendBroadcast(intent);
</code>```

Body:
put a Receiver inside your ActivityMain Class like

BroadcastReceiver receiverFragmentImages = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                textView.setText(intent.getStringExtra("extra"));
        }
    };

and register it like...

registerReceiver(receiverFragmentImages , new IntentFilter("trigger"));

and call it like

Intent intent = new Intent("trigger");
intent.putStringExtra("extra", "data");
 sendBroadcast(intent);


问:
Why the call to thrust::inclusive_scan is much slower than subsequent calls?
When I call thrust::inclusive_scan several times, why is the first time much slower than subsequent calls?

Here is the code

```<code>float ttime;
for(int i=0;i<5;i++){
     cudaEvent_t start,stop;
     cudaEventCreate(&start);
     cudaEventCreate(&stop);
     cudaEventRecord(start,0);

     thrust::device_ptr<int > din(device_input);
     thrust::device_ptr<int > dout(device_output);
     thrust::inclusive_scan(din,din+N,dout);

     cudaEventRecord(stop,0);
     cudaEventSynchronize(stop);
     cudaEventElapsedTime(&ttime,start,stop);
     printf("cost %fms\n",ttime);
}
</code>```

I run it on GTX1080,and result are

```<code>cost 39.180702ms
cost 0.200704ms
cost 0.201728ms
cost 0.202752ms
cost 0.197632ms
</code>```

Can anybody help explain this?

答:
Thrust is built using the CUDA runtime API, and that API uses lazy context initialisation.

The exact initialisation sequence is not documented and there is empirical evidence that it had changed over time. However, it appears that context setup is done on an ad hoc basis.

It is likely that the slow first call is related to loading and initialisation of the module containing the thrust code within your program. You might be able to verify this by profiling your code and looking at the profile execution time versus the wall clock time for that first call.

Body:
When I call thrust::inclusive_scan several times, why is the first time much slower than subsequent calls?

Here is the code

float ttime;
for(int i=0;i<5;i++){
     cudaEvent_t start,stop;
     cudaEventCreate(&start);
     cudaEventCreate(&stop);
     cudaEventRecord(start,0);

     thrust::device_ptr<int > din(device_input);
     thrust::device_ptr<int > dout(device_output);
     thrust::inclusive_scan(din,din+N,dout);

     cudaEventRecord(stop,0);
     cudaEventSynchronize(stop);
     cudaEventElapsedTime(&ttime,start,stop);
     printf("cost %fms\n",ttime);
}

I run it on GTX1080,and result are

cost 39.180702ms
cost 0.200704ms
cost 0.201728ms
cost 0.202752ms
cost 0.197632ms

Can anybody help explain this?


答:
You posted 2 questions, and for me they are related.  The answers however seem to be indirect as an answer goes, so maybe a brief discussion?

I like to use class properties and methods whenever possible (read: I understand them), not only for convenience sake, but also for stability and life-time sake. There is 1) a level of trust that it has been tested and 2) that it will remain at least until somebody thoroughly tests it. Additionally, should the property or method ever change, a Find...Replace usually clears it right up.

Past this, consider what I do:

```<code>(object)$db=new mysqli(HOST_DEF, USER_DEF, PASS_DEF, DB_DEF);
if($db->connect_errno || $db->errno) {
    //Do error stuff here
}
(string)$sql = sprintf("SELECT * FROM Table WHERE User='%s'",
                       filter_input(INPUT_POST, '$UserStringPassedInMaybe'));
(object)$result=$db->query($sql);
if(!$result || $result->num_rows()===0) {
    @$result->free();
    $db->close();
    unset($sql);
    //Handle that stuff here
}
</code>```

You want to trap (quantify) the recordset somehow, and you can kind of compact how you do it.  However, if all you're wanting to do is test the presence of a recordset, and you do it enough, then you can save a few lines of code by farming it out to function that returns a boolean, but you're still evaluating that return, when you could just evaluate $result itself as a boolean (as long as it's empty). Kind of dirty since it either evaluates as a boolean false, or an array.  In this sense, no, you do not need num_rows.

Title: Why would you use num_rows

Body:
Whenever i need something from a database, lets say when a user login, and i need to verify & get the userdata, i do it this way:

Check if user exists with num_rows

Get userdata with fetch_array

So my questions are the following:

I'm just thinking, isn't there an easier way to do all this. Like just use fetch_array and if it doesn't exist, it will return false or whatever it does.

If there is a 1-statement way to do this, what do you need num_rows for?

Body:
You posted 2 questions, and for me they are related.  The answers however seem to be indirect as an answer goes, so maybe a brief discussion?

I like to use class properties and methods whenever possible (read: I understand them), not only for convenience sake, but also for stability and life-time sake. There is 1) a level of trust that it has been tested and 2) that it will remain at least until somebody thoroughly tests it. Additionally, should the property or method ever change, a Find...Replace usually clears it right up.

Past this, consider what I do:

(object)$db=new mysqli(HOST_DEF, USER_DEF, PASS_DEF, DB_DEF);
if($db->connect_errno || $db->errno) {
    //Do error stuff here
}
(string)$sql = sprintf("SELECT * FROM Table WHERE User='%s'",
                       filter_input(INPUT_POST, '$UserStringPassedInMaybe'));
(object)$result=$db->query($sql);
if(!$result || $result->num_rows()===0) {
    @$result->free();
    $db->close();
    unset($sql);
    //Handle that stuff here
}

You want to trap (quantify) the recordset somehow, and you can kind of compact how you do it.  However, if all you're wanting to do is test the presence of a recordset, and you do it enough, then you can save a few lines of code by farming it out to function that returns a boolean, but you're still evaluating that return, when you could just evaluate $result itself as a boolean (as long as it's empty). Kind of dirty since it either evaluates as a boolean false, or an array.  In this sense, no, you do not need num_rows.


问:
Cannot resolve symbol 'Theme.AppCompat.Light.DarkActionBar' in styles.xml
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

```<code>build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }
</code>```

答: Change in style.xml file as

Body:
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }

Body: Change in style.xml file as <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar"></style>


问:
Background image clipped to draggable div
i'm trying to make this thing where i have a div with a full background image and a div on top with a container, and this div is draggable, and when dragged it shows the same image as the background but altered.

Well, something among the lines of this pen

My CSS so far:

```<code>.contain{
    position:relative;
}

#dummy{
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}
</code>```

答:
If I understand your requirements correctly, you can do this by finding the current position of the draggable object as it moves, and then using those values to set the background-position of the screen's background, giving a sort of x-ray glasses effect.

```<code>var imageOffset = {
    top: 30,
    left: 32
};

$(function() {
    var screenHeight = $('body').height() - 300; // 300: moa height

    $(".screen").css('background-position', -(imageOffset.left) + 'px ' + -(screenHeight + imageOffset.top) + 'px');

    $(".mao").draggable({
        axis: "x",
        drag: function(event, ui) {
            $(".screen").css('background-position', -(ui.position.left + imageOffset.left) + 'px ' + -(ui.position.top + imageOffset.top) + 'px');
        }
    });
})
</code>```

Example Codepen: http://codepen.io/anon/pen/JWxwzK?editors=0000

You can also use the same piece of code to constrain the hand to the left/right boundaries of the screen. There's an example of code to do that in the official docs: http://api.jqueryui.com/draggable/#event-drag

Body:
i'm trying to make this thing where i have a div with a full background image and a div on top with a container, and this div is draggable, and when dragged it shows the same image as the background but altered.

Well, something among the lines of this pen

My CSS so far:

.contain{
    position:relative;
}

#dummy{
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}

Body:
If I understand your requirements correctly, you can do this by finding the current position of the draggable object as it moves, and then using those values to set the background-position of the screen's background, giving a sort of x-ray glasses effect.

var imageOffset = {
    top: 30,
    left: 32
};

$(function() {
    var screenHeight = $('body').height() - 300; // 300: moa height

    $(".screen").css('background-position', -(imageOffset.left) + 'px ' + -(screenHeight + imageOffset.top) + 'px');

    $(".mao").draggable({
        axis: "x",
        drag: function(event, ui) {
            $(".screen").css('background-position', -(ui.position.left + imageOffset.left) + 'px ' + -(ui.position.top + imageOffset.top) + 'px');
        }
    });
})

Example Codepen: http://codepen.io/anon/pen/JWxwzK?editors=0000

You can also use the same piece of code to constrain the hand to the left/right boundaries of the screen. There's an example of code to do that in the official docs: http://api.jqueryui.com/draggable/#event-drag


问:
Should I use real or sample data for unit tests?
I'm writing a parser for the output of a legacy application, and since there are no specs on the file syntax I've got as many samples of these files as I could.

Now I'm writing the unit tests before implementing the parser (because there is no other sane way to do this) but I'm not sure whether I should:

use the real files produced by the application, reading from them and comparing the output with the output that I would store in json format in another file.

or create a sample string with the tokens and possibilities I want to test and a dict (this is python) with the expected output.

I'm inclined to use the second alternative because I would test only what I need to, without all the "real-world" data included on the actual files, but I'm afraid I could forget to test for one possibility or another.

What do you think?

答:
My suggestion is to do both.  Write a set of integration tests that run through all the files you have with the expected outputs then unit test with your expected inputs to isolate the parsing logic.

I would recommend writing the integration tests first so you write your parser outside in, it might be disparaging to see a bunch of failing tests, but it'll help you isolate your edge cases earlier.

Btw, I think this is a great question.  I recently came across something a similar problem which was transforming large xml feeds from an upstream system into a proprietary format.  My solution was to write a set of integration black box tests for the full feeds testing things like record counts and other high level success metrics, then break down inputs into smaller and smaller chunks until I was able to test all the permutations of the data.  It was only then that I had a good understanding of how to build the parser.

ContentLicense: CC BY-SA 2.5


问:
Jetty doesn't send .ts files from server in my typescript with java EE project
I have built a simple services framework for java [to be opensourced soon].

I have a demo client built with typescript that compiles and runs fine. The project is configure to use jetty maven plugin with the following configuration -

```<code><!-- jetty configuration -->
<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.4.0.v20161208</version>
    <configuration>
        <webapp>
            <contextPath>/</contextPath>
        </webapp>
        <webAppSourceDirectory>${project.basedir}/WebContent</webAppSourceDirectory>
        <stopWait>10</stopWait>
        <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                <port>8080</port>
                <maxIdleTime>60000</maxIdleTime>
            </connector>
        </connectors>

        <dependencies>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>0.9.29</version>
            </dependency>
        </dependencies>
        <!-- <requestLog implementation="org.mortbay.jetty.NCSARequestLog">
            <filename>./target/yyyy_mm_dd.request.log</filename> <retainDays>90</retainDays>
            <append>true</append> <extended>false</extended> <logTimeZone>GMT</logTimeZone>
            </requestLog> -->
    </configuration>
</plugin>
</code>```

the problem is that when the client is running jetty doesn't seem to deliver the typescript files for the javascript generated though my source map configuration seems accurate i.e. it generates the source maps properly and on the client it shows the typescript file names. But I see only empty files.

After some research it seems to be a jetty configuration issue i.e. it doesn't deliver the typescript files.

Any clues please ?

答:
Thanks to @Joakim Erdfelt comment I rectified the plugin configuration and removed the Connector part. Since Jetty 9 this connector can be optionally configured in Jetty.xml rather then in the plugin.

Using the defaults like this  -

```<code><plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.0.v20161208</version>
            <configuration>
                <webapp>
                    <contextPath>/</contextPath>
                </webapp>
                <webAppSourceDirectory>${project.basedir}/WebContent</webAppSourceDirectory>
                <stopWait>10</stopWait>

                <dependencies>
                    <dependency>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-classic</artifactId>
                        <version>0.9.29</version>
                    </dependency>
                </dependencies>
            </configuration>
        </plugin>
</code>```

solves the issue of typescript files not being served. I still haven't figured the correct version of logback and will update this answer once I do.

Also found this Mycong example that drives the point home for reference on jetty 9 configuration-

https://www.mkyong.com/maven/maven-jetty-plugin-examples/

Body:
I have built a simple services framework for java [to be opensourced soon].

I have a demo client built with typescript that compiles and runs fine. The project is configure to use jetty maven plugin with the following configuration -

<plugin>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-maven-plugin</artifactId>
    <version>9.4.0.v20161208</version>
    <configuration>
        <webapp>
            <contextPath>/</contextPath>
        </webapp>
        <webAppSourceDirectory>${project.basedir}/WebContent</webAppSourceDirectory>
        <stopWait>10</stopWait>
        <connectors>
            <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
                <port>8080</port>
                <maxIdleTime>60000</maxIdleTime>
            </connector>
        </connectors>

        <dependencies>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>0.9.29</version>
            </dependency>
        </dependencies>

    </configuration>
</plugin>

the problem is that when the client is running jetty doesn't seem to deliver the typescript files for the javascript generated though my source map configuration seems accurate i.e. it generates the source maps properly and on the client it shows the typescript file names. But I see only empty files.

After some research it seems to be a jetty configuration issue i.e. it doesn't deliver the typescript files.

Any clues please ?

Body:
Thanks to @Joakim Erdfelt comment I rectified the plugin configuration and removed the Connector part. Since Jetty 9 this connector can be optionally configured in Jetty.xml rather then in the plugin.

Using the defaults like this  -

<plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.0.v20161208</version>
            <configuration>
                <webapp>
                    <contextPath>/</contextPath>
                </webapp>
                <webAppSourceDirectory>${project.basedir}/WebContent</webAppSourceDirectory>
                <stopWait>10</stopWait>

                <dependencies>
                    <dependency>
                        <groupId>ch.qos.logback</groupId>
                        <artifactId>logback-classic</artifactId>
                        <version>0.9.29</version>
                    </dependency>
                </dependencies>
            </configuration>
        </plugin>

solves the issue of typescript files not being served. I still haven't figured the correct version of logback and will update this answer once I do.

Also found this Mycong example that drives the point home for reference on jetty 9 configuration-

https://www.mkyong.com/maven/maven-jetty-plugin-examples/


问:
I am not able to get data from model in codeigniter
Model

//returns an array having different arrays inside it with keys id ,name and thumbnail taken from the database

```<code>function m_get_thumbnails($category){
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    if($query->num_rows()>0)
    {
        $count =0;
        $arr = array();
        foreach ($query->result() as $row)
        {

            $arr[$count++] = array(
                'id'=>$row->id,
                'name'=>$row->name,
                'thumbnail'=>$row->thumbnail
                );
        }
        return $arr;
    }
}
</code>```

function in controller

After that i place the result in an array and pass the array to my view.

```<code>function index_food()
{
    $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
    $this->load->view('food.php',$data);
}
</code>```

View

```<code><script>alert(<?php $cafe[1]; ?>);</script>
//this alert is coming blank.......
</code>```

答:
Simplify your function in Model

```<code>function m_get_thumbnails($category)
{
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food')->result_array();
    return $query;
}
</code>```

In your View

```<code><table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>Thumbnail</td>
</tr>
<?php for($i=0;$i<count($cafe);$i++){?>
<tr>
  <td> <?php echo $cafe[$i]['id']?> </td>
  <td> <?php echo $cafe[$i]['name']?> </td>
  <td> <?php echo $cafe[$i]['thumbnail']?> </td> <!-- Use <img> if you have a url -->
</tr>
<?php }?>
</table>
</code>```

Body:
Model

//returns an array having different arrays inside it with keys id ,name and thumbnail taken from the database

function m_get_thumbnails($category){
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food');
    if($query->num_rows()>0)
    {
        $count =0;
        $arr = array();
        foreach ($query->result() as $row)
        {

            $arr[$count++] = array(
                'id'=>$row->id,
                'name'=>$row->name,
                'thumbnail'=>$row->thumbnail
                );
        }
        return $arr;
    }
}

function in controller

After that i place the result in an array and pass the array to my view.

function index_food()
{
    $data['cafe'] =  $this->mlocus->m_get_thumbnails('cafe');
    $this->load->view('food.php',$data);
}

View

//this alert is coming blank.......

Body:
Simplify your function in Model

function m_get_thumbnails($category)
{
    $this->db->select('id,name,thumbnail');
    $this->db->where('category',$category);
    $query=$this->db->get('food')->result_array();
    return $query;
}

In your View

<table>
<tr>
  <td>ID</td>
  <td>Name</td>
  <td>Thumbnail</td>
</tr>
<?php for($i=0;$i<count($cafe);$i++){?>
<tr>
  <td> <?php echo $cafe[$i]['id']?> </td>
  <td> <?php echo $cafe[$i]['name']?> </td>
  <td> <?php echo $cafe[$i]['thumbnail']?> </td> <!-- Use <img> if you have a url -->
</tr>
<?php }?>
</table>


问:
Google datastore security with objectify
I am experimenting with objectify and GAE (Java, standard environment) to store some data in Google's datastore.
When not using objectify prepared queries are mentioned in the docs in order to save and retrieve data from the datastore.
See: GAE docs

Are there any vulnerabilities similar to SQL injection when using Objectify like this:

```<code>List<Car> cars = ofy().load().type(Car.class).filter("year >", 1999).list();
</code>```

Or like this:

```<code>ofy().save().entity(thing1).now();
Thing th = ofy().load().key(thingKey).now();
</code>```

Thanks in advance

答: No, there's no equivalent of SQL injection because there is no query language.</p>

Body:
I am experimenting with objectify and GAE (Java, standard environment) to store some data in Google's datastore.
When not using objectify prepared queries are mentioned in the docs in order to save and retrieve data from the datastore.
See: GAE docs

Are there any vulnerabilities similar to SQL injection when using Objectify like this:

List<Car> cars = ofy().load().type(Car.class).filter("year >", 1999).list();

Or like this:

ofy().save().entity(thing1).now();
Thing th = ofy().load().key(thingKey).now();

Thanks in advance


问:
Google analytics C# project - authentication fails
I am using this simple server-side code to create a google authentication token that to be used on the client side for embedding a view

```<code>    private void GenarateGAToken()
    {
        GoogleCredential credential;
        string keyFilePath = Server.MapPath("") + MYKEYFILENAME;
        using (Stream stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = GoogleCredential.FromStream(stream);
        }
        string[] scopes = new string[] { AnalyticsService.Scope.Analytics };             credential = credential.CreateScoped(scopes);

        try
        {
            bearer = ((ITokenAccess)credential).GetAccessTokenForRequestAsync().Result;
        }
        catch (AggregateException ex)
        {
            throw ex.InnerException;
        }
    }
</code>```

I use the token on the page to authorise the API

```<code>gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '{{ <%=bearer%> }}'
    }
    });
</code>```

But I get back error 401 "Invalide Credentials":

```<code>{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}
</code>```

Tested the token value on https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=
And it looks valid

The Google account seems to be set correctly with a service account with all required permissions

What am I missing here?

答:
Well, found the stupid copy-paste problem
I copied and pasted this:

```<code>gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '{{ <%=bearer%> }}'
    }
    });
</code>```

The curly brackets are the problem, they are just placeholder and should be removed, so this works:

```<code>gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '<%=bearer%>'
    }
    });
</code>```

Body:
I am using this simple server-side code to create a google authentication token that to be used on the client side for embedding a view

    private void GenarateGAToken()
    {
        GoogleCredential credential;
        string keyFilePath = Server.MapPath("") + MYKEYFILENAME;
        using (Stream stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            credential = GoogleCredential.FromStream(stream);
        }
        string[] scopes = new string[] { AnalyticsService.Scope.Analytics };             credential = credential.CreateScoped(scopes);

        try
        {
            bearer = ((ITokenAccess)credential).GetAccessTokenForRequestAsync().Result;
        }
        catch (AggregateException ex)
        {
            throw ex.InnerException;
        }
    }

I use the token on the page to authorise the API

gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '{{ <%=bearer%> }}'
    }
    });

But I get back error 401 "Invalide Credentials":

{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid Credentials","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid Credentials"}}

Tested the token value on https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=
And it looks valid

The Google account seems to be set correctly with a service account with all required permissions

What am I missing here?

Body:
Well, found the stupid copy-paste problem
I copied and pasted this:

gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '{{ <%=bearer%> }}'
    }
    });

The curly brackets are the problem, they are just placeholder and should be removed, so this works:

gapi.analytics.ready(function() {
    gapi.analytics.auth.authorize({
    'serverAuth': {
        'access_token': '<%=bearer%>'
    }
    });


问:
on click of div Collapse all the other divs
i have 7 divs one beside the other in horizontal line.

i want to make animation when the user click on a div of them the other divs will collapse under the dive clicked.

is there any code to do it no matter what is the code that will do it?

also is the code will work if the divs in a table ?

答:
you have to add any constant class to all div. For example look into the following code sample.

```<code> <div class="all-div">first Div</div>
    <div class="all-div">second Div</div>
    <div class="all-div">third Div</div>
    <div class="all-div">fourth Div</div>
    <div class="all-div">fifth Div</div>
    <div class="all-div">sixth Div</div>
    <script>$(document).ready(function(){
        $(".all-div").on("click",function(){
    var current=this;
    $(".all-div").each(function(key,val){
          if($(val)!=$(current))$(val).hide();
          else $(val).show();
      });
    });
    });</script>
</code>```

this is sample code. You can modify it as per your requirement.

Body:
you have to add any constant class to all div. For example look into the following code sample.

 <div class="all-div">first Div</div>
    <div class="all-div">second Div</div>
    <div class="all-div">third Div</div>
    <div class="all-div">fourth Div</div>
    <div class="all-div">fifth Div</div>
    <div class="all-div">sixth Div</div>
    <script>$(document).ready(function(){
        $(".all-div").on("click",function(){
    var current=this;
    $(".all-div").each(function(key,val){
          if($(val)!=$(current))$(val).hide();
          else $(val).show();
      });
    });
    });</script>

this is sample code. You can modify it as per your requirement.


问:
How to establish connection with HIVE using JDBC?
HOW TO CONFIGURE JDBC WITH HIVE

```<code>import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class table {
   private static String driverName = "org.apache.hadoop.hive.mysql.jdbc.Driver";

   public static void main(String[] args) throws SQLException {
      // Register driver and create driver instance

         try {
        Class.forName(driverName);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:1000/default", "", "");
      Statement stmt = con.createStatement();

      stmt.executeQuery("CREATE DATABASE userdb");
    //  System.out.println(“Database userdb created successfully”);

      con.close();
   }
}

akshay@akshay:~$ javac table.java
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
akshay@akshay:~$ java table
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
java.lang.ClassNotFoundException: org.apache.hadoop.hive.mysql.jdbc.Driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at table.main(table.java:14)
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:1000/default
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at table.main(table.java:20)
</code>```

My hive-site.xml contains

```<code><property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
    <description>MySQL JDBC driver class</description>
  </property>

<property>
   <name>javax.jdo.option.ConnectionURL</name>
   <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
   <description>metadata is stored in a MySQL server </description>
</property>
</code>```

I have configured meta store of hive with MySQL. So what should my ConnectionURL and Drivername in JAVA connection code?
I am not getting where I am going wrong. Please provide solution for above problem.

答:
For running hive queries using JDBC API's, you need to start your hiveserver2 first. Configure the thrift server port in your hive-site.xml file as shown below

```<code><property>
<name>hive.server2.thrift.port</name>
<value>10000</value>
<description>TCP port number to listen on, default 10000</description>
</property>
</code>```

Start the hiveserver2 using the command

```<code>cd $HIVE_HOME/bin
./hiveserver2
</code>```

Also you need to add the below dependencies to your project.

```<code>Hive-jdbc-*-standalone.jar

hive-jdb-*.jar

hive-metastore-*.jar

hive-service-*.jar
</code>```

After that try running the program. You can refer to this blog for more information on step by step  procedure to run hive queries using java programs.

Body:
HOW TO CONFIGURE JDBC WITH HIVE

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;

public class table {
   private static String driverName = "org.apache.hadoop.hive.mysql.jdbc.Driver";

   public static void main(String[] args) throws SQLException {
      // Register driver and create driver instance

         try {
        Class.forName(driverName);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:1000/default", "", "");
      Statement stmt = con.createStatement();

      stmt.executeQuery("CREATE DATABASE userdb");
    //  System.out.println(“Database userdb created successfully”);

      con.close();
   }
}

akshay@akshay:~$ javac table.java
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
akshay@akshay:~$ java table
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
java.lang.ClassNotFoundException: org.apache.hadoop.hive.mysql.jdbc.Driver
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at table.main(table.java:14)
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:1000/default
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at table.main(table.java:20)

My hive-site.xml contains

<property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
    <description>MySQL JDBC driver class</description>
  </property>

<property>
   <name>javax.jdo.option.ConnectionURL</name>
   <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
   <description>metadata is stored in a MySQL server </description>
</property>

I have configured meta store of hive with MySQL. So what should my ConnectionURL and Drivername in JAVA connection code?
I am not getting where I am going wrong. Please provide solution for above problem.

Body:
For running hive queries using JDBC API's, you need to start your hiveserver2 first. Configure the thrift server port in your hive-site.xml file as shown below

<property>
<name>hive.server2.thrift.port</name>
<value>10000</value>
<description>TCP port number to listen on, default 10000</description>
</property>

Start the hiveserver2 using the command

cd $HIVE_HOME/bin
./hiveserver2

Also you need to add the below dependencies to your project.

Hive-jdbc-*-standalone.jar

hive-jdb-*.jar

hive-metastore-*.jar

hive-service-*.jar

After that try running the program. You can refer to this blog for more information on step by step  procedure to run hive queries using java programs.


问:
How to create multiple page in dompdf
I created a dompdf which fetch data from database mysql. But my problem is how i am going to iterate a page if the data of each user will exceed 19 transactions?

```<code><?php
define( 'WP_USE_THEMES', false );
define( 'COOKIE_DOMAIN', false );
define( 'DISABLE_WP_CRON', true );
require('wp-load.php');

global $current_user;
get_currentuserinfo();

$d = $current_user->user_login;

// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();

$html = '<html><body>'.
        '<p>Date | Details </p>';

$ff = $wpdb->get_results( "SELECT * FROM table WHERE dd = '$d' ORDER by tdate");
    foreach ( $ff as $jj ) {
     $html = '<p>'.$jj->tdate.' | '.$jj->details.'</p>';
    }

$html .= ''</body></html>';

$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
//$dompdf->stream();

// Output the generated PDF (1 = download and 0 = preview)
$dompdf->stream("codex",array("Attachment"=>0));
</code>```

For now it works fine for 1 page only but my problem is when the data of each user exceeds 19 to higher transactions it will break the page. I want to set 19 transaction per page.

BTW sample output look like this:

Can anyone here help me?

Thanks.

答:
try this

```<code>$start = '<html><body>';
$body  = '<p>Date | Details </p>';
$ff = $wpdb->get_results( "SELECT * FROM table WHERE dd = '$d' ORDER by tdate");
    foreach ( $ff as $jj ) {
     $body .= '<p>'.$jj->tdate.' | '.$jj->details.'</p>';
    }
$end= '</body></html>';
$dompdf->loadHtml($start.$body.$body.$end);
</code>```

implement this code in your code.

Title: How to create multiple page in dompdf

Body:
I created a dompdf which fetch data from database mysql. But my problem is how i am going to iterate a page if the data of each user will exceed 19 transactions?

<?php
define( 'WP_USE_THEMES', false );
define( 'COOKIE_DOMAIN', false );
define( 'DISABLE_WP_CRON', true );
require('wp-load.php');

global $current_user;
get_currentuserinfo();

$d = $current_user->user_login;

// include autoloader
require_once 'dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();

$html = ''.
        '
Date | Details
';

$ff = $wpdb->get_results( "SELECT * FROM table WHERE dd = '$d' ORDER by tdate");
    foreach ( $ff as $jj ) {
     $html = '
'.$jj->tdate.' | '.$jj->details.'
';
    }

$html .= ''';

$dompdf->loadHtml($html);

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
//$dompdf->stream();

// Output the generated PDF (1 = download and 0 = preview)
$dompdf->stream("codex",array("Attachment"=>0));

For now it works fine for 1 page only but my problem is when the data of each user exceeds 19 to higher transactions it will break the page. I want to set 19 transaction per page.

BTW sample output look like this:

Can anyone here help me?

Thanks.

Body:
try this

$start = '<html><body>';
$body  = '<p>Date | Details </p>';
$ff = $wpdb->get_results( "SELECT * FROM table WHERE dd = '$d' ORDER by tdate");
    foreach ( $ff as $jj ) {
     $body .= '<p>'.$jj->tdate.' | '.$jj->details.'</p>';
    }
$end= '</body></html>';
$dompdf->loadHtml($start.$body.$body.$end);

implement this code in your code.


问:
format HTML5 date picker UI for android
is there any way to show the date picker in the following way in android using HTML5,

i am using HTML5 date to show the datepicker(showing like calendar) but i want to show the simpler way.

```<code><input tye="date">
</code>```

答: Generally every browser implements their own calendar differently. The best way is to use any external library (like jQuery UI Date-picker) and customize it according to your need !</p>

Title: format HTML5 date picker UI for android

Body:
is there any way to show the date picker in the following way in android using HTML5,

i am using HTML5 date to show the datepicker(showing like calendar) but i want to show the simpler way.

<input tye="date">


问:
C# Avoiding Duplicated Logic
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

```<code>public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}
</code>```

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

```<code>// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}
</code>```

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

答:
This is clunky and it can be cleaned up with C# 7.0 and pattern matching, but I am not there yet.

```<code>public interface A { }
public struct B :A { }
public struct C :A { }
public struct D: A { }

public class MyClass
{
    int counter;
    private void DoSomething(B b) { ... }
    private void DoSomething(C c) { ... }
    private void DoSomething(D d) { ... }

    public void DoSomethingExternal(A arg)
    {
        if (arg is B)
        {
            DoSomething((B)arg);
        }
        else if (arg is C)
        {
            DoSomething((C)arg);
        }
        else if (arg is D)
        {
            DoSomething((D)arg);
        }
        else
        {
            // If `A` is not of `B`, `C` or `D` types return without incrementing counter
            return;
        }
        counter++;
    }
}
</code>```

Edit 1

if a common interface or class A does not exist, then you have to use object.

```<code>public void DoSomethingExternal(object arg)
{
}
</code>```

Title: C# Avoiding Duplicated Logic

Body:
Suppose I had a base class A, with subclasses B, C and D. I have a class, MyClass which contains an overload for each of them. I want a counter to increment any time one of these methods is invoked from anywhere other than inside MyClass. This can be accomplished with a few simple helper methods:

public class MyClass
{
   int counter;

   public doSomethingExternal(B b) {counter++; doSomething(b);}
   public doSomethingExternal(C c) {counter++; doSomething(c);}
   public doSomethingExternal(D d) {counter++; doSomething(d);}

   private doSomething(B b) {...}
   private doSomething(C c) {...}
   private doSomething(D d) {...}
}

This really bothers the dev in me. Is there no way better way we can write those helper methods so that we don't have duplicated logic for every subclass? The solution I envision is something like:

// Magically, we know which type we are and call the correct doSomething
public doSomethingExternal(A a) {counter++; doSomething(a);}

I think this kind of generalization could be accomplished with Reflection, but I have heard that reflection is generally slow and can be complicated to understand. I am curious if there is a more conventional pattern I am overlooking that solves this logic-duplication issue.

Body:
This is clunky and it can be cleaned up with C# 7.0 and pattern matching, but I am not there yet.

public interface A { }
public struct B :A { }
public struct C :A { }
public struct D: A { }

public class MyClass
{
    int counter;
    private void DoSomething(B b) { ... }
    private void DoSomething(C c) { ... }
    private void DoSomething(D d) { ... }

    public void DoSomethingExternal(A arg)
    {
        if (arg is B)
        {
            DoSomething((B)arg);
        }
        else if (arg is C)
        {
            DoSomething((C)arg);
        }
        else if (arg is D)
        {
            DoSomething((D)arg);
        }
        else
        {
            // If `A` is not of `B`, `C` or `D` types return without incrementing counter
            return;
        }
        counter++;
    }
}

Edit 1

if a common interface or class A does not exist, then you have to use object.

public void DoSomethingExternal(object arg)
{
}


问:
Excel dynamic range offset formula exclude #n/a
I have data that changes depending on the slicer, and I can't figure out the correct offset formula to select only data values that are valid or in other words, exclude any #N/A values. The data looks something like this:

```<code>|Column A   |  Column B   |Column C|
|----------------------------------|
|Jan        |   #N/A      |    #N/A|
|Feb        |   4         |     40 |
|Mar        |   5         |    38  |
|Apr        |   12        |     10 |
|May        |   #N/A      |    #N/A|
|Jun        |   #N/A      |    #N/A|
</code>```

I want the offset range to select only Feb/Mar/Apr rows. But if the data changes because I click on a different filter (example below), I want it to still select only the non-error data (rows Jan/Feb/Mar/Apr):

```<code>|Column A   |  Column B  | Column C|
|----------------------------------|
|Jan        |   30       |      60 |
|Feb        |   8        |      83 |
|Mar        |   53       |      14 |
|Apr        |   11       |      41 |
|May        |   #N/A     |     #N/A|
|Jun        |   #N/A     |     #N/A|
</code>```

Please help! Thank you.

答:
The offset function can only select a single range of cells, however this should still be suitable for your needs. A graph with months along the x-axis should include all months even if there isn't a value. The offset function will just cause the graph to start at the earliest month with a value and finish at the latest month with a value. Any months in between without a value will just have nothing plotted on the chart.

To use named ranges in a chart, you have to name each individual series. You can't use a dynamic range for the entire chart source data range.

Define the following three named ranges for use in your chart. There is one named range for each column A, B and C. Each named range looks at Column B to determine which rows to include:

Months:

```<code>=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$A$2,OFFSET(Sheet1!$A$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))
</code>```

Series1:

```<code>=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$B$2,OFFSET(Sheet1!$B$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))
</code>```

Series2:

```<code>=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$C$2,OFFSET(Sheet1!$C$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))
</code>```

You can then set up your chart, but remember you need to add/edit each series individually. Ignore the Chart Data Range field:

When you set each series or x-axis to the named range, you need to qualify it with a reference to the current worksheet or workbook. If you just specify the range name, Excel won't recognize it:

After you have set everything up, the Chart Data Range field will show the consolidated range that covers all data for your change. Do not touch this field. The dynamic ranges have been set for the series. As your data changes, FMS will automatically recalculate the Chart Data Range.

Body:
I have data that changes depending on the slicer, and I can't figure out the correct offset formula to select only data values that are valid or in other words, exclude any #N/A values. The data looks something like this:

|Column A   |  Column B   |Column C|
|----------------------------------|
|Jan        |   #N/A      |    #N/A|
|Feb        |   4         |     40 |
|Mar        |   5         |    38  |
|Apr        |   12        |     10 |
|May        |   #N/A      |    #N/A|
|Jun        |   #N/A      |    #N/A|

I want the offset range to select only Feb/Mar/Apr rows. But if the data changes because I click on a different filter (example below), I want it to still select only the non-error data (rows Jan/Feb/Mar/Apr):

|Column A   |  Column B  | Column C|
|----------------------------------|
|Jan        |   30       |      60 |
|Feb        |   8        |      83 |
|Mar        |   53       |      14 |
|Apr        |   11       |      41 |
|May        |   #N/A     |     #N/A|
|Jun        |   #N/A     |     #N/A|

Please help! Thank you.

Body:
The offset function can only select a single range of cells, however this should still be suitable for your needs. A graph with months along the x-axis should include all months even if there isn't a value. The offset function will just cause the graph to start at the earliest month with a value and finish at the latest month with a value. Any months in between without a value will just have nothing plotted on the chart.

To use named ranges in a chart, you have to name each individual series. You can't use a dynamic range for the entire chart source data range.

Define the following three named ranges for use in your chart. There is one named range for each column A, B and C. Each named range looks at Column B to determine which rows to include:

Months:

=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$A$2,OFFSET(Sheet1!$A$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))

Series1:

=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$B$2,OFFSET(Sheet1!$B$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))

Series2:

=IF(COUNT(Sheet1!$B$2:$B$7)=0,Sheet1!$C$2,OFFSET(Sheet1!$C$1,MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-1,0,MAX(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))-MIN(IF(ISERROR(Sheet1!$B$2:$B$7),"",ROW(Sheet1!$B$2:$B$7)))+1,1))

You can then set up your chart, but remember you need to add/edit each series individually. Ignore the Chart Data Range field:

When you set each series or x-axis to the named range, you need to qualify it with a reference to the current worksheet or workbook. If you just specify the range name, Excel won't recognize it:

After you have set everything up, the Chart Data Range field will show the consolidated range that covers all data for your change. Do not touch this field. The dynamic ranges have been set for the series. As your data changes, FMS will automatically recalculate the Chart Data Range.


问:
Java comparing two arrays and checking if the First array is consecutive of the Second
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.</p>

```<code> public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}
</code>```

答:
If anybody needs an algorithmic answer....(I've reversed arrayA and arrayB assignments).</p>

```<code>public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
    int[] arrayB = {7,14,21,28};
    int[] arrayA = {1,3,5,7,14,21,28,32};

    boolean result = false;

    for(int A = 0; A < arrayA.length; A++)
    {
         if( arrayA[A] != arrayB[0]) continue;
         //else ...
         for(int B = 0; B < arrayB.length; B++)
         {
                    if(arrayA[A] != arrayB[B] || A>=arrayA.length)
                        break;
                    if(B+1 == arrayB.length)
                        {
                            result = true;
                            break;
                        }
                    A++;
         }
        if(result)
            break;

      }
      System.out.println("Contains :"+ result);
 }
</code>```

Body:
Long story short beginner programer here practicing with java. Right now I'm taking two arrays and I want to find out if int arrayA (7,14,21,28) is consecutive to int ArrayB meaning does arrayB have (7,14,21,28) consecutively within the array. If it is the boolean returns true if not it shall simply return false. Here is an example of my code.

 public class Harrison7aTest
 {
 public static void main(String [] args)
 {
  int[] arrayA = {7,14,21,28};
  int[] arrayB = {1,3,5,7,14,21,28,32};

 boolean result = false;

  for(int A = 0; A < arrayA.length - 1; A++)
  {
     for(int B = 0; B < arrayB.length - 1; B++)
     {

     }

  }

}
}

Body:
If anybody needs an algorithmic answer....(I've reversed arrayA and arrayB assignments).

public static void main (String[] args) throws java.lang.Exception
{
    // your code goes here
    int[] arrayB = {7,14,21,28};
    int[] arrayA = {1,3,5,7,14,21,28,32};

    boolean result = false;

    for(int A = 0; A < arrayA.length; A++)
    {
         if( arrayA[A] != arrayB[0]) continue;
         //else ...
         for(int B = 0; B < arrayB.length; B++)
         {
                    if(arrayA[A] != arrayB[B] || A>=arrayA.length)
                        break;
                    if(B+1 == arrayB.length)
                        {
                            result = true;
                            break;
                        }
                    A++;
         }
        if(result)
            break;

      }
      System.out.println("Contains :"+ result);
 }


问:
How to add and remove active class to anchor tag within li using Jquery/Javascript
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

```<code><ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
<li><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>

</ul>
</code>```

My active class is given below.

```<code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}
</code>```

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

答:
$('.abc').click(function () {
  $('.abc').removeClass('active');
  $(this).addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}</code>```

<!DOCTYPE html>

href='javascript:void(0)' onclick='savesubcat()'>ABC

href='javascript:void(0)' onclick='savesubcat()'>ABF

href='javascript:void(0)' onclick='savesubcat()'>ABK

```

Body:
I need one help. I have multiple li values I need to add active class when clicked any value and removed from others using Jquery/Javascript.I am explaining my code below.

ABC

ABF

ABK

My active class is given below.

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

Here I need while user will click on one value that only will be remain active and other will not have the active class.Please help me.

Body:
$('.abc').click(function () {
  $('.abc').removeClass('active');
  $(this).addClass('active');
});

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

<!DOCTYPE html>

<HTML>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  </head>
  <body>
    <div>
      <ul id="ulCategory">
        <li class="abc active"><a href='javascript:void(0)' onclick='savesubcat()'>ABC</li>
        <li class="abc"><a href='javascript:void(0)' onclick='savesubcat()'>ABF</li>
        <li class="abc"><a href='javascript:void(0)' onclick='savesubcat()'>ABK</li>
      </ul>
    </div>
  </body>
</html>

ContentLicense: CC BY-SA 4.0


问:
Control 'ctl00' of type 'RadioButton' must be placed inside a form tag with runat=server
I got an error as shown below. Can anyone help me to fix the issue please?
enter image description here

I tried adding form tag as

```<code><form id="form1" runat="server" >
<table border="0" class="forms">
<tbody>
<tr>
<td>
<asp:RadioButton runat="server" name="RadioButton1" id="ctl00_ctl36_g_ad6f39ad_7948_409d_ba2a_e8c922b9bcdf_RadioButton1" value="RFP" text="RFP" checked="true">
</asp:RadioButton>
</td>
<td>
<asp:RadioButton runat="server" name="RadioButton2" id="ctl00_ctl36_g_ad6f39ad_7948_409d_ba2a_e8c922b9bcdf_RadioButton2" value="RFQ" text="RFQ"></asp:RadioButton>
</td>
</tr>
</tbody>
</table>
</form>
</code>```

still the issue persists.
Thanks In Advance.

答:
First of all your name properties are different.

are you using content template?

Body:
I got an error as shown below. Can anyone help me to fix the issue please?
enter image description here

I tried adding form tag as

<form id="form1" runat="server" >

<asp:RadioButton runat="server" name="RadioButton1" id="ctl00_ctl36_g_ad6f39ad_7948_409d_ba2a_e8c922b9bcdf_RadioButton1" value="RFP" text="RFP" checked="true">
</asp:RadioButton>

<asp:RadioButton runat="server" name="RadioButton2" id="ctl00_ctl36_g_ad6f39ad_7948_409d_ba2a_e8c922b9bcdf_RadioButton2" value="RFQ" text="RFQ"></asp:RadioButton>

</form>

still the issue persists.
Thanks In Advance.


问:
How to centralize all IIS-centric data to a shared network drive?
I have an azure windows VM with IIS with a shared network drive attached to it.
Now I add another VM combined with a load balancer, but to prevent having to maintain IIS in 2 VM's, I thought about moving the IIS settings to my shared drive (which is already used for data storage for my webapps).

How can I do this? I have similar issues for windows taskscheduler, is there a way to move these settings to different (shared) locations?

答:
is there a way to move these settings to different (shared) locations

Do you mean two VMs use the one configure file? yes, this same as on-prem, we can mount the shared network drive to two VMs, and delegating configuration sections from server-level configuration files to Web.config files in your sites, applications, and virtual or physical directories.

More information about IIS configuration files, please refer to this link.


问:
I want to get id of multiple checkboxes
I want id of selected items from checkbox and insert to database. I can insert other items to database but id of selected checkbox is not inserting.

```<code>    <div class="row" >
      <div class="col-xs-3">
      <form action="itemad.php" method="post">

      <div class="multiselect">
      <input type="text" name="datepicker" id="datepicker" placeholder="Date"     </p>
        <b>Select Menu:</b>
          <div class="checkbox" onclick="showCheckboxes()">
            <select>
                  <option>Select an option</option>
           </select>
         <div class="overSelect"></div>
        </div>

     <div id="checkboxes">

        <?php
            include 'connection.php';
           $query="select item from item";
            $result=mysql_query("$query");
             while($row=mysql_fetch_array($result)):;
              echo $row['item'];
               for($i=0; $i<=count('item'); $i++ )
        ?>
      <input type="checkbox" name="check_list[]" value="" ></input><br>
           <?php endwhile;?>
           </div>
         <input type="text" name="price" Placeholder="Pricee" minlength="1" ><br><br>
         <input type="submit" name="submit">
      </div>
     </div>
          <script type="text/javascript">
            var expanded = false;
            function showCheckboxes() {
              var checkboxes = document.getElementById("checkboxes");
              if (!expanded)
              {
                checkboxes.style.display = "block";
                expanded = true;
              }
              else
               {
                checkboxes.style.display = "none";
                expanded = false;
               }
            }
          </script>
  </form>
  </div>
  </div>
</code>```

itemad.php:

```<code>if(isset($_POST['submit']))
{
if(!empty($_POST['check_list']))
{
    // Counting number of checked checkboxes.
    $checked_count = count($_POST['check_list']);
    echo "You have selected following ".$checked_count." option(s): <br/>";
    // Loop to store and display values of individual checked checkbox.
    foreach($_POST['check_list'] as $id)
        {
            echo "<p>".$id ."</p>";
        } }
else
    { echo "<b>Please Select Atleast One Option.</b>"; }
   $price=$_POST['price'];
        $date=$_POST['datepicker'];
        $query= "insert into menu(item,price,date) values('$id','$price','$date')";
       $result=mysql_query($query);
       echo "suucesful";
    }
</code>```

i want to store id of each item in database. but in database i am not getting id for selected items.

答:
You missed one thing:

```<code><input type="checkbox" name="check_list[]" value="" />
</code>```

The check_list array should not have an empty value. You should have to put a value into it.

```<code><?php
  $query="select item_id, item from item";
  $result=mysql_query("$query");
  while($row=mysql_fetch_array($result)):;
  ?>
 <input type="checkbox" name="check_list[]" value="<?php echo $row['item_id']; ?>" /><br>
 <?php endwhile;?>
</code>```

Title: I want to get id of multiple checkboxes

Body:
I want id of selected items from checkbox and insert to database. I can insert other items to database but id of selected checkbox is not inserting.

      <form action="itemad.php" method="post">

      <input type="text" name="datepicker" id="datepicker" placeholder="Date"

        Select Menu:

            <select>
                  <option>Select an option</option>
           </select>

        <?php
            include 'connection.php';
           $query="select item from item";
            $result=mysql_query("$query");
             while($row=mysql_fetch_array($result)):;
              echo $row['item'];
               for($i=0; $i<=count('item'); $i++ )
        ?>
      <input type="checkbox" name="check_list[]" value="" ></input>

           <?php endwhile;?>

         <input type="text" name="price" Placeholder="Pricee" minlength="1" >

         <input type="submit" name="submit">

  </form>

itemad.php:

if(isset($_POST['submit']))
{
if(!empty($_POST['check_list']))
{
    // Counting number of checked checkboxes.
    $checked_count = count($_POST['check_list']);
    echo "You have selected following ".$checked_count." option(s):
";
    // Loop to store and display values of individual checked checkbox.
    foreach($_POST['check_list'] as $id)
        {
            echo "
".$id ."
";
        } }
else
    { echo "Please Select Atleast One Option."; }
   $price=$_POST['price'];
        $date=$_POST['datepicker'];
        $query= "insert into menu(item,price,date) values('$id','$price','$date')";
       $result=mysql_query($query);
       echo "suucesful";
    }

i want to store id of each item in database. but in database i am not getting id for selected items.

Body:
You missed one thing:

<input type="checkbox" name="check_list[]" value="" />

The check_list array should not have an empty value. You should have to put a value into it.

<?php
  $query="select item_id, item from item";
  $result=mysql_query("$query");
  while($row=mysql_fetch_array($result)):;
  ?>
 <input type="checkbox" name="check_list[]" value="<?php echo $row['item_id']; ?>" /><br>
 <?php endwhile;?>


答:
You can use siblings method.

siblings method gets the siblings of each element in the set of
  matched elements, optionally filtered by a selector.

$("ul li").click(function() {
  $(this).addClass('active').andSelf().siblings().removeClass();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}</code>```

href="javascript:void(0)" class="subcategory">ABC

href="javascript:void(0)" class="subcategory">ABF

href="javascript:void(0)" class="subcategory">ABK

```

Title: How to add and remove active class to anchor tag within li using Jquery/Javascript

Body:
You can use siblings method.

siblings method gets the siblings of each element in the set of
  matched elements, optionally filtered by a selector.

$("ul li").click(function() {
  $(this).addClass('active').andSelf().siblings().removeClass();
});

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
  <li><a href="javascript:void(0)" class="subcategory">ABC</li>
  <li><a href="javascript:void(0)" class="subcategory">ABF</li>
  <li><a href="javascript:void(0)" class="subcategory">ABK</li>
</ul>


问:
how to stop webpage click events from like firefox/chrome developer console inspector tools?
Question #1:

I am working on a chrome extension where it requires an inspector like tool to let user hover on a webpage. And to show outline on hover on a DOM element.
When user clicks on any element, I need to show a popup besides the element.
But at the same time that elements click event must not execute. It is very similar to developer consoles inspector tool. Can you please help how to do this ?

Question #2:

Can you please suggest why Chrome developer console's inspector tool does not work in this case ?

To reproduce:

1. Go to https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjQ377A-8vQAhUHQY8KHUHxCv0QFggaMAA&url=https%3A%2F%2Fconsole.developers.google.com%2F&usg=AFQjCNF0eH059mv86nMIlRmfsf42kde-wA&bvm=bv.139782543,d.c2I

2. Click on "products & services" menu (3 horizontal lines icon) in left top. A slide menu will open.

3. Start developer console (click F12).

4. Select anything on this menu.

Actual result:  Side menu closes.

Expected result: Side menu should not have closed and developer console should have shown its html.

答:
I got a solution to this. I created a div (of size 4x4 px). I move
this div with the mouse move event.  I set the div coordinates so
that mouse tip is exactly at the middle of the div.

Div background is kept transparent, so that it is not visible to
users. So when user clicks on element, he is actually clicking on
the div.

And inside the div mouse down event, I stop event propagation.
Please let me know if anyone reading need any more pointers.


问:
What is the best way to query SharePoint data?
Should I just use ADO.NET to directly access the underlying data in the database or does .NET have a better way to do this?

I am currently using SharePoint 2007 but we are about to move to 2010.  I am using Visual Studio 2010.

答:
I would highly recommend using the SharePoint objects for accessing data (either SP* classes, or using SharePoint web services, LINQ to SharePoint etc).

Don't directly access the underlying database using pure ADO.NET. The main reason is that, by using the supported (official) way of accessing data, you lessen the risk of causing problems. For example, when changing data in a table, you don't know if there is a mandatory requirement for another table in the database to be updated also. The SharePoint objects will take care of that for you.

Plus, I think Microsoft will not support issues with your SharePoint code if it's directly accessing the database and there is a risk your code may not execute after any hot fix or SP release as Microsoft may change the Database structure any time .


问:
How to write laravel model based in this query with pagination?
```<code>for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }
</code>```

Hear my Query is

```<code>$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");
</code>```

How to write laravel model based in this query with pagination???

答:
```<code>Post::where('skills' , 'like' , '%php%')->orWhere('skills' , 'like' , '%javascript%')->where('status' , 1)->orderBy('id' , 'desc')->paginate(10);
</code>```

Body:
for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }

Hear my Query is

$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");

How to write laravel model based in this query with pagination???


问:
Iteration error in Entity Framework
I'm creating a simple Messaging application with C# Winforms. I'm connecting to a SQLEXPRESS server running on my computer and storing everything there.

Here is my schema:

```<code>public class UserContext : DbContext {
    public UserContext() : base("name=BuddyDatabase") {

    }
    public DbSet<User> Users { get; set; }
    public DbSet<Message> Messages { get; set; }
}

public class User {
    [Key]
    public string username { get; set; }
    public string password { get; set; }

    public static implicit operator User(bool v) {
        throw new NotImplementedException();
    }

    public virtual List<User> friends { get; set; }
}

public class Message {
    [Key]
    public int ID { get; set; }

    public virtual User sender { get; set; }
    public virtual User recipient { get; set; }

    public string content { get; set; }

    public virtual List<User> group { get; set; }
}
</code>```

Pretty simple

Sending messages to a single recipient works but group messaging doesn't, whenever I open the "Messages Screen" I get this error:

Unable to create a constant value of type 'WindowsFormsApp1.User'. Only primitive types or enumeration types are supported in this context.

And this is the method I have run when the Message Screen loads up:

```<code>var x = db.Messages.Where(b => b.recipient.username == currentuser.username);
foreach (var y in x) {
    MainMessagesBox.Text += y.content;
}
x = null;

var z = db.Messages.Where(b => b.group.Contains(currentuser));
foreach (var y in z) {
    MainMessagesBox.Text += y.content;
}
</code>```

(Visual Studio highlights the 'in' in this line as the cause of the error.)

foreach (var y in z) {

Thought this might be a problem with me using the Where method and involving non-primitives (as the error message suggests) so I tried changing my schema so that group is a list of strings that contain the usernames of the intended recipients and modified the methods accordingly but that didn't work either. Will provide code and errors for that trial on request.

Here is the actual "Send Message" code:

```<code>if (!textBox1.Text.Contains(',')) {
    db.Messages.Add(new Message { sender = currentuser, recipient = db.Users.Find(textBox1.Text), content = currentuser.username + ": " + ContentBox.Text + "\n" });
    db.SaveChanges();
} else {
     List<User> recips = new List<User>();
     string[] poop = textBox1.Text.Split(',');

     foreach (var x in poop) {
         recips.Add(db.Users.Find(x));
     }

     db.Messages.Add(new Message { sender = currentuser, group = recips, content = ContentBox.Text });
     db.SaveChanges();
}
</code>```

poop is an array of the intended recipients separated by comma from a textbox, this is temporary.

Sorry if anything is misformatted or I'm unclear, this is my first question.

Thank you in advance.

答:
The problem is the Select query on message table where you check for the current user to be in the group list. This won't work, because the query has to be translated to SQL to be send to the database.

SQL does not understand what a ´User´ type is and can't compare references. And actually, neither does C# compare this properly. Two objects of type ´User´ with the same username would not be equal in your case. You need to compare the username of those objects.

Regardless, as Bitmask explained in a comment, you have to properly define the foreign key for the messages.

It's quite easy for the sender of the messages. You have a public virtual ICollection<Message> Messages { get; set; } in your User class.

But for the recipients, it's a many-to-many relation. So both, the User class and the Message class have a collection to Message and User respectively.

Something like this should work:

```<code>public class User {
    [Key]
    public string username { get; set; }
    public string password { get; set; }

    public static implicit operator User(bool v) {
        throw new NotImplementedException();
    }

    public virtual ICollection<Message> SentMessages { get; set; }
    public virtual ICollection<Message> ReceivedMessages { get; set; }

    public virtual List<User> friends { get; set; }
}

public class Message {
    [Key]
    public int ID { get; set; }

    public virtual User Sender { get; set; }
    public virtual ICollection<User> Recipients { get; set; }

    public string content { get; set; }
}
</code>```

Check this link for an example on how to define a many-to-many relation either using data annotations or fluent API. This assumes you're using EF6 though. If you're using an older version of EF, you might have to define the joining table yourself to get the many-to-many relation.

And as for the query. You can use the following in your message screen OnLoad method:

```<code>MainMessagesBox.Text = string.Join(System.Environment.NewLine, currentuser.ReceivedMessages.Select(m => m.content))
</code>```

This concatenates all messages, separated with a new line.

Title: Iteration error in Entity Framework

Body:
I'm creating a simple Messaging application with C# Winforms. I'm connecting to a SQLEXPRESS server running on my computer and storing everything there.

Here is my schema:

public class UserContext : DbContext {
    public UserContext() : base("name=BuddyDatabase") {

    }
    public DbSet<User> Users { get; set; }
    public DbSet<Message> Messages { get; set; }
}

public class User {
    [Key]
    public string username { get; set; }
    public string password { get; set; }

    public static implicit operator User(bool v) {
        throw new NotImplementedException();
    }

    public virtual List<User> friends { get; set; }
}

public class Message {
    [Key]
    public int ID { get; set; }

    public virtual User sender { get; set; }
    public virtual User recipient { get; set; }

    public string content { get; set; }

    public virtual List<User> group { get; set; }
}

Pretty simple

Sending messages to a single recipient works but group messaging doesn't, whenever I open the "Messages Screen" I get this error:

Unable to create a constant value of type 'WindowsFormsApp1.User'. Only primitive types or enumeration types are supported in this context.

And this is the method I have run when the Message Screen loads up:

var x = db.Messages.Where(b => b.recipient.username == currentuser.username);
foreach (var y in x) {
    MainMessagesBox.Text += y.content;
}
x = null;

var z = db.Messages.Where(b => b.group.Contains(currentuser));
foreach (var y in z) {
    MainMessagesBox.Text += y.content;
}

(Visual Studio highlights the 'in' in this line as the cause of the error.)

foreach (var y in z) {

Thought this might be a problem with me using the Where method and involving non-primitives (as the error message suggests) so I tried changing my schema so that group is a list of strings that contain the usernames of the intended recipients and modified the methods accordingly but that didn't work either. Will provide code and errors for that trial on request.

Here is the actual "Send Message" code:

if (!textBox1.Text.Contains(',')) {
    db.Messages.Add(new Message { sender = currentuser, recipient = db.Users.Find(textBox1.Text), content = currentuser.username + ": " + ContentBox.Text + "\n" });
    db.SaveChanges();
} else {
     List<User> recips = new List<User>();
     string[] poop = textBox1.Text.Split(',');

     foreach (var x in poop) {
         recips.Add(db.Users.Find(x));
     }

     db.Messages.Add(new Message { sender = currentuser, group = recips, content = ContentBox.Text });
     db.SaveChanges();
}

poop is an array of the intended recipients separated by comma from a textbox, this is temporary.

Sorry if anything is misformatted or I'm unclear, this is my first question.

Thank you in advance.

Body:
The problem is the Select query on message table where you check for the current user to be in the group list. This won't work, because the query has to be translated to SQL to be send to the database.

SQL does not understand what a ´User´ type is and can't compare references. And actually, neither does C# compare this properly. Two objects of type ´User´ with the same username would not be equal in your case. You need to compare the username of those objects.

Regardless, as Bitmask explained in a comment, you have to properly define the foreign key for the messages.

It's quite easy for the sender of the messages. You have a public virtual ICollection<Message> Messages { get; set; } in your User class.

But for the recipients, it's a many-to-many relation. So both, the User class and the Message class have a collection to Message and User respectively.

Something like this should work:

public class User {
    [Key]
    public string username { get; set; }
    public string password { get; set; }

    public static implicit operator User(bool v) {
        throw new NotImplementedException();
    }

    public virtual ICollection<Message> SentMessages { get; set; }
    public virtual ICollection<Message> ReceivedMessages { get; set; }

    public virtual List<User> friends { get; set; }
}

public class Message {
    [Key]
    public int ID { get; set; }

    public virtual User Sender { get; set; }
    public virtual ICollection<User> Recipients { get; set; }

    public string content { get; set; }
}

Check this link for an example on how to define a many-to-many relation either using data annotations or fluent API. This assumes you're using EF6 though. If you're using an older version of EF, you might have to define the joining table yourself to get the many-to-many relation.

And as for the query. You can use the following in your message screen OnLoad method:

MainMessagesBox.Text = string.Join(System.Environment.NewLine, currentuser.ReceivedMessages.Select(m => m.content))

This concatenates all messages, separated with a new line.


问:
Curious behavior while formatting dates
I'm getting a string representation of a date from a json that looks like the following:

```<code>let dateString = "2016-12-31T00:10:00+01:00"
</code>```

In order to model it as a Date object I'm using a date formatter like so:

```<code>let dateForm = DateFormatter()
dateForm.locale = Locale(identifier: "fr_FR")
dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateForm.timeZone = TimeZone.current
</code>```

When I turn it into a Date, my Playground output is correct:

```<code>let date = dateForm.date(from: dateString)
</code>```

=> Output: "Dec 31, 2016, 12:10 AM"

But if I try to print this exact same object (date) I get the following output:

```<code>print(date!)
</code>```

=> Output: "2016-12-30 23:10:00 +0000\n"

My question is: How can I be sure that I'm dealing with the correct date (by correct I mean with my local time zone (GMT+01)) ?

答:
When you print the date output 2016-12-30 23:10:00 +0000 and your GMT is +00:00
but when you get  the string from date it will return string as per your given format And your Locale (fr_FR) output 2016-12-31T00:10:00+01:00 and your GMT is +01:00
if you want to date from string then

date output = your string date - (your GMT)

In your case

```<code>2016-12-30 23:10:00 = 2016-12-31 00:10:00 - (+01:00)
</code>```

Title: Curious behavior while formatting dates

Body:
I'm getting a string representation of a date from a json that looks like the following:

let dateString = "2016-12-31T00:10:00+01:00"

In order to model it as a Date object I'm using a date formatter like so:

let dateForm = DateFormatter()
dateForm.locale = Locale(identifier: "fr_FR")
dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateForm.timeZone = TimeZone.current

When I turn it into a Date, my Playground output is correct:

let date = dateForm.date(from: dateString)

=> Output: "Dec 31, 2016, 12:10 AM"

But if I try to print this exact same object (date) I get the following output:

print(date!)

=> Output: "2016-12-30 23:10:00 +0000\n"

My question is: How can I be sure that I'm dealing with the correct date (by correct I mean with my local time zone (GMT+01)) ?

Body:
When you print the date output 2016-12-30 23:10:00 +0000 and your GMT is +00:00
but when you get  the string from date it will return string as per your given format And your Locale (fr_FR) output 2016-12-31T00:10:00+01:00 and your GMT is +01:00
if you want to date from string then

date output = your string date - (your GMT)

In your case

2016-12-30 23:10:00 = 2016-12-31 00:10:00 - (+01:00)


答:
You can try something like this

```<code>  $('ul li a').click(function() {
      $(this).parent().siblings().children().removeClass( "active" );
      $(this).addClass( "active" );
    });
</code>```

$('ul li a').click(function() {
  $(this).parent().siblings().children().removeClass( "active" );
  $(this).addClass( "active" );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}</code>```

href='javascript:void(0)' onclick=''>ABC

href='javascript:void(0)' onclick=''>ABF

href='javascript:void(0)' onclick=''>ABK

```

Body:
You can try something like this

  $('ul li a').click(function() {
      $(this).parent().siblings().children().removeClass( "active" );
      $(this).addClass( "active" );
    });

$('ul li a').click(function() {
  $(this).parent().siblings().children().removeClass( "active" );
  $(this).addClass( "active" );
});

.active {text-align: left; color: #fff; background-color:#ffbb00; text-decoration: none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ulCategory">
   <li><a href='javascript:void(0)' onclick=''>ABC</li>
<li><a href='javascript:void(0)' onclick=''>ABF</li>
<li><a href='javascript:void(0)' onclick=''>ABK</li>

</ul>