答:
You need to actually do validate on the form.

https://jqueryvalidation.org/

After you have added jquery validation and set it up you can use

```<code><form id="myForm">
<input type="submit" value="Send"/>
</form>

<script>
    $("#myForm").submit(function(){
       $("#myForm").validate();
    };
</script>
</code>```

Title: jquery not working while submitting a form

Body:
You need to actually do validate on the form.

https://jqueryvalidation.org/

After you have added jquery validation and set it up you can use

<form id="myForm">
<input type="submit" value="Send"/>
</form>

<script>
    $("#myForm").submit(function(){
       $("#myForm").validate();
    };
</script>


来源: stackexchange

问:
NSTimer stop while taking screenshot of UiView iOS?
I am taking screen shot of UIView while the screen is updating using NStimer method but Timer stops as i take screenshot of view

I am taking 5 to 8 screenshot frequently for capturing the updating on the view

But timer stops and cant get the Exact screenshot as required

My code:

```<code> -(void)StartAnmation {

  timer= [NSTimer scheduledTimerWithTimeInterval:0.2 target:self  selector:@selector(methodToAddImages) userInfo:nil repeats:YES];
 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

 - (void)methodsave
{
   for (int i=0; i<5; i++) {
    UIImage *img=[self screenshotimageWithView:self.mainview];
    [gifimages addObject:img];
       }

}
</code>```

// screenshot

```<code>- (UIImage ) screenshotimageWithView:(UIView )view
{

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

NSData *miths=UIImagePNGRepresentation(img);

UIImage *imge=[UIImage imageWithData:miths];

UIGraphicsEndImageContext();

return imge;
}
</code>```

答: Make sure you're not blocking the main thread while taking the screenshots or with another expensive operation.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am taking screen shot of UIView while the screen is updating using NStimer method but Timer stops as i take screenshot of view

I am taking 5 to 8 screenshot frequently for capturing the updating on the view

But timer stops and cant get the Exact screenshot as required

My code:

 -(void)StartAnmation {

  timer= [NSTimer scheduledTimerWithTimeInterval:0.2 target:self  selector:@selector(methodToAddImages) userInfo:nil repeats:YES];
 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

 - (void)methodsave
{
   for (int i=0; i<5; i++) {
    UIImage *img=[self screenshotimageWithView:self.mainview];
    [gifimages addObject:img];
       }

}

// screenshot

- (UIImage ) screenshotimageWithView:(UIView )view
{

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

NSData *miths=UIImagePNGRepresentation(img);

UIImage *imge=[UIImage imageWithData:miths];

UIGraphicsEndImageContext();

return imge;
}


问:
Java fibonacci stack overflow error
```<code>public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}
</code>```

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

```<code>public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}
</code>```

I wont get error, even I just enter 1, could I ask why?

答:
You don't handle the case of num == 0, so when you call fibonacci(0) the recursion never ends, leading to StackOverflowError when the stack is full.

You can solve it by changing the range of your loop

```<code> for (int j=1; j<i; j++) {
     System.out.println(fibonacci(j));
 }
</code>```

or by changing the stopping condition of your recursive method:

```<code>public static int fibonacci(int num) {
    if (num <= 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}
</code>```

That said, it would be much more efficient to store the intermediate results of fibonacci(i), and re-use them when calculating fibonacci(n) for n > i (instead of making unnecessary expansive recursive calls).

Title: Java fibonacci stack overflow error

Body:
public static void main(String[] args) {
    one();
    System.out.println();
}

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();

  for (int j=0; j<i; j++) {
      System.out.println(fibonacci(j));
  }
}

public static int fibonacci(int num){
    if (num == 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}

When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to

public static void one() {
  Scanner sc = new Scanner(System.in);
  System.out.println("Enter a number:");
  int i = sc.nextInt();
  System.out.println(fibonacci(j));
}

I wont get error, even I just enter 1, could I ask why?

Body:
You don't handle the case of num == 0, so when you call fibonacci(0) the recursion never ends, leading to StackOverflowError when the stack is full.

You can solve it by changing the range of your loop

 for (int j=1; j<i; j++) {
     System.out.println(fibonacci(j));
 }

or by changing the stopping condition of your recursive method:

public static int fibonacci(int num) {
    if (num <= 1) {
        return 0;
    }
    else if (num == 2 || num == 3){
        return 1;
    }
    else {
        return fibonacci(num-1) + fibonacci(num-2);
    }
}

That said, it would be much more efficient to store the intermediate results of fibonacci(i), and re-use them when calculating fibonacci(n) for n > i (instead of making unnecessary expansive recursive calls).


问:
Universal library for C++ strings
Please recommend me universal library for C++ strings. I want to manipulate ascii text and unicode text in one build without making two versions of builds for std::string/char and for std::wstring/wchar; Also I want to convert them to each other (where it is possible);

Thank you very much!!!

答:
I don't know of such a library, but I'd like to point out you can always go from one to another, e.g.:

```<code>string s;
foo(s.c_str());
</code>```

or

```<code>char *s;
foo(string(s));
</code>```

Just be careful going from wstring to char* or string as you will have to perform some conversion.

ContentLicense: CC BY-SA 2.5

Title: Universal library for C++ strings

Body:
I don't know of such a library, but I'd like to point out you can always go from one to another, e.g.:

string s;
foo(s.c_str());

or

char *s;
foo(string(s));

Just be careful going from wstring to char* or string as you will have to perform some conversion.


问:
How to send a notification When the particular Wifi BBSID (in Shared Preference )mobile connected with wifi BBSID with service?
I have one BBSID in my shared preference. Whenever a user connect to a Wifi network my service have to check if it is the same BBSID as the one stored in SharedPreferences. I have implemented below code but the problem is that the Notification is created multiple times when connected to a wifi network .

```<code>public class WifiConnectionNotificationService extends Service {
BroadcastReceiver mReceiver;
String bssid = "64:66:b3:f0:ce:81";
/*
WifiConnectionNotificationService(String ssid) {
    this.ssid = ssid;
}*/

// use this as an inner class like here or as a top-level class
public class IsWifiConnectedBroadcastReceiver extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (intent.getAction().contentEquals("android.net.wifi.STATE_CHANGE") || intent.getAction().contentEquals("android.net.conn.CONNECTIVITY_CHANGE")) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            if (wifiManager.isWifiEnabled()) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
                    if (wifiInfo.getBSSID().contentEquals(bssid)) {
                        PushNotification(context);
                    } else {
                        if (Context.NOTIFICATION_SERVICE != null) {
                            notificationManager.cancelAll();
                        }
                    }
                }
            } else {
                if (Context.NOTIFICATION_SERVICE != null) {
                    notificationManager.cancelAll();
                }
            }
        }
    }
}

@Override
public void onCreate() {
    // get an instance of the receiver in your service
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.wifi.STATE_CHANGE");
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    mReceiver = new IsWifiConnectedBroadcastReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification(Context context) {
    NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, Register.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(android.R.drawable.ic_notification_clear_all);
    builder.setContentText("Do you want me to start your Bike ?");
    builder.setContentTitle("Keyless Moto");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int) System.currentTimeMillis(), notification);
}
</code>```

}

答:
This line is probably wrong:

```<code>nm.notify((int) System.currentTimeMillis(), notification);
</code>```

Use a constant id :

```<code>nm.notify(12345, notification);
</code>```

And cancel it when a new one is created:

```<code>notificationManager.cancel(12345)
PushNotification(context);
</code>```

I also suggest you this link to filter more efficiently ssid changes : Android WIFI How To Detect When Specific WIFI Connection is Available

Body:
I have one BBSID in my shared preference. Whenever a user connect to a Wifi network my service have to check if it is the same BBSID as the one stored in SharedPreferences. I have implemented below code but the problem is that the Notification is created multiple times when connected to a wifi network .

public class WifiConnectionNotificationService extends Service {
BroadcastReceiver mReceiver;
String bssid = "64:66:b3:f0:ce:81";
/*
WifiConnectionNotificationService(String ssid) {
    this.ssid = ssid;
}*/

// use this as an inner class like here or as a top-level class
public class IsWifiConnectedBroadcastReceiver extends BroadcastReceiver {

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (intent.getAction().contentEquals("android.net.wifi.STATE_CHANGE") || intent.getAction().contentEquals("android.net.conn.CONNECTIVITY_CHANGE")) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            if (wifiManager.isWifiEnabled()) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
                    if (wifiInfo.getBSSID().contentEquals(bssid)) {
                        PushNotification(context);
                    } else {
                        if (Context.NOTIFICATION_SERVICE != null) {
                            notificationManager.cancelAll();
                        }
                    }
                }
            } else {
                if (Context.NOTIFICATION_SERVICE != null) {
                    notificationManager.cancelAll();
                }
            }
        }
    }
}

@Override
public void onCreate() {
    // get an instance of the receiver in your service
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.net.wifi.STATE_CHANGE");
    filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    mReceiver = new IsWifiConnectedBroadcastReceiver();
    registerReceiver(mReceiver, filter);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification(Context context) {
    NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, Register.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(android.R.drawable.ic_notification_clear_all);
    builder.setContentText("Do you want me to start your Bike ?");
    builder.setContentTitle("Keyless Moto");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int) System.currentTimeMillis(), notification);
}

}

Body:
This line is probably wrong:

nm.notify((int) System.currentTimeMillis(), notification);

Use a constant id :

nm.notify(12345, notification);

And cancel it when a new one is created:

notificationManager.cancel(12345)
PushNotification(context);

I also suggest you this link to filter more efficiently ssid changes : Android WIFI How To Detect When Specific WIFI Connection is Available


问:
How to separate and use alphabet search and datatable in to two different HTML div on same page?
I'm using responsive data tables and alphabet search together in an app,
I've everything ready.

Code Snippet is not working on stackoverflow or i do not know how to properly include the code.. please see on jsfiddle

$(document).ready(function() {
  var table = $('#example').DataTable({
    ajax: 'https://api.myjson.com/bins/qgcu',
    dom: 'Alfrtip',
    alphabetSearch: {
      column: 0
    },
    responsive: true
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table.dataTable.select tbody tr,
table.dataTable thead th:first-child {
  cursor: pointer;
}</code>```

<link href="https://gyrocode.github.io/jquery-datatables-alphabetSearch/1.1.1/css/dataTables.alphabetSearch.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/v/dt/dt-1.10.15/r-2.1.1/datatables.min.css" rel="stylesheet" />

jQuery DataTables – Alphabetical Search

See full article on Gyrocode.com

      Name
      Position
      Office
      Extn
      Start date
      Salary

      Name
      Position
      Office
      Age
      Start date
      Salary

```

Now the thing is i want to separate and use alphabets somewhere in a different division on the same page.  i dont want to see alphabets on top of the datatable.

How to display/call only alphabets in a different div?

Please help.

答:
SOLUTION

Use dom option to manipulate markup for A feature and the rest of the table. Use custom CSS to modify appearance of the alphabet control.

For example.

JavaScript

```<code>var table = $('#example').DataTable({
   dom: '<"alphabet-container"A><"table-container"lfrtip>',
   alphabetSearch: {
      column: 0
   },
   responsive: true
});
</code>```

CSS

.alphabet-container {
   float: left;
   width: 10%;
}

.table-container {
   float: left;
   width: 90%;
}

.alphabet-container .alphabet-info,
.alphabet-container .alphabet-info-display {
   display: none
}

.alphabet-container .alphabet ul,
.alphabet-container .alphabet li,
.alphabet-container .alphabet a {
   display: block;
}

.alphabet-container .alphabet {
   margin: 0 15px 0 0;
}

.alphabet-group td:first-child::before {
   display:none !important;
}
```

EXAMPLE

See this example for code and demonstration.

LINKS

jQuery DataTables AlphabetSearch - feature plug-in for the jQuery DataTables library that provides A-Z alphabetical search feature.

Body:
I'm using responsive data tables and alphabet search together in an app,
I've everything ready.

Code Snippet is not working on stackoverflow or i do not know how to properly include the code.. please see on jsfiddle

$(document).ready(function() {
  var table = $('#example').DataTable({
    ajax: 'https://api.myjson.com/bins/qgcu',
    dom: 'Alfrtip',
    alphabetSearch: {
      column: 0
    },
    responsive: true
  });
});

table.dataTable.select tbody tr,
table.dataTable thead th:first-child {
  cursor: pointer;
}

<link href="https://gyrocode.github.io/jquery-datatables-alphabetSearch/1.1.1/css/dataTables.alphabetSearch.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/v/dt/dt-1.10.15/r-2.1.1/datatables.min.css" rel="stylesheet" />

jQuery DataTables – Alphabetical Search

See full article on Gyrocode.com

      Name
      Position
      Office
      Extn
      Start date
      Salary

      Name
      Position
      Office
      Age
      Start date
      Salary

Now the thing is i want to separate and use alphabets somewhere in a different division on the same page.  i dont want to see alphabets on top of the datatable.

How to display/call only alphabets in a different div?

Please help.

Body:
SOLUTION

Use dom option to manipulate markup for A feature and the rest of the table. Use custom CSS to modify appearance of the alphabet control.

For example.

JavaScript

var table = $('#example').DataTable({
   dom: '<"alphabet-container"A><"table-container"lfrtip>',
   alphabetSearch: {
      column: 0
   },
   responsive: true
});

CSS

.alphabet-container {
   float: left;
   width: 10%;
}

.table-container {
   float: left;
   width: 90%;
}

.alphabet-container .alphabet-info,
.alphabet-container .alphabet-info-display {
   display: none
}

.alphabet-container .alphabet ul,
.alphabet-container .alphabet li,
.alphabet-container .alphabet a {
   display: block;
}

.alphabet-container .alphabet {
   margin: 0 15px 0 0;
}

.alphabet-group td:first-child::before {
   display:none !important;
}

EXAMPLE

See this example for code and demonstration.

LINKS

jQuery DataTables AlphabetSearch - feature plug-in for the jQuery DataTables library that provides A-Z alphabetical search feature.


问:
Chrome on mac adding www before subdomain
I have recently hosted my site which intends to use wildcard subdomains in its general use. A user would go to account.website.com to access their part of the site. The site is a rails app hosted on heroku and domain is through 123-reg. DNS is set up as per heroku - * , cname , wildcard.app.heroku...

At first i thought 123-reg couldnt handle wildcard routing and i would have to change dns provider as whenever i go to account.website.com it will send me to www.account.website.com which is extremely irritating, but then i found that this does not happen on my windows machine, only on my dev machine (macbook pro). In both cases i am using Chrome. Firefox works as desired, only chrome is messing up.

Any insight into why this is happening would be fantastic.

Thanks

答: Obviously i immediately solve it after asking and look like a fool - Apparently the cache remembers the redirect from when i assume i hadnt yet set up dns correctly. If you get the same problem, clear browser cache</p>


问:
How to store and retrieve state in a callback()?
I'm trying to simulate reading data from a queue such as kafka.  I need to maintain a pointer to the current record when I am streaming data from a file.  Currently I'm doing this with a global variable, but this appears to be shared across all user sessions.

How can I save this user state in bokeh?

def modify_doc(doc):

    df_all = pd.read_csv('data.csv')
    df_all['Date'] = pd.to_datetime(df_all['Date'])

    start_data = df_all[0:10].to_dict(orient='list')
    source = ColumnDataSource(data=start_data)
    ...

    def callback():

        # FIXME: how can we save the current_record in the user's session?

        global current_record
        try:
            current_record
        except NameError:
            current_record = 10

        df = df_all[current_record:current_record+1]

        if df.shape[0] > 0:
            # we have another record so display it
            new_data = df.to_dict(orient='list')
            source.stream( new_data )
            current_record = current_record + 1

    doc.add_root(plot)
    doc.add_periodic_callback(callback, 250)
```

<p>I've seen the documentation for ClientSession, but this appears to work at the whole document level?</p>

<hr>

<p>I've included a Minimal, Complete and Verifiable example below:</p>

<p><strong>file: bokeh_server.py</strong></p>

<p>Run locally with: <code>python3 bokeh_server.py</code></p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd
from tornado.ioloop import IOLoop
import yaml
from jinja2 import Template

from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
from bokeh.server.server import Server
from bokeh.themes import Theme
from bokeh.client import push_session

import os

# if running locally, listen on port 5000
PORT = int(os.getenv('PORT', '5000'))
HOST = "0.0.0.0"

try:
    # This is set in the cloud foundry manifest. If we are running on
    # cloud foundry, this will be set for us.
    ALLOW_WEBSOCKET_ORIGIN = os.getenv("ALLOW_WEBSOCKET_ORIGIN").split(',')
except:
    # We are not running on cloud foundry so we must be running locally
    ALLOW_WEBSOCKET_ORIGIN = [ 'localhost:{0}'.format(PORT) ]

io_loop = IOLoop.current()

# This example simulates reading from a stream such as kafka

def modify_doc(doc):

    df_all = pd.read_csv('data.csv')
    df_all['Date'] = pd.to_datetime(df_all['Date'])

    start_data = df_all[0:10].to_dict(orient='list')

    source = ColumnDataSource(data=start_data)

    plot = figure(x_axis_type='datetime',
                  y_range=(0, 10000000),
                  y_axis_label='Y Label',
                  title="Title")

    plot.line('Date', 'ALL_EXCL_FUEL',   color='blue',      alpha=1, source=source)
    plot.line('Date', 'MOSTLY_FOOD',     color='lightblue', alpha=1, source=source)
    plot.line('Date', 'NON_SPECIALISED', color='grey',      alpha=1, source=source)

    def callback():
        # FIXME: how can we save this in the user's session?
        global counter
        try:
           counter
        except NameError:
            counter = 10

        df = df_all[counter:counter+1]

        if df.shape[0] > 0:
            # hardcode update values for now
            new_data = df.to_dict(orient='list')
            source.stream( new_data )
            counter = counter + 1

    doc.add_root(plot)
    doc.add_periodic_callback(callback, 250)

bokeh_app = Application(FunctionHandler(modify_doc))

server = Server(
        {'/': bokeh_app},
        io_loop=io_loop,
        allow_websocket_origin=ALLOW_WEBSOCKET_ORIGIN,
        **{'port': PORT, 'address': HOST}
        )
server.start()

if __name__ == '__main__':
    io_loop.add_callback(server.show, "/")
    io_loop.start()
</code>```

file: data.csv

```<code>Date,ALL_EXCL_FUEL,MOSTLY_FOOD,NON_SPECIALISED,TEXTILE,HOUSEHOLD,OTHER,NON_STORE
1986 Jan,1883154,747432,163708,267774,261453,281699,161088
1986 Feb,1819796,773161,152656,223836,246502,275121,148519
1986 Mar,1912582,797104,169440,251438,249614,292348,152638
1986 Apr,1974419,809334,170540,275975,260086,299271,159213
1986 May,1948915,800193,170173,274979,251175,297655,154740
1986 Jun,2019114,821785,178366,295463,251507,311447,160546
1986 Jul,2051539,816033,184812,297969,269786,323187,159752
1986 Aug,2011746,804386,180911,297138,263427,310220,155665
1986 Sep,2046678,792943,181055,305350,280640,318368,168322
1986 Oct,2110669,810147,187728,308919,298637,325617,179621
1986 Nov,2315710,847794,231599,352009,332079,358077,194152
1986 Dec,2830206,970987,319570,490001,373714,469399,206536
1987 Jan,2032021,798562,172215,288186,288534,307900,176624
1987 Feb,1980748,805713,165682,247219,282836,313577,165721
1987 Mar,2009717,816051,174034,256756,280207,315562,167106
1987 Apr,2156967,862749,189729,308543,284440,336755,174751
1987 May,2075808,834375,175464,287515,280404,330093,167957
1987 Jun,2137092,844051,183014,304706,286522,345149,173651
1987 Jul,2208377,847098,198848,330804,301537,356037,174054
</code>```

答:
I performed some testing and found that every time a new browser session was opened with the bokeh chart url, a new bokeh Document instance was created.  The answer for me was to save the state in the document instance:

def modify_doc(doc):

    # The first 100 records of data.csv will be loaded immediately
    # The remaining records will be read one-by-one in the update
    # callback which is used to simulate new, realtime data arriving

    doc.realtime_rec_ptr = 100

    df_all = pd.read_csv('data.csv')
    df_all['Date'] = pd.to_datetime(df_all['Date'])

    start_data_df = df_all[0:doc.realtime_rec_ptr]
    start_data_df.loc[ :, 'color' ] = 'green'

    src = ColumnDataSource(data=start_data_df.to_dict(orient='list'))

    p = figure(x_axis_type='datetime', title="Title"
                  y_range=(0, 10000000), y_axis_label='Y Label')

    p.line('Date','ALL_EXCL_FUEL',color='blue',alpha=1,source=src)

    # realtime markers will be colored green, others will be blue
    p.circle('Date','ALL_EXCL_FUEL',color='color',fill_alpha=0.2,size=4,source=src)

    def callback():
        df = df_all[doc.realtime_rec_ptr:realtime_rec_ptr+1]

        if df.shape[0] > 0:
            df.loc[ :, 'color' ] = 'blue'
            new_data = df.to_dict(orient='list')
            #print(new_data)
            source.stream( new_data )
            doc.realtime_rec_ptr = doc.realtime_rec_ptr + 1

    doc.add_root(p)
    doc.add_periodic_callback(callback, 250)
```

Body:
I'm trying to simulate reading data from a queue such as kafka.  I need to maintain a pointer to the current record when I am streaming data from a file.  Currently I'm doing this with a global variable, but this appears to be shared across all user sessions.

How can I save this user state in bokeh?

def modify_doc(doc):

    df_all = pd.read_csv('data.csv')
    df_all['Date'] = pd.to_datetime(df_all['Date'])

    start_data = df_all[0:10].to_dict(orient='list')
    source = ColumnDataSource(data=start_data)
    ...

    def callback():

        # FIXME: how can we save the current_record in the user's session?

        global current_record
        try:
            current_record
        except NameError:
            current_record = 10

        df = df_all[current_record:current_record+1]

        if df.shape[0] > 0:
            # we have another record so display it
            new_data = df.to_dict(orient='list')
            source.stream( new_data )
            current_record = current_record + 1

    doc.add_root(plot)
    doc.add_periodic_callback(callback, 250)

I've seen the documentation for ClientSession, but this appears to work at the whole document level?

I've included a Minimal, Complete and Verifiable example below:

file: bokeh_server.py

Run locally with: python3 bokeh_server.py

import pandas as pd
from tornado.ioloop import IOLoop
import yaml
from jinja2 import Template

from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, Slider, Div
from bokeh.plotting import figure
from bokeh.server.server import Server
from bokeh.themes import Theme
from bokeh.client import push_session

import os

# if running locally, listen on port 5000
PORT = int(os.getenv('PORT', '5000'))
HOST = "0.0.0.0"

try:
    # This is set in the cloud foundry manifest. If we are running on
    # cloud foundry, this will be set for us.
    ALLOW_WEBSOCKET_ORIGIN = os.getenv("ALLOW_WEBSOCKET_ORIGIN").split(',')
except:
    # We are not running on cloud foundry so we must be running locally
    ALLOW_WEBSOCKET_ORIGIN = [ 'localhost:{0}'.format(PORT) ]

io_loop = IOLoop.current()

# This example simulates reading from a stream such as kafka

def modify_doc(doc):

    df_all = pd.read_csv('data.csv')
    df_all['Date'] = pd.to_datetime(df_all['Date'])

    start_data = df_all[0:10].to_dict(orient='list')

    source = ColumnDataSource(data=start_data)

    plot = figure(x_axis_type='datetime',
                  y_range=(0, 10000000),
                  y_axis_label='Y Label',
                  title="Title")

    plot.line('Date', 'ALL_EXCL_FUEL',   color='blue',      alpha=1, source=source)
    plot.line('Date', 'MOSTLY_FOOD',     color='lightblue', alpha=1, source=source)
    plot.line('Date', 'NON_SPECIALISED', color='grey',      alpha=1, source=source)

    def callback():
        # FIXME: how can we save this in the user's session?
        global counter
        try:
           counter
        except NameError:
            counter = 10

        df = df_all[counter:counter+1]

        if df.shape[0] > 0:
            # hardcode update values for now
            new_data = df.to_dict(orient='list')
            source.stream( new_data )
            counter = counter + 1

    doc.add_root(plot)
    doc.add_periodic_callback(callback, 250)

bokeh_app = Application(FunctionHandler(modify_doc))

server = Server(
        {'/': bokeh_app},
        io_loop=io_loop,
        allow_websocket_origin=ALLOW_WEBSOCKET_ORIGIN,
        **{'port': PORT, 'address': HOST}
        )
server.start()

if __name__ == '__main__':
    io_loop.add_callback(server.show, "/")
    io_loop.start()

file: data.csv

Date,ALL_EXCL_FUEL,MOSTLY_FOOD,NON_SPECIALISED,TEXTILE,HOUSEHOLD,OTHER,NON_STORE
1986 Jan,1883154,747432,163708,267774,261453,281699,161088
1986 Feb,1819796,773161,152656,223836,246502,275121,148519
1986 Mar,1912582,797104,169440,251438,249614,292348,152638
1986 Apr,1974419,809334,170540,275975,260086,299271,159213
1986 May,1948915,800193,170173,274979,251175,297655,154740
1986 Jun,2019114,821785,178366,295463,251507,311447,160546
1986 Jul,2051539,816033,184812,297969,269786,323187,159752
1986 Aug,2011746,804386,180911,297138,263427,310220,155665
1986 Sep,2046678,792943,181055,305350,280640,318368,168322
1986 Oct,2110669,810147,187728,308919,298637,325617,179621
1986 Nov,2315710,847794,231599,352009,332079,358077,194152
1986 Dec,2830206,970987,319570,490001,373714,469399,206536
1987 Jan,2032021,798562,172215,288186,288534,307900,176624
1987 Feb,1980748,805713,165682,247219,282836,313577,165721
1987 Mar,2009717,816051,174034,256756,280207,315562,167106
1987 Apr,2156967,862749,189729,308543,284440,336755,174751
1987 May,2075808,834375,175464,287515,280404,330093,167957
1987 Jun,2137092,844051,183014,304706,286522,345149,173651
1987 Jul,2208377,847098,198848,330804,301537,356037,174054


问:
Phalcon-compose & Docker Toolbox web-server sees no files
My OS is Windows 7 and I'm using Docker Toolbox. I was following this tutorial, but then I got stuck when trying to open the web-page because my browser said it couldn't establish a connection.

variables.env (the rest is default):

```<code># Application
WEB_DOCUMENT_ROOT=/project/public
WEB_ALIAS_DOMAIN=localhost
APPLICATION_CACHE=/project/cache
APPLICATION_LOGS=/project/logs
# production | development | staging | testing
APPLICATION_ENV=development
</code>```

hosts:

```<code># Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
127.0.0.1       localhost
</code>```

Then I found that there's a program called Kitematic that had been installed with Docker Tools so I opened it and saw all of my containers. I went to "wildlife_app_1" which is my web-server and saw a console with a warning in it:

```<code>[WARNING] WEB_DOCUMENT_ROOT does not exists with path "/project/public"!
</code>```

There was a button called "exec" which allows to open a container's terminal so I opened it and I found that there actually wasn't such a directory as "public" in "/project".

Does anyone know how to fix that? Thanks in advance!

答:
The following is rather a workaround than a solution, but anyway. I've changed the "." dots in the config file with the absolute path to the project directory from.

Before:

```<code>  - ./application:/project
  - ./cache:/project/cache
  - ./logs:/project/logs
</code>```

After:

```<code>  - C:/Users/Dmitriy/Desktop/projects/Wildlife/application:/project
  - C:/Users/Dmitriy/Desktop/projects/Wildlife/cache:/project/cache
  - C:/Users/Dmitriy/Desktop/projects/Wildlife/logs:/project/logs
</code>```

And it works now.

Body:
My OS is Windows 7 and I'm using Docker Toolbox. I was following this tutorial, but then I got stuck when trying to open the web-page because my browser said it couldn't establish a connection.

variables.env (the rest is default):

# Application
WEB_DOCUMENT_ROOT=/project/public
WEB_ALIAS_DOMAIN=localhost
APPLICATION_CACHE=/project/cache
APPLICATION_LOGS=/project/logs
# production | development | staging | testing
APPLICATION_ENV=development

hosts:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
127.0.0.1       localhost

Then I found that there's a program called Kitematic that had been installed with Docker Tools so I opened it and saw all of my containers. I went to "wildlife_app_1" which is my web-server and saw a console with a warning in it:

[WARNING] WEB_DOCUMENT_ROOT does not exists with path "/project/public"!

There was a button called "exec" which allows to open a container's terminal so I opened it and I found that there actually wasn't such a directory as "public" in "/project".

Does anyone know how to fix that? Thanks in advance!

Body:
The following is rather a workaround than a solution, but anyway. I've changed the "." dots in the config file with the absolute path to the project directory from.

Before:

  - ./application:/project
  - ./cache:/project/cache
  - ./logs:/project/logs

After:

  - C:/Users/Dmitriy/Desktop/projects/Wildlife/application:/project
  - C:/Users/Dmitriy/Desktop/projects/Wildlife/cache:/project/cache
  - C:/Users/Dmitriy/Desktop/projects/Wildlife/logs:/project/logs

And it works now.


问:
Translated category is not found
I have a SAP Business One server on one end and a Wordpress with Woocommerce and WPML on the other end.

I clone product categories and products from SAP to Wordpress. The connections between the products, product categories and the languages (English and Hebrew) are made in one script with PHP and MySQL.

After the cloning is done, all the categories, products and their translations look fine in the Wordpress Dashboard. I can switch to the translated product and the translated category without any problems.

When i browse the website, i can view a product and switch between languages for the product, BUT this doesn't work for the categories!

When i try to visit a translated category (from EN to HE) i get 404.
The category title in the URL is the translated one and so it seems like the connection between categories exists, but i cant see the translated category...

I tried:

Rebuilding the links

Disabling plugins

In Woocommerce,the taxonomy hierarchy synchronization is synchronized

答:
This is really silly but i forgot to urlencode the category slug...
Did this for the products but forgot the categories! Ran a quick fix, everything works fine now.</p>

Title: Translated category is not found


问:
c# entity framework with virtual property query
I have this class:

```<code>    public class Message
    {
        public Message()
        {
            Contacts = new List<Contact>();
        }

        public Message(string Sub_Message, string Body_Message, string Date_Send_Message)
        {
            Contacts = new List<Contact>();

            Subject = Sub_Message;
            Body = Body_Message;
            Date = Date_Send_Message;
        }

        public int MessageId { get; set; }
        public string Subject { get; set; }

        public string Date { get; set; }

        public string Body { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }
</code>```

I want to get the table of the Contact, because of that Messages is virtual and all the lazy loading stuff,

This call didn't work to me and got this error:

The ObjectContext instance has been disposed and can no longer be used
  for operations that require a connection. in Reference Table

syntax:

```<code>    public ObservableCollection<Model.Message> LoadMessages()
    {
      using (db) {
       var x = from qr in db.Messages
                            order by qr.Subject
                            select qr;
          }
     }
</code>```

While this works:

```<code>public ObservableCollection<Model.Message> LoadMessages()
{
    using (db)
    {
        var Messages = db.Messages.Include(z => z.Contacts).ToList();

        return new ObservableCollection<Model.Message>(Messages);
    }
}
</code>```

So I am using the queries inside a service called MessageService, Everytime I want to use the dbContext I create a function for it and put it inside using(db)

Like this:

```<code>     public class MessageService
        {
            ReadingFromData db = new ReadingFromData();
            public ObservableCollection<Model.Message> LoadMessages()
            {
                using (db)
                {
                    //Do something with db
                }
            }
}
</code>```

Also, can someone explain to me how this works, and how to work with entity framework queries correct

Thanks

答:
First of all, you should understand that this code does not query database:

```<code>var x = from qr in db.Messages
        orderby qr.Subject
        select qr;
</code>```

it's just a query definition (expression) which should be translated into SQL and sent to the database server when you'll execute it. Executing is enumerating query results, or using one of LINQ operators with immediate execution type (see Classification of Standard Query Operators by Manner of Execution). I.e. when later in the code you'll enumerate x or if you'll try to store query results in a list, it is possible that database context db will be already disposed. And of course, you will get an error

```<code>var x = db.Messages; // query is not executed
db.Dispose(); // context disposed
foreach(var m in x) // exception here, you try to execute query which uses disposed context
   ...
</code>```

Now about lazy-loading. It works by storing database context in the proxy entities which inherit from your entities. So actually db.Messages will return entities of some type MessageWithDbContext with db value stored internally. It is required for making additional 'lazy' database queries later. And again, if at that point of time database context is disposed, then you'll get an exception:

```<code> var x = db.Messages.ToList(); // query is executed, messages are loaded
 db.Dispose();  // context disposed
 foreach(var m in x)
    m.Contacts.Count(); // exception - you try to execute contacts query with disposed db
</code>```

How to solve this issue? Either make sure that database context is not disposed while you are working with the query and making additional 'lazy' calls. Or use eager loading as you are doing in the second example. Eager loading allows you to load related entities when you are executing the query:

```<code> // both messages and contacts are loaded from database when you execute the query
 var x = db.Message.Include(m => m.Contacts).ToList();
 db.Dispose();
 foreach(var m in x)
    m.Contacts.Count();
</code>```

In this case no additional 'lazy' calls are required, so you can dispose database context and work with query results.

Body:
I have this class:

    public class Message
    {
        public Message()
        {
            Contacts = new List<Contact>();
        }

        public Message(string Sub_Message, string Body_Message, string Date_Send_Message)
        {
            Contacts = new List<Contact>();

            Subject = Sub_Message;
            Body = Body_Message;
            Date = Date_Send_Message;
        }

        public int MessageId { get; set; }
        public string Subject { get; set; }

        public string Date { get; set; }

        public string Body { get; set; }

        public virtual IList<Contact> Contacts { get; set; }
    }

I want to get the table of the Contact, because of that Messages is virtual and all the lazy loading stuff,

This call didn't work to me and got this error:

The ObjectContext instance has been disposed and can no longer be used
  for operations that require a connection. in Reference Table

syntax:

    public ObservableCollection<Model.Message> LoadMessages()
    {
      using (db) {
       var x = from qr in db.Messages
                            order by qr.Subject
                            select qr;
          }
     }

While this works:

public ObservableCollection<Model.Message> LoadMessages()
{
    using (db)
    {
        var Messages = db.Messages.Include(z => z.Contacts).ToList();

        return new ObservableCollection<Model.Message>(Messages);
    }
}

So I am using the queries inside a service called MessageService, Everytime I want to use the dbContext I create a function for it and put it inside using(db)

Like this:

     public class MessageService
        {
            ReadingFromData db = new ReadingFromData();
            public ObservableCollection<Model.Message> LoadMessages()
            {
                using (db)
                {
                    //Do something with db
                }
            }
}

Also, can someone explain to me how this works, and how to work with entity framework queries correct

Thanks

Body:
First of all, you should understand that this code does not query database:

var x = from qr in db.Messages
        orderby qr.Subject
        select qr;

it's just a query definition (expression) which should be translated into SQL and sent to the database server when you'll execute it. Executing is enumerating query results, or using one of LINQ operators with immediate execution type (see Classification of Standard Query Operators by Manner of Execution). I.e. when later in the code you'll enumerate x or if you'll try to store query results in a list, it is possible that database context db will be already disposed. And of course, you will get an error

var x = db.Messages; // query is not executed
db.Dispose(); // context disposed
foreach(var m in x) // exception here, you try to execute query which uses disposed context
   ...

Now about lazy-loading. It works by storing database context in the proxy entities which inherit from your entities. So actually db.Messages will return entities of some type MessageWithDbContext with db value stored internally. It is required for making additional 'lazy' database queries later. And again, if at that point of time database context is disposed, then you'll get an exception:

 var x = db.Messages.ToList(); // query is executed, messages are loaded
 db.Dispose();  // context disposed
 foreach(var m in x)
    m.Contacts.Count(); // exception - you try to execute contacts query with disposed db

How to solve this issue? Either make sure that database context is not disposed while you are working with the query and making additional 'lazy' calls. Or use eager loading as you are doing in the second example. Eager loading allows you to load related entities when you are executing the query:

 // both messages and contacts are loaded from database when you execute the query
 var x = db.Message.Include(m => m.Contacts).ToList();
 db.Dispose();
 foreach(var m in x)
    m.Contacts.Count();

In this case no additional 'lazy' calls are required, so you can dispose database context and work with query results.


问:
Is there a GUI for creating GUIs in Scala?
Is there something like WindowBuilder for Scala?</p>

答:
I don't know of any WYSIWYG GUI builder for Scala. But you don't need one. In fact, strictly speaking, Scala doesn't have a GUI; it just uses the underlying platform's GUI (or GUIs).

So, the JVM port of Scala uses AWT, Swing or SWT and the CLI port of Scala uses WinForms or WPF. I've heard rumors of ports of Scala to the ECMAScript runtime and the Objective-C runtime, and those would presumable use HTML5 and Quartz/Cocoa, respectively.

This means that you can just use the existing tools, like Expression Blend for WPF or Matisse for Swing.

Note, however, that at least for Swing, there is the brilliant scala.swing library, which contains an embedded DSL for building GUIs programmatically. This is not WYSIWYG, so it's not exactly what you are asking for, but I much prefer it, because it is WYMIWYG (What You Mean Is What You Get), which with all the GUI tools I have used so far, seems to be almost impossible to achieve.


问:
Generics with optional multiple bounds, e.g. List<? extends Integer OR String>
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

```<code>map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error
</code>```

It is not possible to declare a Map as below (to enforce compile time check).

```<code>void setProperties(Map<String, ? extends Integer || String> properties)
</code>```

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

```<code>void setProperties(Map<String, ?> properties)
</code>```

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

答:
I'm fairly certain if any language was going to disallow multiple accepted types for a value, it would be Java. If you really need this kind of capability, I'd suggest looking into other languages. Python can definitely do it.

What's the use case for having both Integers and Strings as the values to your map? If we are really dealing with just Integers and Strings, you're going to have to either:

Define a wrapper object that can hold either a String or an Integer. I would advise against this though, because it will look a lot like the other solution below.

Pick either String or Integer to be the value (String seems like the easier choice), and then just do extra work outside of the map to work with both data types.

```<code>Map<String, String> map;
Integer myValue = 5;
if (myValue instanceof Integer) {
    String temp = myValue.toString();
    map.put(key, temp);
}

// taking things out of the map requires more delicate care.
try { // parseInt() can throw a NumberFormatException
    Integer result = Integer.parseInt(map.get(key));
}
catch (NumberFormatException e) {} // do something here
</code>```

This is a very ugly solution, but it's probably one of the only reasonable solutions that can be provided using Java to maintain some sense of strong typing to your values.

Body:
I have a method that should only accept a Map whose key is of type String and value of type Integer or String, but not, say, Boolean.

For example,

map.put("prop1", 1); // allowed
map.put("prop2", "value"); // allowed
map.put("prop3", true); // compile time error

It is not possible to declare a Map as below (to enforce compile time check).

void setProperties(Map<String, ? extends Integer || String> properties)

What is the best alternative other than declaring the value type as an unbounded wildcard and validating for Integer or String at runtime?

void setProperties(Map<String, ?> properties)

This method accepts a set of properties to configure an underlying service entity. The entity supports property values of type String and Integer alone. For example, a property maxLength=2 is valid, defaultTimezone=UTC is also valid, but allowDuplicate=false is invalid.

Body:
I'm fairly certain if any language was going to disallow multiple accepted types for a value, it would be Java. If you really need this kind of capability, I'd suggest looking into other languages. Python can definitely do it.

What's the use case for having both Integers and Strings as the values to your map? If we are really dealing with just Integers and Strings, you're going to have to either:

Define a wrapper object that can hold either a String or an Integer. I would advise against this though, because it will look a lot like the other solution below.

Pick either String or Integer to be the value (String seems like the easier choice), and then just do extra work outside of the map to work with both data types.

Map<String, String> map;
Integer myValue = 5;
if (myValue instanceof Integer) {
    String temp = myValue.toString();
    map.put(key, temp);
}

// taking things out of the map requires more delicate care.
try { // parseInt() can throw a NumberFormatException
    Integer result = Integer.parseInt(map.get(key));
}
catch (NumberFormatException e) {} // do something here

This is a very ugly solution, but it's probably one of the only reasonable solutions that can be provided using Java to maintain some sense of strong typing to your values.


问:
Is this the correct way to handle a response in Xamarin Forms?
```<code>var response = await App.PhrasespageCS.DisplayAlert("Reset score",
     "You have more than 50 points. Are you sure you want to reset it to 0?",
     "Yes", "No");

if (response == true)
{
    App.DB.ResetPointsForSelectedPhrase(App.cfs);
}
</code>```

I am not clear on the use of await here and would appreciate advice.  Also could this be combined into one statement?

答:
Await means the app has created a dialog for you and is gonna wait till the answer comes in return.
And that's the correct way to write it. Also if you wanna reduce the code you can put it as below,</p>

```<code>if (await App.PhrasespageCS.DisplayAlert("Reset score", "You have more than 50 points.Are you sure you want to reset it to 0 ? ", "Yes", "No"))
            App.DB.ResetPointsForSelectedPhrase(App.cfs);
</code>```

Body:
var response = await App.PhrasespageCS.DisplayAlert("Reset score",
     "You have more than 50 points. Are you sure you want to reset it to 0?",
     "Yes", "No");

if (response == true)
{
    App.DB.ResetPointsForSelectedPhrase(App.cfs);
}

I am not clear on the use of await here and would appreciate advice.  Also could this be combined into one statement?

Body:
Await means the app has created a dialog for you and is gonna wait till the answer comes in return.
And that's the correct way to write it. Also if you wanna reduce the code you can put it as below,

if (await App.PhrasespageCS.DisplayAlert("Reset score", "You have more than 50 points.Are you sure you want to reset it to 0 ? ", "Yes", "No"))
            App.DB.ResetPointsForSelectedPhrase(App.cfs);


问:
Filter Comments in the language of the node
I put the comments on nodes but I'm puzzled about the fact that the comments are not filtered by language. And I don't find a solution about that.

When I'm on a french page, I got the comments in french but also in chinese.

Also when you post a new comment on a chinese page, stating that the comment is in chinese, there's a redirection to the default language of the node (here in french). I fixed this problem with a hook...

But I still have a mixed language of contents whatever the language node is. I tried different hook (hook_comment_view_alter or hook_comment_load) and I see the comments before rendering but I'm not able to remove the comment in different language of the page I'm on. So is there a way to filter the comments on the basic Drupal8 comment system ?

答:
I found the solution using hook_query_TAG_alter (so hook_query_comment_filter_alter for the comments).

see here :
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21database.api.php/function/hook_query_TAG_alter/8.3.x


问:
Close other accordions on click (without toggling class)
I'm currently using some code that closely resembles the example this w3schools link, but I can't seem to figure out what to add to the javascript in order to close other tabs when clicking on one of the tabs.

I have gone through a few SO answers regarding closing other accordions on click (such as here) - but they mostly deal with removing classes (".active") from siblings, which (may?) or may not work in this case.

I'm not very familiar with the code but I'm under the impression that it's the JS that's animating the panel sliding down, and not a CSS animation.

Currently my code looks like this : https://jsfiddle.net/joshuacsk/yw7eygxk/
and the JS in question like so:

JS

```<code>var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
</code>```

Is there any way to close other tabs using the style of code above, or is there any other better way to do this?

答:
You can add:

```<code>for(j = 0; j < acc.length; j++) {
    acc[j].nextElementSibling.style.maxHeight = null;
}
</code>```

to close all tabs. See the snippet at the bottom of my answer.

PS: The animation of the panels slding up/down is CSS, the JavaScript only triggers it by modifying the height.

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    for(j = 0; j < acc.length; j++) {
      acc[j].nextElementSibling.style.maxHeight = null;
    }
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordiontext{
  font-family:futura-pt;
  font-weight:300;
  font-size:11;
}
button{
    font-family:futura-pt;
    font-weight: bold;
    font-size: 20px;
    letter-spacing: 0.2em;
    box-sizing:border-box;
    box-shadow: inset 0 0 0 3px #202020;
    position:relative;
    vertical-align:middle;
    border: 0;
}
button.accordion {
    background-color: #fff;
    color: #202020;
    cursor: pointer;
    padding-top: 8px;
    padding-bottom: 8px;
    width: 100%;
    text-align: left;
    background: linear-gradient(to right, #202020 50%, #ffffff 50%);
    background-size: 205% 100%;
    background-position:right bottom;
    transition:all 1s ease;
}

button.accordion.active, button.accordion:hover {
    background-position:left bottom;
    color: #ffffff;

}

/* Style the accordion panel. Note: hidden by default */
div.panel {
    padding: 8px 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.6s ease;
}

button.accordion:after {
    content: '\e009'; /* Unicode character before click  */
    color: #202020;
    font-family: 'squarespace-ui-font';
    font-style: normal;
    font-weight: normal;
    float: right;
    margin-right: 12px;
    transition: all 0.3s ease-in

}

button.accordion.active:after {
    content: "\e006"; /* Unicode character after click */
    color: #ffffff;
}</code>```

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

<button class="accordion">Titleasdasdasd</button>

Lorem ipsum

```

Body:
I'm currently using some code that closely resembles the example this w3schools link, but I can't seem to figure out what to add to the javascript in order to close other tabs when clicking on one of the tabs.

I have gone through a few SO answers regarding closing other accordions on click (such as here) - but they mostly deal with removing classes (".active") from siblings, which (may?) or may not work in this case.

I'm not very familiar with the code but I'm under the impression that it's the JS that's animating the panel sliding down, and not a CSS animation.

Currently my code looks like this : https://jsfiddle.net/joshuacsk/yw7eygxk/
and the JS in question like so:

JS

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

Is there any way to close other tabs using the style of code above, or is there any other better way to do this?

Body:
You can add:

for(j = 0; j < acc.length; j++) {
    acc[j].nextElementSibling.style.maxHeight = null;
}

to close all tabs. See the snippet at the bottom of my answer.

PS: The animation of the panels slding up/down is CSS, the JavaScript only triggers it by modifying the height.

var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    for(j = 0; j < acc.length; j++) {
      acc[j].nextElementSibling.style.maxHeight = null;
    }
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}

.accordiontext{
  font-family:futura-pt;
  font-weight:300;
  font-size:11;
}
button{
    font-family:futura-pt;
    font-weight: bold;
    font-size: 20px;
    letter-spacing: 0.2em;
    box-sizing:border-box;
    box-shadow: inset 0 0 0 3px #202020;
    position:relative;
    vertical-align:middle;
    border: 0;
}
button.accordion {
    background-color: #fff;
    color: #202020;
    cursor: pointer;
    padding-top: 8px;
    padding-bottom: 8px;
    width: 100%;
    text-align: left;
    background: linear-gradient(to right, #202020 50%, #ffffff 50%);
    background-size: 205% 100%;
    background-position:right bottom;
    transition:all 1s ease;
}

button.accordion.active, button.accordion:hover {
    background-position:left bottom;
    color: #ffffff;

}

/* Style the accordion panel. Note: hidden by default */
div.panel {
    padding: 8px 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.6s ease;
}

button.accordion:after {
    content: '\e009'; /* Unicode character before click  */
    color: #202020;
    font-family: 'squarespace-ui-font';
    font-style: normal;
    font-weight: normal;
    float: right;
    margin-right: 12px;
    transition: all 0.3s ease-in

}

button.accordion.active:after {
    content: "\e006"; /* Unicode character after click */
    color: #ffffff;
}

<div class="accordionholder">
<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>

<button class="accordion">Titleasdasdasd</button> <!--title-->
<div class="panel">
  <p  class="accordiontext">Lorem ipsum</p> <!--content-->
</div>
</div>


答:
Another solution would be a custom Map implementation and overrides of the put and putAll methods to validate the data:

```<code>public class ValidatedMap extends HashMap<String, Object> {
    @Override
    public Object put(final String key, final Object value) {
        validate(value);
        return super.put(key, value);
    }

    @Override
    public void putAll(final Map<? extends String, ?> m) {
        m.values().forEach(v -> validate(v));
        super.putAll(m);
    }

    private void validate(final Object value) {
        if (value instanceof String || value instanceof Integer) {
            // OK
        } else {
            // TODO: use some custom exception
            throw new RuntimeException("Illegal value type");
        }
    }
}
</code>```

NB: use the Map implementation that fits your needs as base class

Title: Generics with optional multiple bounds, e.g. List<? extends Integer OR String>

Body:
Another solution would be a custom Map implementation and overrides of the put and putAll methods to validate the data:

public class ValidatedMap extends HashMap<String, Object> {
    @Override
    public Object put(final String key, final Object value) {
        validate(value);
        return super.put(key, value);
    }

    @Override
    public void putAll(final Map<? extends String, ?> m) {
        m.values().forEach(v -> validate(v));
        super.putAll(m);
    }

    private void validate(final Object value) {
        if (value instanceof String || value instanceof Integer) {
            // OK
        } else {
            // TODO: use some custom exception
            throw new RuntimeException("Illegal value type");
        }
    }
}

NB: use the Map implementation that fits your needs as base class


问:
emacs public/protected/private label indentation of C++ header file not working for zero offset
I cannot get zero offset for some things for my C++ header files in emacs even if I have it defined in my .emacs file.

The header file below shows a class definition inside two namespaces and most importantly the public keyword I would like to have with zero offset like below.

```<code>namespace n1
{
namespace n2 // no offset
{

class SomeClass // no offset from namespace open curly
{
public: // this line with zero offset
    SomeClass(); // offset 4
    ...
};

inline SomeClass::SomeClass() // no offset
{
}

} // n2
} // n2
</code>```

In my .emacs file I have added label like this:

```<code>(c-set-offset 'label 0)
</code>```

I used Ctrl-C Ctrl-S to find out what to modify. Other offsets I have defined in the .emacs file are working fine and also values other than 0 work for label.

When I set offset 0 for label it turns out to be 1 when hitting tab for that line. This is strange and looks like something else is overriding or adding a minimum of 1.

Can anyone explain how I can achieve what I want and maybe also an explanation what is happening currently?

Phew, this was my first question here. Thanks :)

UPDATE:

Thanks to the answers I have been able to get a bit farther, but still no solution overall, because changing the things necessary to get total offset 0 for the accessors result in other things I don't want. Thsi is where I'm currently:

```<code>(c-set-offset 'access-label 0)
</code>```

I also needed to get the .h file to be understoor as C++, so I added:

```<code>(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
</code>```

This alone is not removing the 1 offset I was seeing, but it seems there is also inclass for the accessor. Setting this to 0 actually results in total 0 offset.

```<code>(c-set-offset 'inclass 0)
</code>```

Problem is that now other things such as members are with total of 0 like below:

```<code>class Foo
{
public:
Foo();
~Foo();
</code>```

To remedy this I changed topmost-intro to offset 4

```<code>(c-set-offset 'topmost-intro 4)
</code>```

Which in turn resulted in other changes for e.g. inline function declarations in the same file. All in all, I'm not sure how to tweak this the way I want it.

UPDATE2:

Added inline declaration of SomeClass ctor with no offset.

答: I believe you want access-label instead of label. See here.</p>

Body:
I cannot get zero offset for some things for my C++ header files in emacs even if I have it defined in my .emacs file.

The header file below shows a class definition inside two namespaces and most importantly the public keyword I would like to have with zero offset like below.

namespace n1
{
namespace n2 // no offset
{

class SomeClass // no offset from namespace open curly
{
public: // this line with zero offset
    SomeClass(); // offset 4
    ...
};

inline SomeClass::SomeClass() // no offset
{
}

} // n2
} // n2

In my .emacs file I have added label like this:

(c-set-offset 'label 0)

I used Ctrl-C Ctrl-S to find out what to modify. Other offsets I have defined in the .emacs file are working fine and also values other than 0 work for label.

When I set offset 0 for label it turns out to be 1 when hitting tab for that line. This is strange and looks like something else is overriding or adding a minimum of 1.

Can anyone explain how I can achieve what I want and maybe also an explanation what is happening currently?

Phew, this was my first question here. Thanks :)

UPDATE:

Thanks to the answers I have been able to get a bit farther, but still no solution overall, because changing the things necessary to get total offset 0 for the accessors result in other things I don't want. Thsi is where I'm currently:

(c-set-offset 'access-label 0)

I also needed to get the .h file to be understoor as C++, so I added:

(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))

This alone is not removing the 1 offset I was seeing, but it seems there is also inclass for the accessor. Setting this to 0 actually results in total 0 offset.

(c-set-offset 'inclass 0)

Problem is that now other things such as members are with total of 0 like below:

class Foo
{
public:
Foo();
~Foo();

To remedy this I changed topmost-intro to offset 4

(c-set-offset 'topmost-intro 4)

Which in turn resulted in other changes for e.g. inline function declarations in the same file. All in all, I'm not sure how to tweak this the way I want it.

UPDATE2:

Added inline declaration of SomeClass ctor with no offset.


问:
How to save Multiple files into single zip using asp.net web form
How to save Multiple files into single zip using asp.net web form, actually I am download files from Gridview button base on Registration Id into zip. And I am not able to add two or more files into zip. One file is downloading correctly, when I will add second file to zip not getting any logic.

Single file download correctly.

```<code>zip.AddFile(LatterAcceptance,"My folder");
</code>```

when I will add one more file into zip

```<code>zip.AddFile((LatterAcceptance,HighestDegree),"My folder");
</code>```

However, If I add another file into zip like HighestDegree getting the following error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is my c# code.

```<code>    ZipFile zip = new ZipFile();
    DataTable dt = new DataTable();
    LinkButton Type = sender as LinkButton;
    GridViewRow grow = (GridViewRow)Type.NamingContainer;
    string RegistrationId = gv_TotalAllReg.DataKeys[grow.RowIndex].Values[0].ToString();

    bo.Para1 = RegistrationId;//RegId;
    bo.Para2 = "3";//Paravalue
    dt = bl.Admin_Get_UserInformation(bo);

    foreach(DataRow row in dt.Rows)
   {
        string LA = row["LatterAcceptance"].ToString();
        string LatterAcceptance = Server.MapPath("~/LatterAcceptance/" + LA);

        string HD = row["HighestDegree"].ToString();
        string HighestDegree = Server.MapPath("~/HighestDegree/" + HD);

        zip.AddFile(LatterAcceptance,"My folder");
   }

    Response.Clear();
    Response.BufferOutput = false;
    string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HHmmss"));
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "attachment;fileName=" + zipName);
    zip.Save(Response.OutputStream);
    Response.End();
</code>```

答:
You are using the DotNetZip library. It may help to read the documentation.

You will find the following:

```<code>using (ZipFile zip = new ZipFile())
 {
     // add this map file into the "images" directory in the zip archive
     zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
     // add the report into a different directory in the archive
     zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
     zip.AddFile("ReadMe.txt");
     zip.Save("MyZipFile.zip");
 }
</code>```

You need to do zip.AddFile() for each individual file you wish to add to the ZIP.

Body:
How to save Multiple files into single zip using asp.net web form, actually I am download files from Gridview button base on Registration Id into zip. And I am not able to add two or more files into zip. One file is downloading correctly, when I will add second file to zip not getting any logic.

Single file download correctly.

zip.AddFile(LatterAcceptance,"My folder");

when I will add one more file into zip

zip.AddFile((LatterAcceptance,HighestDegree),"My folder");

However, If I add another file into zip like HighestDegree getting the following error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is my c# code.

    ZipFile zip = new ZipFile();
    DataTable dt = new DataTable();
    LinkButton Type = sender as LinkButton;
    GridViewRow grow = (GridViewRow)Type.NamingContainer;
    string RegistrationId = gv_TotalAllReg.DataKeys[grow.RowIndex].Values[0].ToString();

    bo.Para1 = RegistrationId;//RegId;
    bo.Para2 = "3";//Paravalue
    dt = bl.Admin_Get_UserInformation(bo);

    foreach(DataRow row in dt.Rows)
   {
        string LA = row["LatterAcceptance"].ToString();
        string LatterAcceptance = Server.MapPath("~/LatterAcceptance/" + LA);

        string HD = row["HighestDegree"].ToString();
        string HighestDegree = Server.MapPath("~/HighestDegree/" + HD);

        zip.AddFile(LatterAcceptance,"My folder");
   }

    Response.Clear();
    Response.BufferOutput = false;
    string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MM-dd-HHmmss"));
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "attachment;fileName=" + zipName);
    zip.Save(Response.OutputStream);
    Response.End();

Body:
You are using the DotNetZip library. It may help to read the documentation.

You will find the following:

using (ZipFile zip = new ZipFile())
 {
     // add this map file into the "images" directory in the zip archive
     zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
     // add the report into a different directory in the archive
     zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
     zip.AddFile("ReadMe.txt");
     zip.Save("MyZipFile.zip");
 }

You need to do zip.AddFile() for each individual file you wish to add to the ZIP.


问:
Searching Two Columns in a Data Frame in R
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

```<code>Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321
</code>```

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

答:
Data.table solution, 1 line.

```<code>library(data.table)

dt <- data.table(Index = 1:9,
                 Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                 Midquote = c('5.319','5.323','5.325','5.322','5.325',NA,NA,'5.321','5.321')
                )

> dt[ Times != Times[.N] & !is.na(Midquote), max(Index) ]
[1] 5
</code>```

EDIT

To remove the Index column you have (at least) two options

```<code>dt2 <- data.table(Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                  Midquote = c('5.319','5.323','5.325','5.322','5.325',NA,NA,'5.321','5.321'))

# Option 1 - create an id column on the fly (unfortunately data.table recalculate .I after evaluating the "where" clause... so you need to save it)
dt2[, cbind(.SD, id=.I)][ Times != Times[.N] & !is.na(Midquote), max(id) ]

# Option 2 - simply check the last position of where your condition is met
dt2[, max(which(Times != Times[.N] & !is.na(Midquote))) ]
</code>```

NB You can't do nrow because you can have, say, the 1st, 2nd, and 4th records matching your condition, and nrow would give you 3, which is wrong because the 3rd row does not match.

EDIT 2 (option 3 is not correct)

```<code>dt3 <- data.table(Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                  Midquote = c('5.319','5.323', NA,'5.322','5.325', NA, NA,'5.321','5.321'))

# Option 1 - create an id column on the fly (unfortunately data.table recalculate .I after evaluating the "where" clause... so you need to save it)
dt3[, cbind(.SD, id=.I)][ Times != Times[.N] & !is.na(Midquote), max(id) ]
[1] 5

# Option 2 - simply check the last position of where your condition is met
dt3[, max(which(Times != Times[.N] & !is.na(Midquote))) ]
[1] 5

# Option 3 - good luck with this
nrow(dt3[Times != Times[.N] & !is.na(Midquote)])
[1] 4
</code>```

Body:
I have a question about searching for values in R, it is actually a bit similar to a question which was posted yesterday (as given over here: Searching a vector/data table backwards in R) except I think my problem is a bit more complicated (and also the opposite of what I want to do), and since I'm very new to R I'm not too sure how to solve this problem.

I have a data frame similar to one given below, and I wish to find a previous index value to my current one where the Times column is different to my current time and the Midquote column does not have an NA value.

Index               Times    |    Midquote
                -----------------------------
   1            10:30:45.58  |    5.319
   2            10:30:45.93  |    5.323
   3            10:30:45.104 |    5.325
   4            10:30:45.127 |    5.322
   5            10:30:45.188 |    5.325
   6            10:30:45.188 |    NA
   7            10:30:45.212 |    NA
   8            10:30:45.231 |    5.321
   9            10:30:45.231 |    5.321

If we start at the bottom of the data frame  and take this to be the 'current' time, this is found to be at index 9 and which has a Times value of 10:30:45.231 and Midquote value of 5.321, then if I want to find the first index where the time is different to my current time, we see this is found to be index 7, which has a time of 10:30:45.212 (since index 8 has the same time). But we also see that at index 7 the Midquote value is NA so I now have to check the data frame again. Index 6 again has a different time (i.e. 10:30:45.188 ) but it also has an NA value again in the Midquote column, so moving up again to index 5 we see that the Times column has a different time to my current time (i.e. 10:30:45.188 again)  and that the Midquotes  value is 5.325.

Therefore, since at index 5 the time is 10:30:45.188 (which is different to my current time which was 10:30:45.231) and since the Midquote value at index 5 is not NA, I wish to obtain the output '5' since it is the index value which fulfills both criteria.

My question is, is there a good way of doing this? I am sorry if this is an easy question, I am very new to R and I don't know much about working with data frames...

EDIT: I would also like to do it preferably without adding another column to the data frame (as is given in the top answer of the link I mentioned above), if that is possible

Body:
Data.table solution, 1 line.

library(data.table)

dt <- data.table(Index = 1:9,
                 Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                 Midquote = c('5.319','5.323','5.325','5.322','5.325',NA,NA,'5.321','5.321')
                )

> dt[ Times != Times[.N] & !is.na(Midquote), max(Index) ]
[1] 5

EDIT

To remove the Index column you have (at least) two options

dt2 <- data.table(Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                  Midquote = c('5.319','5.323','5.325','5.322','5.325',NA,NA,'5.321','5.321'))

# Option 1 - create an id column on the fly (unfortunately data.table recalculate .I after evaluating the "where" clause... so you need to save it)
dt2[, cbind(.SD, id=.I)][ Times != Times[.N] & !is.na(Midquote), max(id) ]

# Option 2 - simply check the last position of where your condition is met
dt2[, max(which(Times != Times[.N] & !is.na(Midquote))) ]

NB You can't do nrow because you can have, say, the 1st, 2nd, and 4th records matching your condition, and nrow would give you 3, which is wrong because the 3rd row does not match.

EDIT 2 (option 3 is not correct)

dt3 <- data.table(Times = c( '10:30:45.58', '10:30:45.93','10:30:45.104','10:30:45.127','10:30:45.188','10:30:45.188','10:30:45.212','10:30:45.231','10:30:45.231' ),
                  Midquote = c('5.319','5.323', NA,'5.322','5.325', NA, NA,'5.321','5.321'))

# Option 1 - create an id column on the fly (unfortunately data.table recalculate .I after evaluating the "where" clause... so you need to save it)
dt3[, cbind(.SD, id=.I)][ Times != Times[.N] & !is.na(Midquote), max(id) ]
[1] 5

# Option 2 - simply check the last position of where your condition is met
dt3[, max(which(Times != Times[.N] & !is.na(Midquote))) ]
[1] 5

# Option 3 - good luck with this
nrow(dt3[Times != Times[.N] & !is.na(Midquote)])
[1] 4


问:
How do I create a stata local macro in python?
Let me edit my question to clarify.  Here is the python code:

```<code>decade_begin = 1970

while decade_begin <= 1994:
    for x in range(0, 10):
        a= decade_begin + x
    decade_begin = a+1
    decade_end=a

print "year_",decade_begin,"s" #start year
</code>```

The output of the last line is:

```<code>year_1980s
year_1990s
</code>```

I want to be able to create a variable such that:

```<code>year_1990s = [a]
</code>```

In stata this is quite easy, using a local macro `x'.  But in python I think mixing string and int in a variable name is not allowed.

```<code>forval i = 1979/1994 {
whatever if year == `i'
save year_`i'.dta, replace
}
</code>```

Any ideas on how to implement in python?

答:
If I understand correctly, you'd like to create a variable name using a string to name the variable. (The equivalent of local macros in Stata are called variables in Python). You can do this using the exec function:

```<code>>>> for i in range(1979, 1995):
...    exec("name_" + str(i) + " = " + str(i))

>>> print(name_1994)
1994
</code>```

This code assumes you're using Python 3. If you're using Python 2, remove the outer parentheses for the lines with exec and print.

Using exec is not the best way to approach this problem in Python, however (as explained here). You will likely run into problems later on if you try to code in Python the same way you're used to coding in Stata.

A better approach might be to create a dictionary and use a different key for each number. For example:

```<code>>>> names = {}
>>> for i in range(1979, 1995):
...    names[i] = i
>>> print(names)
{1979: 1979, 1980: 1980, 1981: 1981, 1982: 1982, 1983: 1983, 1984: 1984, 1985: 1985, 1986: 1986, 1987: 1987, 1988: 1988, 1989: 1989, 1990: 1990, 1991: 1991, 1992: 1992, 1993: 1993, 1994: 1994}
</code>```

Body:
Let me edit my question to clarify.  Here is the python code:

decade_begin = 1970

while decade_begin <= 1994:
    for x in range(0, 10):
        a= decade_begin + x
    decade_begin = a+1
    decade_end=a

print "year_",decade_begin,"s" #start year

The output of the last line is:

year_1980s
year_1990s

I want to be able to create a variable such that:

year_1990s = [a]

In stata this is quite easy, using a local macro `x'.  But in python I think mixing string and int in a variable name is not allowed.

forval i = 1979/1994 {
whatever if year == `i'
save year_`i'.dta, replace
}

Any ideas on how to implement in python?

Body:
If I understand correctly, you'd like to create a variable name using a string to name the variable. (The equivalent of local macros in Stata are called variables in Python). You can do this using the exec function:

>>> for i in range(1979, 1995):
...    exec("name_" + str(i) + " = " + str(i))

>>> print(name_1994)
1994

This code assumes you're using Python 3. If you're using Python 2, remove the outer parentheses for the lines with exec and print.

Using exec is not the best way to approach this problem in Python, however (as explained here). You will likely run into problems later on if you try to code in Python the same way you're used to coding in Stata.

A better approach might be to create a dictionary and use a different key for each number. For example:

>>> names = {}
>>> for i in range(1979, 1995):
...    names[i] = i
>>> print(names)
{1979: 1979, 1980: 1980, 1981: 1981, 1982: 1982, 1983: 1983, 1984: 1984, 1985: 1985, 1986: 1986, 1987: 1987, 1988: 1988, 1989: 1989, 1990: 1990, 1991: 1991, 1992: 1992, 1993: 1993, 1994: 1994}


问:
rVest: How to extract values (ignoring children)
I would like to extract the values from a webpage, but for certain xml structures, I seem to get out aggregate values.

```<code>data
{xml_nodeset (1)}
[1] <span class="match">tusinde<span class="super">1</span></span>
</code>```

If I extract the text I get:

```<code>data %>% html_text()
tusinde1
</code>```

What I want is:

```<code>tusinde
</code>```

答:
Without more background on the general question and a reproducible example, it is difficult to come with a solution that works beyond the particular example you give.

The following code, for instance, solves your problem, but I don't know how well in generalizes beyond that particular case.

```<code>data <- "<span class=\"match\">tusinde<span class=\"super\">1</span></span>"

out <- data %>% read_xml() %>% xml_contents()

as.character(out[1])
</code>```

Gives you:

```<code>[1] "tusinde"
</code>```

Body:
I would like to extract the values from a webpage, but for certain xml structures, I seem to get out aggregate values.

data
{xml_nodeset (1)}
[1] tusinde1

If I extract the text I get:

data %>% html_text()
tusinde1

What I want is:

tusinde

Body:
Without more background on the general question and a reproducible example, it is difficult to come with a solution that works beyond the particular example you give.

The following code, for instance, solves your problem, but I don't know how well in generalizes beyond that particular case.

data <- "<span class=\"match\">tusinde<span class=\"super\">1</span></span>"

out <- data %>% read_xml() %>% xml_contents()

as.character(out[1])

Gives you:

[1] "tusinde"


问:
how to get title of of row selected in UITableview
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

but how can i get that title of that row ?

thanks in advance

regards

答:
you can access each row of your uitabelview using the following (uitableview-)function:

```<code>cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
</code>```

by the way, to access your tableview in other methods than uitableview's delegate method, you have to hook it up in IB (for example..)

hope it helps

Body:
I have tableview with some names on each cell , how can i get that name when select row  ?

i know that i have to use delegate method

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

but how can i get that title of that row ?

thanks in advance

regards

Body:
you can access each row of your uitabelview using the following (uitableview-)function:

cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]

by the way, to access your tableview in other methods than uitableview's delegate method, you have to hook it up in IB (for example..)

hope it helps


问:
Interface reference that specifies I need an object implementing 2 or more interfaces
Let us say I have this overly simple code here:

```<code>class Person
{
    public int age;
    public string name;
    public Person(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
public class MySimpleDatabase
{
    List<Person> people;

    internal List<Person> People
    {
        get
        {
            if(people == null)
            {
                people = new List<Person>();
                people.Add(new Person(24, "ASD"));
                people.Add(new Person(35, "QWE"));
                people.Add(new Person(12, "MNB"));
            }
            return people;
        }
    }
}
public class ProcessPeopleConcrete
{
    public void WriteNames()
    {
        List<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
public class ProcessPeopleInterface
{
    public void WriteNames()
    {
        //question for here.
        IEnumerable<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
</code>```

Here I have the concrete processor as well as the interface based one. Here the interface processor is more maintainable of course, but as far as I know

```<code>   //edited here to clarify
</code>```

I can specify only one type for a variable that I require, in my case it is the IEnumerable<Person>.

What if I need something there that implements not one, but two interfaces at the same time, that have nothing to do with each other (one doesn't implement the other)?

So say I need any collection that has to implement both ICloneable and IEnumerator. In a comment it was put correctly that I could define another interface that implements both of them. But if I use pre-defined collections, I can't do that becuase then I won't be able to toss any of them as they obviously don't implement my custom made interface.

What sort of type would I specify in this case to my variable people (commented with "question here")? If there was a variable declaration like <IEnumerable, ICloneable> people; that would imaginarily mean I need something that implements both IEnumerable and ICloneable. But is there a language feature similar to that or it is what I said it is - imaginary only?

答:
As you have figured out, you cannot force classes to implement interfaces which they don't ;)

You have also noted that interfaces are used to solve a specific problem. In one case they solve how collections can be enumerated,  and in the other case they solve how an object can be cloned.

From your question I take it that you want to be able to tell that the returned object solves both problems and you wonder how you can tell that in the method contract.

You do it by defining a new interface:

```<code>public interface ISuperClonableList<T> : IEnumerable<T>, IClonable
{
}
</code>```

That's it.

If the list itself isn't clonable you need to wrap it in a new class which implements both interfaces. Pass the actual list as a constructor parameter and call it in every IEnumerable method implementation.

The problem with cloning interfaces is that they typically do not specify if it should be a deep or shallow clone. It's important to know that since it can cause large problems if the contained items are mutable.

Example generated from ReSharper:

```<code>public class MyListWrapper<T> : ISuperClonableList<T>
{
    private readonly ISuperClonableList<T> _innerList;

    public MyListWrapper(ISuperClonableList<T> innerList)
    {
        _innerList = innerList;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable) _innerList).GetEnumerator();
    }

    public void Add(T item)
    {
        _innerList.Add(item);
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    public bool Contains(T item)
    {
        return _innerList.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _innerList.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        return _innerList.Remove(item);
    }

    public int Count
    {
        get { return _innerList.Count; }
    }

    public bool IsReadOnly
    {
        get { return _innerList.IsReadOnly; }
    }

    public int IndexOf(T item)
    {
        return _innerList.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _innerList.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }

    public T this[int index]
    {
        get { return _innerList[index]; }
        set { _innerList[index] = value; }
    }
}
</code>```

Body:
Let us say I have this overly simple code here:

class Person
{
    public int age;
    public string name;
    public Person(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
public class MySimpleDatabase
{
    List<Person> people;

    internal List<Person> People
    {
        get
        {
            if(people == null)
            {
                people = new List<Person>();
                people.Add(new Person(24, "ASD"));
                people.Add(new Person(35, "QWE"));
                people.Add(new Person(12, "MNB"));
            }
            return people;
        }
    }
}
public class ProcessPeopleConcrete
{
    public void WriteNames()
    {
        List<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}
public class ProcessPeopleInterface
{
    public void WriteNames()
    {
        //question for here.
        IEnumerable<Person> people = new MySimpleDatabase().People;
        foreach (var person in people)
        {
            Console.WriteLine(person.name);
        }
    }
}

Here I have the concrete processor as well as the interface based one. Here the interface processor is more maintainable of course, but as far as I know

   //edited here to clarify

I can specify only one type for a variable that I require, in my case it is the IEnumerable<Person>.

What if I need something there that implements not one, but two interfaces at the same time, that have nothing to do with each other (one doesn't implement the other)?

So say I need any collection that has to implement both ICloneable and IEnumerator. In a comment it was put correctly that I could define another interface that implements both of them. But if I use pre-defined collections, I can't do that becuase then I won't be able to toss any of them as they obviously don't implement my custom made interface.

What sort of type would I specify in this case to my variable people (commented with "question here")? If there was a variable declaration like <IEnumerable, ICloneable> people; that would imaginarily mean I need something that implements both IEnumerable and ICloneable. But is there a language feature similar to that or it is what I said it is - imaginary only?

Body:
As you have figured out, you cannot force classes to implement interfaces which they don't ;)

You have also noted that interfaces are used to solve a specific problem. In one case they solve how collections can be enumerated,  and in the other case they solve how an object can be cloned.

From your question I take it that you want to be able to tell that the returned object solves both problems and you wonder how you can tell that in the method contract.

You do it by defining a new interface:

public interface ISuperClonableList<T> : IEnumerable<T>, IClonable
{
}

That's it.

If the list itself isn't clonable you need to wrap it in a new class which implements both interfaces. Pass the actual list as a constructor parameter and call it in every IEnumerable method implementation.

The problem with cloning interfaces is that they typically do not specify if it should be a deep or shallow clone. It's important to know that since it can cause large problems if the contained items are mutable.

Example generated from ReSharper:

public class MyListWrapper<T> : ISuperClonableList<T>
{
    private readonly ISuperClonableList<T> _innerList;

    public MyListWrapper(ISuperClonableList<T> innerList)
    {
        _innerList = innerList;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable) _innerList).GetEnumerator();
    }

    public void Add(T item)
    {
        _innerList.Add(item);
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    public bool Contains(T item)
    {
        return _innerList.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _innerList.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        return _innerList.Remove(item);
    }

    public int Count
    {
        get { return _innerList.Count; }
    }

    public bool IsReadOnly
    {
        get { return _innerList.IsReadOnly; }
    }

    public int IndexOf(T item)
    {
        return _innerList.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _innerList.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }

    public T this[int index]
    {
        get { return _innerList[index]; }
        set { _innerList[index] = value; }
    }
}